FabGL2 2.0.0
ESP32 Display Controller and Graphics Library for ESP-IDF
Loading...
Searching...
No Matches
NetworkTerminal

A WiFi network terminal with a small command shell: scan and connect to WiFi networks, ping hosts and open telnet sessions to remote computers, BBSes and servers. It runs in the VGA text mode (80x25, 16 colors).

At startup it runs info, keyb us and scan automatically, then shows the > prompt.

Commands

Command Description
help Shows the list of commands
info Shows screen and terminal size, free memory, WiFi SSID and IP address
scan Scans the WiFi networks: SSID, signal strength (dBm), channel and encryption
wifi SSID [PASSWORD] Connects to a WiFi network (omit the password for open networks). Example: wifi MyWifi MyPassword
telnet HOST [PORT] Opens a telnet session with HOST (IP address or host name), default port 23. Example: telnet towel.blinkenlights.nl
ping HOST Pings HOST every second until Ctrl+C is pressed, then prints the statistics. Example: ping 8.8.8.8
keyb LAYOUT Sets the keyboard layout: us, uk, de, it, es, fr, be, no
reboot Restarts the board

The command line supports editing with the arrow keys, Home, End, Backspace and Delete (fabgl::LineEditor).

During a telnet session every key is sent to the remote host. The session ends (and the prompt comes back) when the remote host closes the connection. The terminal reports itself as wsvt25 with a 80x25 window size.

What it demonstrates

Hardware

  • VGA output (default pins)
  • PS/2 keyboard on port 0 (CLK = GPIO33, DATA = GPIO32)

Build

See Building the examples.

Source code

Main file of the example, main/NetworkTerminal.cpp. The complete project is in the examples/VGA/NetworkTerminal folder.

