@geastack/targets 0.1.90 → 0.1.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -92,6 +92,13 @@ open/capture methods in both modes, checks clock conflicts, and verifies that
92
92
  a blocked RX read permits TX progress only in the opted-in mode. Its executable
93
93
  uses the board's existing ignored `build/` directory.
94
94
 
95
+ With `GEA_AUDIO_ECHO_CANCELLATION=1`, applications can scale the board's calibrated
96
+ post-AEC gain with `GEA_AUDIO_AEC_OUTPUT_GAIN_SCALE`. Its default is `1.0f`;
97
+ `0.501187234f` reduces gain by 6 dB. Scaling happens before int16 clipping,
98
+ without changing ADC gain or the echo reference. Valid scales are 0 through 64.
99
+ `node targets/esp32/test/audio-aec-output-gain.test.mjs` verifies both AMOLED
100
+ calibrations and rejects invalid scales without creating build artifacts.
101
+
95
102
  ## License
96
103
 
97
104
  This repo is the GeaStack **embedded board support** (ESP32, RP2350) and is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/targets",
3
- "version": "0.1.90",
3
+ "version": "0.1.92",
4
4
  "description": "Native embedded build targets (ESP32-IDF, RP2350) for geastack apps: board sources, target catalog, and CMake glue driven by the gea CLI.",
5
5
  "license": "GPL-3.0-only",
6
6
  "repository": {
@@ -125,7 +125,15 @@ constexpr float aecOutputGainOf(const AudioConfig &audio) {
125
125
  return 1.0f;
126
126
  }
127
127
  constexpr float kAecMicGain = aecMicGainOf(gea::platform::board::audio);
128
- constexpr float kAecOutputGain = aecOutputGainOf(gea::platform::board::audio);
128
+ #ifndef GEA_AUDIO_AEC_OUTPUT_GAIN_SCALE
129
+ #define GEA_AUDIO_AEC_OUTPUT_GAIN_SCALE 1.0f
130
+ #endif
131
+ static_assert(GEA_AUDIO_AEC_OUTPUT_GAIN_SCALE >= 0.0f && GEA_AUDIO_AEC_OUTPUT_GAIN_SCALE <= 64.0f,
132
+ "AEC output gain scale must be between 0 and 64");
133
+ // Apply before the AEC output is clamped to int16. Scaling the published
134
+ // microphone packets afterward cannot recover samples already clipped here.
135
+ constexpr float kAecOutputGain = aecOutputGainOf(gea::platform::board::audio) *
136
+ GEA_AUDIO_AEC_OUTPUT_GAIN_SCALE;
129
137
  template <typename AudioConfig>
130
138
  constexpr bool aecAggressiveNlpOf(const AudioConfig &audio) {
131
139
  if constexpr (requires { audio.aecAggressiveNlp; }) return audio.aecAggressiveNlp;
@@ -6,8 +6,38 @@
6
6
 
7
7
  #include <algorithm>
8
8
 
9
+ #include "driver/gpio.h"
10
+ #include "esp_attr.h"
9
11
  #include "esp_lcd_panel_io.h"
12
+ // The CST92xx family shares this binding. A board whose controller is the
13
+ // CST9220 (the ESP-Mosaico) sets GEA_BOARD_TOUCH_CST9220: that part speaks
14
+ // either the legacy report protocol or HYN212, which needs a mode switch
15
+ // before reports arrive, and only Espressif's CST9220 driver handles both.
16
+ #if GEA_BOARD_TOUCH_CST9220
17
+ #include "esp_lcd_touch_cst9220.h"
18
+ #define GEA_CST92XX_NEW esp_lcd_touch_new_i2c_cst9220
19
+ namespace {
20
+ // ESP_LCD_TOUCH_IO_I2C_CST9220_CONFIG() lists its designators out of
21
+ // declaration order, which C++ rejects; the same values, field by field.
22
+ esp_lcd_panel_io_i2c_config_t cst9220IoConfig()
23
+ {
24
+ esp_lcd_panel_io_i2c_config_t config = {};
25
+ config.dev_addr = ESP_LCD_TOUCH_IO_I2C_CST9220_ADDRESS;
26
+ config.control_phase_bytes = 1;
27
+ config.dc_bit_offset = 0;
28
+ config.lcd_cmd_bits = 8;
29
+ config.lcd_param_bits = 8;
30
+ config.flags.disable_control_phase = 1;
31
+ config.scl_speed_hz = 400000;
32
+ return config;
33
+ }
34
+ } // namespace
35
+ #define GEA_CST92XX_IO_CONFIG cst9220IoConfig
36
+ #else
10
37
  #include "esp_lcd_touch_cst9217.h"
38
+ #define GEA_CST92XX_IO_CONFIG ESP_LCD_TOUCH_IO_I2C_CST9217_CONFIG
39
+ #define GEA_CST92XX_NEW esp_lcd_touch_new_i2c_cst9217
40
+ #endif
11
41
  #include "esp_log.h"
12
42
 
13
43
  namespace {
@@ -18,6 +48,23 @@ constexpr gpio_num_t kInterruptPin = gea::platform::board::touch.interrupt;
18
48
  constexpr int kPollIntervalMs = 10;
19
49
  constexpr int kTaskPriority = 10;
20
50
 
51
+ #if GEA_BOARD_TOUCH_CST9220
52
+ // The CST9220 raises INT (low) once per report. Reading between reports finds
53
+ // the frame the driver already acknowledged -- it logs "Malformed report
54
+ // header" and drops the sample -- so this binding reads on INT instead of on
55
+ // a timer. While a finger is down it still re-reads after kLiftTimeoutMs of
56
+ // silence, so a missed final report cannot leave a finger stuck down.
57
+ constexpr int kLiftTimeoutMs = 60;
58
+
59
+ void IRAM_ATTR touchInterrupt(void *arg)
60
+ {
61
+ auto *task = static_cast<TaskHandle_t *>(arg);
62
+ BaseType_t woken = pdFALSE;
63
+ if (*task) vTaskNotifyGiveFromISR(*task, &woken);
64
+ portYIELD_FROM_ISR(woken);
65
+ }
66
+ #endif
67
+
21
68
  } // namespace
22
69
 
23
70
  namespace gea::platform::esp32::chip_bindings::cst9217 {
@@ -87,7 +134,7 @@ void TouchController::consumeLatestMove(int *x, int *y)
87
134
 
88
135
  esp_err_t TouchController::attachTouchDevice()
89
136
  {
90
- esp_lcd_panel_io_i2c_config_t io_config = ESP_LCD_TOUCH_IO_I2C_CST9217_CONFIG();
137
+ esp_lcd_panel_io_i2c_config_t io_config = GEA_CST92XX_IO_CONFIG();
91
138
  io_config.scl_speed_hz = 400000;
92
139
  esp_err_t err = esp_lcd_new_panel_io_i2c(bus_, &io_config, &io_);
93
140
  if (err != ESP_OK) {
@@ -110,8 +157,19 @@ esp_err_t TouchController::attachTouchDevice()
110
157
  .mirror_y = gea::platform::board::touch.mirrorY,
111
158
  },
112
159
  };
113
- err = esp_lcd_touch_new_i2c_cst9217(io_, &touch_config, &touch_);
114
- if (err != ESP_OK) ESP_LOGE(kTag, "Failed to create CST9217 touch device: %s", esp_err_to_name(err));
160
+ err = GEA_CST92XX_NEW(io_, &touch_config, &touch_);
161
+ if (err != ESP_OK) {
162
+ ESP_LOGE(kTag, "Failed to create CST92xx touch device: %s", esp_err_to_name(err));
163
+ return err;
164
+ }
165
+ #if GEA_BOARD_TOUCH_CST9220
166
+ // The driver configured INT as a falling-edge input; hook it to the task.
167
+ err = gpio_install_isr_service(0);
168
+ if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) return err;
169
+ err = gpio_isr_handler_add(kInterruptPin, touchInterrupt, &task_);
170
+ if (err == ESP_OK) err = gpio_intr_enable(kInterruptPin);
171
+ if (err != ESP_OK) ESP_LOGE(kTag, "Touch INT GPIO%d hook failed: %s", static_cast<int>(kInterruptPin), esp_err_to_name(err));
172
+ #endif
115
173
  return err;
116
174
  }
117
175
 
@@ -155,7 +213,13 @@ void TouchController::pollLoop()
155
213
  int slotY[kMaxFingers] = {0, 0};
156
214
 
157
215
  while (true) {
216
+ #if GEA_BOARD_TOUCH_CST9220
217
+ const bool anyActive = slotActive[0] || slotActive[1];
218
+ if (ulTaskNotifyTake(pdTRUE, anyActive ? pdMS_TO_TICKS(kLiftTimeoutMs) : portMAX_DELAY) == 0 && !anyActive)
219
+ continue;
220
+ #else
158
221
  vTaskDelay(pdMS_TO_TICKS(kPollIntervalMs));
222
+ #endif
159
223
 
160
224
  const MultiSample multi = readMulti();
161
225
  if (multi.count > 0) {
@@ -1,4 +1,5 @@
1
1
  #include "display.h"
2
+ #include "render_worker_join.h"
2
3
 
3
4
  #include "board.h"
4
5
  #include "canvas.h"
@@ -6053,25 +6054,20 @@ extern "C" void gea_render_parallel_wait()
6053
6054
  {
6054
6055
  if (!g_geaRenderWorker.task)
6055
6056
  return;
6056
- // The worker's band is sub-millisecond; spin (the render core's idle task only
6057
- // needs to run within the ~5s watchdog window, so a short spin is fine). The
6058
- // esp_timer deadline guards against a wedged worker so we can never hang.
6057
+ // Keep the borrowed band context alive until completion, including when
6058
+ // higher-priority audio work delays the worker beyond the slow-job threshold.
6059
6059
  const std::int64_t w0 = esp_timer_get_time();
6060
- const std::int64_t deadline = w0 + 100000; // 100ms safety net
6061
- while (!g_geaRenderWorker.done.load(std::memory_order_acquire))
6062
- {
6060
+ gea::platform::esp32::display::detail::joinRenderWorker(g_geaRenderWorker.done,
6061
+ [] {
6063
6062
  #if defined(GEA_EMBEDDED_APP_USES_AUDIO) && GEA_EMBEDDED_APP_USES_AUDIO
6064
- // Media load makes a band much longer than the graphics-only spin window.
6065
- // Its worker already notifies completion: park instead of burning CPU0
6066
- // while the microphone encoder and idle task need to run.
6067
- ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(2));
6068
- #endif
6069
- if (esp_timer_get_time() > deadline)
6070
- {
6071
- std::printf("[render-worker] WAIT TIMEOUT — worker wedged?\n");
6072
- break;
6073
- }
6074
- }
6063
+ ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(2));
6064
+ #endif
6065
+ },
6066
+ [] { return esp_timer_get_time(); },
6067
+ [](std::int64_t elapsed, bool stuck) {
6068
+ std::printf("[render-worker] WAIT %s after %lld us; job still pending\n",
6069
+ stuck ? "STUCK" : "SLOW", static_cast<long long>(elapsed));
6070
+ });
6075
6071
  const std::int64_t waitThis = esp_timer_get_time() - w0;
6076
6072
  g_wkWaitUs += waitThis;
6077
6073
  // Adaptive row-share controller (visual-neutral: only shifts WHICH rows each core
@@ -6108,21 +6104,13 @@ extern "C" void gea_render_parallel_wait_blocking()
6108
6104
  {
6109
6105
  if (!g_geaRenderWorker.task)
6110
6106
  return;
6111
- // Unlike the spin wait above, PARK the caller (yield the core) until the worker
6112
- // finishes — so a lower-priority task sharing this core (the app frame task,
6113
- // pinned to core 0 alongside the gea3d present) runs during the chunk raster
6114
- // instead of the present spinning it away. The worker notifyGives us on done;
6115
- // the short timeout re-checks in case the notify landed before we parked.
6116
- const std::int64_t deadline = esp_timer_get_time() + 100000; // 100ms safety net
6117
- while (!g_geaRenderWorker.done.load(std::memory_order_acquire))
6118
- {
6119
- ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(2));
6120
- if (esp_timer_get_time() > deadline)
6121
- {
6122
- std::printf("[render-worker] BLOCKING WAIT TIMEOUT — worker wedged?\n");
6123
- break;
6124
- }
6125
- }
6107
+ gea::platform::esp32::display::detail::joinRenderWorker(g_geaRenderWorker.done,
6108
+ [] { ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(2)); },
6109
+ [] { return esp_timer_get_time(); },
6110
+ [](std::int64_t elapsed, bool stuck) {
6111
+ std::printf("[render-worker] BLOCKING WAIT %s after %lld us; job still pending\n",
6112
+ stuck ? "STUCK" : "SLOW", static_cast<long long>(elapsed));
6113
+ });
6126
6114
  }
