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

A complete serial VT/ANSI terminal: connect the board to a retro computer, a Z80/CP/M board (e.g. MBC2, RC2014), a Raspberry Pi, a Linux console or any device with a serial port, and use it with a VGA monitor and a PS/2 keyboard and mouse. All the settings are configured on screen and saved in NVS.

At boot the terminal shows version, screen and terminal size, keyboard layout, terminal type and serial parameters (this can be disabled with Show Info).

Default settings

Setting Default
Serial port TX = GPIO2, RX = GPIO34 (FabGL Terminal port), RTS = GPIO13, CTS = GPIO35
Serial parameters 115200 baud, 8N1, no flow control
Terminal type ANSI Legacy
Keyboard layout US
Resolution 640x480 60 Hz, 16 colors, font chosen automatically for 80x25
Colors bright green on black

Keys

Key Action
F12 Opens the Terminal Configuration dialog
Ctrl + Alt + F12 Resets all settings to the defaults and reboots
Pause/Break Sends a serial BREAK (233 ms)
Shift + Pause/Break Sends a long serial BREAK (3.5 s)

Terminal Configuration dialog (F12)

Use Tab / Shift+Tab to move between fields, or the mouse.

Field Values
Terminal Type ANSI, ADM 3A, ADM 31, Hazeltine 1500, Osborne, Kaypro, VT52, ANSI Legacy
Keyboard Layout DE, IT, UK, US, ES, FR, BE, NO, JP
Background / Foreground Color Any of the 16 terminal colors
Baud Rate 110 ... 2000000
Data Length / Parity / Stop Bits 5-8 bits / None, Even, Odd / 1, 1.5, 2, 3
Flow Control None, XON/XOFF, RTS/CTS, Combi (both)
Resolution 1280x768 B&W, 1024x720 4 colors, 800x600 8 colors, 720x520 16 colors, 640x480 73 Hz or 60 Hz 16 colors, 640x350 16 colors, 512x384 64 colors, 400x300 64 colors
Font Auto, or one of the 31 included fonts (from 4x6 to 10x20, plus decorative fonts)
Columns / Rows Max (as many as fit), 80 or 132 / Max, 24 or 25
Port FabGL Terminal (TX=2, RX=34), USB (TX=1, RX=3: the USB-serial chip, so the terminal can be driven by a PC), PS/2 Mouse (TX=27, RX=26: uses the mouse port, the mouse is disabled)
Show Info Shows the information screen at boot
RTS / CTS RTS can be toggled by clicking it; CTS shows the input line state

Buttons:

Button Action
Quit [ESC] Closes the dialog without saving
Save & Quit [F10] Saves the settings. Changes of resolution, font, columns, rows, background color or port reboot the terminal
Reboot [CTRL+ESC] Reboots the board
Install Programs Sends a sample BASIC program to the host (see below)

Install Programs

When the host runs CP/M, Install Programs types PIP <NAME>.BAS=CON: on the host and then sends the program text, so the file is saved on the host disk. Then run it with MBASIC (MBASIC <NAME>). The programs use the FabGL-specific escape sequences to control GPIOs, read the ADC, play sounds, read the mouse and draw graphics and sprites:

Program Description
BLINK.BAS Sets GPIO12 as output and turns it on and off
GPIOREAD.BAS Sets GPIO36 as digital input and continuously prints its value
ADC.BAS Sets GPIO36 as analog input and draws its value
ADCVOLTS.BAS Sets GPIO36 as analog input and prints its value in Volts
SOUND.BAS Generates some sounds
MOUSE.BAS Shows mouse position and buttons
GRAPH.BAS Draws some graphics
SPRITE.BAS Creates and moves sprites

The same programs are in Extras/Terminal BASIC Programs. The full list of FabGL sequences is in FabGL Specific Terminal Sequences.

Changing resolution from the host

The host can switch resolution by sending the user sequence ESC _ # <mode> $, where <mode> is one of 1280x768x2, 1024x720x4, 800x600x8, 720x520x16, 640x480@73x16, 640x480@60x16, 640x350x16, 512x384x64, 400x300x64. The terminal reboots in the new mode for one session only (the saved resolution is not changed). Example from MBASIC: PRINT CHR$(27);"_#800x600x8$";

