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

IBM PC/XT emulator: Intel 8086/8088 CPU, 1 MB of RAM, CGA (text, 320x200 and 640x200 graphics) and Hercules (720x348) video, PC speaker, PS/2 keyboard and mouse, two floppy drives, two hard disks and a serial port. It runs MS-DOS, FreeDOS, CP/M-86, Linux ELKS, Windows 3.0, GEM, GEOS and many DOS programs and games. Watch it on YouTube.

Requirements

  • An ESP32 board with PSRAM (the emulated RAM lives in PSRAM), for example TTGO VGA32 v1.4 or the Olimex ESP32-SBC-FabGL
  • An SD card (FAT32): disk images and the machine configurations are stored on it
  • WiFi, the first time, to download the disk images (or copy them to the SD card from a PC)
  • VGA monitor, PS/2 keyboard, optional PS/2 mouse, audio on GPIO25 for the PC speaker

Getting started

  1. Insert the SD card and flash the example.
  2. If the date and time are not known yet (cold boot) the emulator asks to configure the WiFi: choose a network and type the password. The time is taken from an NTP server (pool.ntp.org) and the board restarts. Without WiFi the date is set to 14 August 1984.
  3. The Machine Configurations list appears. Choose a machine and press Run (if you do nothing, the last used machine starts after 6 seconds).
  4. If the disk images of the machine are not on the SD card yet, they are downloaded from www.fabglib.org (a progress bar shows the progress; big images take some minutes, interrupted downloads are resumed automatically). After the download the board restarts and boots the machine.

Predefined machines

Machine Disk image
FreeDOS (floppy 1.44 MB) floppy_FREEDOS.img
MS-DOS 3.31 (floppy 1.44 MB) floppy_MSDOS331.img
CP/M 86 + Turbo Pascal 3 (floppy 1.44 MB) floppy_CPM86.img
Linux ELKS 0.4.0 (floppy 1.44 MB) floppy_ELK040.img
FreeDOS (HDD 8 MB) hd8_FREEDOS.img
DOS Programs and Games (HDD 20 MB) hd20_DOSPROG.img
DOS Programming Tools (HDD 20 MB) hd20_DOSDEV.img
Windows 3.0 (HDD 20 MB) hd20_WINHERC.img
GEM 3.13 (HDD 8 MB) hd8_GEM31.img
GEOS 2.0 (HDD 20 MB) hd20_GEOS20.img
MS-DOS 5.00 (HDD 8 MB) hd8_MSDOS500.img
MS-DOS 6.22 (HDD 8 MB) hd8_MSDOS622.img
SvarDOS (HDD 10 MB) hd10_SVARDOS.img

All the images are downloaded from the downloads folder of www.fabglib.org into the root of the SD card. You can also download them with a PC and copy them to the SD card.

Machine Configurations screen

Button Action
Run Starts the selected machine
Files Browses the files and directories on the SD card
Machine > Edit Edits the selected configuration
Machine > New Creates a new configuration
Machine > Remove Removes the selected configuration

The configuration editor has these fields:

Field Meaning
Description Name shown in the list
Floppy 0 / Floppy 1 Image of drive A: / B: (a file on the SD card, or an HTTP / HTTPS URL to download it)
HDD 0 / HDD 1 Image of the first / second hard disk (C: / D:), with its geometry (Cylinders, Heads, Sectors; leave 0 to compute it from the file size)
Boot Drive Floppy 0, Floppy 1, HDD 0 or HDD 1
... Selects an image file from the SD card
Create Disk Creates a new empty disk image: formatted floppy (320K, 360K, 720K, 1.2M, 1.44M, 2.88M, FAT12) or unformatted hard disk of the given size in MB (partition and format it from DOS with FDISK and FORMAT)

The configurations are saved in mconfs.txt in the root of the SD card. It is a text file, one machine per line, that can also be edited on a PC:

desc "FreeDOS (A:) + DOS Programming Tools (C:)" fd0 https://www.fabglib.org/downloads/floppy_FREEDOS.img hd0 https://www.fabglib.org/downloads/hd20_DOSDEV.img
desc "My Own MSDOS" hd0 HDD_10M.IMG chs0 306,4,17 boot hd0
desc "Machine1" fd0 msdos3/disk1.img

