-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcdc1_control.c
More file actions
384 lines (358 loc) · 21.1 KB
/
Copy pathcdc1_control.c
File metadata and controls
384 lines (358 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
* Hackagotchi — CDC1 JSON control channel. SPDX-License-Identifier: MIT
*
* CDC1 (instance 1) is a LINE-oriented request/response control port, separate from CDC0 (the target-
* UART bridge in cdc_uart.c). Each request is one line of JSON — {"q":"<command>"} — and each reply is
* one line of JSON. M1 replaces the Gate-2 strstr() prototype with a real jsmn parse over a bounded
* line buffer, so a command is matched on the STRUCTURED value of the "q" key, not a substring:
* {"note":"status please"} no longer false-triggers `status` the way the strstr prototype did.
*
* Commands: status, dump, lastfault, wd_arm, next, prev (request/response); crash, wd_test, bootsel
* (no reply — the device faults/wedges/reboots and the host detects re-enumeration).
*
* Runs in the tud_task()/usb_thread (TUD task) context, so replies are same-task-safe and never touch
* the DAP/SWD path.
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h> // atoi (numeric jsmn values for beep/led test commands)
#include <stdbool.h>
#include <pico/stdlib.h>
#include "pico/bootrom.h" // reset_usb_boot for {"q":"bootsel"}
#include "FreeRTOS.h"
#include "task.h"
#include "tusb.h"
#define JSMN_STATIC // keep jsmn symbols file-local (header-only, single TU)
#include "jsmn.h"
#include "probe_config.h" // PROBE_UART_INTERFACE (for the uart loopback HIL test)
#include "hackagotchi_dashboard.h" // g_dash_counter, g_dash_stall_us (self-attestation telemetry)
#include "crash_box.h" // lastfault readout + the crash HIL self-test
#include "watchdog_task.h" // wd_arm + g_tud_wedge (watchdog control + HIL test)
#include "uart_bridge.h" // uart ring stats + loopback toggle (CDC0 bridge HIL test)
#include "sd_gate.h" // M2: SD bring-up self-test result ({"q":"sd"})
#include "feedback.h" // M3.0: LED/buzzer HW-reconciliation test commands
#include "hg_config.h" // M4.2: macro list ({"q":"macros"} / {"q":"macro"})
#include "dap_health.h" // DAP transfer/health witness ({"q":"status"} dap_xfers/dap_idle_ms)
#include "hg_input.h" // v1.2: button/joystick readback ({"q":"btn"} / {"q":"joy"})
// Build-discriminating tags compiled into the status reply so the RUNNING firmware proves its OWN
// identity (closes the Gate-1 provenance gap). Mirror the CMake -D flags (PRIVATE on the target).
#ifndef ADVERSARIAL_STALL_MS
#define ADVERSARIAL_STALL_MS 0
#endif
#ifdef ADVERSARIAL_AT_DAP_PRIO
#define HACKA_DASH_PRIO 1
#else
#define HACKA_DASH_PRIO 0
#endif
// M5: release semver, set by -DHG_VERSION from the CMake cache var (build_fork.sh VERSION / CI input).
// Falls back to a dev marker for a bare `make`. Reported as "ver" in {"q":"status"} for provenance.
#ifndef HG_VERSION
#define HG_VERSION "0.0.0-dev"
#endif
#define CDC_ITF_CONTROL 1 // CDC1 = JSON control (CDC0 / instance 0 = UART bridge, in cdc_uart.c)
#define LINE_MAX 128 // bounded request line buffer — overflow resets it, never overruns
#define MAX_TOK 16 // enough tokens for our small {"q":"..."} requests
// Screen navigation: the M3 dashboard OWNS the screen index; CDC1 only posts intents (dash_nav_step /
// dash_nav_to) that the dashboard consumes + clamps. The current index is read back from g_dash_screen.
// Count of rx-callbacks that ended holding a partial line (= a request spanned >1 USB packet and the
// line buffer reassembled it). Exposed as `frag` so the HIL fragmentation test can prove the
// reassembly path actually ran, instead of trusting host-side packetization timing.
static uint32_t s_partial = 0;
static void reply(uint8_t itf, const char *s) {
tud_cdc_n_write(itf, s, (uint32_t) strlen(s));
tud_cdc_n_write_flush(itf);
}
// The status/telemetry line. "fw" stays first by convention (gate2_cdc.py checks fw PRESENCE via
// obj.get("fw"), not position, so field order is actually free); "ver" is the M5 compiled-in release
// semver (provenance); n/stall_*/prio self-attest the build; crashes/wd_armed/page expose the M1
// reliability + nav state.
// NOTE: reply/token buffers are `static`, NOT stack — this callback runs only in the single (non-
// reentrant) TUD task, and ~0.5 KB of JSON locals on the small USB task stack overflows it (corrupts
// the USB endpoint state -> the host sees ENXIO). Keep big buffers off this stack.
static void write_status(uint8_t itf) {
static char r[320];
int len = snprintf(r, sizeof r,
"{\"fw\":\"Hackagotchi\",\"ver\":\"%s\",\"heap\":%u,\"up\":%u,\"n\":%u,"
"\"stall_cfg\":%d,\"stall_us\":%u,\"prio\":%d,"
"\"dap_xfers\":%u,\"dap_idle_ms\":%u,"
"\"crashes\":%u,\"wd_armed\":%d,\"wd_gap\":%u,\"tud\":%u,\"page\":%d,"
"\"urx_drop\":%u,\"urx_hw\":%u,\"utx_drop\":%u,\"frag\":%u,"
"\"px\":%u,\"btn\":%d,\"joy\":%d}\n",
HG_VERSION,
(unsigned) xPortGetFreeHeapSize(),
(unsigned) (time_us_64() / 1000000ull),
(unsigned) g_dash_counter, (int) ADVERSARIAL_STALL_MS,
(unsigned) g_dash_stall_us, (int) HACKA_DASH_PRIO,
(unsigned) dap_health_xfers(), (unsigned) dap_health_idle_ms(),
(unsigned) crash_box_count(), (int) wd_is_armed(), (unsigned) wd_max_gap_ms(),
(unsigned) g_tud_checkin, (int) g_dash_screen,
(unsigned) uart_bridge_drops(), (unsigned) uart_bridge_highwater(),
(unsigned) cdc_uart_tx_overflow(), (unsigned) s_partial,
(unsigned) feedback_pixel_count(), hg_button_down(), hg_joy_ok());
if (len > 0) reply(itf, r);
}
static void write_lastfault(uint8_t itf) {
static char r[200];
int len = snprintf(r, sizeof r, "{\"fault\":%s}\n", crash_box_report());
if (len > 0) reply(itf, r);
}
static void write_page(uint8_t itf) {
char r[40];
int len = snprintf(r, sizeof r, "{\"page\":%d,\"n\":%d}\n", (int)g_dash_screen, dash_screen_count());
if (len > 0) reply(itf, r);
}
// M3.1 self-attestation: the current screen index + the EXACT text the dashboard drew this frame, plus
// the show-success / loop counters. A host test asserts content + that frames actually flush (shows
// climbing), with no camera. Newlines in the rendered text become '|'; '"'/'\' are escaped.
static void write_screen(uint8_t itf) {
static char txt[160];
int idx = dash_get_attest(txt, sizeof txt);
static char esc[200];
size_t o = 0;
for (size_t i = 0; txt[i] && o + 2 < sizeof esc; i++) {
char c = txt[i];
if (c == '\n') esc[o++] = '|';
else if (c == '"' || c == '\\') { esc[o++] = '\\'; esc[o++] = c; }
else if (c >= 32 && c <= 126) esc[o++] = c;
}
esc[o] = '\0';
static char r[280];
int len = snprintf(r, sizeof r,
"{\"screen\":%d,\"n\":%d,\"shows\":%u,\"loops\":%u,\"dstack\":%u,\"text\":\"%s\"}\n",
idx, dash_screen_count(), (unsigned)g_dash_shows, (unsigned)g_dash_counter,
(unsigned)g_dash_stack_free, esc);
if (len > 0) reply(itf, r);
}
// jsmn helper: does token `t` (within json string `js`) equal C-string `s`?
static bool tok_eq(const char *js, const jsmntok_t *t, const char *s) {
return t->type == JSMN_STRING &&
(int) strlen(s) == (t->end - t->start) &&
strncmp(js + t->start, s, (size_t)(t->end - t->start)) == 0;
}
// Copy the value of the top-level "q" key into out[]. Returns true iff found as a string value.
static bool get_q(const char *js, const jsmntok_t *tok, int ntok, char *out, size_t outsz) {
for (int i = 1; i + 1 < ntok; i++) {
if (tok_eq(js, &tok[i], "q") && tok[i + 1].type == JSMN_STRING) {
int vlen = tok[i + 1].end - tok[i + 1].start;
if (vlen <= 0 || (size_t) vlen >= outsz) return false;
memcpy(out, js + tok[i + 1].start, (size_t) vlen);
out[vlen] = '\0';
return true;
}
}
return false;
}
// Read the integer value of top-level key `key` (a jsmn PRIMITIVE number). atoi() stops at the token's
// trailing delimiter (the value isn't NUL-terminated in `js`, but ',' / '}' bounds it). Returns true iff found.
static bool get_int(const char *js, const jsmntok_t *tok, int ntok, const char *key, int *out) {
for (int i = 1; i + 1 < ntok; i++) {
if (tok_eq(js, &tok[i], key) && tok[i + 1].type == JSMN_PRIMITIVE) {
*out = atoi(js + tok[i + 1].start);
return true;
}
}
return false;
}
// Copy the string value of top-level key `key` into out[]. Returns true iff found as a string value.
static bool get_str(const char *js, const jsmntok_t *tok, int ntok,
const char *key, char *out, size_t outsz) {
for (int i = 1; i + 1 < ntok; i++) {
if (tok_eq(js, &tok[i], key) && tok[i + 1].type == JSMN_STRING) {
int vlen = tok[i + 1].end - tok[i + 1].start;
if (vlen <= 0 || (size_t) vlen >= outsz) return false;
memcpy(out, js + tok[i + 1].start, (size_t) vlen);
out[vlen] = '\0';
return true;
}
}
return false;
}
// Parse + dispatch one complete JSON request line.
static void handle_line(uint8_t itf, const char *line, int len) {
jsmn_parser p;
static jsmntok_t tok[MAX_TOK]; // static: keep 256 B off the small TUD task stack (see write_status)
jsmn_init(&p);
int n = jsmn_parse(&p, line, (size_t) len, tok, MAX_TOK);
if (n < 1 || tok[0].type != JSMN_OBJECT) { reply(itf, "{\"err\":\"badjson\"}\n"); return; }
char q[24];
if (!get_q(line, tok, n, q, sizeof q)) { reply(itf, "{\"err\":\"noq\"}\n"); return; }
// Commands that do NOT return (device reboots / wedges; host detects re-enumeration).
if (!strcmp(q, "bootsel")) { reset_usb_boot(0, 0); return; }
if (!strcmp(q, "crash")) { *(volatile uint32_t *)0xF0000000u = 0xDEADBEEFu; return; }
if (!strcmp(q, "wd_test")) { g_tud_wedge = true; return; }
// Request/response commands.
if (!strcmp(q, "status")) { write_status(itf); return; }
if (!strcmp(q, "lastfault")) { write_lastfault(itf); return; }
if (!strcmp(q, "dump")) { write_status(itf); write_lastfault(itf); return; }
if (!strcmp(q, "wd_arm")) { wd_arm(); reply(itf, "{\"wd\":\"armed\"}\n"); return; }
if (!strcmp(q, "wd_reset")) { wd_gap_reset(); reply(itf, "{\"wd_gap\":0}\n"); return; }
if (!strcmp(q, "sd")) { static char r[160]; sd_gate_status_json(r, sizeof r); reply(itf, r); return; }
if (!strcmp(q, "rec")) { static char r[256]; sd_rec_status_json(r, sizeof r); reply(itf, r); return; }
// {"q":"tail"}: request a tail read (SD task does the FatFs read off the hot path) AND return the
// PREVIOUS read — so send it twice (request, then collect) to verify on-card log content.
if (!strcmp(q, "tail")) { static char r[256]; sd_rec_tail_json(r, sizeof r); sd_rec_tail_request(); reply(itf, r); return; }
// M4.4 SD explorer (async like tail: returns the PREVIOUS result + requests a fresh one — call twice).
if (!strcmp(q, "ls")) { static char r[480]; sd_ls_json(r, sizeof r); sd_ls_request(); reply(itf, r); return; }
if (!strcmp(q, "cat")) {
int idx; if (!get_int(line, tok, n, "i", &idx)) { reply(itf, "{\"err\":\"noi\"}\n"); return; }
int off = 0; get_int(line, tok, n, "off", &off);
static char r[256]; sd_cat_json(r, sizeof r); sd_cat_request(idx, (uint32_t)(off < 0 ? 0 : off)); reply(itf, r); return;
}
if (!strcmp(q, "next")) { dash_nav_step(+1); write_page(itf); return; }
if (!strcmp(q, "prev")) { dash_nav_step(-1); write_page(itf); return; }
// {"q":"screen"} -> report the current screen + rendered-text attestation (HIL: content + frames-flush).
// {"q":"screen","n":N} -> jump to screen N (clamped by the dashboard), then report.
if (!strcmp(q, "screen")) { int v; if (get_int(line, tok, n, "n", &v)) dash_nav_to(v); write_screen(itf); return; }
if (!strcmp(q, "hex")) { bool m = dash_hex_toggle(); char r[20]; snprintf(r, sizeof r, "{\"hex\":%d}\n", m ? 1 : 0); reply(itf, r); return; }
// M-UI-5 companion interaction (the cat + ghost respond to the operator; there is no physical button).
if (!strcmp(q, "pet")) { dash_pet(); feedback_beep(1760, 80); reply(itf, "{\"pet\":1}\n"); return; }
if (!strcmp(q, "summon")) { dash_ghost_summon(1); reply(itf, "{\"ghost\":\"summon\"}\n"); return; }
if (!strcmp(q, "banish")) { dash_ghost_summon(0); reply(itf, "{\"ghost\":\"banish\"}\n"); return; }
if (!strcmp(q, "exorcise")) { dash_exorcise(); feedback_beep(1200, 160); reply(itf, "{\"exorcise\":1}\n"); return; }
// {"q":"ghost","on":0/1} mutes/unmutes the whole character layer (pure-instrument <-> companion);
// {"q":"ghost"} with no "on" returns the ghost to AUTO (clears a summon/banish override). Echoes char state.
if (!strcmp(q, "ghost")) {
int on; if (get_int(line, tok, n, "on", &on)) dash_char_enable(on); else dash_ghost_summon(-1);
char r[28]; snprintf(r, sizeof r, "{\"char\":%d}\n", dash_char_enabled()); reply(itf, r); return;
}
if (!strcmp(q, "theme")) { int v = 1; get_int(line, tok, n, "n", &v); dash_theme(v); char r[24]; snprintf(r, sizeof r, "{\"theme\":%d}\n", v ? 1 : 0); reply(itf, r); return; }
// M4.2 macro sender: list the configured macros / send macro i (TEXT + CRLF) out the target UART.
if (!strcmp(q, "macros")) {
static char r[160]; int o = snprintf(r, sizeof r, "{\"macros\":[");
for (int i = 0; i < HG_N_MACROS; i++)
o += snprintf(r + o, sizeof r - (size_t)o, "%s\"%s\"", i ? "," : "", hg_macro(i));
snprintf(r + o, sizeof r - (size_t)o, "]}\n");
reply(itf, r); return;
}
if (!strcmp(q, "macro")) {
int i; if (!get_int(line, tok, n, "i", &i)) { reply(itf, "{\"err\":\"noi\"}\n"); return; }
const char *m = hg_macro(i); // "" if i out of range / empty
if (!m[0]) { reply(itf, "{\"err\":\"range\"}\n"); return; }
char buf[HG_MACRO_MAX + 2]; int bn = snprintf(buf, sizeof buf, "%s\r\n", m);
if (!cdc_uart_inject(buf, (size_t)bn)) { reply(itf, "{\"err\":\"busy\"}\n"); return; }
dash_macro_mark(i);
static char r[48]; snprintf(r, sizeof r, "{\"sent\":%d,\"macro\":\"%s\"}\n", i, m);
reply(itf, r); return;
}
// M4.5: edit a macro and persist. {"q":"setmacro","i":N,"s":"TEXT"} (TEXT truncated to 14).
if (!strcmp(q, "setmacro")) {
int i; if (!get_int(line, tok, n, "i", &i)) { reply(itf, "{\"err\":\"noi\"}\n"); return; }
if (i < 0 || i >= HG_N_MACROS) { reply(itf, "{\"err\":\"range\"}\n"); return; }
char sv[HG_MACRO_MAX]; if (!get_str(line, tok, n, "s", sv, sizeof sv)) { reply(itf, "{\"err\":\"nos\"}\n"); return; }
hg_set_macro(i, sv); sd_config_save_request();
static char r[48]; snprintf(r, sizeof r, "{\"macro\":%d,\"set\":\"%s\"}\n", i, hg_macro(i));
reply(itf, r); return;
}
// M4.3 baud selector: {"q":"baud"} reads current + options; {"q":"baud","v":N} sets it (validated).
if (!strcmp(q, "baud")) {
int v;
if (get_int(line, tok, n, "v", &v)) {
if (!hg_set_baud((uint32_t)v)) { reply(itf, "{\"err\":\"badbaud\"}\n"); return; }
cdc_uart_set_baud_request((uint32_t)v); // applied by cdc_task (the UART owner)
sd_config_save_request(); // M4.5: persist the new baud to SD
char r[24]; snprintf(r, sizeof r, "{\"baud\":%d}\n", v); reply(itf, r); return;
}
static char r[120]; int o = snprintf(r, sizeof r, "{\"baud\":%lu,\"opts\":[", (unsigned long)hg_baud());
for (int i = 0; i < HG_N_BAUDS; i++)
o += snprintf(r + o, sizeof r - (size_t)o, "%s%lu", i ? "," : "", (unsigned long)HG_BAUDS[i]);
snprintf(r + o, sizeof r - (size_t)o, "]}\n");
reply(itf, r); return;
}
// UART-bridge HIL self-test: PL011 internal loopback (TX->RX in-chip) — round-trip CDC0 with no jumper.
if (!strcmp(q, "uloop_on")) { uart_bridge_set_loopback(PROBE_UART_INTERFACE, true); reply(itf, "{\"uloop\":1}\n"); return; }
if (!strcmp(q, "uloop_off")) { uart_bridge_set_loopback(PROBE_UART_INTERFACE, false); reply(itf, "{\"uloop\":0}\n"); return; }
// Reliability HIL hook: exhaust the FreeRTOS heap so vApplicationMallocFailedHook fires -> crash box
// records kind=mallocfail + reboots (directly proves the malloc-fail path, not just the shared code).
if (!strcmp(q, "oom_test")) { for (;;) (void) pvPortMalloc(1024); return; /* hook reboots first */ }
// M2 coexistence soak: device-side recorder load (continuous SD writes, no host UART traffic) so a
// concurrent probe-rs flash soak measures pure SD-vs-DAP contention without host USB confounds.
if (!strcmp(q, "recgen_on")) { sd_recgen_set(true); reply(itf, "{\"recgen\":1}\n"); return; }
if (!strcmp(q, "recgen_off")) { sd_recgen_set(false); reply(itf, "{\"recgen\":0}\n"); return; }
// M3.0 HW-reconciliation: drive the buzzer (GP29) + the WS2812 NeoPixel (GP12/GP11) to confirm the
// outputs work post-SWD-remap. {"q":"led"} maps red/green flags to the NeoPixel via feedback_led ->
// feedback_pixel — NOT the onboard GP17/16 RGB, which Finding M3-1 abandoned as an unreliable channel.
// Non-blocking (the SD task's feedback_service does the actual drive/dwell).
// {"q":"beep","hz":2000,"ms":120} / {"q":"led","r":1,"g":0} / {"q":"pixel","r":..,"g":..,"b":..}
if (!strcmp(q, "beep")) {
int hz = 2000, ms = 120; get_int(line, tok, n, "hz", &hz); get_int(line, tok, n, "ms", &ms);
feedback_beep((uint16_t)(hz < 0 ? 0 : hz), (uint16_t)(ms < 0 ? 0 : ms));
char r[40]; snprintf(r, sizeof r, "{\"beep\":%d,\"ms\":%d}\n", hz, ms); reply(itf, r); return;
}
if (!strcmp(q, "led")) {
int rr = 0, gg = 0; get_int(line, tok, n, "r", &rr); get_int(line, tok, n, "g", &gg);
feedback_led(rr != 0, gg != 0);
char r[32]; snprintf(r, sizeof r, "{\"led_r\":%d,\"led_g\":%d}\n", rr ? 1 : 0, gg ? 1 : 0); reply(itf, r); return;
}
// {"q":"pixel","r":0..255,"g":..,"b":..} — drive the NeoPixel to an arbitrary colour (HW-reconcile/test).
if (!strcmp(q, "pixel")) {
int rr = 0, gg = 0, bb = 0;
get_int(line, tok, n, "r", &rr); get_int(line, tok, n, "g", &gg); get_int(line, tok, n, "b", &bb);
#define CLAMP8(v) ((uint8_t)((v) < 0 ? 0 : (v) > 255 ? 255 : (v)))
feedback_pixel(CLAMP8(rr), CLAMP8(gg), CLAMP8(bb));
#undef CLAMP8
char r[48]; snprintf(r, sizeof r, "{\"pixel\":[%d,%d,%d]}\n", rr, gg, bb); reply(itf, r); return;
}
// v1.2 "Companion": drive the WHOLE WS2812 chain to one colour. {"q":"fill","r":..,"g":..,"b":..}
if (!strcmp(q, "fill")) {
int rr = 0, gg = 0, bb = 0;
get_int(line, tok, n, "r", &rr); get_int(line, tok, n, "g", &gg); get_int(line, tok, n, "b", &bb);
#define CLAMP8(v) ((uint8_t)((v) < 0 ? 0 : (v) > 255 ? 255 : (v)))
feedback_fill(CLAMP8(rr), CLAMP8(gg), CLAMP8(bb));
#undef CLAMP8
char r[56]; snprintf(r, sizeof r, "{\"fill\":[%d,%d,%d],\"px\":%d}\n", rr, gg, bb, feedback_pixel_count());
reply(itf, r); return;
}
// v1.2: set an animated MOOD on the chain. {"q":"mood","n":0..6} (optional "i":0..255 intensity)
if (!strcmp(q, "mood")) {
int m = 0, inten = 200; get_int(line, tok, n, "n", &m); get_int(line, tok, n, "i", &inten);
if (inten < 0) inten = 0;
if (inten > 255) inten = 255;
feedback_mood(m, (uint8_t)inten);
char r[40]; snprintf(r, sizeof r, "{\"mood\":%d,\"i\":%d}\n", m, inten); reply(itf, r); return;
}
// v1.2 HIL readback: the on-device button (GP16). {"q":"btn"} -> held state + taps since boot.
if (!strcmp(q, "btn")) {
char r[48]; snprintf(r, sizeof r, "{\"down\":%d,\"presses\":%u}\n", hg_button_down(), (unsigned)hg_button_presses());
reply(itf, r); return;
}
// v1.2 HIL readback: the joystick (ADS1115). {"q":"joy"} -> present? + raw X/Y + decoded direction.
if (!strcmp(q, "joy")) {
char r[72]; snprintf(r, sizeof r, "{\"ok\":%d,\"x\":%d,\"y\":%d,\"dir\":%d}\n",
hg_joy_ok(), hg_joy_x(), hg_joy_y(), hg_joy_dir());
reply(itf, r); return;
}
// M3 closeout HIL: feedback-layer readback — proves drive_feedback drove the buzzer/NeoPixel on events.
if (!strcmp(q, "fb")) {
uint32_t c = feedback_color();
char r[72];
snprintf(r, sizeof r, "{\"beeps\":%u,\"beeping\":%d,\"r\":%u,\"g\":%u,\"b\":%u}\n",
(unsigned)feedback_beep_count(), feedback_is_beeping() ? 1 : 0,
(unsigned)((c >> 8) & 0xFFu), (unsigned)((c >> 16) & 0xFFu), (unsigned)(c & 0xFFu));
reply(itf, r); return;
}
reply(itf, "{\"err\":\"unknown\"}\n");
}
// TinyUSB CDC RX callback (ALL instances). We own ONLY CDC1; CDC0's bytes stay in their FIFO for
// cdc_task(). Bytes are accumulated into a BOUNDED line buffer and dispatched per newline, so a
// request split across USB packets is reassembled and an over-long line is dropped (never overruns).
void tud_cdc_rx_cb(uint8_t itf) {
if (itf != CDC_ITF_CONTROL) return;
static char line[LINE_MAX];
static int llen = 0;
uint8_t buf[64];
uint32_t n;
while ((n = tud_cdc_n_read(itf, buf, sizeof buf)) > 0) {
for (uint32_t i = 0; i < n; i++) {
char c = (char) buf[i];
if (c == '\n' || c == '\r') {
if (llen > 0) { handle_line(itf, line, llen); llen = 0; }
} else if (llen < LINE_MAX - 1) {
line[llen++] = c;
} else {
llen = 0; // over-long line: drop it defensively
reply(itf, "{\"err\":\"toolong\"}\n");
}
}
}
if (llen > 0) s_partial++; // ended holding a partial line -> a request spanned >1 packet
}