What it demonstrates

  • fabgl::Terminal connected to a UART through fabgl::SerialPort and fabgl::SerialPortTerminalConnector (hardware and software flow control, BREAK)
  • Terminal emulations, fonts, colors and keyboard layouts selectable at run time
  • Choosing the display controller (2, 4, 8, 16 or 64 colors) at run time according to the resolution
  • A configuration GUI (uiApp) shown on top of the terminal, fabgl::Preferences (NVS)
  • Terminal user sequences (Terminal.onUserSequence)

Hardware

  • VGA output (default pins)
  • PS/2 keyboard on port 0 and PS/2 mouse on port 1 (optional)
  • Serial connection to the host (3.3 V logic levels; use a level shifter for RS-232 or 5 V devices)

Build

See Building the examples.

Source code

Main file of the example, main/AnsiTerminal.cpp. The complete project is in the examples/VGA/AnsiTerminal 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/*
28
29 Credits:
30 - Guido Lehwalder, https://github.com/guidol70 : using USB-serial Port for ANSI-Terminal (https://github.com/fdivitto/FabGL/issues/110)
31
32*/
33
34#include "freertos/FreeRTOS.h"
35#include "freertos/task.h"
36#include "esp_system.h"
37#include "fabgl.h"
38
39
40fabgl::BitmappedDisplayController * DisplayController;
41fabgl::PS2Controller PS2Controller;
42fabgl::Terminal Terminal;
43fabgl::SerialPort SerialPort;
44fabgl::SerialPortTerminalConnector SerialPortTerminalConnector;
45
46
47// RTS/CTS hardware flow gpios
48#define UART_RTS 13
49#define UART_CTS 35
50
51
52// settings reset control
53/* for old WROOM-32 boards
54#define RESET_PIN 12
55#define RESET_PIN_ACTIVE 1 // 0 = reset when low, 1 = reset when high
56#define USERESETPIN 1 // 1 = reset enabled
57//*/
58#define RESET_PIN 39
59#define RESET_PIN_ACTIVE 0 // 0 = reset when low, 1 = reset when high
60#define USERESETPIN 0 // 1 = reset enabled
61
62
63#define SHOWBREAKS 0
64
65
66
67
68#include "confdialog.h"
69
70
71#if FABGLIB_TERMINAL_DEBUG_REPORT
72fabgl::UARTStream Console; // UART0 (console) stream, used for debug
73#endif
74
75
76void setup()
77{
78 #if FABGLIB_TERMINAL_DEBUG_REPORT
79 Console.begin(); vTaskDelay(pdMS_TO_TICKS(500)); printf("\n\nReset\n\n"); // DEBUG ONLY
80 #endif
81
82
83 // more stack is required for the UI (used inside Terminal.onVirtualKey)
84 Terminal.keyboardReaderTaskStackSize = 3000;
85
86 Terminal.inputQueueSize = 2048; // 2048 good to pass vttest
87
88 preferences.begin("AnsiTerminal", false);
89
90 ConfDialogApp::checkVersion();
91
92 #if USERESETPIN
93 fabgl::configureGPIO((gpio_num_t)(RESET_PIN), GPIO_MODE_INPUT);
94 if (gpio_get_level((gpio_num_t)(RESET_PIN)) == RESET_PIN_ACTIVE)
95 preferences.clear();
96 #endif
97
98 // because mouse is optional, don't re-try if it is not found (to speed-up boot)
100
101 // keyboard configured on port 0, and optionally mouse on port 1
102 if (UARTPORT_FLAGS[ConfDialogApp::getUARTPortIndex()] & UARTFLAG_USE_PS2PORT1)
103 PS2Controller.begin(PS2Preset::KeyboardPort0); // mouse port used as serial port, so no mouse available
104 else
105 PS2Controller.begin(PS2Preset::KeyboardPort0_MousePort1);
106
107 ConfDialogApp::setupDisplay();
108
109 ConfDialogApp::loadConfiguration();
110
111 #if FABGLIB_TERMINAL_DEBUG_REPORT
112 Terminal.setLogStream(Console); // debug only
113 #endif
114
115 Terminal.clear();
116 Terminal.enableCursor(true);
117
118 if (ConfDialogApp::getBootInfo() == BOOTINFO_ENABLED) {
119 Terminal.write("* * FabGL - Serial Terminal * *\r\n");
120 Terminal.write("* * 2019-2026 by Fabrizio Di Vittorio - www.fabgl.com * *\r\n\n");
121 Terminal.printf("Version : %d.%d\r\n", TERMVERSION_MAJ, TERMVERSION_MIN);
122 Terminal.printf("Screen Size : %d x %d\r\n", DisplayController->getViewPortWidth(), DisplayController->getViewPortHeight());
123 Terminal.printf("Terminal Size : %d x %d\r\n", Terminal.getColumns(), Terminal.getRows());
124 Terminal.printf("Keyboard Layout : %s\r\n", PS2Controller.keyboard()->isKeyboardAvailable() ? SupportedLayouts::names()[ConfDialogApp::getKbdLayoutIndex()] : "No Keyboard");
125 //Terminal.printf("Mouse : %s\r\n", PS2Controller.mouse()->isMouseAvailable() ? "Yes" : "No");
126 Terminal.printf("Terminal Type : %s\r\n", SupportedTerminals::names()[(int)ConfDialogApp::getTermType()]);
127 //Terminal.printf("Free Memory : %d bytes\r\n", heap_caps_get_free_size(MALLOC_CAP_32BIT));
128 Terminal.printf("Serial Port : %s\r\n", UARTPORT_STR[ConfDialogApp::getUARTPortIndex()]);
129 Terminal.printf("Serial Parameters : %s\r\n", ConfDialogApp::getSerParamStr());
130
131 Terminal.write("\r\nPress F12 to change terminal configuration and CTRL-ALT-F12 to reset settings\r\n\n");
132 } else if (ConfDialogApp::getBootInfo() == BOOTINFO_TEMPDISABLED) {
133 preferences.putInt(PREF_BOOTINFO, BOOTINFO_ENABLED);
134 }
135
136 // onVirtualKey is triggered whenever a key is pressed or released
137 Terminal.onVirtualKeyItem = [&](VirtualKeyItem * vkItem) {
138 if (vkItem->vk == VirtualKey::VK_F12) {
139 // CTRL ALT F12 -> show reboot dialog
140 // F12 -> show configuration dialog
141 if (vkItem->CTRL && (vkItem->LALT || vkItem->RALT)) {
142 Terminal.deactivate();
143 preferences.clear();
144 // show reboot dialog
145 auto rebootApp = new RebootDialogApp;
146 rebootApp->run(DisplayController);
147 } else if (!vkItem->CTRL && !vkItem->LALT && !vkItem->RALT && !vkItem->down) {
148 // releasing F12 key to open configuration dialog
149 Terminal.deactivate();
150 if (PS2Controller.mouse())
151 PS2Controller.mouse()->emptyQueue(); // avoid previous mouse movements to be showed on UI
152 auto dlgApp = new ConfDialogApp;
153 dlgApp->run(DisplayController);
154 auto progToInstall = dlgApp->progToInstall;
155 // this is required, because the terminal may not cover the entire screen
156 Terminal.canvas()->reset();
157 Terminal.canvas()->setBrushColor(dlgApp->getBGColor());
158 Terminal.canvas()->fillRectangle(dlgApp->frameRect);
159 delete dlgApp;
160 Terminal.keyboard()->emptyVirtualKeyQueue();
161 Terminal.activate();
162 // it has been requested to install a demo program?
163 if (progToInstall > -1)
164 installProgram(progToInstall);
165 vkItem->vk = VirtualKey::VK_NONE;
166 }
167 } else if (vkItem->vk == VirtualKey::VK_BREAK && !vkItem->down) {
168 // BREAK (CTRL PAUSE) -> short break (TX low for 3.5 s)
169 // SHIFT BREAK (SHIFT CTRL PAUSE) -> long break (TX low for 0.233 ms)
170 SerialPort.sendBreak(true);
171 vTaskDelay((vkItem->SHIFT ? 3500 : 233) / portTICK_PERIOD_MS);
172 SerialPort.sendBreak(false);
173 vkItem->vk = VirtualKey::VK_NONE;
174 }
175 };
176
177 // onUserSequence is triggered whenever a User Sequence has been received (ESC + '_#' ... '$'), where '...' is sent here
178 Terminal.onUserSequence = [&](char const * seq) {
179 // 'R': change resolution (for example: ESC + "_#R512x384x64$")
180 for (int i = 0; i < RESOLUTIONS_COUNT; ++i)
181 if (strcmp(RESOLUTIONS_CMDSTR[i], seq) == 0) {
182 // found resolution string
183 preferences.putInt(PREF_TEMPRESOLUTION, i);
184 if (ConfDialogApp::getBootInfo() == BOOTINFO_ENABLED)
185 preferences.putInt(PREF_BOOTINFO, BOOTINFO_TEMPDISABLED);
186 esp_restart();
187 }
188 };
189}
190
191
192void loop()
193{
194 #if SHOWBREAKS
195 if (SerialPort.breakDetected()) {
196 Terminal.printf("BREAK\r\n");
197 }
198 vTaskDelay(50);
199 #else
200
201 // the job is done using UART interrupts
202 vTaskDelete(NULL);
203
204 #endif
205}
206
207
208extern "C" void app_main()
209{
210 setup();
211 while (true)
212 loop();
213}
int getViewPortHeight()
Determines the height of the viewport.
int getViewPortWidth()
Determines the width of the viewport.
Represents the base abstract class for bitmapped display controllers.
void fillRectangle(int X1, int Y1, int X2, int Y2)
Fills a rectangle using the current brush color.
Definition canvas.cpp:278
void setBrushColor(uint8_t red, uint8_t green, uint8_t blue)
Sets the brush (background) color from its color components.
Definition canvas.cpp:214
void reset()
Resets the paint state and other display controller settings.
Definition canvas.cpp:118
bool isKeyboardAvailable()
Checks whether the keyboard has been detected and correctly initialized.
Definition keyboard.h:168
void emptyVirtualKeyQueue()
Empties the virtual key queue.
Definition keyboard.cpp:722
void emptyQueue()
Empties the mouse status and event queues.
Definition mouse.cpp:426
static void quickCheckHardware()
Disables retries when no mouse is found.
Definition mouse.h:379
static Mouse * mouse()
Returns the Mouse object automatically created by PS2Controller.
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.
void sendBreak(bool value)
Activates or deactivates the break condition.
bool breakDetected()
Gets the break detected flag.
Definition serialport.h:273
SerialPort handles UART configuration and communication.
Definition serialport.h:67
SerialPortTerminalConnector is a helper class that connects a Terminal to a SerialPort.
Definition serialport.h:325
int getRows()
Returns the number of lines.
Definition terminal.h:1075
void clear(bool moveCursor=true)
Clears the screen.
Definition terminal.cpp:797
void setLogStream(Stream &stream)
Sets the stream that receives debug logs.
Definition terminal.h:992
int getColumns()
Returns the number of columns.
Definition terminal.h:1068
static int keyboardReaderTaskStackSize
Stack size of the task that reads keys from the keyboard and sends the corresponding ANSI/VT codes to...
Definition terminal.h:1374
size_t write(const uint8_t *buffer, size_t size)
Sends the specified number of codes to the display.
Canvas * canvas()
Gets the associated canvas object.
Definition terminal.h:1238
void deactivate()
Deactivates this terminal.
Definition terminal.cpp:274
Keyboard * keyboard()
Gets the associated keyboard object.
Definition terminal.h:1231
static int inputQueueSize
Number of characters the terminal can accept without blocking (increase it if characters are lost on ...
Definition terminal.h:1356
void activate(TerminalTransition transition=TerminalTransition::None)
Activates this terminal for input and output.
Definition terminal.cpp:199
void enableCursor(bool value)
Enables or disables the cursor.
Definition terminal.cpp:902
Delegate< VirtualKeyItem * > onVirtualKeyItem
Delegate called whenever a new virtual key is received from the keyboard, including shift states.
Definition terminal.h:1309
Delegate< char const * > onUserSequence
Delegate called whenever a new user sequence has been received.
Definition terminal.h:1319
An ANSI-VT100 compatible display terminal.
Definition terminal.h:883
bool begin(int port=0, int baud=0, int rxPin=-1, int txPin=-1, int rxBufferSize=1024, int txBufferSize=0)
Initializes the UART.
A Stream implemented on top of the ESP-IDF UART driver.
Definition uartstream.h:68
Single include file of the FabGL library.
Contains a virtual key, its state and the associated scancode.
Definition fabutils.h:1660