Tags: desc (description), fd0 / fd1 (floppy A / B), hd0 / hd1 (hard disks), chs0 / chs1 (hard disk geometry: cylinders,heads,sectors), boot (fd0, fd1, hd0, hd1; default fd0). File names are relative to the SD card root. Delete mconfs.txt to restore the predefined list.

Using images

  • Floppy images must be raw sector images (.img, .ima) of 160K, 180K, 320K, 360K, 720K, 1.2M, 1.44M or 2.88M.
  • Hard disk images are raw images (no VHD header). When no geometry is given, it is computed from the file size (63 sectors per track, up to 16 heads). If the image was partitioned with a different geometry, specify it with chs0 / chs1 (or in the Cyls / Head / Sect fields).
  • To exchange files with a PC, create a floppy image (Create Disk), mount it on the PC (e.g. with a disk image tool or mtools), copy the files, put it back on the SD card and mount it in the emulator (see Mount Disk below).

Keys while the emulator runs

Keys Action
Alt + PrtScr (SysReq: press both, then release PrtScr and Alt) Opens the emulator menu

Emulator menu:

Command Action
Restart Emulator Restarts the board and shows the machine list again
Restart Machine Resets the emulated PC (like the reset button)
Mount Disk Changes the image of Floppy A (fd0) or Floppy B (fd1) without restarting: useful for programs on several disks
Continue Returns to the emulated PC

The PS/2 mouse is seen by the PC as a PS/2 mouse: load a DOS mouse driver that supports PS/2 mice (for example CTMOUSE) to use it in DOS programs.

Serial port and I/O expander

  • COM1 is connected to the USB serial port (TX = GPIO1, RX = GPIO3): use a terminal program on the PC to talk with DOS programs (for example CTTY COM1, or a communication program).
  • If a MCP23S17 GPIO expander is connected, its pins are available on the I/O ports E0h...E9h. See the GW-BASIC and QBasic examples in Extras/PC Emulator BASIC Programs.

What it demonstrates

  • The fabgl::i8086 CPU core and the emulated chips of the library: PIC8259, PIT8253, i8042 (keyboard and mouse controller), PC8250 (UART), MC146818 (RTC), and the CGA/Hercules GraphicsAdapter rendered with VGADirectController
  • PSRAM mapped and accessed directly as emulated RAM (CONFIG_SPIRAM_USE_MEMMAP)
  • fabgl::InputBox for the setup UI, fabgl::HTTPRequest for HTTPS downloads with resume (HTTP Range), WiFi + SNTP for the real-time clock
  • Running network and SD card work on the core not used by the VGA interrupt (CoreUsage::quietCore())

Build

The example ships a partitions.csv with a 3 MB application partition, and an sdkconfig.defaults that enables PSRAM. See Building the examples.

Source code