1/*
2 Created by Fabrizio Di Vittorio (fdivitto2013@gmail.com) - <http://www.fabgl.com>
3 Copyright (c) 2019-2026 Fabrizio Di Vittorio.
4 All rights reserved.
5
6
7* Please contact fdivitto2013@gmail.com if you need a commercial license.
8
9
10* This library and related software is available under GPL v3.
11
12 FabGL is free software: you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation, either version 3 of the License, or
15 (at your option) any later version.
16
17 FabGL is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with FabGL. If not, see <http://www.gnu.org/licenses/>.
24 */
25
26
27#include "freertos/FreeRTOS.h"
28#include "freertos/task.h"
29#include "esp_system.h"
30#include "fabgl.h"
31
32
33#include "network/ICMP.h"
34#include "network/netutils.h"
35
36
37
38
39char const * AUTOEXEC = "info\r"
40 "keyb us\r"
41 "scan\r";
42
43
44enum class State { Prompt,
45 PromptInput,
46 UnknownCommand,
47 Help,
48 Info,
49 Wifi,
50 TelnetInit,
51 Telnet,
52 Scan,
53 Ping,
54 Reset,
55 Keyb
56 };
57
58
59State state = State::Prompt;
60fabgl::TCPClient client;
62char const * currentScript = nullptr;
63bool error = false;
64
65
66fabgl::VGATextController DisplayController;
67fabgl::PS2Controller PS2Controller;
68fabgl::Terminal Terminal;
70
71
72void exe_info()
73{
74 Terminal.write("\e[97m* * FabGL - Network VT/ANSI Terminal\r\n");
75 Terminal.write("\e[94m* * 2019-2026 by Fabrizio Di Vittorio - www.fabgl.com\e[92m\r\n\n");
76 Terminal.printf("\e[92mScreen Size :\e[93m %d x %d\r\n", DisplayController.getViewPortWidth(), DisplayController.getViewPortHeight());
77 Terminal.printf("\e[92mTerminal Size :\e[93m %d x %d\r\n", Terminal.getColumns(), Terminal.getRows());
78 Terminal.printf("\e[92mFree DMA Memory :\e[93m %d\r\n", heap_caps_get_free_size(MALLOC_CAP_DMA));
79 Terminal.printf("\e[92mFree 32 bit Memory :\e[93m %d\r\n", heap_caps_get_free_size(MALLOC_CAP_32BIT));
81 Terminal.printf("\e[92mWiFi SSID :\e[93m %s\r\n", wifi.SSID());
82 Terminal.printf("\e[92mCurrent IP :\e[93m %s\r\n", wifi.IPString());
83 }
84 Terminal.write("\n\e[92mType \e[93mhelp\e[92m to print all available commands.\r\n");
85 error = false;
86 state = State::Prompt;
87}
88
89
90void exe_help()
91{
92 Terminal.write("\e[93mhelp\e[92m\r\n");
93 Terminal.write("\e[97m Shows this help.\r\n");
94 Terminal.write("\e[93minfo\r\n");
95 Terminal.write("\e[97m Shows system info.\r\n");
96 Terminal.write("\e[93mscan\r\n");
97 Terminal.write("\e[97m Scan for WiFi networks.\r\n");
98 Terminal.write("\e[93mwifi [SSID PASSWORD]\r\n");
99 Terminal.write("\e[97m Connect to SSID using PASSWORD.\r\n");
100 Terminal.write("\e[97m Example:\r\n");
101 Terminal.write("\e[97m wifi MyWifi MyPassword\r\n");
102 Terminal.write("\e[93mtelnet HOST [PORT]\r\n");
103 Terminal.write("\e[97m Open telnet session with HOST (IP or host name) using PORT.\r\n");
104 Terminal.write("\e[97m Example:\r\n");
105 Terminal.write("\e[97m telnet towel.blinkenlights.nl\e[92m\r\n");
106 Terminal.write("\e[93mping HOST\r\n");
107 Terminal.write("\e[97m Ping a HOST (IP or host name).\r\n");
108 Terminal.write("\e[97m Example:\r\n");
109 Terminal.write("\e[97m ping 8.8.8.8\e[92m\r\n");
110 Terminal.write("\e[93mreboot\r\n");
111 Terminal.write("\e[97m Restart the system.\e[92m\r\n");
112 Terminal.write("\e[93mkeyb LAYOUT\r\n");
113 Terminal.write("\e[97m Set keyboard layout. LAYOUT can be 'us', 'uk', 'de', 'it', 'es', 'fr', 'be', 'no'\r\n");
114 Terminal.write("\e[97m Example:\r\n");
115 Terminal.write("\e[97m keyb de\e[92m\r\n");
116 error = false;
117 state = State::Prompt;
118}
119
120
121void decode_command()
122{
123 auto inputLine = LineEditor.get();
124 if (*inputLine == 0)
125 state = State::Prompt;
126 else if (strncmp(inputLine, "help", 4) == 0)
127 state = State::Help;
128 else if (strncmp(inputLine, "info", 4) == 0)
129 state = State::Info;
130 else if (strncmp(inputLine, "wifi", 4) == 0)
131 state = State::Wifi;
132 else if (strncmp(inputLine, "telnet", 6) == 0)
133 state = State::TelnetInit;
134 else if (strncmp(inputLine, "scan", 4) == 0)
135 state = State::Scan;
136 else if (strncmp(inputLine, "ping", 4) == 0)
137 state = State::Ping;
138 else if (strncmp(inputLine, "reboot", 6) == 0)
139 state = State::Reset;
140 else if (strncmp(inputLine, "keyb", 4) == 0)
141 state = State::Keyb;
142 else
143 state = State::UnknownCommand;
144}
145
146
147void exe_prompt()
148{
149 if (currentScript) {
150 // process commands from script
151 if (*currentScript == 0 || error) {
152 // end of script, return to prompt
153 currentScript = nullptr;
154 state = State::Prompt;
155 } else {
156 // execute current line and move to the next one
157 int linelen = strchr(currentScript, '\r') - currentScript;
158 LineEditor.setText(currentScript, linelen);
159 currentScript += linelen + 1;
160 decode_command();
161 }
162 } else {
163 // process commands from keyboard
164 Terminal.write(">");
165 state = State::PromptInput;
166 }
167}
168
169
170void exe_promptInput()
171{
174 decode_command();
175}
176
177
178void exe_scan()
179{
180 Terminal.write("Scanning...");
181 Terminal.flush();
182 fabgl::WiFiScanner scanner;
183 int networksCount = scanner.scan(32) ? scanner.count() : 0;
184 Terminal.printf("%d network(s) found\r\n", networksCount);
185 if (networksCount) {
186 Terminal.write ("\e[90m #\e[4GSSID\e[45GRSSI\e[55GCh\e[60GEncryption\e[92m\r\n");
187 for (int i = 0; i < networksCount; ++i)
188 Terminal.printf("\e[93m %d\e[4G%s\e[93m\e[45G%d dBm\e[55G%d\e[60G%s\e[92m\r\n", i + 1, (char const *) scanner.get(i)->ssid, scanner.get(i)->rssi, scanner.get(i)->primary, fabgl::WiFiScanner::authModeStr(scanner.get(i)->authmode));
189 }
190 error = false;
191 state = State::Prompt;
192}
193
194
195void exe_wifi()
196{
197 static const int MAX_SSID_SIZE = 32;
198 static const int MAX_PSW_SIZE = 32;
199 char ssid[MAX_SSID_SIZE + 1];
200 char psw[MAX_PSW_SIZE + 1] = {0};
201 error = true;
202 auto inputLine = LineEditor.get();
203 if (sscanf(inputLine, "wifi %32s %32s", ssid, psw) >= 1) {
204 Terminal.write("Connecting WiFi...");
205 Terminal.flush();
206 wifi.disconnect();
207 for (int i = 0; i < 2; ++i) {
208 if (wifi.connect(ssid, psw, 10000) == fabgl::WiFiConnectionState::Connected)
209 break;
210 wifi.disconnect();
211 }
213 Terminal.printf("connected to %s, IP is %s\r\n", wifi.SSID(), wifi.IPString());
214 error = false;
215 } else {
216 Terminal.write("failed!\r\n");
217 }
218 }
219 state = State::Prompt;
220}
221
222
223void exe_telnetInit()
224{
225 static const int MAX_HOST_SIZE = 32;
226 char host[MAX_HOST_SIZE + 1];
227 int port;
228 error = true;
229 auto inputLine = LineEditor.get();
230 int pCount = sscanf(inputLine, "telnet %32s %d", host, &port);
231 if (pCount > 0) {
232 if (pCount == 1)
233 port = 23;
234 Terminal.printf("Trying %s...\r\n", host);
235 if (client.connect(host, port)) {
236 Terminal.printf("Connected to %s\r\n", host);
237 error = false;
238 state = State::Telnet;
239 } else {
240 Terminal.write("Unable to connect to remote host\r\n");
241 state = State::Prompt;
242 }
243 } else {
244 Terminal.write("Mistake\r\n");
245 state = State::Prompt;
246 }
247}
248
249
250int clientWaitForChar()
251{
252 while (!client.available() && client.connected())
253 vTaskDelay(1);
254 return client.read();
255}
256
257
258void exe_telnet()
259{
260 // process data from remote host (up to 1024 codes at the time)
261 for (int i = 0; client.available() && i < 1024; ++i) {
262 int c = client.read();
263 if (c == 0xFF) {
264 // IAC (Interpret As Command)
265 uint8_t cmd = clientWaitForChar();
266 uint8_t opt = clientWaitForChar();
267 if (cmd == 0xFD && opt == 0x1F) {
268 // DO WINDOWSIZE
269 client.write("\xFF\xFB\x1F", 3); // IAC WILL WINDOWSIZE
270 client.write("\xFF\xFA\x1F" "\x00\x50\x00\x19" "\xFF\xF0", 9); // IAC SB WINDOWSIZE 0 80 0 25 IAC SE
271 } else if (cmd == 0xFD && opt == 0x18) {
272 // DO TERMINALTYPE
273 client.write("\xFF\xFB\x18", 3); // IAC WILL TERMINALTYPE
274 } else if (cmd == 0xFA && opt == 0x18) {
275 // SB TERMINALTYPE
276 c = clientWaitForChar(); // bypass '1'
277 c = clientWaitForChar(); // bypass IAC
278 c = clientWaitForChar(); // bypass SE
279 client.write("\xFF\xFA\x18\x00" "wsvt25" "\xFF\xF0", 12); // IAC SB TERMINALTYPE 0 "...." IAC SE
280 } else {
281 uint8_t pck[3] = {0xFF, 0, opt};
282 if (cmd == 0xFD) // DO -> WONT
283 pck[1] = 0xFC;
284 else if (cmd == 0xFB) // WILL -> DO
285 pck[1] = 0xFD;
286 client.write(pck, 3);
287 }
288 } else {
289 Terminal.write(c);
290 }
291 }
292 // process data from terminal (keyboard)
293 while (Terminal.available()) {
294 client.write( Terminal.read() );
295 }
296 // return to prompt?
297 if (!client.connected()) {
298 client.stop();
299 state = State::Prompt;
300 }
301}
302
303
304void exe_ping()
305{
306 char host[64];
307 auto inputLine = LineEditor.get();
308 int pcount = sscanf(inputLine, "ping %s", host);
309 if (pcount > 0) {
310 int sent = 0, recv = 0;
311 fabgl::ICMP icmp;
312 while (true) {
313
314 // CTRL-C ?
315 if (Terminal.available() && Terminal.read() == 0x03)
316 break;
317
318 int t = icmp.ping(host);
319 if (t >= 0) {
320 Terminal.printf("%d bytes from %s: icmp_seq=%d ttl=%d time=%.3f ms\r\n", icmp.receivedBytes(), icmp.hostIPString(), icmp.receivedSeq(), icmp.receivedTTL(), (double)t/1000.0);
321 vTaskDelay(pdMS_TO_TICKS(1000));
322 ++recv;
323 } else if (t == -2) {
324 Terminal.printf("Cannot resolve %s: Unknown host\r\n", host);
325 break;
326 } else {
327 Terminal.printf("Request timeout for icmp_seq %d\r\n", icmp.receivedSeq());
328 }
329 ++sent;
330
331 }
332 if (sent > 0) {
333 Terminal.printf("--- %s ping statistics ---\r\n", host);
334 Terminal.printf("%d packets transmitted, %d packets received, %.1f%% packet loss\r\n", sent, recv, (double)(sent - recv) / sent * 100.0);
335 }
336 }
337 state = State::Prompt;
338}
339
340
341void exe_keyb()
342{
343 if (PS2Controller.keyboard()->isKeyboardAvailable()) {
344 char layout[3];
345 auto inputLine = LineEditor.get();
346 if (sscanf(inputLine, "keyb %2s", layout) == 1) {
347 if (strcasecmp(layout, "US") == 0)
348 Terminal.keyboard()->setLayout(&fabgl::USLayout);
349 else if (strcasecmp(layout, "UK") == 0)
350 Terminal.keyboard()->setLayout(&fabgl::UKLayout);
351 else if (strcasecmp(layout, "DE") == 0)
352 Terminal.keyboard()->setLayout(&fabgl::GermanLayout);
353 else if (strcasecmp(layout, "IT") == 0)
354 Terminal.keyboard()->setLayout(&fabgl::ItalianLayout);
355 else if (strcasecmp(layout, "ES") == 0)
356 Terminal.keyboard()->setLayout(&fabgl::SpanishLayout);
357 else if (strcasecmp(layout, "FR") == 0)
358 Terminal.keyboard()->setLayout(&fabgl::FrenchLayout);
359 else if (strcasecmp(layout, "BE") == 0)
360 Terminal.keyboard()->setLayout(&fabgl::BelgianLayout);
361 else if (strcasecmp(layout, "NO") == 0)
362 Terminal.keyboard()->setLayout(&fabgl::NorwegianLayout);
363 else {
364 Terminal.printf("Error! Invalid keyboard layout.\r\n");
365 state = State::Prompt;
366 return;
367 }
368 }
369 Terminal.printf("\r\nKeyboard layout is : \e[93m%s\e[92m\r\n\r\n", Terminal.keyboard()->getLayout()->desc);
370 } else {
371 Terminal.printf("No keyboard present\r\n");
372 }
373 state = State::Prompt;
374}
375
376
377void setup()
378{
379
380 PS2Controller.begin(PS2Preset::KeyboardPort0);
381
382 DisplayController.begin();
383 DisplayController.setResolution();
384
385 Terminal.begin(&DisplayController);
386 Terminal.connectLocally(); // to use Terminal.read(), available(), etc..
387 //Terminal.setLogStream(Console); // DEBUG ONLY (requires "fabgl::UARTStream Console; Console.begin();")
388
389 Terminal.setBackgroundColor(Color::Black);
390 Terminal.setForegroundColor(Color::BrightGreen);
391 Terminal.clear();
392
393 Terminal.enableCursor(true);
394
395 currentScript = AUTOEXEC;
396}
397
398
399void loop()
400{
401 switch (state) {
402
403 case State::Prompt:
404 exe_prompt();
405 break;
406
407 case State::PromptInput:
408 exe_promptInput();
409 break;
410
411 case State::Help:
412 exe_help();
413 break;
414
415 case State::Info:
416 exe_info();
417 break;
418
419 case State::Wifi:
420 exe_wifi();
421 break;
422
423 case State::TelnetInit:
424 exe_telnetInit();
425 break;
426
427 case State::Telnet:
428 exe_telnet();
429 break;
430
431 case State::Scan:
432 exe_scan();
433 break;
434
435 case State::Ping:
436 exe_ping();
437 break;
438
439 case State::Reset:
440 esp_restart();
441 break;
442
443 case State::Keyb:
444 exe_keyb();
445 break;
446
447 case State::UnknownCommand:
448 Terminal.write("\r\nMistake\r\n");
449 state = State::Prompt;
450 break;
451
452 default:
453 Terminal.write("\r\nNot Implemeted\r\n");
454 state = State::Prompt;
455 break;
456
457 }
458}
459
460
461extern "C" void app_main()
462{
463 setup();
464 while (true)
465 loop();
466}
This file contains the fabgl::ICMP definition (ping).
char const * edit(int maxLength=0)
Reads user input and returns the entered line.
void setText(char const *text, bool moveCursor=true)
Sets initial text.
LineEditor(Terminal *terminal)
Object constructor.
char const * get()
Gets the current content.
Definition terminal.h:1933
LineEditor is a single-line editor, spanning multiple rows if needed, that uses a Terminal object for...
Definition terminal.h:1865
int getViewPortHeight()
Determines the height of the viewport.
int getViewPortWidth()
Determines the width of the viewport.
int ping(esp_ip4_addr_t const &dest)
Sends an echo request and waits for the echo reply.
Definition ICMP.cpp:75
char const * hostIPString()
Returns the last destination IP address as a dotted string.
Definition ICMP.cpp:136
ICMP echo (ping) helper class.
Definition ICMP.h:65
void setLayout(KeyboardLayout const *layout)
Sets the keyboard layout.
Definition keyboard.cpp:224
KeyboardLayout const * getLayout()
Gets the current keyboard layout.
Definition keyboard.h:191
bool isKeyboardAvailable()
Checks whether the keyboard has been detected and correctly initialized.
Definition keyboard.h:168
LineEditor is a single-line editor, spanning multiple rows if needed, that uses a Terminal object for...
Definition terminal.h:1865
static Keyboard * keyboard()
Returns the Keyboard object automatically created by PS2Controller.
static void begin(gpio_num_t port0_clkGPIO, gpio_num_t port0_datGPIO, gpio_num_t port1_clkGPIO=GPIO_UNUSED, gpio_num_t port1_datGPIO=GPIO_UNUSED)
Initializes the PS/2 device controller.
PS/2 device controller.
int available()
Returns the number of bytes available for reading.
Definition netutils.cpp:645
size_t write(uint8_t c)
Sends one byte.
Definition netutils.h:452
bool connected()
Determines whether the connection is still open (or received data is still pending).
Definition netutils.cpp:638
void stop()
Closes the connection.
Definition netutils.cpp:612
int read()
Reads one byte (returns -1 if no data is available).
Definition netutils.cpp:659
bool connect(char const *host, int port, int timeOutMS=5000)
Connects to the specified host and port.
Definition netutils.cpp:558
Simple TCP client based on BSD sockets (lwIP).
Definition netutils.h:404
void connectLocally()
Allows the terminal to be used locally.
Definition terminal.cpp:439
int getRows()
Returns the number of lines.
Definition terminal.h:1075
void clear(bool moveCursor=true)
Clears the screen.
Definition terminal.cpp:797
int available()
Gets the number of codes available in the keyboard queue.
int getColumns()
Returns the number of columns.
Definition terminal.h:1068
size_t write(const uint8_t *buffer, size_t size)
Sends the specified number of codes to the display.
Keyboard * keyboard()
Gets the associated keyboard object.
Definition terminal.h:1231
int read()
Reads codes from keyboard.
void enableCursor(bool value)
Enables or disables the cursor.
Definition terminal.cpp:902
void setBackgroundColor(Color color, bool setAsDefault=true)
Sets the background color.
Definition terminal.cpp:707
bool begin(BaseDisplayController *displayController, int maxColumns=-1, int maxRows=-1, Keyboard *keyboard=nullptr)
Initializes the terminal.
Definition terminal.cpp:307
void flush(bool waitVSync)
Waits until all codes sent to the display have been processed.
Definition terminal.cpp:674
void setForegroundColor(Color color, bool setAsDefault=true)
Sets the foreground color.
Definition terminal.cpp:727
An ANSI-VT100 compatible display terminal.
Definition terminal.h:883
void begin(gpio_num_t redGPIO, gpio_num_t greenGPIO, gpio_num_t blueGPIO, gpio_num_t HSyncGPIO, gpio_num_t VSyncGPIO)
Initializer for 8 colors (5 GPIOs).
void setResolution(char const *modeline=nullptr, int viewPortWidth=-1, int viewPortHeight=-1, bool doubleBuffered=false)
Sets the fixed resolution.
VGA text-only display controller.
char const * SSID()
Returns the SSID of the network.
Definition netutils.h:222
WiFiConnectionState connect(char const *ssid, char const *password, int waitConnectionTimeOutMS=10000)
Tries to connect to a WiFi network.
Definition netutils.cpp:201
WiFiConnectionState state()
Returns the connection state.
Definition netutils.h:191
void disconnect()
Disconnects from the WiFi network.
Definition netutils.cpp:249
char const * IPString()
Returns the current IP address as a dotted string.
Definition netutils.cpp:185
WiFi connection helper class.
Definition netutils.h:163
static char const * authModeStr(wifi_auth_mode_t mode)
Returns a textual description of an authentication mode.
Definition netutils.cpp:144
int count()
Returns the number of networks found (limited to the requested maximum).
Definition netutils.h:100
bool scan(int maxItems=8, bool justCount=false)
Performs a WiFi scan.
Definition netutils.cpp:81
wifi_ap_record_t * get(int index)
Returns information about the specified network.
Definition netutils.h:109
WiFi scanner helper class.
Definition netutils.h:78
Single include file of the FabGL library.
This file contains the fabgl::WiFiScanner, fabgl::WiFiConnection, fabgl::HTTPRequest and fabgl::TCPCl...
const char * desc
Definition kbdlayouts.h:92