6127
6115
 
6128
6116
  // Adaptive main-core row share for the 2-core replay split (overrides the renderer's
@@ -0,0 +1,32 @@
1
+ #pragma once
2
+
3
+ #include <atomic>
4
+ #include <cstdint>
5
+ #include <cstdlib>
6
+
7
+ namespace gea::platform::esp32::display::detail {
8
+
9
+ // A submitted raster job borrows its caller's stack and framebuffer. A slow
10
+ // worker cannot be abandoned: returning would release both while it still draws.
11
+ template <typename Park, typename Clock, typename Report>
12
+ void joinRenderWorker(const std::atomic<bool> &done, Park park, Clock now, Report report) {
13
+ const std::int64_t started = now();
14
+ bool reportedSlow = false;
15
+ while (!done.load(std::memory_order_acquire)) {
16
+ park();
17
+ const std::int64_t elapsed = now() - started;
18
+ if (done.load(std::memory_order_acquire))
19
+ break;
20
+ if (elapsed >= 5000000) {
21
+ report(elapsed, true);
22
+ // A genuinely stuck worker must stop the app, never return a live job.
23
+ std::abort();
24
+ }
25
+ if (!reportedSlow && elapsed >= 100000) {
26
+ report(elapsed, false);
27
+ reportedSlow = true;
28
+ }
29
+ }
30
+ }
31
+
32
+ } // namespace gea::platform::esp32::display::detail
@@ -61,6 +61,15 @@ extern "C" uint32_t gea_display_completed_chunks() __attribute__((weak));
61
61
  #include <sys/stat.h> // ::mkdir for GEADEV PUSH parent dirs
62
62
  #include <sys/time.h>
63
63
  #include "esp_system.h" // esp_restart() for GEADEV REBOOT
64
+ #if CONFIG_IDF_TARGET_ESP32P4
65
+ #include "soc/lp_system_reg.h" // FORCE_DOWNLOAD_BOOT for GEADEV DOWNLOAD
66
+ #elif CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32C3
67
+ #include "soc/rtc_cntl_reg.h" // FORCE_DOWNLOAD_BOOT for GEADEV DOWNLOAD
68
+ #endif
69
+ #if GEA_DEVICE_CONTROL_USB_OTA
70
+ #include "esp_ota_ops.h" // GEADEV OTA
71
+ #include <algorithm>
72
+ #endif
64
73
  #include "audio.h" // gea::platform::audio::AudioSystem for GEADEV PLAYFILE
65
74
  #include "power.h" // Power::batteryPercent() for STATE battery
66
75
  #include "host/notify.h" // gea::host::postNotification() for GEADEV NOTIFY