Main file of the example, main/PCEmulator.cpp. The complete project is in the examples/VGA/PCEmulator 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 /* Instructions:
28
29 - to run this application you need an ESP32 with PSRAM installed and an SD-CARD slot (ie TTGO VGA32 v1.4 or FabGL Development Board with WROVER)
30 - PSRAM is mapped by ESP-IDF (CONFIG_SPIRAM_USE_MEMMAP=y, see sdkconfig.defaults) and accessed directly by the emulator
31 - the partition table is provided (partitions.csv, large app partition)
32 - build and flash with: idf.py build flash monitor
33
34 */
35
36
37#include "freertos/FreeRTOS.h"
38#include "freertos/task.h"
39#include "freertos/semphr.h"
40#include "esp_system.h"
41#include <memory>
42
43extern "C" {
44#include "esp_psram.h"
45}
46#include "esp_sntp.h"
47#include "esp_wifi.h"
48
49
50#include "fabgl.h"
51#include "network/netutils.h"
52
53#include "mconf.h"
54#include "machine.h"
55
56
57
58// UART Pins for USB serial
59#define UART_URX 3
60#define UART_UTX 1
61
62
63
64using std::unique_ptr;
65
66using fabgl::StringList;
67using fabgl::imin;
68using fabgl::imax;
69
70
71
72Preferences preferences;
73InputBox ibox;
74Machine * machine;
75
76
77// noinit! Used to maintain datetime between reboots
78__NOINIT_ATTR static timeval savedTimeValue;
79
80
81static fabgl::WiFiConnection wifi;
82static bool wifiConnected = false;
83static bool downloadOK = false;
84
85
86// try to connected using saved parameters
87bool tryToConnect()
88{
89 bool connected = wifi.state() == fabgl::WiFiConnectionState::Connected;
90 if (!connected) {
91 char SSID[32] = "";
92 char psw[32] = "";
93 if (preferences.getString("SSID", SSID, sizeof(SSID)) && preferences.getString("WiFiPsw", psw, sizeof(psw))) {
94 ibox.progressBox("", "Abort", true, 200, [&](fabgl::ProgressForm * form) {
95 wifi.connect(SSID, psw, 0); // just start connection
96 for (int i = 0; i < 32 && wifi.state() != fabgl::WiFiConnectionState::Connected; ++i) {
97 if (!form->update(i * 100 / 32, "Connecting to %s...", SSID))
98 break;
99 vTaskDelay(pdMS_TO_TICKS(500));
100 }
101 connected = (wifi.state() == fabgl::WiFiConnectionState::Connected);
102 });
103 // show to user the connection state
104 if (!connected) {
105 wifi.disconnect();
106 ibox.message("", "WiFi Connection failed!");
107 }
108 }
109 }
110 return connected;
111}
112
113
114bool checkWiFi()
115{
116 wifiConnected = tryToConnect();
117 if (!wifiConnected) {
118
119 // configure WiFi?
120 if (ibox.message("WiFi Configuration", "Configure WiFi?", "No", "Yes") == InputResult::Enter) {
121
122 // repeat until connected or until user cancels
123 do {
124
125 // yes, scan for networks showing a progress dialog box
126 int networksCount = 0;
127 fabgl::WiFiScanner scanner;
128 ibox.progressBox("", nullptr, false, 200, [&](fabgl::ProgressForm * form) {
129 form->update(0, "Scanning WiFi networks...");
130 if (scanner.scan(16))
131 networksCount = scanner.count();
132 });
133
134 // are there available WiFi?
135 if (networksCount > 0) {
136
137 // yes, show a selectable list
138 StringList list;
139 for (int i = 0; i < networksCount; ++i)
140 list.appendFmt("%s (%d dBm)", (char const *) scanner.get(i)->ssid, scanner.get(i)->rssi);
141 int s = ibox.menu("WiFi Configuration", "Please select a WiFi network", &list);
142
143 // user selected something?
144 if (s > -1) {
145 // yes, ask for WiFi password
146 char psw[32] = "";
147 if (ibox.textInput("WiFi Configuration", "Insert WiFi password", psw, 31, "Cancel", "OK", true) == InputResult::Enter) {
148 // user pressed OK, connect to WiFi...
149 preferences.putString("SSID", (char const *) scanner.get(s)->ssid);
150 preferences.putString("WiFiPsw", psw);
151 wifiConnected = tryToConnect();
152 // show to user the connection state
153 if (wifiConnected)
154 ibox.message("", "Connection succeeded!");
155 } else
156 break;
157 } else
158 break;
159 } else {
160 // there is no WiFi
161 ibox.message("", "No WiFi network found!");
162 break;
163 }
164
165 } while (!wifiConnected);
166
167 }
168
169 }
170
171 return wifiConnected;
172}
173
174
175// handle soft restart
176void shutdownHandler()
177{
178 // save current datetime into Preferences
179 gettimeofday(&savedTimeValue, nullptr);
180}
181
182
183void updateDateTime()
184{
185 // Set timezone
186 setenv("TZ", "CET-1CEST,M3.5.0,M10.5.0/3", 1);
187 tzset();
188
189 // get datetime from savedTimeValue? (noinit section)
190 if (esp_reset_reason() == ESP_RST_SW) {
191 // adjust time taking account elapsed time since ESP32 started
192 savedTimeValue.tv_usec += (int) esp_timer_get_time();
193 savedTimeValue.tv_sec += savedTimeValue.tv_usec / 1000000;
194 savedTimeValue.tv_usec %= 1000000;
195 settimeofday(&savedTimeValue, nullptr);
196 return;
197 }
198
199 if (checkWiFi()) {
200
201 // we need time right now
202 ibox.progressBox("", nullptr, true, 200, [&](fabgl::ProgressForm * form) {
203 esp_sntp_setoperatingmode(SNTP_OPMODE_POLL);
204 esp_sntp_setservername(0, "pool.ntp.org");
205 esp_sntp_init();
206 for (int i = 0; i < 12 && sntp_get_sync_status() != SNTP_SYNC_STATUS_COMPLETED; ++i) {
207 form->update(i * 100 / 12, "Getting date-time from SNTP...");
208 vTaskDelay(pdMS_TO_TICKS(500));
209 }
210 esp_sntp_stop();
211 ibox.setAutoOK(2);
212 ibox.message("", "Date and Time updated. Restarting...");
213 #ifndef FABGL_EMULATED
214 esp_restart();
215 #endif
216 });
217
218 } else {
219
220 // set default time
221 struct tm tm = { };
222 tm.tm_hour = 8;
223 tm.tm_mday = 14;
224 tm.tm_mon = 7;
225 tm.tm_year = 84;
226 timeval now = { };
227 now.tv_sec = mktime(&tm);
228 settimeofday(&now, nullptr);
229
230 }
231}
232
233
234// state shared between downloadURL() and downloadTask()
235struct DownloadJob {
236 char const * URL;
237 FILE * file;
238 volatile int64_t received;
239 volatile int64_t total; // -1 = unknown
240 volatile int retries; // reconnections done
241 volatile bool abort; // set by the UI
242 volatile bool success;
243 SemaphoreHandle_t done;
244};
245
246
247// Downloads URL into job->file. Runs on the core used by WiFi (the VGA signal is generated by the other core),
248// so network, TLS and SD card work don't delay the video interrupt.
249// A connection that stalls or drops is reopened and the download resumes from the received bytes (HTTP Range).
250static void downloadTask(void * arg)
251{
252 constexpr int MAXRETRIES = 10; // consecutive reconnections without receiving data
253
254 auto job = (DownloadJob *) arg;
255 auto buf = (uint8_t*) SOC_EXTRAM_DATA_LOW; // use PSRAM as buffer (the machine isn't running yet)
256 bool writeError = false;
257 int failures = 0;
258
259 // WiFi power save (modem sleep) limits the download speed. Disable it during the download (the board restarts
260 // without WiFi after downloading, so the emulator isn't affected).
261 wifi_ps_type_t savedPS = WIFI_PS_MIN_MODEM;
262 esp_wifi_get_ps(&savedPS);
263 esp_wifi_set_ps(WIFI_PS_NONE);
264
266 while (!job->abort && !writeError && failures <= MAXRETRIES) {
267 if (failures > 0) {
268 job->retries = job->retries + 1;
269 vTaskDelay(pdMS_TO_TICKS(1000));
270 }
271 int64_t offset = job->received;
272 int status = http.open(job->URL, offset);
273 if (status != 200 && status != 206)
274 ESP_LOGW("download", "open at %lld: HTTP status %d", (long long) offset, status);
275 if (offset == 0 && status == 200) {
276 job->total = http.contentLength();
277 } else if (offset > 0 && status == 206) {
278 // resumed
279 } else if (offset > 0 && status == 200) {
280 // server ignores Range: restart from the beginning
281 if (fseek(job->file, 0, SEEK_SET) != 0)
282 break;
283 job->received = 0;
284 job->total = http.contentLength();
285 } else if (status >= 400 && status < 500 && status != 408 && status != 429) {
286 break; // permanent error (not found, forbidden...)
287 } else {
288 ++failures;
289 http.close();
290 continue;
291 }
292 // read until the connection fails or ends
293 while (!job->abort) {
294 int c = http.read(buf, 16384);
295 if (c <= 0) {
296 if (c < 0 || (job->total >= 0 && job->received < job->total))
297 ESP_LOGW("download", "read returned %d at %lld", c, (long long) job->received);
298 break;
299 }
300 if (fwrite(buf, 1, c, job->file) != c) {
301 ESP_LOGE("download", "SD card write failed at %lld (errno %d)", (long long) job->received, errno);
302 writeError = true;
303 break;
304 }
305 job->received = job->received + c;
306 failures = 0;
307 }
308 http.close();
309 if (job->total >= 0 ? job->received >= job->total : (job->received > 0 && !writeError)) {
310 job->success = !job->abort && !writeError;
311 break;
312 }
313 ++failures;
314 }
315
316 esp_wifi_set_ps(savedPS);
317 xSemaphoreGive(job->done);
318 vTaskDelete(nullptr);
319}
320
321
322// download specified filename from URL
323bool downloadURL(char const * URL, FILE * file)
324{
325 downloadOK = false;
326 if (!file)
327 return false;
328
329 char const * filename = strrchr(URL, '/') + 1;
330
331 DownloadJob job = { };
332 job.URL = URL;
333 job.file = file;
334 job.total = -1;
335 job.done = xSemaphoreCreateBinary();
336
337 ibox.progressBox("", "Abort", true, 380, [&](fabgl::ProgressForm * form) {
338 form->update(0, "Preparing to download %s", filename);
339 // the UI task stays on this core, the download runs on the other one
340 if (xTaskCreatePinnedToCore(downloadTask, "download", 8192, &job, 5, nullptr, CoreUsage::quietCore() < 0 ? 0 : CoreUsage::quietCore()) != pdPASS)
341 return;
342 while (xSemaphoreTake(job.done, pdMS_TO_TICKS(250)) == pdFALSE) {
343 int64_t received = job.received;
344 int64_t total = job.total;
345 bool cont;
346 if (job.retries > 0)
347 cont = form->update(total > 0 ? received * 100 / total : 0, "Downloading %s (%.2f / %.2f MB) retry %d", filename, received / 1048576.0, total / 1048576.0, job.retries);
348 else
349 cont = form->update(total > 0 ? received * 100 / total : 0, "Downloading %s (%.2f / %.2f MB)", filename, received / 1048576.0, total / 1048576.0);
350 if (!cont)
351 job.abort = true; // the task ends after the current read (at most the network timeout)
352 }
353 downloadOK = job.success;
354 });
355
356 vSemaphoreDelete(job.done);
357 return downloadOK;
358}
359
360
361// return filename if successfully downloaded or already exist
362char const * getDisk(char const * url)
363{
364 FileBrowser fb(SD_MOUNT_PATH);
365
366 char const * filename = nullptr;
367 if (url) {
368 if (strncmp("http://", url, 7) == 0 || strncmp("https://", url, 7) == 0) {
369 // this is actually an URL
370 filename = strrchr(url, '/') + 1;
371 if (filename && !fb.exists(filename, false)) {
372 // disk doesn't exist, try to download
373 if (!checkWiFi())
374 return nullptr;
375 auto file = fb.openFile(filename, "wb");
376 bool success = downloadURL(url, file);
377 fclose(file);
378 if (!success) {
379 fb.remove(filename);
380 return nullptr;
381 }
382 }
383 } else {
384 // this is just a file
385 if (fb.filePathExists(url))
386 filename = url;
387 }
388 }
389 return filename;
390}
391
392
393// user pressed SYSREQ (ALT + PRINTSCREEN)
394void sysReqCallback()
395{
396 machine->graphicsAdapter()->enableVideo(false);
397 ibox.begin(VGA_640x480_60Hz, 500, 400, 4);
398
399 int s = ibox.menu("", "Select a command", "Restart Emulator;Restart Machine;Mount Disk;Continue");
400 switch (s) {
401
402 // Restart Emulator
403 case 0:
404 esp_restart();
405 break;
406
407 // Restart Machine
408 case 1:
409 machine->trigReset();
410 break;
411
412 // Mount Disk
413 case 2:
414 {
415 int s = ibox.menu("", "Select Drive", "Floppy A (fd0);Floppy B (fd1)");
416 if (s > -1) {
417 constexpr int MAXNAMELEN = 256;
418 unique_ptr<char[]> dir(new char[MAXNAMELEN + 1] { '/', 'S', 'D', 0 } );
419 unique_ptr<char[]> filename(new char[MAXNAMELEN + 1] { 0 } );
420 if (machine->diskFilename(s))
421 strcpy(filename.get(), machine->diskFilename(s));
422 if (ibox.fileSelector("Select Disk Image", "Image Filename", dir.get(), MAXNAMELEN, filename.get(), MAXNAMELEN) == InputResult::Enter) {
423 machine->setDriveImage(s, filename.get());
424 }
425 }
426 break;
427 }
428
429 // Continue
430 default:
431 break;
432 }
433
434 ibox.end();
435 PS2Controller::keyboard()->enableVirtualKeys(false, false); // don't use virtual keys
436 machine->graphicsAdapter()->enableVideo(true);
437}
438
439
440void setup()
441{
442 vTaskDelay(pdMS_TO_TICKS(500)); printf("\n\n\nReset\n\n");// DEBUG ONLY
443
444
445
446 preferences.begin("PCEmulator", false);
447
448 // uncomment to clear preferences
449 //preferences.clear();
450
451 // save some space reducing UI queue
453
454 ibox.begin(VGA_640x480_60Hz, 500, 400, 4);
455 ibox.setBackgroundColor(RGB888(0, 0, 0));
456
457 ibox.onPaint = [&](Canvas * canvas) { drawInfo(canvas); };
458
459 // This app requires PSRAM. PSRAM is just mapped into the address space (CONFIG_SPIRAM_USE_MEMMAP=y) at SOC_EXTRAM_DATA_LOW,
460 // and it is directly accessed by the app. Compiler workaround for PSRAM bug (CONFIG_SPIRAM_CACHE_WORKAROUND)
461 // is disabled because it slows down CPU too much (see sdkconfig.defaults).
462 if (!esp_psram_is_initialized())
463 ibox.message("Error!", "This app requires a board with PSRAM!", nullptr, nullptr);
464
465 if (!FileBrowser::mountSDCard(false, SD_MOUNT_PATH, 8)) // @TODO: reduce to 4?
466 ibox.message("Error!", "This app requires a SD-CARD!", nullptr, nullptr);
467
468 // uncomment to format SD!
469 //FileBrowser::format(fabgl::DriveType::SDCard, 0);
470
471 esp_register_shutdown_handler(shutdownHandler);
472
473 updateDateTime();
474
475
476 // machine configurations
477 MachineConf mconf;
478
479 // show a list of machine configurations
480
481 ibox.setAutoOK(6);
482 int idx = preferences.getInt("dconf", 0);
483
484 for (bool showDialog = true; showDialog; ) {
485
486 loadMachineConfiguration(&mconf);
487
488 StringList dconfs;
489 for (auto conf = mconf.getFirstItem(); conf; conf = conf->next)
490 dconfs.append(conf->desc);
491 dconfs.select(idx, true);
492
493 ibox.setupButton(0, "Files");
494 ibox.setupButton(1, "Machine", "Edit;New;Remove", 52);
495 auto r = ibox.select("Machine Configurations", "Please select a machine configuration", &dconfs, nullptr, "Run");
496
497 idx = dconfs.getFirstSelected();
498
499 switch (r) {
500 case InputResult::ButtonExt0:
501 // Browse Files
502 ibox.folderBrowser("Browse Files", SD_MOUNT_PATH);
503 break;
504 case InputResult::ButtonExt1:
505 // Machine
506 switch (ibox.selectedSubItem()) {
507 // Edit
508 case 0:
509 editConfigDialog(&ibox, &mconf, idx);
510 break;
511 // New
512 case 1:
513 newConfigDialog(&ibox, &mconf, idx);
514 break;
515 // Remove
516 case 2:
517 delConfigDialog(&ibox, &mconf, idx);
518 break;
519 };
520 break;
521 case InputResult::Enter:
522 // Run
523 showDialog = false;
524 break;
525 default:
526 break;
527 }
528
529 // next selection will not have timeout
530 ibox.setAutoOK(0);
531 }
532
533 idx = imax(idx, 0);
534 preferences.putInt("dconf", idx);
535
536 // setup selected configuration
537 auto conf = mconf.getItem(idx);
538
539 char const * diskFilename[DISKCOUNT];
540 downloadOK = true;
541 for (int i = 0; i < DISKCOUNT && downloadOK; ++i)
542 diskFilename[i] = getDisk(conf->disk[i]);
543
544 if (!downloadOK || (!diskFilename[0] && !diskFilename[2])) {
545 // unable to get boot disks
546 ibox.message("Error!", "Unable to get system disks!");
547 esp_restart();
548 }
549
550 if (wifiConnected) {
551 // disk downloaded from the Internet, need to reboot to fully disable wifi
552 ibox.setAutoOK(2);
553 ibox.message("", "Disks downloaded. Restarting...");
554 #ifndef FABGL_EMULATED
555 esp_restart();
556 #endif
557 }
558
559 ibox.end();
560
561 // without WiFi it is possible to increase SD card speed
562 FileBrowser::setSDCardMaxFreqKHz(SDMMC_FREQ_DEFAULT);
564
565 machine = new Machine;
566
567 machine->setBaseDirectory(SD_MOUNT_PATH);
568 for (int i = 0; i < DISKCOUNT; ++i)
569 machine->setDriveImage(i, diskFilename[i], conf->cylinders[i], conf->heads[i], conf->sectors[i]);
570
571 machine->setBootDrive(conf->bootDrive);
572
573 auto serial1 = new SerialPort;
574 serial1->setSignals(UART_URX, UART_UTX);
575 machine->setCOM1(serial1);
576
577 /*
578 printf("MALLOC_CAP_32BIT : %d bytes (largest %d bytes)\r\n", heap_caps_get_free_size(MALLOC_CAP_32BIT), heap_caps_get_largest_free_block(MALLOC_CAP_32BIT));
579 printf("MALLOC_CAP_8BIT : %d bytes (largest %d bytes)\r\n", heap_caps_get_free_size(MALLOC_CAP_8BIT), heap_caps_get_largest_free_block(MALLOC_CAP_8BIT));
580 printf("MALLOC_CAP_DMA : %d bytes (largest %d bytes)\r\n\n", heap_caps_get_free_size(MALLOC_CAP_DMA), heap_caps_get_largest_free_block(MALLOC_CAP_DMA));
581
582 heap_caps_dump_all();
583 */
584
585 machine->setSysReqCallback(sysReqCallback);
586
587 machine->run();
588}
589
590
591
592#if FABGLIB_VGAXCONTROLLER_PERFORMANCE_CHECK
593namespace fabgl {
594 extern volatile uint64_t s_vgapalctrlcycles;
595}
596using fabgl::s_vgapalctrlcycles;
597#endif
598
599
600
601void loop()
602{
603
604#if FABGLIB_VGAXCONTROLLER_PERFORMANCE_CHECK
605 static uint32_t tcpu = 0, s1 = 0, count = 0;
606 tcpu = machine->ticksCounter();
607 s_vgapalctrlcycles = 0;
608 s1 = fabgl::getCycleCount();
609 vTaskDelay(pdMS_TO_TICKS(1000));
610 printf("%d\tCPU: %d", count, machine->ticksCounter() - tcpu);
611 printf(" Graph: %lld / %d (%d%%)\n", s_vgapalctrlcycles, fabgl::getCycleCount() - s1, (int)((double)s_vgapalctrlcycles/240000000*100));
612 ++count;
613#else
614
615 vTaskDelete(NULL);
616
617#endif
618}
619
620
621extern "C" void app_main()
622{
623 setup();
624 while (true)
625 loop();
626}
Provides a set of drawing methods.
Definition canvas.h:73
static bool mountSDCard(bool formatOnFail, char const *mountPath, size_t maxFiles=4, int allocationUnitSize=16 *1024, int MISO=16, int MOSI=17, int CLK=14, int CS=13)
Mounts the filesystem of the SD Card.
static bool remountSDCard()
Mounts the SD Card filesystem again, using the same parameters.
FileBrowser provides basic file system operations (directory listing, mkdir, remove and rename).
Definition fabutils.h:698
InputResult textInput(char const *titleText, char const *labelText, char *inOutString, int maxLength, char const *buttonCancelText="Cancel", char const *buttonOKText="OK", bool passwordMode=false)
Shows a dialog with a label and a text edit box.
Definition inputbox.cpp:149
InputResult message(char const *titleText, char const *messageText, char const *buttonCancelText=nullptr, char const *buttonOKText="OK")
Shows a dialog with just a label.
Definition inputbox.cpp:167
InputResult progressBox(char const *titleText, char const *buttonCancelText, bool hasProgressBar, int width, Func execFunc)
Shows a dialog with a label and a progress bar, updated by a user function.
Definition inputbox.h:625
void setupButton(int index, char const *text, char const *subItems=nullptr, int subItemsHeight=80)
Sets up an extended button or split button.
Definition inputbox.cpp:115
InputResult fileSelector(char const *titleText, char const *messageText, char *inOutDirectory, int maxDirectoryLength, char *inOutFilename, int maxFilenameLength, char const *buttonCancelText="Cancel", char const *buttonOKText="OK")
Lets the user select a file and a directory, starting from the specified path.
Definition inputbox.cpp:298
int selectedSubItem()
Gets the selected item of a split button.
Definition inputbox.h:427
int menu(char const *titleText, char const *messageText, char const *itemsText, char separator=';')
Shows a dialog with a label and a list box. The dialog closes as soon as an item is selected,...
Definition inputbox.cpp:238
void end()
Releases resources and, if it was created by InputBox, disables the display output.
Definition inputbox.cpp:105
int select(char const *titleText, char const *messageText, char const *itemsText, char separator=';', char const *buttonCancelText="Cancel", char const *buttonOKText="OK")
Shows a dialog with a label and a list box.
Definition inputbox.cpp:200
void begin(char const *modeline=nullptr, int viewPortWidth=-1, int viewPortHeight=-1, int displayColors=16)
Initializes InputBox from a VGA modeline, creating a VGA display controller.
Definition inputbox.cpp:74
void setAutoOK(int timeout)
Specifies a timeout for the dialog.
Definition inputbox.h:386
InputResult folderBrowser(char const *titleText, char const *directory="/", char const *buttonOKText="Close")
Shows a dialog listing files and folders, with buttons to create folders and to delete and rename fil...
Definition inputbox.cpp:284
Delegate< Canvas * > onPaint
Paint event delegate.
Definition inputbox.h:684
void setBackgroundColor(RGB888 const &value)
Sets the background color.
Definition inputbox.h:375
InputBox is a helper class to build simple user interfaces, such as wizards and input boxes.
Definition inputbox.h:328
size_t getString(char const *key, char *value, size_t maxLen)
Gets a string.
bool begin(char const *name, bool readOnly=false)
Opens the specified namespace.
Simple key/value storage in non-volatile flash (NVS).
Definition preferences.h:61
static int queueSize
Size of the display controller primitives queue.
int open(char const *URL, int64_t rangeStart=0)
Opens a streaming GET request (follows redirects).
Definition netutils.cpp:477
int contentLength()
Gets the content length.
Definition netutils.h:303
void close()
Closes the HTTP connection.
Definition netutils.cpp:527
int read(void *buffer, int length)
Reads content after a successful open().
Definition netutils.cpp:519
HTTP connection and request helper.
Definition netutils.h:280
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
WiFi connection helper class.
Definition netutils.h:163
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.
#define VGA_640x480_60Hz
Definition fabglconf.h:246
This file contains the fabgl::WiFiScanner, fabgl::WiFiConnection, fabgl::HTTPRequest and fabgl::TCPCl...
Represents a 24-bit RGB color.