@@ -1291,6 +1300,7 @@ void handlePush(char *args)
1291
1300
  while (got < size) {
1292
1301
  const std::size_t n = std::fread(mem + got, 1, static_cast<std::size_t>(size - got), stdin);
1293
1302
  if (n == 0) {
1303
+ std::clearerr(stdin); // an idle read sets the sticky EOF flag
1294
1304
  if (++stalls > 20000) { // ~40s of silence → abort
1295
1305
  ioError = true;
1296
1306
  break;
@@ -1321,6 +1331,98 @@ void handlePush(char *args)
1321
1331
  std::printf("GEADEV:PUSH OK path=%s bytes=%ld crc=0x%08x\n", path, size, static_cast<unsigned>(finalCrc));
1322
1332
  }
1323
1333
 
1334
+ // ── GEADEV OTA: install a new app image over the USB console ─────────────────
1335
+ // The PUSH transfer, written to the next OTA slot instead of a file:
1336
+ // GEADEV OTA <size> <crc32>\n
1337
+ // then exactly <size> raw bytes. The image is drained into PSRAM first (the
1338
+ // console has no flow control, so flash erases must not stall the read),
1339
+ // checked against the CRC, written with esp_ota_*, selected for boot, and the
1340
+ // board restarts into it. This is how a board whose USB port is not a ROM
1341
+ // console -- the ESP32-S31's OTG port -- is flashed without the BOOT button.
1342
+ // Compiled only for boards that ask for it (GEA_DEVICE_CONTROL_USB_OTA).
1343
+ #if GEA_DEVICE_CONTROL_USB_OTA
1344
+ void handleOta(char *args)
1345
+ {
1346
+ char *sizeTok = nextToken(args);
1347
+ char *crcTok = nextToken(args);
1348
+ if (!sizeTok || !crcTok) {
1349
+ std::printf("GEADEV:OTA ERR usage=GEADEV_OTA_size_crc32\n");
1350
+ return;
1351
+ }
1352
+ char *end = nullptr;
1353
+ const long size = std::strtol(sizeTok, &end, 10);
1354
+ if (!end || *end != '\0' || size <= 0) {
1355
+ std::printf("GEADEV:OTA ERR bad-size\n");
1356
+ return;
1357
+ }
1358
+ const std::uint32_t expectCrc = static_cast<std::uint32_t>(std::strtoul(crcTok, nullptr, 0));
1359
+ const esp_partition_t *slot = esp_ota_get_next_update_partition(nullptr);
1360
+ if (!slot) {
1361
+ std::printf("GEADEV:OTA ERR no-ota-slot\n");
1362
+ return;
1363
+ }
1364
+ if (static_cast<std::size_t>(size) > slot->size) {
1365
+ std::printf("GEADEV:OTA ERR too-large bytes=%ld slot=%u\n", size, static_cast<unsigned>(slot->size));
1366
+ return;
1367
+ }
1368
+ auto *mem = static_cast<std::uint8_t *>(heap_caps_malloc(static_cast<std::size_t>(size), MALLOC_CAP_SPIRAM));
1369
+ if (!mem) {
1370
+ std::printf("GEADEV:OTA ERR no-memory bytes=%ld\n", size);
1371
+ return;
1372
+ }
1373
+ std::printf("GEADEV:OTA READY slot=%s bytes=%ld\n", slot->label, size);
1374
+ std::fflush(stdout);
1375
+
1376
+ long got = 0;
1377
+ int stalls = 0;
1378
+ while (got < size) {
1379
+ const std::size_t n = std::fread(mem + got, 1, static_cast<std::size_t>(size - got), stdin);
1380
+ if (n == 0) {
1381
+ std::clearerr(stdin); // an idle read sets the sticky EOF flag
1382
+ if (++stalls > 5000) break; // ~10s of silence
1383
+ vTaskDelay(pdMS_TO_TICKS(2));
1384
+ continue;
1385
+ }
1386
+ stalls = 0;
1387
+ got += static_cast<long>(n);
1388
+ }
1389
+ if (got != size) {
1390
+ heap_caps_free(mem);
1391
+ std::printf("GEADEV:OTA ERR transfer-failed got=%ld\n", got);
1392
+ return;
1393
+ }
1394
+ const std::uint32_t crc = crc32Stream(0xFFFFFFFFu, mem, static_cast<std::size_t>(size)) ^ 0xFFFFFFFFu;
1395
+ if (crc != expectCrc) {
1396
+ heap_caps_free(mem);
1397
+ std::printf("GEADEV:OTA ERR crc-mismatch got=0x%08x want=0x%08x\n",
1398
+ static_cast<unsigned>(crc), static_cast<unsigned>(expectCrc));
1399
+ return;
1400
+ }
1401
+
1402
+ esp_ota_handle_t handle = 0;
1403
+ esp_err_t err = esp_ota_begin(slot, static_cast<std::size_t>(size), &handle);
1404
+ if (err == ESP_OK) {
1405
+ constexpr std::size_t kChunk = 64 * 1024;
1406
+ for (long offset = 0; offset < size && err == ESP_OK; offset += static_cast<long>(kChunk)) {
1407
+ const std::size_t n = std::min<std::size_t>(kChunk, static_cast<std::size_t>(size - offset));
1408
+ err = esp_ota_write(handle, mem + offset, n);
1409
+ }
1410
+ const esp_err_t ended = esp_ota_end(handle);
1411
+ if (err == ESP_OK) err = ended;
1412
+ }
1413
+ heap_caps_free(mem);
1414
+ if (err == ESP_OK) err = esp_ota_set_boot_partition(slot);
1415
+ if (err != ESP_OK) {
1416
+ std::printf("GEADEV:OTA ERR write-failed slot=%s err=%s\n", slot->label, esp_err_to_name(err));
1417
+ return;
1418
+ }
1419
+ std::printf("GEADEV:OTA OK slot=%s bytes=%ld crc=0x%08x\n", slot->label, size, static_cast<unsigned>(crc));
1420
+ std::fflush(stdout);
1421
+ vTaskDelay(pdMS_TO_TICKS(200)); // let the reply reach the host before the reset
1422
+ esp_restart();
1423
+ }
1424
+ #endif // GEA_DEVICE_CONTROL_USB_OTA
1425
+
1324
1426
  void handlePushBase64(char *args)
1325
1427
  {
1326
1428
  char *pathTok = nextToken(args);
@@ -1866,6 +1968,25 @@ void handleCommand(char *line, CommandSource source)
1866
1968
  handleNode(cursor);
1867
1969
  } else if (tokenEquals(command, "HITTEST")) {
1868
1970
  handleHitTest(cursor);
1971
+ } else if (tokenEquals(command, "DOWNLOAD")) {
1972
+ // Restart into ROM download mode, so a host can flash over a UART bridge
1973
+ // whose DTR/RTS lines cannot reset the chip (e.g. the Waveshare P4 LCD-3.5).
1974
+ // The flag survives a watchdog reset; the flasher clears it before resetting.
1975
+ #if CONFIG_IDF_TARGET_ESP32P4
1976
+ std::printf("GEADEV:OK DOWNLOAD\n");
1977
+ std::fflush(stdout);
1978
+ vTaskDelay(pdMS_TO_TICKS(120));
1979
+ REG_SET_BIT(LP_SYSTEM_REG_SYS_CTRL_REG, LP_SYSTEM_REG_FORCE_DOWNLOAD_BOOT);
1980
+ esp_restart();
1981
+ #elif CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32C3
1982
+ std::printf("GEADEV:OK DOWNLOAD\n");
1983
+ std::fflush(stdout);
1984
+ vTaskDelay(pdMS_TO_TICKS(120));
1985
+ REG_WRITE(RTC_CNTL_OPTION1_REG, RTC_CNTL_FORCE_DOWNLOAD_BOOT);
1986
+ esp_restart();
1987
+ #else
1988
+ std::printf("GEADEV:ERR DOWNLOAD unsupported-chip\n");
1989
+ #endif
1869
1990
  } else if (tokenEquals(command, "REBOOT")) {
1870
1991
  // Soft-reboot the device. Lets the Mac companion apply a face change
1871
1992
  // (SETDEFAULT writes NVS; the new default only takes effect on boot).
@@ -1882,6 +2003,11 @@ void handleCommand(char *line, CommandSource source)
1882
2003
  } else if (tokenEquals(command, "PUSH")) {
1883
2004
  if (source == CommandSource::Stdio) handlePush(cursor);
1884
2005
  else std::printf("GEADEV:PUSH ERR unsupported-on-usb-direct\n");
2006
+ #if GEA_DEVICE_CONTROL_USB_OTA
2007
+ } else if (tokenEquals(command, "OTA")) {
2008
+ if (source == CommandSource::Stdio) handleOta(cursor);
2009
+ else std::printf("GEADEV:OTA ERR unsupported-on-usb-direct\n");
2010
+ #endif
1885
2011
  } else if (tokenEquals(command, "PUSH64")) {
1886
2012
  if (source == CommandSource::Stdio) handlePushBase64(cursor);
1887
2013
  else std::printf("GEADEV:PUSH64 ERR unsupported-on-usb-direct\n");
@@ -2035,6 +2161,10 @@ public:
2035
2161
  CommandLineAccumulator parser(CommandSource::Stdio);
2036
2162
  while (true) {
2037
2163
  if (!std::fgets(readBuffer, sizeof(readBuffer), stdin)) {
2164
+ // A console whose read returns 0 when idle (the TinyUSB CDC VFS)
2165
+ // sets stdin's end-of-file flag, and that flag is sticky: every
2166
+ // later fgets fails at once until it is cleared.
2167
+ std::clearerr(stdin);
2038
2168
  vTaskDelay(pdMS_TO_TICKS(50));
2039
2169
  continue;
2040
2170
  }
@@ -657,6 +657,9 @@ add_custom_command(
657
657
  --font-device-pixel-ratio ${GEA_EMBEDDED_CSS_DEVICE_PIXEL_RATIO}
658
658
  --pixel-panel-endian 1
659
659
  --gea-ir-backend
660
+ # Stylesheet registration becomes a function app_main calls, not a
661
+ # static constructor on the small pre-FreeRTOS startup stack.
662
+ --cpp-prelude-symbol gea_plugin_cpp_register_prelude
660
663
  # gea.compilerPlugins: an app's own geatsc plugins, e.g. the one that
661
664
  # declares its native host-function boundary. Empty for most apps.
662
665
  ${GEA_EMBEDDED_APP_GEATSC_PLUGIN_ARGS}
@@ -127,8 +127,16 @@ void runtimeTask(void *)
127
127
 
128
128
  } // namespace
129
129
 
130
+ // The app's stylesheet registration, emitted as a function (--cpp-prelude-symbol)
131
+ // rather than a file-scope global constructor. Static constructors run on the
132
+ // ROM's startup stack before FreeRTOS -- 8 KB on the ESP32-S31 -- and a CSS
133
+ // app's registration body alone takes a 3.5 KB frame, so it overran that stack
134
+ // into the heap. Weak: canvas-only builds emit no registration.
135
+ void gea_plugin_cpp_register_prelude() __attribute__((weak));
136
+
130
137
  extern "C" void app_main(void)
131
138
  {
139
+ if (gea_plugin_cpp_register_prelude) gea_plugin_cpp_register_prelude();
132
140
  // Force the targets/esp32/apps/app_manager.cpp TU to be linked in. That
133
141
  // TU's only side effect is a file-scope `PlatformRegistration` whose
134
142
  // constructor calls AppManager::setPlatform(...). With -Wl,--gc-sections
@@ -5,7 +5,7 @@ Target ID: `esp32-s31-espressif-mosaico`. Select **Espressif ESP-Mosaico
5
5
 
6
6
  This target supports hardware **V1.2** (V1.1 shares the pin mapping). The board
7
7
  is an ESP32-S31 (dual-core RISC-V at 320 MHz) with 16 MB in-package octal
8
- PSRAM, 16 MB quad NOR flash, a 480x480 CO5300 QSPI AMOLED with CST92xx touch,
8
+ PSRAM, 16 MB quad NOR flash, a 480x480 CO5300 QSPI AMOLED with CST9220 touch,
9
9
  an ES8311 codec with NS4150B amplifier, a BMI270 IMU, two BMM150
10
10
  magnetometers, a BQ27220 fuel gauge and 128 MB SPI NAND. V1.0 swaps the LCD
11
11
  clock and reset lines and moves the onboard I2C bus, so it is not supported.
@@ -31,11 +31,17 @@ gea build --board mosaico
31
31
  gea flash --board mosaico
32
32
  ```
33
33
 
34
- The USB-C port is the S31's high-speed USB OTG controller. It has no
35
- DTR/RTS reset circuit, and V1.2 ships with automatic download mode disabled,
36
- so the target flashes in manual boot mode (`manualBoot: true`): **hold BOOT
37
- while power-cycling the board** (or pressing reset) to enter the ROM loader,
38
- then run `gea flash`.
34
+ The USB-C port is the S31's high-speed USB OTG controller, not a ROM console:
35
+ it has no DTR/RTS reset circuit, V1.2 ships with automatic download mode
36
+ disabled, and a software reset into the downloader leaves the ROM silent on
37
+ that port until a power cycle. So `gea flash` installs the app through the app
38
+ already running (`usbAppUpdate: "geadev-ota"`): the image goes over the USB
39
+ console into the next OTA slot and the board restarts into it. No buttons.
40
+
41
+ The ROM downloader is still needed for the first flash, or when no gea app is
42
+ running: **hold BOOT while powering the board on** (POWER until dark, hold
43
+ BOOT, press POWER, release BOOT), then `gea flash --board mosaico --manual-boot`.
44
+ `gea flash` falls back to that by itself when no app answers.
39
45
 
40
46
  ## Console
41
47
 
@@ -52,5 +58,8 @@ GPIO60 (active low). `main/board_power.cpp` soft-starts it through an LEDC
52
58
  fade, as the BSP does, and releases the PWR_SW power-off request on GPIO57
53
59
  before display init touches the panel.
54
60
 
61
+ The panel's TE line is wired on GPIO43, so apps that ask for vsync
62
+ (`Display.setVSync(true)`) render locked to the panel's ~60 Hz refresh.
63
+
55
64
  Not yet wired: the BQ27220 fuel gauge (the board reports no battery reading),
56
- the panel's TE line on GPIO43, the magnetometers and the SPI NAND.
65
+ the magnetometers and the SPI NAND.
@@ -71,6 +71,24 @@ dependencies:
71
71
  registry_url: https://components.espressif.com
72
72
  type: service
73
73
  version: 1.2.1
74
+ espressif/esp_lcd_touch_cst9220:
75
+ component_hash: 519c0aed2d41307a9110f034b1eff8fa9a0e47621b1e1cd1b1a5e76183c8a6e8
76
+ dependencies:
77
+ - name: espressif/cmake_utilities
78
+ registry_url: https://components.espressif.com
79
+ require: private
80
+ version: 0.*
81
+ - name: espressif/esp_lcd_touch
82
+ registry_url: https://components.espressif.com
83
+ require: public
84
+ version: ^1.2.0
85
+ - name: idf
86
+ require: private
87
+ version: '>=5.3'
88
+ source:
89
+ registry_url: https://components.espressif.com/
90
+ type: service
91
+ version: 0.1.1
74
92
  espressif/esp_tinyusb:
75
93
  component_hash: 0fab24246e07bdf919c6489d17a590cffbffbbf6a9c44d6235641645c8b946b7
76
94
  dependencies:
@@ -111,27 +129,13 @@ dependencies:
111
129
  source:
112
130
  type: idf
113
131
  version: 6.2.0
114
- waveshare/esp_lcd_touch_cst9217:
115
- component_hash: 27a00845832b7987cacf4c4125cbed5415d940987583065b01870ac080930856
116
- dependencies:
117
- - name: espressif/esp_lcd_touch
118
- registry_url: https://components.espressif.com
119
- require: public
120
- version: ^1.1.0
121
- - name: idf
122
- require: private
123
- version: '>=4.4.2'
124
- source:
125
- registry_url: https://components.espressif.com/
126
- type: service
127
- version: 1.0.4
128
132
  direct_dependencies:
129
133
  - espressif/esp_codec_dev
130
134
  - espressif/esp_lcd_co5300
131
135
  - espressif/esp_lcd_panel_io_additions
136
+ - espressif/esp_lcd_touch_cst9220
132
137
  - espressif/esp_tinyusb
133
138
  - idf
134
- - waveshare/esp_lcd_touch_cst9217
135
- manifest_hash: d00ef0d696c011ff4e97bae2f217371293df338c57deca4f5e143663d8e1a2fe
139
+ manifest_hash: 7782d7a5b27bfbc269f69f2c3c7e7310e0524b6aeb8064924ee09ef7486f5eb8
136
140
  target: esp32s31
137
141
  version: 3.0.0
@@ -27,13 +27,13 @@ set(GEA_BOARD_EXTRA_REQUIRES
27
27
  esp_codec_dev
28
28
  esp_driver_ledc
29
29
  espressif__esp_tinyusb
30
- # The RTC watchdog reset behind the USB downloader request (board_power.cpp).
31
- esp_hal_wdt
32
30
  )
33
31
 
34
32
  set(GEA_BOARD_EXTRA_COMPILE_DEFINITIONS
35
33
  GEA_BOARD_PREPARE_DISPLAY_PANEL=1
36
34
  GEA_BOARD_USB_CONSOLE=1
35
+ # `gea flash` installs apps through the running app (usbAppUpdate).
36
+ GEA_DEVICE_CONTROL_USB_OTA=1
37
37
  GEA_EMBEDDED_CO5300_MOSAICO_INIT=1
38
38
  GEA_EMBEDDED_CO5300_PANEL_X_GAP=0
39
39
  GEA_EMBEDDED_CO5300_PANEL_Y_GAP=0
@@ -41,6 +41,7 @@ set(GEA_BOARD_EXTRA_COMPILE_DEFINITIONS
41
41
  GEA_BOARD_ES8311_I2C_ADDRESS=0x19
42
42
  # The side "AI" button; GPIO0 is the expansion I2C bus on this board.
43
43
  GEA_BOARD_LAUNCHER_BUTTON_GPIO=7
44
+ GEA_BOARD_TOUCH_CST9220=1
44
45
  )
45
46
 
46
47
  set(GEA_BOARD_PLATFORM_SOURCES
@@ -61,3 +62,16 @@ set(GEA_BOARD_PLATFORM_SOURCES
61
62
  )
62
63
 
63
64
  include("${CMAKE_CURRENT_LIST_DIR}/../../esp32-s3-touch-amoled-1.8/main/CMakeLists.txt")
65
+
66
+ # IDF 6.2 brings GCC 16 + picolibc: picolibc declares fflush() nonnull, so the
67
+ # runtime's fflush(nullptr) trips -Werror=nonnull, and GCC 16 flags generated
68
+ # std::move()s as redundant. Warnings, not errors, until the compiler runtime
69
+ # and emitter are fixed for this toolchain.
70
+ if(NOT CMAKE_BUILD_EARLY_EXPANSION)
71
+ target_compile_options(${COMPONENT_LIB} PRIVATE -Wno-error=nonnull -Wno-error=redundant-move)
72
+ # board_power.cpp keeps a crash's registers and log across the reset (no UART0 here)
73
+ # and makes the USB console wait for the host instead of dropping output.
74
+ target_link_libraries(${COMPONENT_LIB} INTERFACE "-Wl,--wrap=esp_panic_handler"
75
+ "-Wl,--wrap=tinyusb_cdcacm_write_queue_char"
76
+ "-Wl,--wrap=uart_hal_write_txfifo")
77
+ endif()
@@ -20,50 +20,49 @@
20
20
  // Mosaico by serial exactly as it does every other board. UART0 keeps the
21
21
  // early boot output and remains the fallback when USB does not come up.
22
22
  //
23
- // That console is also how the host gets the board into its ROM downloader,
24
- // since nothing else on the OTG port can: no reset lines, and V1.2 ships with
25
- // automatic download disabled. The host drives esptool's reset pattern on the
26
- // CDC line state -- (DTR=0, RTS=1), then RTS falling -- and the board answers it
27
- // as Espressif's own Mosaico console does (esp-brookesia,
28
- // esp_mosaico_usb_console): RTS falling with DTR high sets the LP-domain
29
- // FORCE_DOWNLOAD_BOOT flag and resets into the downloader; with DTR low it is a
30
- // plain restart. The flag survives the reset, so whoever flashes must clear it
31
- // before the final reset or the board comes straight back to the downloader.
23
+ // That console is also how apps are installed: `gea flash` streams the image to
24
+ // the running app (GEADEV OTA, `usbAppUpdate: "geadev-ota"` in targets.json),
25
+ // which writes the next OTA slot and restarts into it. The OTG port has no reset
26
+ // lines and V1.2 ships with automatic download disabled, so the ROM downloader
27
+ // is for first flash and recovery only (BOOT held through a power cycle). A new
28
+ // app confirms itself after it has run for a few seconds; one that crashes
29
+ // first is rolled back by the bootloader, and the app that comes back reports
30
+ // the crash on the console.
32
31
 
33
32
  #include "board.h"
34
33
 
34
+ #include <algorithm>
35
+ #include <cstddef>
35
36
  #include <cstdint>
36
37
  #include <cstdio>
37
38
 
38
39
  #include "driver/gpio.h"
39
40
  #include "driver/ledc.h"
41
+ #include "esp_attr.h"
40
42
  #include "esp_check.h"
41
43
  #include "esp_err.h"
44
+ #include "esp_heap_caps.h"
42
45
  #include "esp_log.h"
43
46
  #include "esp_mac.h"
47
+ #include "esp_ota_ops.h"
48
+ #include "esp_private/panic_internal.h"
44
49
  #include "esp_private/startup_internal.h"
50
+ #include "esp_rom_sys.h"
51
+ #include "esp_system.h"
45
52
  #include "freertos/FreeRTOS.h"
46
53
  #include "freertos/semphr.h"
47
54
  #include "freertos/task.h"
48
-
49
- // Off until the reset it ends in brings the board back: on V1.2 the RTC
50
- // watchdog reset leaves it off USB (neither the downloader nor the app
51
- // re-enumerates) until it is power-cycled, and a terminal opening the port can
52
- // produce the request pattern by itself.
53
- #ifndef GEA_BOARD_USB_DOWNLOAD_REQUEST
54
- #define GEA_BOARD_USB_DOWNLOAD_REQUEST 0
55
- #endif
56
-
57
- #if GEA_BOARD_USB_CONSOLE
58
- #include "esp_timer.h"
59
- #include "hal/wdt_hal.h"
55
+ #include "hal/uart_hal.h"
56
+ #include "riscv/rvruntime-frames.h"
60
57
  #include "soc/lp_system_reg.h"
61
- #include "soc/rtc.h"
62
58
  #include "soc/soc.h"
59
+
60
+ #if GEA_BOARD_USB_CONSOLE
63
61
  #include "tinyusb.h"
64
62
  #include "tinyusb_cdc_acm.h"
65
63
  #include "tinyusb_console.h"
66
64
  #include "tinyusb_default_config.h"
65
+ #include "vfs_tinyusb.h"
67
66
  #endif
68
67
 
69
68
  namespace
@@ -177,131 +176,6 @@ namespace
177
176
  "ESP-Mosaico Console", // 4: CDC interface
178
177
  };
179
178
 
180
- #if GEA_BOARD_USB_DOWNLOAD_REQUEST
181
- enum class UsbRestart : std::uint32_t
182
- {
183
- None = 0,
184
- Normal,
185
- Downloader,
186
- };
187
-
188
- // Line-state edges arrive on the TinyUSB task; the restart itself runs on a
189
- // task of its own, a little later, so the host sees esptool's reset complete
190
- // before the device drops off the bus.
191
- constexpr std::uint64_t kRestartDelayUs = 50 * 1000;
192
- constexpr std::uint32_t kWatchdogResetMs = 10;
193
- constexpr std::uint32_t kReenumerationDelayMs = 20;
194
- portMUX_TYPE restartLock = portMUX_INITIALIZER_UNLOCKED;
195
- bool resetArmed = false;
196
- UsbRestart pendingRestart = UsbRestart::None;
197
- esp_timer_handle_t restartTimer = nullptr;
198
- TaskHandle_t restartTask = nullptr;
199
-
200
- // esp_restart() resets only the CPUs on the ESP32-S31. The RTC watchdog's
201
- // system reset also resets the USB controller and its PHY -- so the host
202
- // sees a detach -- while keeping the LP-domain force-download flag.
203
- [[noreturn]] void watchdogSystemReset()
204
- {
205
- std::uint32_t ticks = static_cast<std::uint32_t>(
206
- static_cast<std::uint64_t>(kWatchdogResetMs) * rtc_clk_slow_freq_get_hz() / 1000U);
207
- if (ticks == 0)
208
- ticks = 1;
209
- wdt_hal_context_t rtcWdt = {};
210
- wdt_hal_init(&rtcWdt, WDT_RWDT, 0, false);
211
- wdt_hal_write_protect_disable(&rtcWdt);
212
- wdt_hal_config_stage(&rtcWdt, WDT_STAGE0, ticks, WDT_STAGE_ACTION_RESET_SYSTEM);
213
- wdt_hal_enable(&rtcWdt);
214
- wdt_hal_write_protect_enable(&rtcWdt);
215
- for (;;)
216
- {
217
- }
218
- }
219
-
220
- void restartTaskMain(void *)
221
- {
222
- for (;;)
223
- {
224
- std::uint32_t value = 0;
225
- if (xTaskNotifyWait(0, UINT32_MAX, &value, portMAX_DELAY) != pdTRUE)
226
- continue;
227
- const auto restart = static_cast<UsbRestart>(value);
228
- if (restart != UsbRestart::Normal && restart != UsbRestart::Downloader)
229
- continue;
230
- ESP_LOGW(kTag, "host requested %s over USB DTR/RTS",
231
- restart == UsbRestart::Downloader ? "the ROM downloader" : "a restart");
232
- // Leave the bus cleanly first, as Espressif's console does: without a
233
- // visible detach the host never picks up the ROM downloader that
234
- // enumerates after the reset, and the board vanishes from USB.
235
- tinyusb_cdcacm_write_flush(TINYUSB_CDC_ACM_0, pdMS_TO_TICKS(20));
236
- if (tinyusb_console_deinit(TINYUSB_CDC_ACM_0) == ESP_OK)
237
- {
238
- tinyusb_cdcacm_unregister_callback(TINYUSB_CDC_ACM_0, CDC_EVENT_LINE_STATE_CHANGED);
239
- if (tinyusb_cdcacm_deinit(TINYUSB_CDC_ACM_0) == ESP_OK)
240
- tinyusb_driver_uninstall();
241
- }
242
- vTaskDelay(pdMS_TO_TICKS(kReenumerationDelayMs));
243
- if (restart == UsbRestart::Downloader)
244
- REG_SET_BIT(LP_SYSTEM_REG_SYS_CTRL_REG, LP_SYSTEM_REG_FORCE_DOWNLOAD_BOOT);
245
- else
246
- REG_CLR_BIT(LP_SYSTEM_REG_SYS_CTRL_REG, LP_SYSTEM_REG_FORCE_DOWNLOAD_BOOT);
247
- watchdogSystemReset();
248
- }
249
- }
250
-
251
- void restartTimerFired(void *)
252
- {
253
- taskENTER_CRITICAL(&restartLock);
254
- const UsbRestart restart = pendingRestart;
255
- pendingRestart = UsbRestart::None;
256
- taskEXIT_CRITICAL(&restartLock);
257
- if (restart != UsbRestart::None && restartTask)
258
- xTaskNotify(restartTask, static_cast<std::uint32_t>(restart), eSetValueWithOverwrite);
259
- }
260
-
261
- void lineStateChanged(int itf, cdcacm_event_t *event)
262
- {
263
- if (itf != TINYUSB_CDC_ACM_0 || !event || event->type != CDC_EVENT_LINE_STATE_CHANGED)
264
- return;
265
- const bool dtr = event->line_state_changed_data.dtr;
266
- const bool rts = event->line_state_changed_data.rts;
267
- bool restart = false;
268
- taskENTER_CRITICAL(&restartLock);
269
- // (DTR=0, RTS=1) arms; a terminal opening the port toggles both lines, so
270
- // an RTS falling edge alone is not a request.
271
- if (!dtr && rts)
272
- {
273
- resetArmed = true;
274
- }
275
- else if (resetArmed && !rts)
276
- {
277
- pendingRestart = dtr ? UsbRestart::Downloader : UsbRestart::Normal;
278
- resetArmed = false;
279
- restart = true;
280
- }
281
- taskEXIT_CRITICAL(&restartLock);
282
- if (restart && restartTimer)
283
- {
284
- esp_timer_stop(restartTimer);
285
- esp_timer_start_once(restartTimer, kRestartDelayUs);
286
- }
287
- }
288
-
289
- void startUsbRestartHandler()
290
- {
291
- if (xTaskCreatePinnedToCore(restartTaskMain, "mosaico_usb_rst", 3072, nullptr, 20, &restartTask, 0) != pdPASS)
292
- {
293
- ESP_LOGE(kTag, "USB restart task not created; flashing needs BOOT held through a power cycle");
294
- return;
295
- }
296
- esp_timer_create_args_t timer = {};
297
- timer.callback = restartTimerFired;
298
- timer.name = "mosaico_usb_rst";
299
- if (esp_timer_create(&timer, &restartTimer) != ESP_OK)
300
- ESP_LOGE(kTag, "USB restart timer not created; flashing needs BOOT held through a power cycle");
301
- }
302
-
303
- #endif // GEA_BOARD_USB_DOWNLOAD_REQUEST
304
-
305
179
  void startUsbConsole()
306
180
  {
307
181
  std::uint8_t mac[6] = {};
@@ -323,10 +197,6 @@ namespace
323
197
 
324
198
  tinyusb_config_cdcacm_t cdc = {};
325
199
  cdc.cdc_port = TINYUSB_CDC_ACM_0;
326
- #if GEA_BOARD_USB_DOWNLOAD_REQUEST
327
- startUsbRestartHandler();
328
- cdc.callback_line_state_changed = lineStateChanged;
329
- #endif
330
200
  err = tinyusb_cdcacm_init(&cdc);
331
201
  if (err != ESP_OK)
332
202
  {
@@ -340,15 +210,141 @@ namespace
340
210
  ESP_LOGE(kTag, "USB console redirect failed: %s; console stays on UART0", esp_err_to_name(err));
341
211
  return;
342
212
  }
213
+ // Pass console input through untouched. The libc default (CR -> LF) is for
214
+ // a typed terminal; GEADEV's parser takes either line ending, and GEADEV
215
+ // OTA/PUSH stream raw binary that the conversion would corrupt.
216
+ esp_vfs_tusb_cdc_set_rx_line_endings(ESP_LINE_ENDINGS_LF);
343
217
  ESP_LOGI(kTag, "USB CDC console up (serial %s)", usbSerial);
344
218
  }
345
219
  #endif
346
220
 
221
+ // The panic dump only reaches UART0, which nothing on this board exposes, and
222
+ // a crash on boot comes before the USB console. The panic handler is wrapped
223
+ // (-Wl,--wrap=esp_panic_handler) to leave the crash registers in LP_STORE10-14,
224
+ // and the dump itself plus esp_rom_printf output land in an LP RAM ring; both
225
+ // survive the reset. The next app to boot -- after a rollback, the previous
226
+ // one -- prints them (GEADEV:CRASH, GEADEV:CRASHLOG) when a host opens the
227
+ // console.
228
+ constexpr std::uint32_t kPanicMagic = 0x9EA0DEADU;
229
+ constexpr std::uint32_t kCrashLogMagic = 0x9EA01060U;
230
+ constexpr std::size_t kCrashLogBytes = 12 * 1024;
231
+ RTC_NOINIT_ATTR std::uint32_t crashLogMagic;
232
+ RTC_NOINIT_ATTR std::uint32_t crashLogHead;
233
+ RTC_NOINIT_ATTR char crashLog[kCrashLogBytes];
234
+ char *previousCrashLog = nullptr;
235
+ std::size_t previousCrashLogBytes = 0;
236
+
237
+ IRAM_ATTR void crashLogPutc(char c)
238
+ {
239
+ crashLog[crashLogHead % kCrashLogBytes] = c;
240
+ crashLogHead = crashLogHead + 1;
241
+ }
242
+
243
+ bool previousBootCrashed()
244
+ {
245
+ const esp_reset_reason_t reason = esp_reset_reason();
246
+ return REG_READ(LP_SYSTEM_REG_LP_STORE10_REG) == kPanicMagic || reason == ESP_RST_PANIC ||
247
+ reason == ESP_RST_INT_WDT || reason == ESP_RST_TASK_WDT || reason == ESP_RST_WDT ||
248
+ reason == ESP_RST_BROWNOUT;
249
+ }
250
+
251
+ __attribute__((constructor)) void startCrashLog()
252
+ {
253
+ if (crashLogMagic == kCrashLogMagic && previousBootCrashed())
254
+ {
255
+ const std::size_t bytes = crashLogHead < kCrashLogBytes ? crashLogHead : kCrashLogBytes;
256
+ previousCrashLog = static_cast<char *>(heap_caps_malloc(bytes + 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
257
+ if (previousCrashLog)
258
+ {
259
+ const std::size_t start = crashLogHead < kCrashLogBytes ? 0 : crashLogHead % kCrashLogBytes;
260
+ for (std::size_t i = 0; i < bytes; ++i)
261
+ previousCrashLog[i] = crashLog[(start + i) % kCrashLogBytes];
262
+ previousCrashLog[bytes] = 0;
263
+ previousCrashLogBytes = bytes;
264
+ }
265
+ }
266
+ crashLogMagic = kCrashLogMagic;
267
+ crashLogHead = 0;
268
+ esp_rom_install_channel_putc(2, crashLogPutc);
269
+ }
270
+
271
+ #if GEA_BOARD_USB_CONSOLE
272
+ void reportPreviousPanic()
273
+ {
274
+ const bool captured = REG_READ(LP_SYSTEM_REG_LP_STORE10_REG) == kPanicMagic;
275
+ const std::uint32_t mepc = REG_READ(LP_SYSTEM_REG_LP_STORE11_REG);
276
+ const std::uint32_t ra = REG_READ(LP_SYSTEM_REG_LP_STORE12_REG);
277
+ const std::uint32_t mcause = REG_READ(LP_SYSTEM_REG_LP_STORE13_REG);
278
+ const std::uint32_t mtval = REG_READ(LP_SYSTEM_REG_LP_STORE14_REG);
279
+ REG_WRITE(LP_SYSTEM_REG_LP_STORE10_REG, 0);
280
+ // Shown each time a host opens the console, for three minutes.
281
+ const TickType_t until = xTaskGetTickCount() + pdMS_TO_TICKS(180000);
282
+ while (xTaskGetTickCount() < until)
283
+ {
284
+ if (!tud_cdc_n_connected(0))
285
+ {
286
+ vTaskDelay(pdMS_TO_TICKS(100));
287
+ continue;
288
+ }
289
+ vTaskDelay(pdMS_TO_TICKS(1500));
290
+ if (captured)
291
+ std::printf("GEADEV:CRASH reset=%d mepc=0x%08lx ra=0x%08lx mcause=0x%08lx mtval=0x%08lx\n",
292
+ static_cast<int>(esp_reset_reason()), static_cast<unsigned long>(mepc),
293
+ static_cast<unsigned long>(ra), static_cast<unsigned long>(mcause),
294
+ static_cast<unsigned long>(mtval));
295
+ else
296
+ std::printf("GEADEV:CRASH reset=%d (no panic)\n", static_cast<int>(esp_reset_reason()));
297
+ std::printf("GEADEV:CRASHLOG BEGIN bytes=%u\n", static_cast<unsigned>(previousCrashLogBytes));
298
+ for (std::size_t off = 0; off < previousCrashLogBytes; off += 256)
299
+ {
300
+ std::fwrite(previousCrashLog + off, 1, std::min<std::size_t>(256, previousCrashLogBytes - off), stdout);
301
+ std::fflush(stdout);
302
+ }
303
+ std::printf("\nGEADEV:CRASHLOG END\n");
304
+ std::fflush(stdout);
305
+ while (tud_cdc_n_connected(0) && xTaskGetTickCount() < until)
306
+ vTaskDelay(pdMS_TO_TICKS(100));
307
+ }
308
+ }
309
+
310
+ void panicReportTask(void *)
311
+ {
312
+ reportPreviousPanic();
313
+ vTaskDelete(nullptr);
314
+ }
315
+ #endif
316
+
317
+ #if CONFIG_BOOTLOADER_APP_ROLLBACK_CONFIRM_BY_APP
318
+ // A new app (installed over USB into the other OTA slot) is confirmed once it
319
+ // has run this long. One that crashes or hangs-and-resets first is rolled
320
+ // back by the bootloader on the next boot, and the board stays reachable.
321
+ constexpr std::uint32_t kConfirmAfterMs = 8000;
322
+
323
+ void confirmRunningApp()
324
+ {
325
+ esp_ota_img_states_t state;
326
+ if (esp_ota_get_state_partition(esp_ota_get_running_partition(), &state) != ESP_OK ||
327
+ (state != ESP_OTA_IMG_PENDING_VERIFY && state != ESP_OTA_IMG_NEW))
328
+ return;
329
+ vTaskDelay(pdMS_TO_TICKS(kConfirmAfterMs));
330
+ const esp_err_t err = esp_ota_mark_app_valid_cancel_rollback();
331
+ if (err == ESP_OK)
332
+ ESP_LOGI(kTag, "app confirmed after %u ms; rollback cancelled", static_cast<unsigned>(kConfirmAfterMs));
333
+ else
334
+ ESP_LOGE(kTag, "app confirm failed: %s", esp_err_to_name(err));
335
+ }
336
+ #endif
337
+
347
338
  void boardStartTask(void *)
348
339
  {
349
340
  gea::platform::board::powerOnRails();
350
341
  #if GEA_BOARD_USB_CONSOLE
351
342
  startUsbConsole();
343
+ if (previousBootCrashed())
344
+ xTaskCreatePinnedToCore(panicReportTask, "mosaico_panic", 3072, nullptr, 5, nullptr, 0);
345
+ #endif
346
+ #if CONFIG_BOOTLOADER_APP_ROLLBACK_CONFIRM_BY_APP
347
+ confirmRunningApp();
352
348
  #endif
353
349
  vTaskDelete(nullptr);
354
350
  }
@@ -384,3 +380,61 @@ ESP_SYSTEM_INIT_FN(gea_mosaico_board_start, SECONDARY, BIT(0), 999)
384
380
  ESP_EARLY_LOGW(kTag, "board start task not created; display init will open VCC_3V3");
385
381
  return ESP_OK;
386
382
  }
383
+
384
+ extern "C" void __real_esp_panic_handler(panic_info_t *info);
385
+
386
+ extern "C" void __wrap_esp_panic_handler(panic_info_t *info)
387
+ {
388
+ const auto *frame = info ? static_cast<const RvExcFrame *>(info->frame) : nullptr;
389
+ REG_WRITE(LP_SYSTEM_REG_LP_STORE11_REG, frame ? static_cast<std::uint32_t>(frame->mepc) : 0);
390
+ REG_WRITE(LP_SYSTEM_REG_LP_STORE12_REG, frame ? static_cast<std::uint32_t>(frame->ra) : 0);
391
+ REG_WRITE(LP_SYSTEM_REG_LP_STORE13_REG, frame ? static_cast<std::uint32_t>(frame->mcause) : 0);
392
+ REG_WRITE(LP_SYSTEM_REG_LP_STORE14_REG, frame ? static_cast<std::uint32_t>(frame->mtval) : 0);
393
+ REG_WRITE(LP_SYSTEM_REG_LP_STORE10_REG, kPanicMagic);
394
+ __real_esp_panic_handler(info);
395
+ }
396
+
397
+ #if GEA_BOARD_USB_CONSOLE
398
+ // The TinyUSB console drops whatever does not fit the TX FIFO, so under a log
399
+ // flood a GEADEV reply (OTA READY, PONG) is lost and `gea flash` times out.
400
+ // Wait for the host to drain the FIFO instead, while a host is reading; give up
401
+ // after 100 ms and stop waiting until the FIFO takes a byte again, so a host
402
+ // that holds the port open without reading cannot stall the app.
403
+ extern "C" size_t __real_tinyusb_cdcacm_write_queue_char(tinyusb_cdcacm_itf_t itf, char ch);
404
+
405
+ extern "C" size_t __wrap_tinyusb_cdcacm_write_queue_char(tinyusb_cdcacm_itf_t itf, char ch)
406
+ {
407
+ static bool txStalled = false;
408
+ size_t queued = __real_tinyusb_cdcacm_write_queue_char(itf, ch);
409
+ if (queued || txStalled || xPortInIsrContext() || xTaskGetSchedulerState() != taskSCHEDULER_RUNNING ||
410
+ !tud_cdc_n_connected(itf))
411
+ {
412
+ if (queued)
413
+ txStalled = false;
414
+ return queued;
415
+ }
416
+ const TickType_t start = xTaskGetTickCount();
417
+ while (xTaskGetTickCount() - start < pdMS_TO_TICKS(100))
418
+ {
419
+ tud_cdc_n_write_flush(itf);
420
+ vTaskDelay(1);
421
+ queued = __real_tinyusb_cdcacm_write_queue_char(itf, ch);
422
+ if (queued)
423
+ return queued;
424
+ }
425
+ txStalled = true;
426
+ return 0;
427
+ }
428
+ #endif
429
+
430
+ // The panic dump goes out through the UART HAL; keep a copy in the crash log.
431
+ extern "C" void __real_uart_hal_write_txfifo(uart_hal_context_t *hal, const uint8_t *buf, uint32_t size,
432
+ uint32_t *written);
433
+
434
+ extern "C" IRAM_ATTR void __wrap_uart_hal_write_txfifo(uart_hal_context_t *hal, const uint8_t *buf,
435
+ uint32_t size, uint32_t *written)
436
+ {
437
+ __real_uart_hal_write_txfifo(hal, buf, size, written);
438
+ for (uint32_t i = 0; i < *written; ++i)
439
+ crashLogPutc(static_cast<char>(buf[i]));
440
+ }
@@ -7,9 +7,10 @@
7
7
  # former, and an app that asks for echo cancellation is not supported yet.
8
8
  dependencies:
9
9
  espressif/esp_lcd_co5300: '^2.0.3'
10
- # The CST92xx family shares this protocol; the BSP's own CST9220 driver reads
11
- # the same 0xD000 report block at 0x5A.
12
- waveshare/esp_lcd_touch_cst9217: '^1.0.1'
10
+ # The board's touch controller is a CST9220 (Espressif's board definition,
11
+ # esp-brookesia esp_mosaico_v1_2). It may run the HYN212 protocol, which the
12
+ # CST9217 driver does not speak: touch then initializes and never reports.
13
+ espressif/esp_lcd_touch_cst9220: '^0.1.1'
13
14
  espressif/esp_codec_dev: '^1.4.0'
14
15
  esp_lcd_panel_io_additions: '^1'
15
16
  # board_power.cpp: the USB-C port is the S31's high-speed OTG controller, so
@@ -7,7 +7,7 @@
7
7
  // Espressif ESP-Mosaico, hardware V1.2 (V1.1 shares the mapping).
8
8
  //
9
9
  // ESP32-S31 (dual-core RISC-V, 320 MHz) with 16 MB in-package octal PSRAM,
10
- // 16 MB quad NOR flash, a 480x480 CO5300 QSPI AMOLED with a CST92xx touch
10
+ // 16 MB quad NOR flash, a 480x480 CO5300 QSPI AMOLED with a CST9220 touch
11
11
  // controller, ES8311 codec + NS4150B amplifier, BMI270 IMU, two BMM150
12
12
  // magnetometers, a BQ27220 fuel gauge and 128 MB SPI NAND.
13
13
  //
@@ -91,9 +91,9 @@ public:
91
91
  .data2 = GPIO_NUM_35,
92
92
  .data3 = GPIO_NUM_9,
93
93
  .reset = GPIO_NUM_44,
94
- // The panel drives TE on GPIO43 and the init sequence enables it, but
95
- // the runtime does not wait on it yet: bring-up first, tear-free later.
96
- .te = GPIO_NUM_NC,
94
+ // The panel drives TE on GPIO43 (TEON in the init sequence). An app that
95
+ // calls Display.setVSync(true) frames off it, locked to the ~60 Hz scanout.
96
+ .te = GPIO_NUM_43,
97
97
  };
98
98
 
99
99
  // Touch reset is not wired; the controller comes out of power-on reset
@@ -192,3 +192,9 @@ CONFIG_HEAP_TRACING_OFF=y
192
192
  # CONFIG_HEAP_TRACING_TOHOST is not set
193
193
  # CONFIG_HEAP_TRACING is not set
194
194
  # CONFIG_HEAP_TRACE_HASH_MAP is not set
195
+
196
+ # Apps are installed through the running app (usbAppUpdate). Confirm a new app
197
+ # only after it has run for a while (board_power.cpp), so one that crashes on
198
+ # boot rolls back to the previous app instead of needing BOOT to recover.
199
+ CONFIG_BOOTLOADER_APP_ROLLBACK=y
200
+ CONFIG_BOOTLOADER_APP_ROLLBACK_CONFIRM_BY_APP=y
package/targets.json CHANGED
@@ -189,7 +189,7 @@
189
189
  "esptoolChip": "esp32s31",
190
190
  "idfVersion": "6.2",
191
191
  "ipcTaskStackSize": "4096",
192
- "forceDownloadRegister": "0x20700008:0x4",
193
- "manualBoot": true
192
+ "manualBoot": true,
193
+ "usbAppUpdate": "geadev-ota"
194
194
  }
195
195
  }