The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(pro): USB link: ISR byte counts, 300 ms partial-frame expiry, seq + resync (#1422)
0xdiego253e9c63a798c3
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex 53e1af729..df0f6ef2f 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -22,6 +22,8 @@ class LoopbackPort implements CablePort {isOpen = true/** Everything the daemon wrote, decoded back into messages. */readonly sent: Array<Record<string, unknown>> = []+ /** The `seq` of each frame in `sent` (taken off the message, so exact-match specs need not know it); undefined = none. */+ readonly seqs: Array<number | undefined> = []/** The raw bytes of every frame written, so a test can assert the 8 KB cap holds. */readonly frames: Uint8Array[] = []/** Payloads of every pet slice (CableType.Pet) the daemon wrote. */@@ -39,7 +41,9 @@ class LoopbackPort implements CablePort {this.frames.push(bytes)this.decoder.feed(Buffer.from(bytes), (frame) => {if (frame.type === CableType.Json) {- this.sent.push(JSON.parse(Buffer.from(frame.payload).toString('utf8')) as Record<string, unknown>)+ const { seq, ...message } = JSON.parse(Buffer.from(frame.payload).toString('utf8')) as Record<string, unknown>+ this.sent.push(message)+ this.seqs.push(seq as number | undefined)}if (frame.type === CableType.Pet) this.petSlices.push(Buffer.from(frame.payload))})@@ -3043,6 +3047,59 @@ describe('hello capabilities', () => {})}+ it('numbers every frame to a Pro with seq, restarting at each welcome; a round dial gets none', async () => {+ const { session, port } = await connect(richHost())+ try {+ port.say({ ...PRO_HELLO })+ await vi.waitFor(() => expect(port.types()).toContain('notif.replace'))+ await session.turnDone('a1')+ expect(port.sent[0].t).toBe('welcome')+ expect(port.seqs).toEqual(port.seqs.map((_, i) => i)) // 0 on the welcome, then 1, 2, ... with no hole+ port.say({ ...PRO_HELLO }) // the keepalive hello: a new welcome, the count starts over+ await vi.waitFor(() => expect(port.sent.filter((m) => m.t === 'welcome')).toHaveLength(2))+ expect(port.seqs[port.sent.findLastIndex((m) => m.t === 'welcome')]).toBe(0)+ port.sent.length = 0+ port.seqs.length = 0+ port.say({ t: 'hello', product: 'harness', mac: 'cc:dd', hw: 'round' }) // another device, no board+ await vi.waitFor(() => expect(port.types()).toContain('notif.replace'))+ expect(port.seqs.every((q) => q === undefined)).toBe(true)+ } finally { await session.stop() }+ })++ it('advertises resync in the welcome of a Pro only', async () => {+ const { session, port } = await connect(richHost())+ try {+ port.say({ ...PRO_HELLO })+ await vi.waitFor(() => expect(ofType(port, 'welcome')).toHaveLength(1))+ expect(ofType(port, 'welcome')[0].features).toContain('resync')+ port.sent.length = 0+ port.say({ t: 'hello', product: 'harness', mac: 'cc:dd', hw: 'round' })+ await vi.waitFor(() => expect(ofType(port, 'welcome')).toHaveLength(1))+ expect(ofType(port, 'welcome')[0].features).not.toContain('resync')+ } finally { await session.stop() }+ })++ it('answers resync with machines, swarms, agents, notices and open questions, at most once per 2 s', async () => {+ const { session, port } = await connect(richHost())+ try {+ port.say({ ...PRO_HELLO })+ await vi.waitFor(() => expect(port.types()).toContain('notif.replace'))+ await session.question('a1', 'q1', [{ key: 'k', q: 'Ship it?', options: ['yes', 'no'] }])+ await session.question('a2', 'q2', [{ key: 'k', q: 'Closed?', options: ['yes'] }])+ await session.questionClose('a2', 'q2')+ port.sent.length = 0+ port.say({ t: 'resync' })+ await vi.waitFor(() => expect(port.types()).toContain('question'))+ const types = port.types()+ for (const t of ['machines.begin', 'swarms', 'agents.begin', 'agents.end', 'notif.replace']) expect(types).toContain(t)+ expect(ofType(port, 'question')).toMatchObject([{ agentId: 'a1', id: 'q1' }]) // the closed one is not resent+ port.sent.length = 0+ port.say({ t: 'resync' })+ await settle()+ expect(port.sent).toEqual([]) // inside the window+ } finally { await session.stop() }+ })+it('sends turn.stats only to a stats: turn-v1 device, and only when there is something to say', async () => {const { session, port } = await connect(richHost())try {diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex 28d3e4313..305b2aef9 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -605,6 +605,11 @@ export class CableSession {private playerLibraryKey = ''private playerLibraryAt = 0private swarmsTrimmedKey = ''+ /** `hello.board === 'pro'`: every JSON frame to it carries a `seq` (a USB loss on its path is silent, and a hole in+ * the count is how it notices). Per session: each welcome restarts it at 0. A round dial's frames stay as they were. */+ private seqOn = false+ private seq = 0+ private resyncAt = 0/** For the greeting's log line: which capabilities this hello named, or nothing. */private capabilitiesNamed(): string {@@ -615,6 +620,9 @@ export class CableSession {private resetCapabilities(): void {this.swarmMembers = this.longRecap = this.stepsActivity = this.statsTurn = this.playerCapable = false+ this.seqOn = false+ this.seq = 0+ this.resyncAt = 0this.playerOffset = this.playerRequest = 0this.playerLibraryKey = ''this.playerLibraryAt = 0@@ -1170,6 +1178,8 @@ export class CableSession {this.stepsActivity = str('activity') === 'steps-v1'this.statsTurn = str('stats') === 'turn-v1'this.playerCapable = str('player') === 'library-v1'+ this.seqOn = str('board') === 'pro'+ this.seq = 0const mac = str('mac') ?? ''// Rule 1: every greeting is answered, but only an unfamiliar dial gets the full state.await this.send({@@ -1189,6 +1199,8 @@ export class CableSession {'voice.draft','agents.refresh',...(this.playerCapable && this.host.playerLibrary ? ['player.library'] : []),+ // Only a Pro numbers its frames and asks for `resync`; a round dial's feature list stays as it was.+ ...(this.seqOn ? ['resync'] : []),...(this.host.form ? ['form'] : []),...(this.host.selectPassage ? ['selection'] : []),...(this.host.visit ? ['visit'] : []),@@ -1263,6 +1275,9 @@ export class CableSession {case 'swarms.list':await this.syncSwarms(true)return+ case 'resync':+ await this.resync()+ returncase 'swarm.select':// Not answered here: the window switches, its desk changes, and the new `swarms` and ring// pushes are the answer — the same shape as `machine.select`, minus the refusal, because the@@ -2250,7 +2265,8 @@ export class CableSession {private async send(msg: Message): Promise<boolean> {if (!this.link?.isOpen) return falsetry {- await this.put(this.link, encodeCableFrame(CableType.Json, Buffer.from(JSON.stringify(msg), 'utf8')))+ const framed = this.seqOn ? { ...msg, seq: this.seq++ } : msg+ await this.put(this.link, encodeCableFrame(CableType.Json, Buffer.from(JSON.stringify(framed), 'utf8')))return true} catch (err) {this.log(`cable: write failed (${(err as Error).message})`)@@ -2464,6 +2480,24 @@ export class CableSession {await this.replaceNotifications(this.host.listUnread())}+ /**+ * A Pro saw a hole in `seq` (or a frame that failed its CRC): resend what a lost frame could have carried. The attach+ * push minus the history replay, plus the open questions — a replayed `summary` is heavy, and a second burst on a link+ * that just dropped bytes is what the rate limit (once per 2 s, here and on the device) is there to avoid.+ */+ private async resync(): Promise<void> {+ const now = Date.now()+ if (now - this.resyncAt < 2_000) return+ this.resyncAt = now+ await this.syncMachines(true)+ await this.syncSwarms(true)+ await this.syncAgents(true)+ await this.replaceNotifications(this.host.listUnread())+ for (const { agentId, id, questions } of this.questionInbox.open()) {+ if (this.liveTurns.get(agentId) === 'question') await this.send({ t: 'question', agentId, ...this.whoIs(agentId), id, questions })+ }+ }+// ── swarms ────────────────────────────────────────────────────────────────────────────────────────private lastSwarmsKey = ''diff --git a/cli/src/cable/questionInbox.ts b/cli/src/cable/questionInbox.tsindex 7cec062ae..0994af627 100644--- a/cli/src/cable/questionInbox.ts+++ b/cli/src/cable/questionInbox.ts@@ -53,6 +53,11 @@ export class QuestionInbox {this.entries.set(agentId, { agentId, id, token: randomUUID(), signature, questions, drafts: new Map() })}+ /** Every question still open, for a resync. */+ open(): Array<{ agentId: string; id: string; questions: ReviewQuestion[] }> {+ return [...this.entries.values()].map(({ agentId, id, questions }) => ({ agentId, id, questions }))+ }+close(agentId: string, id: string): boolean {const current = this.latestIds.get(agentId)if (current !== undefined && current !== id) return falsediff --git a/devices/harness-pro/docs/cable.md b/devices/harness-pro/docs/cable.mdindex ef67882ea..dc757e602 100644--- a/devices/harness-pro/docs/cable.md+++ b/devices/harness-pro/docs/cable.md@@ -132,3 +132,27 @@ The Pro does use: `welcome`, `ping`, `agents.*`, `agent.updated`, `machines.*`,changes behavior before porting `latestUpdate` (see the Player activity row).Firmware offers: a hello with `board:"pro"` gets no `fw.offer` (no manifest lookup, no transfer) until the Pro has its own OTA channel; a hello without `board` is offered as before.++## 7. Losing bytes on the USB path: `seq` and `resync`++The Pro's USB-Serial/JTAG path loses bytes host to device, each loss under one 64-byte packet. A small frame+(`ping`, `turn.done`, `focus`, `question.close`...) can vanish whole and nothing notices. Three layers catch it:++- **Count below the driver.** The firmware carries a copy of ESP-IDF 5.5.4's `esp_driver_usb_serial_jtag`+ (`firmware/components/`) with two atomic counters; the `alive` heartbeat prints `isr_rx` (bytes the ISR pulled from+ the hardware FIFO) and `ring_drop` (ring-buffer pushes that failed). If `isr_rx` is short of what the daemon wrote,+ the loss is on the wire; if `ring_drop` moves, the reader is too slow.+- **Partial frames.** A frame that stops arriving mid-way (its tail lost) is dropped after 300 ms of silence, counted as+ corrupt and resynced at once, so the next frame is not swallowed by its pending length.+- **`seq`.** The daemon adds an integer `seq` to every JSON frame it sends to a device whose hello says `board:"pro"`.+ Each `welcome` restarts the count at 0 (the welcome itself carries `seq:0`), so a keepalive hello restarts it too.+ Round dials get no `seq`: their frames are byte-identical to before. The Pro takes the first `seq` of a session as+ the base and expects each next one to be exactly +1; anything else is a gap (a frame was lost) and counts in+ `seq_gaps` on the heartbeat. A frame without `seq` (an older daemon) is not checked.++A gap, or a frame that failed its CRC, makes the Pro send `{t:"resync"}`, at most once per 2 s (and not during a+firmware transfer, which has its own resend). The daemon answers with a full snapshot, also rate-limited to once per+2 s: `machines.*`, `swarms`, `agents.*`, `notif.replace` (the notices, including question rows), and a `question`+frame for each question still open. It does not replay recent `summary` history (the attach push does); a lost+`summary` is not repaired by a resync. The welcome of a Pro lists `resync` in `features`; a Pro whose welcome does not (an older daemon) sends the old+`swarms.list` and `agents.list` instead. A welcome without `seq` turns the gap check off for that session.diff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/CMakeLists.txt b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/CMakeLists.txtnew file mode 100644index 000000000..ca7b6a30c--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/CMakeLists.txt@@ -0,0 +1,34 @@+idf_build_get_property(target IDF_TARGET)++set(srcs)+set(include "include")++# USB Serial JTAG related source files+if(CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED)+ list(APPEND srcs "src/usb_serial_jtag.c"+ "src/usb_serial_jtag_connection_monitor.c")+endif()++if(${target} STREQUAL "linux")+ set(priv_requires esp_ringbuf esp_timer)+else()+ set(priv_requires esp_driver_gpio esp_ringbuf esp_pm esp_timer)+endif()++idf_component_register(SRCS ${srcs}+ INCLUDE_DIRS ${include}+ PRIV_REQUIRES "${priv_requires}"+ LDFRAGMENTS "linker.lf"+ )++if(CONFIG_VFS_SUPPORT_IO AND CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED)+ target_link_libraries(${COMPONENT_LIB} PUBLIC idf::vfs)+ target_sources(${COMPONENT_LIB} PRIVATE "src/usb_serial_jtag_vfs.c")+ target_link_libraries(${COMPONENT_LIB} INTERFACE "-u usb_serial_jtag_vfs_include_dev_init")+endif()++# If system needs to monitor USJ connection status, then usb_serial_jtag_connection_monitor object file has to be linked+# to the binary, to allow tick hook to be registered+if(CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION OR CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED)+ target_link_libraries(${COMPONENT_LIB} INTERFACE "-u usb_serial_jtag_connection_monitor_include")+endif()diff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/Kconfig b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/Kconfignew file mode 100644index 000000000..48bb15bcc--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/Kconfig@@ -0,0 +1,28 @@+menu "ESP-Driver:USB Serial/JTAG Configuration"+ depends on SOC_USB_SERIAL_JTAG_SUPPORTED++ config USJ_ENABLE_USB_SERIAL_JTAG+ bool "Enable USB-Serial-JTAG Module"+ default y+ help+ The USB-Serial-JTAG module on ESP chips is turned on by default after power-on.+ If your application does not need it and not rely on it to be used as system+ console or use the built-in JTAG for debugging, you can disable this option,+ then the clock of this module will be disabled at startup, which will save+ some power consumption.++ config USJ_NO_AUTO_LS_ON_CONNECTION+ bool "Don't enter the automatic light sleep when USB Serial/JTAG port is connected"+ depends on PM_ENABLE && ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED && !SOC_USB_SERIAL_JTAG_SUPPORT_LIGHT_SLEEP \+ && USJ_ENABLE_USB_SERIAL_JTAG+ default n+ help+ If enabled, the chip will constantly monitor the connection status of the USB Serial/JTAG port. As long+ as the USB Serial/JTAG is connected, a ESP_PM_NO_LIGHT_SLEEP power management lock will be acquired to+ prevent the system from entering light sleep.+ This option can be useful if serial monitoring is needed via USB Serial/JTAG while power management is+ enabled, as the USB Serial/JTAG cannot work under light sleep and after waking up from light sleep.+ Note. This option can only control the automatic Light-Sleep behavior. If esp_light_sleep_start() is+ called manually from the program, enabling this option will not prevent light sleep entry even if the+ USB Serial/JTAG is in use.+endmenu # USB Serial/JTAG Configurationdiff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/README.md b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/README.mdnew file mode 100644index 000000000..3a3b9c7af--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/README.md@@ -0,0 +1,6 @@+# esp_driver_usb_serial_jtag (project override)++A copy of ESP-IDF 5.5.4's `components/esp_driver_usb_serial_jtag` (Apache-2.0, Espressif headers kept; `test_apps/`+dropped). A project component of the same name replaces the IDF one. The only change is two atomic RX counters in the+ISR and `usb_serial_jtag_rx_stats()`: bytes pulled from the hardware FIFO, and ring-buffer pushes that failed. They+tell a loss below the driver (USB) from a loss above it (ring full, framing). Re-copy from IDF when the IDF version moves.diff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/esp_private/usb_serial_jtag_vfs.h b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/esp_private/usb_serial_jtag_vfs.hnew file mode 100644index 000000000..441544761--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/esp_private/usb_serial_jtag_vfs.h@@ -0,0 +1,27 @@+/*+ * SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD+ *+ * SPDX-License-Identifier: Apache-2.0+ */++#pragma once++#include "esp_vfs.h"++#ifdef __cplusplus+extern "C" {+#endif++/**+ * @brief get pointer of usb_serial_jtag vfs.+ *+ * This function is called in vfs_console in order to get the vfs implementation+ * of usb_serial_jtag.+ *+ * @return pointer to structure esp_vfs_t+ */+const esp_vfs_fs_ops_t *esp_vfs_usb_serial_jtag_get_vfs(void);++#ifdef __cplusplus+}+#endifdiff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag.h b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag.hnew file mode 100644index 000000000..ce85ba803--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag.h@@ -0,0 +1,125 @@+/*+ * SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD+ *+ * SPDX-License-Identifier: Apache-2.0+ */++#pragma once++#include "esp_err.h"+#include "freertos/FreeRTOS.h"+#include "freertos/semphr.h"++#ifdef __cplusplus+extern "C" {+#endif++/**+ * @brief Configuration structure for the usb-serial-jtag-driver. Can be expanded in the future+ *+ * @note tx_buffer_size and rx_buffer_size must be > 0+ */+typedef struct {+ uint32_t tx_buffer_size; /* Size of the buffer (in bytes) for the TX direction */+ uint32_t rx_buffer_size; /* Size of the buffer (in bytes) for the RX direction */+} usb_serial_jtag_driver_config_t;++#define USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT() (usb_serial_jtag_driver_config_t) {\+ .tx_buffer_size = 256,\+ .rx_buffer_size = 256,\+}++/**+ * @brief Install USB-SERIAL-JTAG driver and set the USB-SERIAL-JTAG to the default configuration.+ *+ * USB-SERIAL-JTAG driver's ISR will be attached to the same CPU core that calls this function. Thus, users+ * should ensure that the same core is used when calling `usb_serial_jtag_driver_uninstall()`.+ *+ * @note Blocking mode will result in usb_serial_jtag_write_bytes() blocking for a+ * short period if the TX FIFO if full. It will not block again until the buffer+ * has some space available again.+ *+ * @param usb_serial_jtag_driver_config_t Configuration for usb_serial_jtag driver.+ *+ * @return+ * - ESP_OK Success+ * - ESP_FAIL Failed for some reason.+ */+esp_err_t usb_serial_jtag_driver_install(usb_serial_jtag_driver_config_t *usb_serial_jtag_config);++/**+ * @brief USB_SERIAL_JTAG read bytes from USB_SERIAL_JTAG buffer+ *+ * @param buf pointer to the buffer.+ * @param length data length+ * @param ticks_to_wait Timeout in RTOS ticks+ *+ * @return+ * - The number of bytes read from USB_SERIAL FIFO+ */+int usb_serial_jtag_read_bytes(void* buf, uint32_t length, TickType_t ticks_to_wait);++/**+ * @brief Send data to the USB-UART port from a given buffer and length,+ *+ * Please ensure the `tx_buffer_size is larger than 0`, if the 'tx_buffer_size' > 0, this function will return after copying all the data to tx ring buffer,+ * USB_SERIAL_JTAG ISR will then move data from the ring buffer to TX FIFO gradually.+ *+ * @param src data buffer address+ * @param size data length to send+ * @param ticks_to_wait Maximum timeout in RTOS ticks+ *+ * @return+ * - The number of bytes pushed to the TX FIFO+ */+int usb_serial_jtag_write_bytes(const void* src, size_t size, TickType_t ticks_to_wait);++/**+ * @brief Blocks until all data written using `usb_serial_jtag_write_bytes` is sent to the host, or until timeout.+ *+ * @param ticks_to_wait Maximum timeout in RTOS ticks+ *+ * @return ESP_OK when flushed, ESP_ERR_TIMEOUT on timeout.+ */+esp_err_t usb_serial_jtag_wait_tx_done(TickType_t ticks_to_wait);++/**+ * @brief Uninstall USB-SERIAL-JTAG driver.+ *+ * @return+ * - ESP_OK Success+ */+esp_err_t usb_serial_jtag_driver_uninstall(void);++/**+ * @brief Check if the USB Serial/JTAG port is connected to the host+ *+ * This function checks whether the USB Serial/JTAG (USJ) port is currently connected. USJ is considered "connected"+ * so long as it is receiving SOF packets from the host, even if there is no serial communications occurring (i.e., the+ * USJ is connected to the PC, but the serial port is not opened). Having the USB port connected to a power bank will+ * never be considered as connected (due to the lack of SOF packets).+ *+ * @note If your application needs this function, it will add some extra overhead time to every freertos tick.+ *+ * @return True if USJ is connected, false otherwise+ */+bool usb_serial_jtag_is_connected(void);++/**+ * @brief Get information whether the USB serial JTAG driver is installed or not+ *+ * @return True if driver is installed and False if driver not installed+ */+bool usb_serial_jtag_is_driver_installed(void);++/**+ * @brief Harness Pro addition: cumulative RX counters, since boot+ *+ * @param isr_bytes bytes the ISR read from the hardware FIFO (below the ring buffer)+ * @param ring_drops ring-buffer pushes that failed in the ISR (those bytes are lost); NULL to skip either+ */+void usb_serial_jtag_rx_stats(uint32_t *isr_bytes, uint32_t *ring_drops);++#ifdef __cplusplus+}+#endifdiff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag_select.h b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag_select.hnew file mode 100644index 000000000..4c3e36d9c--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag_select.h@@ -0,0 +1,53 @@++/*+ * SPDX-FileCopyrightText: 2024-2025 Espressif Systems (Shanghai) CO LTD+ *+ * SPDX-License-Identifier: Apache-2.0+ */++#pragma once++#ifdef __cplusplus+extern "C" {+#endif++#include "driver/usb_serial_jtag.h"++typedef enum {+ USJ_SELECT_READ_NOTIF,+ USJ_SELECT_WRITE_NOTIF,+ USJ_SELECT_ERROR_NOTIF,+} usj_select_notif_t;++typedef void (*usj_select_notif_callback_t)(usj_select_notif_t usb_serial_jtag_select_notif, BaseType_t *task_woken);++/**+ * @brief Set notification callback function for select() events+ * @param usb_serial_jtag_select_notif_callback callback function+ */+void usb_serial_jtag_set_select_notif_callback(usj_select_notif_callback_t usb_serial_jtag_select_notif_callback);++/**+ * @brief Return the number of bytes available for reading+ *+ * @return the number of bytes available for reading in the buffer+ */+size_t usb_serial_jtag_get_read_bytes_available(void);++/**+ * @brief Return the readiness status of the driver for read operation+ *+ * @return true if driver read ready, false if not+ */+bool usb_serial_jtag_read_ready(void);++/**+ * @brief Return the readiness status of the driver for write operation+ *+ * @return true if driver is write ready, false if not+ */+bool usb_serial_jtag_write_ready(void);++#ifdef __cplusplus+}+#endifdiff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag_vfs.h b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag_vfs.hnew file mode 100644index 000000000..c5a790ee4--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag_vfs.h@@ -0,0 +1,72 @@+/*+ * SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD+ *+ * SPDX-License-Identifier: Apache-2.0+ */++#pragma once++#include "esp_err.h"+#include "esp_vfs.h"+#include "esp_vfs_common.h"++#ifdef __cplusplus+extern "C" {+#endif++/**+ * @brief add /dev/usbserjtag virtual filesystem driver+ *+ * This function is called from startup code to enable console output+ */+esp_err_t usb_serial_jtag_vfs_register(void);++/**+ * @brief Set the line endings expected to be received+ *+ * This specifies the conversion between line endings received and+ * newlines ('\n', LF) passed into stdin:+ *+ * - ESP_LINE_ENDINGS_CRLF: convert CRLF to LF+ * - ESP_LINE_ENDINGS_CR: convert CR to LF+ * - ESP_LINE_ENDINGS_LF: no modification+ *+ * @note this function is not thread safe w.r.t. reading+ *+ * @param mode line endings expected+ */+void usb_serial_jtag_vfs_set_rx_line_endings(esp_line_endings_t mode);++/**+ * @brief Set the line endings to sent+ *+ * This specifies the conversion between newlines ('\n', LF) on stdout and line+ * endings sent:+ *+ * - ESP_LINE_ENDINGS_CRLF: convert LF to CRLF+ * - ESP_LINE_ENDINGS_CR: convert LF to CR+ * - ESP_LINE_ENDINGS_LF: no modification+ *+ * @note this function is not thread safe w.r.t. writing+ *+ * @param mode line endings to send+ */+void usb_serial_jtag_vfs_set_tx_line_endings(esp_line_endings_t mode);++/**+ * @brief set VFS to use USB-SERIAL-JTAG driver for reading and writing+ * @note application must configure USB-SERIAL-JTAG driver before calling these functions+ * With these functions, read and write are blocking and interrupt-driven.+ */+void usb_serial_jtag_vfs_use_driver(void);++/**+ * @brief set VFS to use simple functions for reading and writing UART+ * Read is non-blocking, write is busy waiting until TX FIFO has enough space.+ * These functions are used by default.+ */+void usb_serial_jtag_vfs_use_nonblocking(void);++#ifdef __cplusplus+}+#endifdiff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/linker.lf b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/linker.lfnew file mode 100644index 000000000..5908799cb--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/linker.lf@@ -0,0 +1,5 @@+[mapping:usb_serial_jtag_vfs]+archive: libesp_driver_usb_serial_jtag.a+entries:+ if VFS_SELECT_IN_RAM = y && SOC_USB_SERIAL_JTAG_SUPPORTED = y:+ usb_serial_jtag_vfs: select_notif_callback_isr (noflash)diff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag.c b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag.cnew file mode 100644index 000000000..963da6bf8--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag.c@@ -0,0 +1,404 @@+/*+ * SPDX-FileCopyrightText: 2021-2025 Espressif Systems (Shanghai) CO LTD+ *+ * SPDX-License-Identifier: Apache-2.0+ */++#include <string.h>+#include <stdbool.h>+#include <stdatomic.h>+#include "esp_log.h"+#include "hal/usb_serial_jtag_ll.h"+#include "freertos/FreeRTOS.h"+#include "freertos/semphr.h"+#include "freertos/ringbuf.h"+#include "esp_intr_alloc.h"+#include "driver/usb_serial_jtag.h"+#include "driver/usb_serial_jtag_select.h"+#include "soc/periph_defs.h"+#include "soc/soc_caps.h"+#include "esp_check.h"+#include "esp_private/periph_ctrl.h"++/*+ Note: Before you add a workaround for an issue in this driver, please please try+ to figure out the actual root cause first. The USB-serial-JTAG is a simple device,+ it shouldn't need anything more than a simple, straightforward driver.+*/++#if !SOC_RCC_IS_INDEPENDENT+#define USJ_RCC_ATOMIC() PERIPH_RCC_ATOMIC()+#else+#define USJ_RCC_ATOMIC()+#endif++// The hardware buffer max size is 64, both for RX and TX.+#define USB_SER_JTAG_ENDP_SIZE (64)+#define USB_SER_JTAG_RX_MAX_SIZE (USB_SER_JTAG_ENDP_SIZE)++typedef struct {+ intr_handle_t intr_handle; /*!< USB-SERIAL-JTAG interrupt handler */++ // RX parameters+ RingbufHandle_t rx_ring_buf; /*!< RX ring buffer handler */++ // TX parameters+ RingbufHandle_t tx_ring_buf; /*!< TX ring buffer handler */+ uint8_t tx_stash_buf[USB_SER_JTAG_ENDP_SIZE]; /*!< Data buffer to stash TX FIFO data */+ size_t tx_stash_cnt; /*!< Number of stashed TX FIFO bytes */++ //Synchronization stuff, only used for flush for now+ SemaphoreHandle_t tx_mux;+ SemaphoreHandle_t tx_idle_sem;++ usj_select_notif_callback_t usj_select_notif_callback; /*!< Notification about select() events */+} usb_serial_jtag_obj_t;++static usb_serial_jtag_obj_t *p_usb_serial_jtag_obj = NULL;++// Harness Pro: bytes the ISR pulled from the hardware FIFO and ring-buffer pushes that failed (the bytes are then gone).+static atomic_uint s_isr_rx_bytes, s_ring_drops;++void usb_serial_jtag_rx_stats(uint32_t *isr_bytes, uint32_t *ring_drops)+{+ if (isr_bytes) *isr_bytes = atomic_load_explicit(&s_isr_rx_bytes, memory_order_relaxed);+ if (ring_drops) *ring_drops = atomic_load_explicit(&s_ring_drops, memory_order_relaxed);+}++static const char* USB_SERIAL_JTAG_TAG = "usb_serial_jtag";++static void usb_serial_jtag_isr_handler_default(void *arg)+{+ BaseType_t xTaskWoken = 0;+ uint32_t usbjtag_intr_status = 0;+ usbjtag_intr_status = usb_serial_jtag_ll_get_intsts_mask();++ if (usbjtag_intr_status & USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY) {+ //Clear interrupt so we won't be called until the next transfer finishes.+ usb_serial_jtag_ll_clr_intsts_mask(USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY);++ // Interrupt tells us the host picked up the data we sent.+ // If we have more data, we can put it in the buffer and the host will pick that up next.+ // We expect the TX FIFO to be writable for this. If it's not, somehow someone else+ // (ROM print routines?) have snuck in a full buffer before we got here. In that case,+ // we simply ignore the interrupt, a new one will come if the buffer is empty again.+ if (usb_serial_jtag_ll_txfifo_writable() == 1) {+ // Retrieve data from either the stash buffer or, if that's empty, from the ring buffer.+ size_t queued_size;+ uint8_t *queued_buf = NULL;+ if (p_usb_serial_jtag_obj->tx_stash_cnt != 0) {+ // Send stashed tx bytes before reading bytes from ring buffer+ queued_buf = p_usb_serial_jtag_obj->tx_stash_buf;+ queued_size = p_usb_serial_jtag_obj->tx_stash_cnt;+ } else {+ // Max 64 data payload size in a single EndPoint+ queued_buf = (uint8_t *)xRingbufferReceiveUpToFromISR(p_usb_serial_jtag_obj->tx_ring_buf, &queued_size, USB_SER_JTAG_ENDP_SIZE);+ }++ if (queued_buf != NULL && queued_size > 0) {+ // We have some data to send. Send it.+ uint32_t sent_size = usb_serial_jtag_ll_write_txfifo(queued_buf, queued_size);+ usb_serial_jtag_ll_txfifo_flush();++ // Check if we were able to send everything.+ if (sent_size < queued_size) {+ // Not all bytes could be sent at once; stash the unwritten bytes in a buffer+ // This will happen if e.g. the rom output functions manage to sneak a few bytes into the+ // TX FIFO before this interrupt triggers. Note stash_size will not larger than+ // USB_SER_JTAG_ENDP_SIZE because queued_size is obtained from xRingbufferReceiveUpToFromISR.+ size_t stash_size = queued_size - sent_size;+ memcpy(p_usb_serial_jtag_obj->tx_stash_buf, &queued_buf[sent_size], stash_size);+ p_usb_serial_jtag_obj->tx_stash_cnt = stash_size;+ } else {+ p_usb_serial_jtag_obj->tx_stash_cnt = 0;+ }+ // Return the buffer if we got it from the ring buffer.+ if (queued_buf != p_usb_serial_jtag_obj->tx_stash_buf) {+ vRingbufferReturnItemFromISR(p_usb_serial_jtag_obj->tx_ring_buf, queued_buf, &xTaskWoken);++ // We just moved items out of the TX ring buffer, the driver is considered write ready, since+ // the TX ring buffer is assured to be not full.+ if (p_usb_serial_jtag_obj->usj_select_notif_callback) {+ p_usb_serial_jtag_obj->usj_select_notif_callback(USJ_SELECT_WRITE_NOTIF, &xTaskWoken);+ }+ }+ } else {+ // No data to send.+ // The last transmit may have sent a full EP worth of data. The host will interpret+ // this as a transaction that hasn't finished yet and keep the data in its internal+ // buffers rather than releasing it to the program listening on the CDC serial port.+ // We need to flush again in order to send a 0-byte packet that ends the transaction.+ usb_serial_jtag_ll_txfifo_flush();++ // We will also disable the interrupt as for now there's no need to handle the+ // TX interrupt again. We'll re-enable this externally if we need data sent.+ usb_serial_jtag_ll_disable_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY);++ // Technically something could have been pushed into the ringbuffer between us checking+ // here and us disabling the interrupt. That would mean that data would not be+ // transmitted anymore. Check for that case.+ UBaseType_t bytes_waiting;+ vRingbufferGetInfo(p_usb_serial_jtag_obj->tx_ring_buf, NULL, NULL, NULL, NULL, &bytes_waiting);+ if (bytes_waiting) {+ // Uh-oh, it happened. Re-enable interrupts so we can process the data the next run.+ usb_serial_jtag_ll_ena_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY);+ } else {+ //Nope, still nothing. Mark tx as idle.+ xSemaphoreGiveFromISR(p_usb_serial_jtag_obj->tx_idle_sem, &xTaskWoken);+ }+ }+ }+ }++ if (usbjtag_intr_status & USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT) {+ // Acknowledge interrupt+ usb_serial_jtag_ll_clr_intsts_mask(USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT);+ // Read RX FIFO and send available data to ringbuffer.+ uint8_t buf[USB_SER_JTAG_RX_MAX_SIZE];+ uint32_t rx_fifo_len = usb_serial_jtag_ll_read_rxfifo(buf, USB_SER_JTAG_RX_MAX_SIZE);+ atomic_fetch_add_explicit(&s_isr_rx_bytes, rx_fifo_len, memory_order_relaxed);+ if (xRingbufferSendFromISR(p_usb_serial_jtag_obj->rx_ring_buf, buf, rx_fifo_len, &xTaskWoken) != pdTRUE) {+ atomic_fetch_add_explicit(&s_ring_drops, 1, memory_order_relaxed);+ }++ if (p_usb_serial_jtag_obj->usj_select_notif_callback) {+ p_usb_serial_jtag_obj->usj_select_notif_callback(USJ_SELECT_READ_NOTIF, &xTaskWoken);+ }+ }++ if (xTaskWoken == pdTRUE) {+ portYIELD_FROM_ISR();+ }+}++esp_err_t usb_serial_jtag_driver_install(usb_serial_jtag_driver_config_t *usb_serial_jtag_config)+{+ esp_err_t err = ESP_OK;+ ESP_RETURN_ON_FALSE((p_usb_serial_jtag_obj == NULL), ESP_ERR_INVALID_STATE, USB_SERIAL_JTAG_TAG, "Driver already installed");+ ESP_RETURN_ON_FALSE((usb_serial_jtag_config->rx_buffer_size > 0), ESP_ERR_INVALID_ARG, USB_SERIAL_JTAG_TAG, "RX buffer is not prepared");+ ESP_RETURN_ON_FALSE((usb_serial_jtag_config->rx_buffer_size > USB_SER_JTAG_RX_MAX_SIZE), ESP_ERR_INVALID_ARG, USB_SERIAL_JTAG_TAG, "RX buffer prepared is so small, should larger than 64");+ ESP_RETURN_ON_FALSE((usb_serial_jtag_config->tx_buffer_size > 0), ESP_ERR_INVALID_ARG, USB_SERIAL_JTAG_TAG, "TX buffer is not prepared");+ p_usb_serial_jtag_obj = (usb_serial_jtag_obj_t*) heap_caps_calloc(1, sizeof(usb_serial_jtag_obj_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);+ if (p_usb_serial_jtag_obj == NULL) {+ ESP_LOGE(USB_SERIAL_JTAG_TAG, "memory allocate error");+ // no `goto _exit` here as there's nothing to clean up and that would make the uninstall+ // routine unhappy.+ return ESP_ERR_NO_MEM;+ }+ p_usb_serial_jtag_obj->tx_stash_cnt = 0;++ p_usb_serial_jtag_obj->rx_ring_buf = xRingbufferCreate(usb_serial_jtag_config->rx_buffer_size, RINGBUF_TYPE_BYTEBUF);+ if (p_usb_serial_jtag_obj->rx_ring_buf == NULL) {+ ESP_LOGE(USB_SERIAL_JTAG_TAG, "ringbuffer create error");+ err = ESP_ERR_NO_MEM;+ goto _exit;+ }++ p_usb_serial_jtag_obj->tx_ring_buf = xRingbufferCreate(usb_serial_jtag_config->tx_buffer_size, RINGBUF_TYPE_BYTEBUF);+ if (p_usb_serial_jtag_obj->tx_ring_buf == NULL) {+ ESP_LOGE(USB_SERIAL_JTAG_TAG, "ringbuffer create error");+ err = ESP_ERR_NO_MEM;+ goto _exit;+ }++ p_usb_serial_jtag_obj->tx_mux = xSemaphoreCreateMutex();+ if (p_usb_serial_jtag_obj->tx_mux == NULL) {+ ESP_LOGE(USB_SERIAL_JTAG_TAG, "tx_mux create error");+ err = ESP_ERR_NO_MEM;+ goto _exit;+ }++ p_usb_serial_jtag_obj->tx_idle_sem = xSemaphoreCreateBinary();+ if (p_usb_serial_jtag_obj->tx_idle_sem == NULL) {+ ESP_LOGE(USB_SERIAL_JTAG_TAG, "tx_idle_sem create error");+ err = ESP_ERR_NO_MEM;+ goto _exit;+ }++ // Enable USB-Serial-JTAG peripheral module clock+ USJ_RCC_ATOMIC() {+ usb_serial_jtag_ll_enable_bus_clock(true);+ }++ // Configure PHY+#if USB_SERIAL_JTAG_LL_EXT_PHY_SUPPORTED+ usb_serial_jtag_ll_phy_enable_external(false); // Use internal PHY+ usb_serial_jtag_ll_phy_enable_pad(true); // Enable USB PHY pads+#else // USB_SERIAL_JTAG_LL_EXT_PHY_SUPPORTED+ usb_serial_jtag_ll_phy_set_defaults(); // External PHY not supported. Set default values.+#endif // USB_WRAP_LL_EXT_PHY_SUPPORTED++ // Note: DO NOT clear the interrupt status bits here. The output routine needs+ // USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY set because it needs the ISR to trigger+ // as soon as data is sent; the input routine needs the status to retrieve any+ // data that is still in the FIFOs.++ // We only enable the RX interrupt; we'll enable the TX one when we actually+ // have anything to send.+ usb_serial_jtag_ll_ena_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT);++ //Assume tx is idle; if any we have nothing in the ringbuffer so this is probably true.+ xSemaphoreGive(p_usb_serial_jtag_obj->tx_idle_sem);++ err = esp_intr_alloc(ETS_USB_SERIAL_JTAG_INTR_SOURCE, 0, usb_serial_jtag_isr_handler_default, NULL, &p_usb_serial_jtag_obj->intr_handle);+ if (err != ESP_OK) {+ goto _exit;+ }+ return ESP_OK;++_exit:+ usb_serial_jtag_driver_uninstall();+ return err;+}++int usb_serial_jtag_read_bytes(void* buf, uint32_t length, TickType_t ticks_to_wait)+{+ uint8_t *data = NULL;+ size_t data_read_len = 0;++ if (length == 0) {+ return 0;+ }++ // Receive new data from ISR+ data = (uint8_t*) xRingbufferReceiveUpTo(p_usb_serial_jtag_obj->rx_ring_buf, &data_read_len, (TickType_t) ticks_to_wait, length);+ if (data == NULL) {+ // If there is no data received from ringbuffer, return 0 directly.+ return 0;+ }++ memcpy((uint8_t*)buf, data, data_read_len);+ vRingbufferReturnItem(p_usb_serial_jtag_obj->rx_ring_buf, data);+ data = NULL;++ return data_read_len;+}++int usb_serial_jtag_write_bytes(const void* src, size_t size, TickType_t ticks_to_wait)+{+ ESP_RETURN_ON_FALSE(src && size, 0, USB_SERIAL_JTAG_TAG, "invalid buffer or size");+ ESP_RETURN_ON_FALSE(p_usb_serial_jtag_obj != NULL, 0, USB_SERIAL_JTAG_TAG, "driver is not initialized yet");++ //This will block when something else is waiting in wait_tx_done, making sure we don't add data to the ringbuffer.+ //Note that the ringbuffer itself is thread-safe, so this is only needed to handle wait_tx_done.+ BaseType_t result = xSemaphoreTake(p_usb_serial_jtag_obj->tx_mux, ticks_to_wait);+ if (result == pdFALSE) {+ return 0;+ }++ //Mark TX as not idle so flush function knows to wait. Note we don't care if it was already not idle, so no+ //timeout and we don't check if this succeeds; we just want to make sure the semaphore is taken.+ xSemaphoreTake(p_usb_serial_jtag_obj->tx_idle_sem, 0);++ result = xRingbufferSend(p_usb_serial_jtag_obj->tx_ring_buf, (void*)src, size, ticks_to_wait);+ // Re-enable the TX interrupt. If this was disabled, this will immediately trigger the ISR+ // and send the things we just put in the ringbuffer. Note that even though this is a+ // read-modify-write operation on the interrupt enable register that could happen at the+ // same point the ISR does a read-modify-write to disable the interrupt,+ usb_serial_jtag_ll_ena_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY);+ xSemaphoreGive(p_usb_serial_jtag_obj->tx_mux);+ return (result == pdFALSE) ? 0 : size;+}++esp_err_t usb_serial_jtag_wait_tx_done(TickType_t ticks_to_wait)+{+ int r;+ TimeOut_t timeout;+ vTaskSetTimeOutState(&timeout);+ // Make sure write_bytes blocks so nothing is added to the ringbuffer.+ // Note that this can time out (e.g. blocked ringbuffer while writing)+ r = xSemaphoreTake(p_usb_serial_jtag_obj->tx_mux, ticks_to_wait);+ if (r) {+ // Adjust timeout to compensate for the time we waited for tx_mux. Note xTaskCheckForTimeOut+ // changes ticks_to_wait accordingly.+ if (xTaskCheckForTimeOut(&timeout, &ticks_to_wait)) {+ // if this triggers, we timed out: we got tx_mux at the exact time of the timeout? Probably+ // never happens, but handle correctly anyway.+ ticks_to_wait = 0;+ }+ // Check if we're idle or wait until we are (or time out)+ r = xSemaphoreTake(p_usb_serial_jtag_obj->tx_idle_sem, ticks_to_wait);+ if (r) {+ // We could take the semaphore, meaning tx is done now. Immediately give it again so+ // the next run of usb_serial_jtag_wait_tx_done also succeeds.+ xSemaphoreGive(p_usb_serial_jtag_obj->tx_idle_sem);+ }+ // Re-allow writes.+ xSemaphoreGive(p_usb_serial_jtag_obj->tx_mux);+ }+ return r ? ESP_OK : ESP_ERR_TIMEOUT;+}++//Note that this is also called when usb_serial_jtag_driver_install errors out and as such should+//work on a half-initialized driver as well.+esp_err_t usb_serial_jtag_driver_uninstall(void)+{+ if (p_usb_serial_jtag_obj == NULL) {+ ESP_LOGE(USB_SERIAL_JTAG_TAG, "uninstall without install called");+ return ESP_OK;+ }++ /* Don't disable the module clock and usb_pad_enable here since the USJ stdout might still depends on it. */++ usb_serial_jtag_ll_disable_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY | USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT);+ if (p_usb_serial_jtag_obj->intr_handle) {+ esp_intr_free(p_usb_serial_jtag_obj->intr_handle);+ }++ if (p_usb_serial_jtag_obj->rx_ring_buf) {+ vRingbufferDelete(p_usb_serial_jtag_obj->rx_ring_buf);+ p_usb_serial_jtag_obj->rx_ring_buf = NULL;+ }+ if (p_usb_serial_jtag_obj->tx_ring_buf) {+ vRingbufferDelete(p_usb_serial_jtag_obj->tx_ring_buf);+ p_usb_serial_jtag_obj->tx_ring_buf = NULL;+ }+ if (p_usb_serial_jtag_obj->tx_idle_sem) {+ vSemaphoreDelete(p_usb_serial_jtag_obj->tx_idle_sem);+ p_usb_serial_jtag_obj->tx_idle_sem = NULL;+ }+ if (p_usb_serial_jtag_obj->tx_mux) {+ vSemaphoreDelete(p_usb_serial_jtag_obj->tx_mux);+ p_usb_serial_jtag_obj->tx_mux = NULL;+ }+ heap_caps_free(p_usb_serial_jtag_obj);+ p_usb_serial_jtag_obj = NULL;+ return ESP_OK;+}++bool usb_serial_jtag_is_driver_installed(void)+{+ return (p_usb_serial_jtag_obj != NULL);+}++void usb_serial_jtag_set_select_notif_callback(usj_select_notif_callback_t usj_select_notif_callback)+{+ if (usb_serial_jtag_is_driver_installed()) {+ p_usb_serial_jtag_obj->usj_select_notif_callback = usj_select_notif_callback;+ }+}++size_t usb_serial_jtag_get_read_bytes_available(void)+{+ // sign the the driver is read ready is that data is waiting in the RX ringbuffer+ UBaseType_t bytes_available = 0;+ if (usb_serial_jtag_is_driver_installed()) {+ vRingbufferGetInfo(p_usb_serial_jtag_obj->rx_ring_buf, NULL, NULL, NULL, NULL, &bytes_available);+ if (bytes_available <= 0) {+ return 0;+ }+ }++ return (size_t)bytes_available;+}++bool usb_serial_jtag_read_ready(void)+{+ return usb_serial_jtag_get_read_bytes_available() != 0;+}++bool usb_serial_jtag_write_ready(void)+{+ // sign that the driver is write ready is that the TX ring buffer is not full+ return (xRingbufferGetCurFreeSize(p_usb_serial_jtag_obj->tx_ring_buf) > 0);+}diff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_connection_monitor.c b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_connection_monitor.cnew file mode 100644index 000000000..a730a636c--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_connection_monitor.c@@ -0,0 +1,95 @@+/*+ * SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD+ *+ * SPDX-License-Identifier: Apache-2.0+ */++#include <stdbool.h>+#include "driver/usb_serial_jtag.h"+#include "hal/usb_serial_jtag_ll.h"+#include "esp_private/startup_internal.h"+#include "esp_freertos_hooks.h"+#include "esp_pm.h"+#include "esp_private/rtc_clk.h"+#include "esp_check.h"+#include "sdkconfig.h"++static volatile bool s_usb_serial_jtag_conn_status;+#if CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION+static esp_pm_lock_handle_t s_usb_serial_jtag_pm_lock;+#endif++// FreeRTOS tick interrupt may get delayed in handling, which could lead to no SOF coming in within the period from+// a delayed tick to the following tick. Therefore, when FREERTOS_HZ is comparable to SOF packet frequency, a NO_SOF+// tolerance needs to be given to avoid a false disconnection detection.+#define USJ_DISCONNECT_CONFIRM_PERIOD_MS 3+#define ALLOWED_NO_SOF_TICKS pdMS_TO_TICKS(USJ_DISCONNECT_CONFIRM_PERIOD_MS)++static uint32_t remaining_allowed_no_sof_ticks;++static __attribute__((unused)) const char *USB_SERIAL_JTAG_CONN_MONITOR_TAG = "usb_serial_jtag";++bool usb_serial_jtag_is_connected(void)+{+ return s_usb_serial_jtag_conn_status;+}++static void IRAM_ATTR usb_serial_jtag_sof_tick_hook(void)+{+ // SOF packet is sent by the HOST every 1ms on a full speed bus+ // Between two consecutive tick hooks, there will be at least 1ms (selectable tick rate range is 1 - 1000Hz)+ // Therefore, SOF intr bit must have be raised at every tick hook if it is connected to a HOST+ // Here, the strategy is: Always assume USB Serial/JTAG is connected until we are sure it is not connected+ // Consider it is disconnected only if SOF intr bit is not raised within (ALLOWED_NO_SOF_TICKS + 1) tick periods+ bool sof_received = (usb_serial_jtag_ll_get_intraw_mask() & USB_SERIAL_JTAG_INTR_SOF);+ usb_serial_jtag_ll_clr_intsts_mask(USB_SERIAL_JTAG_INTR_SOF);+ if (s_usb_serial_jtag_conn_status != sof_received) {+ if (!sof_received) {+ if (remaining_allowed_no_sof_ticks > 0) {+ remaining_allowed_no_sof_ticks--;+ } else {+ // Tolerance credit used up, considered as USJ disconnected+#if CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION+ esp_pm_lock_release(s_usb_serial_jtag_pm_lock);+#endif+#if USB_SERIAL_JTAG_LL_PHY_DEPENDS_ON_BBPLL+ rtc_clk_bbpll_remove_consumer();+#endif+ s_usb_serial_jtag_conn_status = false;+ }+ } else {+ // USJ re-connected+#if CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION+ esp_pm_lock_acquire(s_usb_serial_jtag_pm_lock);+#endif+#if USB_SERIAL_JTAG_LL_PHY_DEPENDS_ON_BBPLL+ rtc_clk_bbpll_add_consumer();+#endif+ s_usb_serial_jtag_conn_status = true;+ remaining_allowed_no_sof_ticks = ALLOWED_NO_SOF_TICKS;+ }+ }+}++ESP_SYSTEM_INIT_FN(usb_serial_jtag_conn_status_init, SECONDARY, BIT(0), 230)+{+#if CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION+ ESP_RETURN_ON_ERROR(esp_pm_lock_create(ESP_PM_NO_LIGHT_SLEEP, 0, "usb_serial_jtag", &s_usb_serial_jtag_pm_lock),+ USB_SERIAL_JTAG_CONN_MONITOR_TAG, "create NO_LIGHT_SLEEP lock failed");+ // We always assume it is connected at first, so acquires the lock to avoid auto light sleep+ esp_pm_lock_acquire(s_usb_serial_jtag_pm_lock);+#endif+#if USB_SERIAL_JTAG_LL_PHY_DEPENDS_ON_BBPLL+// TODO: esp32p4 USJ rely on SPLL, if it will also be disabled during sleep, we need to call spll_add_consumer? IDF-9947+ rtc_clk_bbpll_add_consumer();+#endif+ s_usb_serial_jtag_conn_status = true;+ remaining_allowed_no_sof_ticks = ALLOWED_NO_SOF_TICKS;++ return esp_register_freertos_tick_hook(usb_serial_jtag_sof_tick_hook);+}++void usb_serial_jtag_connection_monitor_include(void)+{+ // Linker hook function, exists to make the linker examine this file+}diff --git a/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_vfs.c b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_vfs.cnew file mode 100644index 000000000..cf0fc5fca--- /dev/null+++ b/devices/harness-pro/firmware/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_vfs.c@@ -0,0 +1,753 @@+/*+ * SPDX-FileCopyrightText: 2015-2025 Espressif Systems (Shanghai) CO LTD+ *+ * SPDX-License-Identifier: Apache-2.0+ */++//This is a simple non-blocking (well, tx may spin for a bit if the buffer+//is full) USB-serial-jtag driver. Select etc is not supported yet.++#include <string.h>+#include <stdbool.h>+#include <stdarg.h>+#include <sys/errno.h>+#include <sys/lock.h>+#include <sys/fcntl.h>+#include <sys/param.h>+#include "esp_timer.h"+#include "esp_vfs.h"+#include "esp_vfs_dev.h" // Old headers for the aliasing functions+#include "esp_vfs_usb_serial_jtag.h" // Old headers for the aliasing functions+#include "esp_attr.h"+#include "esp_log.h"+#include "sdkconfig.h"+#include "soc/soc_caps.h"+#include "hal/usb_serial_jtag_ll.h"+#include "driver/usb_serial_jtag_select.h"+#include "driver/usb_serial_jtag_vfs.h"+#include "driver/usb_serial_jtag.h"+#include "esp_private/startup_internal.h"+#include "esp_heap_caps.h"++// local file descriptor value for the USJ+#define USJ_LOCAL_FD 0++// Token signifying that no character is available+#define NONE -1++#if CONFIG_LIBC_STDOUT_LINE_ENDING_CRLF+# define DEFAULT_TX_MODE ESP_LINE_ENDINGS_CRLF+#elif CONFIG_LIBC_STDOUT_LINE_ENDING_CR+# define DEFAULT_TX_MODE ESP_LINE_ENDINGS_CR+#else+# define DEFAULT_TX_MODE ESP_LINE_ENDINGS_LF+#endif++#if CONFIG_LIBC_STDIN_LINE_ENDING_CRLF+# define DEFAULT_RX_MODE ESP_LINE_ENDINGS_CRLF+#elif CONFIG_LIBC_STDIN_LINE_ENDING_CR+# define DEFAULT_RX_MODE ESP_LINE_ENDINGS_CR+#else+# define DEFAULT_RX_MODE ESP_LINE_ENDINGS_LF+#endif++#if CONFIG_VFS_SELECT_IN_RAM+#define USJ_VFS_MALLOC_FLAGS (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)+#else+#define USJ_VFS_MALLOC_FLAGS MALLOC_CAP_DEFAULT+#endif++// write bytes function type+typedef void (*tx_func_t)(int, int);+// read bytes function type+typedef int (*rx_func_t)(int);+// fsync bytes function type+typedef int (*fsync_func_t)(int);++// Basic functions for sending and receiving bytes and fsync+static void usb_serial_jtag_tx_char_no_driver(int fd, int c);+static int usb_serial_jtag_rx_char_no_driver(int fd);+static int usb_serial_jtag_wait_tx_done_no_driver(int fd);++//If no host is listening to the CDCACM port, the TX buffer+//will never be able to flush to the host. Instead of the Tx+//routines waiting forever, if the buffer hasn't been flushed+//to the host the tx routine will fail fast. (Note that as+//soon as something starts listening, the CDCACM port will+//start working as normal again.)+#define TX_FLUSH_TIMEOUT_US (50*1000LL)+//(As a reference, you'd expect an unloaded usb bus to try to+//pick up tx data once every USB frame, aka every 1ms. We take a+//longer timeout to allow for a loaded bus.)++typedef struct {+ // One-character buffer used for newline conversion code+ int peek_char;+ // Read and write locks, lazily initialized+ _lock_t read_lock;+ _lock_t write_lock;+ // Non-blocking flag.+ // The default implementation does not honor this flag, all reads+ // are non-blocking.+ // When the driver is used (via esp_vfs_usb_serial_jtag_use_driver),+ // reads are either blocking or non-blocking depending on this flag.+ bool non_blocking;+ // TX has already tried a blocking send.+ bool tx_tried_blocking;+ // Newline conversion mode when transmitting+ esp_line_endings_t tx_mode;+ // Newline conversion mode when receiving+ esp_line_endings_t rx_mode;+ // Function used to write bytes to port. Default to "basic" functions.+ tx_func_t tx_func;+ // Function used to read bytes from port. Default to "basic" functions.+ rx_func_t rx_func;+ // Function used to make sure all data is sent to the host.+ fsync_func_t fsync_func;+ // Timestamp of last time we managed to write something to the tx buffer+ int64_t last_tx_ts;+} usb_serial_jtag_vfs_context_t;++//If the context should be dynamically initialized, remove this structure+//and point s_ctx to allocated data.+static usb_serial_jtag_vfs_context_t s_ctx = {+ .peek_char = NONE,+ .tx_mode = DEFAULT_TX_MODE,+ .rx_mode = DEFAULT_RX_MODE,+ .tx_func = usb_serial_jtag_tx_char_no_driver,+ .rx_func = usb_serial_jtag_rx_char_no_driver,+ .fsync_func = usb_serial_jtag_wait_tx_done_no_driver+};++#ifdef CONFIG_VFS_SUPPORT_SELECT++typedef struct {+ esp_vfs_select_sem_t select_sem;+ fd_set *readfds;+ fd_set *writefds;+ fd_set *errorfds;+ fd_set readfds_orig;+ fd_set writefds_orig;+ fd_set errorfds_orig;+} usb_serial_jtag_select_args_t;++static usb_serial_jtag_select_args_t **s_registered_selects = NULL;+static int s_registered_select_num = 0;+static portMUX_TYPE s_registered_select_lock = portMUX_INITIALIZER_UNLOCKED;++static esp_err_t usb_serial_jtag_end_select(void *end_select_args);++#endif // CONFIG_VFS_SUPPORT_SELECT++static int usb_serial_jtag_open(const char * path, int flags, int mode)+{+ s_ctx.non_blocking = ((flags & O_NONBLOCK) == O_NONBLOCK);+ return USJ_LOCAL_FD;+}++static void usb_serial_jtag_tx_char_no_driver(int fd, int c)+{+ uint8_t cc = (uint8_t)c;+ // Try to write to the buffer as long as we still expect the buffer to have+ // a chance of being emptied by an active host. Just drop the data if there's+ // no chance anymore.+ // When we first try to send a character and the buffer is not accessible yet,+ // we wait until the time has been more than TX_FLUSH_TIMEOUT_US since we successfully+ // sent the last byte. If it takes longer than TX_FLUSH_TIMEOUT_US, we drop every+ // byte until the buffer can be accessible again.+ do {+ if (usb_serial_jtag_ll_txfifo_writable()) {+ usb_serial_jtag_ll_write_txfifo(&cc, 1);+ if (c == '\n') {+ //Make sure line doesn't linger in fifo+ usb_serial_jtag_ll_txfifo_flush();+ }+ //update time of last successful tx to now.+ s_ctx.last_tx_ts = esp_timer_get_time();+ break;+ }+ } while ((esp_timer_get_time() - s_ctx.last_tx_ts) < TX_FLUSH_TIMEOUT_US);++}++static int usb_serial_jtag_rx_char_no_driver(int fd)+{+ uint8_t c;+ int l = usb_serial_jtag_ll_read_rxfifo(&c, 1);+ if (l == 0) {+ return NONE;+ }+ return c;+}++static ssize_t usb_serial_jtag_write(int fd, const void * data, size_t size)+{+ if (!usb_serial_jtag_is_connected()) {+ // TODO: IDF-14303+ return -1;+ }+ const char *data_c = (const char *)data;+ /* Even though newlib does stream locking on each individual stream, we need+ * a dedicated lock if two streams (stdout and stderr) point to the+ * same port.+ */+ _lock_acquire_recursive(&s_ctx.write_lock);+ for (size_t i = 0; i < size; i++) {+ int c = data_c[i];+ if (c == '\n' && s_ctx.tx_mode != ESP_LINE_ENDINGS_LF) {+ s_ctx.tx_func(fd, '\r');+ if (s_ctx.tx_mode == ESP_LINE_ENDINGS_CR) {+ continue;+ }+ }+ s_ctx.tx_func(fd, c);+ }+ _lock_release_recursive(&s_ctx.write_lock);+ return size;+}++/* Helper function which returns a previous character or reads a new one from+ * the port. Previous character can be returned ("pushed back") using+ * usb_serial_jtag_return_char function.+ */+static int usb_serial_jtag_read_char(int fd)+{+ /* return character from peek buffer, if it is there */+ if (s_ctx.peek_char != NONE) {+ int c = s_ctx.peek_char;+ s_ctx.peek_char = NONE;+ return c;+ }+ return s_ctx.rx_func(fd);+}++/* Push back a character; it will be returned by next call to usb_serial_jtag_read_char */+static void usb_serial_jtag_return_char(int fd, int c)+{+ assert(s_ctx.peek_char == NONE);+ s_ctx.peek_char = c;+}++static ssize_t usb_serial_jtag_read(int fd, void* data, size_t size)+{+ if (!usb_serial_jtag_is_connected()) {+ // TODO: IDF-14303+ return -1;+ }+ assert(fd == USJ_LOCAL_FD);+ char *data_c = (char *) data;+ size_t received = 0;+ size_t available_size = 0;+ int c = NONE; // store the read char+ _lock_acquire_recursive(&s_ctx.read_lock);++ // if blocking read, wait for data to be available+ if (!s_ctx.non_blocking) {+ c = usb_serial_jtag_read_char(fd);+ }++ // find the actual fetch size+ available_size += usb_serial_jtag_get_read_bytes_available();+ if (c != NONE) {+ available_size++;+ }+ if (s_ctx.peek_char != NONE) {+ available_size++;+ }+ size_t fetch_size = MIN(available_size, size);++ if (fetch_size > 0) {+ do {+ if (c == NONE) { // for non-O_NONBLOCK mode, there is already a pre-fetched char+ c = usb_serial_jtag_read_char(fd);+ }+ assert(c != NONE);++ if (c == '\r') {+ if (s_ctx.rx_mode == ESP_LINE_ENDINGS_CR) {+ c = '\n';+ } else if (s_ctx.rx_mode == ESP_LINE_ENDINGS_CRLF) {+ /* look ahead */+ int c2 = usb_serial_jtag_read_char(fd);+ fetch_size--;+ if (c2 == NONE) {+ /* could not look ahead, put the current character back */+ usb_serial_jtag_return_char(fd, c);+ c = NONE;+ break;+ }+ if (c2 == '\n') {+ /* this was \r\n sequence. discard \r, return \n */+ c = '\n';+ } else {+ /* \r followed by something else. put the second char back,+ * it will be processed on next iteration. return \r now.+ */+ usb_serial_jtag_return_char(fd, c2);+ fetch_size++;+ }+ }+ }++ data_c[received] = (char) c;+ ++received;+ c = NONE;+ } while (received < fetch_size);+ }++ if (c != NONE) { // fetched, but not used+ usb_serial_jtag_return_char(fd, c);+ }+ _lock_release_recursive(&s_ctx.read_lock);+ if (received > 0) {+ return received;+ }+ errno = EWOULDBLOCK;+ return -1;+}++static int usb_serial_jtag_fstat(int fd, struct stat * st)+{+ memset(st, 0, sizeof(*st));+ st->st_mode = S_IFCHR;+ return 0;+}++static int usb_serial_jtag_close(int fd)+{+ return 0;+}++static int usb_serial_jtag_fcntl(int fd, int cmd, int arg)+{+ int result = 0;+ if (cmd == F_GETFL) {+ result |= O_RDWR;+ if (s_ctx.non_blocking) {+ result |= O_NONBLOCK;+ }+ } else if (cmd == F_SETFL) {+ s_ctx.non_blocking = (arg & O_NONBLOCK) != 0;+ } else {+ // unsupported operation+ result = -1;+ errno = ENOSYS;+ }+ return result;+}++static int usb_serial_jtag_wait_tx_done_no_driver(int fd)+{+ usb_serial_jtag_ll_txfifo_flush();+ //Wait for the host to have picked up the buffer, but honour the timeout in+ //case the host is not listening.+ while ((esp_timer_get_time() - s_ctx.last_tx_ts) < TX_FLUSH_TIMEOUT_US) {+ if (usb_serial_jtag_ll_txfifo_writable()) {+ s_ctx.last_tx_ts = esp_timer_get_time();+ //The last transfer may have been a 64-byte one. Flush again in order to+ //send a 0-byte packet to indicate the end of the USB transfer, otherwise+ //those 64 bytes will get stuck in the hosts buffer.+ usb_serial_jtag_ll_txfifo_flush();+ return 0;+ }+ }+ //Timeout. Host probably isn't listening.+ return EIO;+}++static int usb_serial_jtag_fsync(int fd)+{+ if (!usb_serial_jtag_is_connected()) {+ // TODO: IDF-14303+ return -1;+ }+ _lock_acquire_recursive(&s_ctx.write_lock);+ int r = s_ctx.fsync_func(fd);+ _lock_release_recursive(&s_ctx.write_lock);+ if (r == 0) {+ return 0;+ } else {+ errno = r;+ return -1;+ }+}++#ifdef CONFIG_VFS_SUPPORT_SELECT++static void select_notif_callback_isr(usj_select_notif_t usj_select_notif, BaseType_t *task_woken)+{+ portENTER_CRITICAL_ISR(&s_registered_select_lock);+ for (int i = 0; i < s_registered_select_num; ++i) {+ usb_serial_jtag_select_args_t *args = s_registered_selects[i];+ if (args) {+ switch (usj_select_notif) {+ case USJ_SELECT_READ_NOTIF:+ if (FD_ISSET(USJ_LOCAL_FD, &args->readfds_orig)) {+ FD_SET(USJ_LOCAL_FD, args->readfds);+ esp_vfs_select_triggered_isr(args->select_sem, task_woken);+ }+ break;+ case USJ_SELECT_WRITE_NOTIF:+ if (FD_ISSET(USJ_LOCAL_FD, &args->writefds_orig)) {+ FD_SET(USJ_LOCAL_FD, args->writefds);+ esp_vfs_select_triggered_isr(args->select_sem, task_woken);+ }+ break;+ case USJ_SELECT_ERROR_NOTIF:+ if (FD_ISSET(USJ_LOCAL_FD, &args->errorfds_orig)) {+ FD_SET(USJ_LOCAL_FD, args->errorfds);+ esp_vfs_select_triggered_isr(args->select_sem, task_woken);+ }+ break;+ }+ }+ }+ portEXIT_CRITICAL_ISR(&s_registered_select_lock);+}++static esp_err_t register_select(usb_serial_jtag_select_args_t *args)+{+ esp_err_t ret = ESP_ERR_INVALID_ARG;++ if (args) {+ portENTER_CRITICAL(&s_registered_select_lock);+ const int new_size = s_registered_select_num + 1;+ usb_serial_jtag_select_args_t **new_selects;+ if ((new_selects = heap_caps_realloc(s_registered_selects, new_size * sizeof(usb_serial_jtag_select_args_t *), USJ_VFS_MALLOC_FLAGS)) == NULL) {+ ret = ESP_ERR_NO_MEM;+ } else {+ /* on first select registration register the callback */+ if (s_registered_select_num == 0) {+ usb_serial_jtag_set_select_notif_callback(select_notif_callback_isr);+ }++ s_registered_selects = new_selects;+ s_registered_selects[s_registered_select_num] = args;+ s_registered_select_num = new_size;+ ret = ESP_OK;+ }+ portEXIT_CRITICAL(&s_registered_select_lock);+ }++ return ret;+}++static esp_err_t unregister_select(usb_serial_jtag_select_args_t *args)+{+ esp_err_t ret = ESP_OK;+ if (args) {+ ret = ESP_ERR_INVALID_STATE;+ portENTER_CRITICAL(&s_registered_select_lock);+ for (int i = 0; i < s_registered_select_num; ++i) {+ if (s_registered_selects[i] == args) {+ const int new_size = s_registered_select_num - 1;+ // The item is removed by overwriting it with the last item. The subsequent rellocation will drop the+ // last item.+ s_registered_selects[i] = s_registered_selects[new_size];+ s_registered_selects = heap_caps_realloc(s_registered_selects, new_size * sizeof(usb_serial_jtag_select_args_t *), USJ_VFS_MALLOC_FLAGS);+ // Shrinking a buffer with realloc is guaranteed to succeed.+ s_registered_select_num = new_size;++ /* when the last select is unregistered, also unregister the callback */+ if (s_registered_select_num == 0) {+ usb_serial_jtag_set_select_notif_callback(NULL);+ }++ ret = ESP_OK;+ break;+ }+ }+ portEXIT_CRITICAL(&s_registered_select_lock);+ }+ return ret;+}++static esp_err_t usb_serial_jtag_start_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,+ esp_vfs_select_sem_t select_sem, void **end_select_args)+{+ (void)nfds; /* Since there is only 1 usb serial jtag port, this parameter is useless */+ *end_select_args = NULL;+ if (!usb_serial_jtag_is_driver_installed()) {+ return ESP_ERR_INVALID_STATE;+ }++ usb_serial_jtag_select_args_t *args = heap_caps_malloc(sizeof(usb_serial_jtag_select_args_t), USJ_VFS_MALLOC_FLAGS);++ if (args == NULL) {+ return ESP_ERR_NO_MEM;+ }+ args->select_sem = select_sem;+ args->readfds = readfds;+ args->writefds = writefds;+ args->errorfds = exceptfds;+ args->readfds_orig = *readfds; // store the original values because they will be set to zero+ args->writefds_orig = *writefds;+ args->errorfds_orig = *exceptfds;+ FD_ZERO(readfds);+ FD_ZERO(writefds);+ FD_ZERO(exceptfds);++ esp_err_t ret = register_select(args);+ if (ret != ESP_OK) {+ free(args);+ return ret;+ }++ bool trigger_select = false;++ // check if the select should return instantly if the bus is read ready+ if (FD_ISSET(USJ_LOCAL_FD, &args->readfds_orig) && (usb_serial_jtag_get_read_bytes_available() > 0)) {+ // signal immediately when data is buffered+ FD_SET(USJ_LOCAL_FD, readfds);+ trigger_select = true;+ }++ // check if the select should return instantly if the bus is write ready+ if (FD_ISSET(USJ_LOCAL_FD, &args->writefds_orig) && usb_serial_jtag_write_ready()) {+ // signal immediately when data can be written+ FD_SET(USJ_LOCAL_FD, writefds);+ trigger_select = true;+ }++ if (trigger_select) {+ esp_vfs_select_triggered(args->select_sem);+ }++ *end_select_args = args;+ return ESP_OK;+}++static esp_err_t usb_serial_jtag_end_select(void *end_select_args)+{+ usb_serial_jtag_select_args_t *args = end_select_args;+ esp_err_t ret = unregister_select(args);+ if (args) {+ free(args);+ }++ return ret;+}++#endif // CONFIG_VFS_SUPPORT_SELECT++#ifdef CONFIG_VFS_SUPPORT_TERMIOS+static int usb_serial_jtag_tcsetattr(int fd, int optional_actions, const struct termios *p)+{+ if (p == NULL) {+ errno = EINVAL;+ return -1;+ }++ switch (optional_actions) {+ case TCSANOW:+ // nothing to do+ break;+ case TCSADRAIN:+ usb_serial_jtag_fsync(fd);+ break;+ case TCSAFLUSH:+ // Not applicable.+ break;+ default:+ errno = EINVAL;+ return -1;+ }++ if (p->c_iflag & IGNCR) {+ s_ctx.rx_mode = ESP_LINE_ENDINGS_CRLF;+ } else if (p->c_iflag & ICRNL) {+ s_ctx.rx_mode = ESP_LINE_ENDINGS_CR;+ } else {+ s_ctx.rx_mode = ESP_LINE_ENDINGS_LF;+ }+ return 0;+}++static int usb_serial_jtag_tcgetattr(int fd, struct termios *p)+{+ if (p == NULL) {+ errno = EINVAL;+ return -1;+ }++ memset(p, 0, sizeof(struct termios));++ if (s_ctx.rx_mode == ESP_LINE_ENDINGS_CRLF) {+ p->c_iflag |= IGNCR;+ } else if (s_ctx.rx_mode == ESP_LINE_ENDINGS_CR) {+ p->c_iflag |= ICRNL;+ }++ //Dummy values that vaguely make sense on a not-actually-rs232 port.+ //Should be good enough to keep software that expects an actual+ //serial port happy.+ p->c_cflag &= (~CSIZE);+ p->c_cflag |= CS8;+ p->c_ispeed = p->c_ospeed = 1000000;++ return 0;+}++static int usb_serial_jtag_tcdrain(int fd)+{+ usb_serial_jtag_fsync(fd);+ return 0;+}++static int usb_serial_jtag_tcflush(int fd, int select)+{+ //Flushing is not supported.+ errno = EINVAL;+ return -1;+}+#endif // CONFIG_VFS_SUPPORT_TERMIOS++void usb_serial_jtag_vfs_set_tx_line_endings(esp_line_endings_t mode)+{+ s_ctx.tx_mode = mode;+}++void usb_serial_jtag_vfs_set_rx_line_endings(esp_line_endings_t mode)+{+ s_ctx.rx_mode = mode;+}++#ifdef CONFIG_VFS_SUPPORT_SELECT+static const esp_vfs_select_ops_t s_vfs_jtag_select = {+ .start_select = &usb_serial_jtag_start_select,+ .end_select = &usb_serial_jtag_end_select,+};+#endif // CONFIG_VFS_SUPPORT_SELECT+#ifdef CONFIG_VFS_SUPPORT_TERMIOS+static const esp_vfs_termios_ops_t s_vfs_jtag_termios = {+ .tcsetattr = &usb_serial_jtag_tcsetattr,+ .tcgetattr = &usb_serial_jtag_tcgetattr,+ .tcdrain = &usb_serial_jtag_tcdrain,+ .tcflush = &usb_serial_jtag_tcflush,+};+#endif // CONFIG_VFS_SUPPORT_TERMIOS++static const esp_vfs_fs_ops_t s_vfs_jtag = {+ .write = &usb_serial_jtag_write,+ .open = &usb_serial_jtag_open,+ .fstat = &usb_serial_jtag_fstat,+ .close = &usb_serial_jtag_close,+ .read = &usb_serial_jtag_read,+ .fcntl = &usb_serial_jtag_fcntl,+ .fsync = &usb_serial_jtag_fsync,++#ifdef CONFIG_VFS_SUPPORT_SELECT+ .select = &s_vfs_jtag_select,+#endif // CONFIG_VFS_SUPPORT_SELECT++#ifdef CONFIG_VFS_SUPPORT_TERMIOS+ .termios = &s_vfs_jtag_termios,+#endif // CONFIG_VFS_SUPPORT_TERMIOS+};++const esp_vfs_fs_ops_t* esp_vfs_usb_serial_jtag_get_vfs(void)+{+ return &s_vfs_jtag;+}++esp_err_t usb_serial_jtag_vfs_register(void)+{+ // "/dev/usb_serial_jtag" unfortunately is too long for vfs+ return esp_vfs_register_fs("/dev/usbserjtag", &s_vfs_jtag, ESP_VFS_FLAG_STATIC, NULL);+}++#if CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG+ESP_SYSTEM_INIT_FN(init_vfs_usj, CORE, BIT(0), 111)+{+ usb_serial_jtag_vfs_register();+ return ESP_OK;+}+#endif++#if CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG+ESP_SYSTEM_INIT_FN(init_vfs_usj_sec, CORE, BIT(0), 112)+{+ // "/dev/seccondary_usb_serial_jtag" unfortunately is too long for vfs+ esp_vfs_register_fs("/dev/secondary", &s_vfs_jtag, ESP_VFS_FLAG_STATIC, NULL);+ return ESP_OK;+}+#endif++/***********************************************************+ * VFS uses USB-SERIAL-JTAG driver part.+ **********************************************************/++static int usbjtag_rx_char_via_driver(int fd)+{+ uint8_t c;+ TickType_t timeout = s_ctx.non_blocking ? 0 : portMAX_DELAY;+ int n = usb_serial_jtag_read_bytes(&c, 1, timeout);+ if (n <= 0) {+ return NONE;+ }+ return c;+}++static void usbjtag_tx_char_via_driver(int fd, int c)+{+ char ch = (char) c;+ TickType_t ticks = (TX_FLUSH_TIMEOUT_US / 1000) / portTICK_PERIOD_MS;+ if (usb_serial_jtag_write_bytes(&ch, 1, 0) != 0) {+ s_ctx.tx_tried_blocking = false;+ return;+ }++ if (s_ctx.tx_tried_blocking == false) {+ if (usb_serial_jtag_write_bytes(&ch, 1, ticks) != 0) {+ return;+ } else {+ s_ctx.tx_tried_blocking = true;+ }+ }+}++static int usbjtag_wait_tx_done_via_driver(int fd)+{+ TickType_t ticks = (TX_FLUSH_TIMEOUT_US / 1000) / portTICK_PERIOD_MS;+ esp_err_t r = usb_serial_jtag_wait_tx_done(ticks);+ return (r == ESP_OK) ? 0 : EIO;+}++void usb_serial_jtag_vfs_use_nonblocking(void)+{+ _lock_acquire_recursive(&s_ctx.read_lock);+ _lock_acquire_recursive(&s_ctx.write_lock);+ s_ctx.tx_func = usb_serial_jtag_tx_char_no_driver;+ s_ctx.rx_func = usb_serial_jtag_rx_char_no_driver;+ s_ctx.fsync_func = usb_serial_jtag_wait_tx_done_no_driver;+ _lock_release_recursive(&s_ctx.write_lock);+ _lock_release_recursive(&s_ctx.read_lock);+}++void usb_serial_jtag_vfs_use_driver(void)+{+ _lock_acquire_recursive(&s_ctx.read_lock);+ _lock_acquire_recursive(&s_ctx.write_lock);+ s_ctx.tx_func = usbjtag_tx_char_via_driver;+ s_ctx.rx_func = usbjtag_rx_char_via_driver;+ s_ctx.fsync_func = usbjtag_wait_tx_done_via_driver;+ _lock_release_recursive(&s_ctx.write_lock);+ _lock_release_recursive(&s_ctx.read_lock);+}++void usb_serial_jtag_vfs_include_dev_init(void)+{+ // Linker hook function, exists to make the linker examine this file+}++// -------------------------- esp_vfs_usb_serial_jtag_xxx ALIAS (deprecated) ----------------------------++esp_err_t esp_vfs_dev_usb_serial_jtag_register(void) __attribute__((alias("usb_serial_jtag_vfs_register")));++void esp_vfs_dev_usb_serial_jtag_set_rx_line_endings(esp_line_endings_t mode) __attribute__((alias("usb_serial_jtag_vfs_set_rx_line_endings")));++void esp_vfs_dev_usb_serial_jtag_set_tx_line_endings(esp_line_endings_t mode) __attribute__((alias("usb_serial_jtag_vfs_set_tx_line_endings")));++void esp_vfs_usb_serial_jtag_use_nonblocking(void) __attribute__((alias("usb_serial_jtag_vfs_use_nonblocking")));++void esp_vfs_usb_serial_jtag_use_driver(void) __attribute__((alias("usb_serial_jtag_vfs_use_driver")));diff --git a/devices/harness-pro/firmware/main/app/pro_app.c b/devices/harness-pro/firmware/main/app/pro_app.cindex a35d52b68..0bf1a65fb 100644--- a/devices/harness-pro/firmware/main/app/pro_app.c+++ b/devices/harness-pro/firmware/main/app/pro_app.c@@ -845,12 +845,13 @@ static void heartbeat(uint32_t frames, uint32_t raster_max_us, uint32_t frame_mauint32_t bad = 0, unknown = 0;pro_cable_counters(&bad, &unknown);// The host watches this line while the renderer is alive, including while asleep.- ESP_LOGI(TAG, "alive up=%lus heap=%u/%u psram=%u touches=%lu read_fails=%lu frames=%lu raster_max_us=%lu frame_max_us=%lu stack_free=%u muted=%d link_rx=%lu link_frames=%lu link_corrupt=%lu link_discarded=%lu link_dropped_logs=%lu msg_bad=%lu msg_unknown=%lu%s%s",+ ESP_LOGI(TAG, "alive up=%lus heap=%u/%u psram=%u touches=%lu read_fails=%lu frames=%lu raster_max_us=%lu frame_max_us=%lu stack_free=%u muted=%d isr_rx=%lu ring_drop=%lu seq_gaps=%lu link_rx=%lu link_frames=%lu link_corrupt=%lu link_discarded=%lu link_dropped_logs=%lu msg_bad=%lu msg_unknown=%lu%s%s",(unsigned long)(now / 1000), (unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL),(unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL), (unsigned)heap_caps_get_free_size(MALLOC_CAP_SPIRAM),(unsigned long)touch.presses, (unsigned long)touch.read_failures, (unsigned long)frames,(unsigned long)raster_max_us, (unsigned long)frame_max_us,(unsigned)uxTaskGetStackHighWaterMark(NULL), (int)pro_settings_muted(),+ (unsigned long)link.isr_rx, (unsigned long)link.ring_drop, (unsigned long)pro_cable_seq_gaps(),(unsigned long)link.rx_bytes, (unsigned long)link.frames_ok, (unsigned long)link.corrupt_frames,(unsigned long)link.discarded_bytes, (unsigned long)link.dropped_logs, (unsigned long)bad, (unsigned long)unknown,touch.controller_ok ? "" : " TOUCH-DEAD", pro_app_asleep() ? " asleep" : "");diff --git a/devices/harness-pro/firmware/main/cable/cable_features.c b/devices/harness-pro/firmware/main/cable/cable_features.cindex 1c83e2dd9..cf66638a6 100644--- a/devices/harness-pro/firmware/main/cable/cable_features.c+++ b/devices/harness-pro/firmware/main/cable/cable_features.c@@ -12,6 +12,7 @@ uint32_t cable_features_parse(const cJSON *welcome)cJSON_ArrayForEach(item, features) {if (++count > 16 || !cJSON_IsString(item)) return 0;if (!strcmp(item->valuestring, "player.library")) result |= CABLE_FEATURE_PLAYER_LIBRARY;+ if (!strcmp(item->valuestring, "resync")) result |= CABLE_FEATURE_RESYNC;}return result;}diff --git a/devices/harness-pro/firmware/main/cable/cable_features.h b/devices/harness-pro/firmware/main/cable/cable_features.hindex d6aeed557..56d2a4723 100644--- a/devices/harness-pro/firmware/main/cable/cable_features.h+++ b/devices/harness-pro/firmware/main/cable/cable_features.h@@ -2,9 +2,10 @@#include <stdint.h>typedef struct cJSON cJSON;-// The Pro reads one welcome feature: the player library (the daemon answers `player.library.get`).+// The Pro reads two welcome features: the player library (the daemon answers `player.library.get`) and `resync`.enum {CABLE_FEATURE_PLAYER_LIBRARY = 1u << 0,+ CABLE_FEATURE_RESYNC = 1u << 1, // the daemon answers `resync` with a full snapshot (older ones do not know it)};// Optional welcome field. Older daemons omit it; unknown names are ignored. More than 16 entries, or andiff --git a/devices/harness-pro/firmware/main/cable/cable_frame.c b/devices/harness-pro/firmware/main/cable/cable_frame.cindex 524a19fc8..0f2de707d 100644--- a/devices/harness-pro/firmware/main/cable/cable_frame.c+++ b/devices/harness-pro/firmware/main/cable/cable_frame.c@@ -190,3 +190,19 @@ void cable_decoder_feed(cable_decoder_t *d, const uint8_t *data, size_t n,}}}++bool cable_decoder_expire(cable_decoder_t *d, cable_frame_cb cb, void *ctx)+{+ if (!d->len) return false;+ const bool partial = d->len >= 2 && d->buf[0] == CABLE_MAGIC_0 && d->buf[1] == CABLE_MAGIC_1;+ if (partial) {+ // Step over the magic, not the whole buffer: a whole frame may sit behind a lost tail, and the scan finds it.+ d->corrupt_frames++;+ discard(d, 1);+ }+ while (take_front(d, cb, ctx)) {+ }+ // A lone trailing A5 can no longer be the start of anything.+ if (d->len) discard(d, d->len);+ return partial;+}diff --git a/devices/harness-pro/firmware/main/cable/cable_frame.h b/devices/harness-pro/firmware/main/cable/cable_frame.hindex eafaf1ac5..af8d2dc8d 100644--- a/devices/harness-pro/firmware/main/cable/cable_frame.h+++ b/devices/harness-pro/firmware/main/cable/cable_frame.h@@ -125,3 +125,7 @@ void cable_decoder_reset(cable_decoder_t *d);// makes no sense is to step over it.void cable_decoder_feed(cable_decoder_t *d, const uint8_t *data, size_t n,cable_frame_cb cb, void *ctx);++// The link has gone quiet with bytes still pending: give up on a partial frame (counted corrupt, the way a bad CRC is)+// and resync now, delivering any whole frame that sits behind it. Returns true when a partial frame was dropped.+bool cable_decoder_expire(cable_decoder_t *d, cable_frame_cb cb, void *ctx);diff --git a/devices/harness-pro/firmware/main/cable/cable_link.c b/devices/harness-pro/firmware/main/cable/cable_link.cindex 985364529..5ea9a745f 100644--- a/devices/harness-pro/firmware/main/cable/cable_link.c+++ b/devices/harness-pro/firmware/main/cable/cable_link.c@@ -53,10 +53,11 @@ static const char *TAG = "cable";// anything arrives. It only bounds how long the task sleeps with nothing to do.#define READ_WAIT_MS 100-// A stopped host can leave a legal-length header followed by only half its-// payload. Magic inside the next welcome cannot escape that pending payload.-// Expire only an idle gap, not the total duration of a slowly fragmented frame.-#define FRAME_IDLE_US INT64_C(15000000)+// The host writes a frame in one go, so a frame whose bytes stop for this long has lost its tail (the USB path drops+// whole 64-byte packets) or the host stopped mid-write. Waiting for the rest would swallow the next frame instead:+// a legal-length header holds the decoder until its payload length is met. Only an idle gap counts, not the total+// duration of a slowly fragmented frame, and the clock starts after the callbacks (a flash erase blocks this task).+#define FRAME_IDLE_US INT64_C(300000)// How long a write waits for the host to make room. Finite, and that is the point: an unplugged cable or// an unopened port fills the TX FIFO and never drains it, and portMAX_DELAY there parks whatever task@@ -171,25 +172,32 @@ static void count_frame(uint8_t version, uint8_t type, const uint8_t *payload, ss_cb(version, type, payload, payload_len, ctx);}+static int64_t s_last_rx_us; // reader only++// One read's worth: expire a stale partial frame, then feed. Split from the loop for the host test.+static void reader_step(const uint8_t *chunk, int n)+{+ // This task owns the decoder. Expire before feeding a newly arrived read too: scheduling need not provide an+ // intervening empty read.+ if (s_decoder.len && esp_timer_get_time() - s_last_rx_us >= FRAME_IDLE_US) {+ cable_decoder_expire(&s_decoder, count_frame, s_ctx);+ s_last_rx_us = esp_timer_get_time();+ }+ // Never fails and never rejects: everything arriving here is untrusted, starts mid-stream after+ // every boot, and the only useful response to a byte that makes no sense is to step over it.+ if (n > 0) {+ atomic_fetch_add_explicit(&s_rx_bytes, (unsigned)n, memory_order_relaxed);+ cable_decoder_feed(&s_decoder, chunk, (size_t)n, count_frame, s_ctx);+ s_last_rx_us = esp_timer_get_time(); // after the callbacks, which may block+ }+}+static void reader_task(void *arg){(void)arg;uint8_t chunk[READ_CHUNK];- int64_t last_rx_us = 0;while (1) {- int n = usb_serial_jtag_read_bytes(chunk, sizeof(chunk), pdMS_TO_TICKS(READ_WAIT_MS));- const int64_t now = esp_timer_get_time();- // This task owns the decoder. Reset before feeding a newly arrived- // read too: scheduling need not provide an intervening empty read.- if (s_decoder.len && now - last_rx_us >= FRAME_IDLE_US)- cable_decoder_reset(&s_decoder);- // Never fails and never rejects: everything arriving here is untrusted, starts mid-stream after- // every boot, and the only useful response to a byte that makes no sense is to step over it.- if (n > 0) {- atomic_fetch_add_explicit(&s_rx_bytes, (unsigned)n, memory_order_relaxed);- cable_decoder_feed(&s_decoder, chunk, (size_t)n, count_frame, s_ctx);- last_rx_us = now;- }+ reader_step(chunk, usb_serial_jtag_read_bytes(chunk, sizeof(chunk), pdMS_TO_TICKS(READ_WAIT_MS)));if (s_tick) s_tick(s_ctx);}}@@ -294,7 +302,11 @@ void cable_link_counters(uint32_t *corrupt_frames, uint32_t *discarded_bytes)cable_link_stats_t cable_link_stats(void){// The decoder's two counters are plain words that only the reader writes; a 32-bit read is not torn.+ uint32_t isr_rx = 0, ring_drop = 0;+ usb_serial_jtag_rx_stats(&isr_rx, &ring_drop);return (cable_link_stats_t){+ .isr_rx = isr_rx,+ .ring_drop = ring_drop,.rx_bytes = atomic_load_explicit(&s_rx_bytes, memory_order_relaxed),.frames_ok = atomic_load_explicit(&s_frames_ok, memory_order_relaxed),.corrupt_frames = s_decoder.corrupt_frames,diff --git a/devices/harness-pro/firmware/main/cable/cable_link.h b/devices/harness-pro/firmware/main/cable/cable_link.hindex 9a4f321a2..04c999ac8 100644--- a/devices/harness-pro/firmware/main/cable/cable_link.h+++ b/devices/harness-pro/firmware/main/cable/cable_link.h@@ -88,6 +88,8 @@ bool cable_link_host_present(void);// the two sides disagree about the format or the cable is bad. Without a count those look identical.// Safe from any task; the reader owns the writes.typedef struct {+ uint32_t isr_rx; // bytes the ISR pulled from the hardware FIFO (below the driver's ring buffer)+ uint32_t ring_drop; // ring-buffer pushes that failed in the ISR: those bytes are goneuint32_t rx_bytes; // bytes read off the portuint32_t frames_ok; // frames decoded and delivereduint32_t corrupt_frames; // a frame whose CRC or length failed@@ -103,5 +105,5 @@ void cable_link_counters(uint32_t *corrupt_frames, uint32_t *discarded_bytes);//// Call it only from the reader's frame or tick callback. The decoder has one// reader and no lock; another task must not reset it during a feed. The reader-// also expires a partial frame after a 15-second gap in received bytes.+// also expires a partial frame after a 300 ms gap in received bytes (counted corrupt, resynced at once).void cable_link_reset_decoder(void);diff --git a/devices/harness-pro/firmware/main/cable/pro_cable.c b/devices/harness-pro/firmware/main/cable/pro_cable.cindex 2dc4e53d8..863dfd563 100644--- a/devices/harness-pro/firmware/main/cable/pro_cable.c+++ b/devices/harness-pro/firmware/main/cable/pro_cable.c@@ -55,6 +55,11 @@ static uint32_t s_bad, s_unknown;static char s_machine_name[CABLE_NAME_MAX];static char s_machine_id[MACHINE_ID_MAX];static cable_machines_t s_machines;+// The daemon numbers every JSON frame it sends us (`seq`, reset by each welcome); a hole means a frame was lost on the way in.+static int64_t s_seq_last = -1; // -1: none seen this session+static uint32_t s_seq_gaps;+static bool s_resync_pending;+static bool s_seq_on; // the welcome carried a seq// The id of the recording in flight: written by the voice task, read by the cable_link task to match a reply.static SemaphoreHandle_t s_upload_lock;@@ -352,6 +357,21 @@ void pro_cable_counters(uint32_t *bad, uint32_t *unknown)if (unknown) *unknown = s_unknown;}+uint32_t pro_cable_seq_gaps(void) { return s_seq_gaps; }++// A frame with a `seq` that does not follow the last one means frames in between never arrived (the USB path drops+// whole packets, and a small frame vanishes without a trace). Count it and ask for a snapshot (link_resync).+static void track_seq(const cJSON *root, bool welcome)+{+ const cJSON *v = cJSON_GetObjectItemCaseSensitive(root, "seq");+ const bool ok = cJSON_IsNumber(v) && v->valuedouble >= 0 && v->valuedouble < 4294967296.0;+ if (welcome) s_seq_on = ok; // a daemon that does not number its frames is not checked at all+ if (!s_seq_on || !ok) return;+ const int64_t seq = (int64_t)v->valuedouble;+ if (!welcome && s_seq_last >= 0 && seq != s_seq_last + 1) { s_seq_gaps++; s_resync_pending = true; }+ s_seq_last = seq; // a welcome restarts the count+}+// ── the agent list ──────────────────────────────────────────────────────────────────────────────────// It arrives streamed (begin, one `agent` per agent, end) because a frame is capped and a list is not. The Pro// holds it in static scratch and hands pro_app the whole roster once, at `agents.end`.@@ -802,6 +822,10 @@ static void session_down(const char *why)s_agent_count = 0;s_machine_name[0] = 0;s_machine_id[0] = 0;+ s_seq_last = -1;+ s_seq_on = false;+ s_resync_pending = false;+ cable_link_reset_decoder(); // runs on the tick: whatever is half-received belonged to the session that endedcable_link_set_log_framing(false); // first: what follows should be readable on a plain monitorESP_LOGI(TAG, "session down (%s)", why);fw_update_abort("session down");@@ -905,26 +929,34 @@ void pro_cable_on_frame(uint8_t version, uint8_t type, const uint8_t *payload, s}if (!root) { s_bad++; ESP_LOGW(TAG, "frame did not parse: %u B", (unsigned)payload_len); return; }s_last_rx_us = esp_timer_get_time();+ const char *kind = str_of(root, "t");+ track_seq(root, kind && !strcmp(kind, "welcome"));handle_message(root);cJSON_Delete(root);}-// A frame lost on the way in may have been a roster push; the daemon answers these requests with a forced push. During a-// transfer the resend logic covers it (the loss is consumed, not replayed after). At most once per 5 s.+// A frame lost on the way in (a bad CRC or a seq gap) may have been a roster push; `resync` (when the welcome advertises it, else the+// old swarms.list + agents.list) asks the daemon for the whole snapshot: machines, swarms, agents, notices and open questions. During a transfer the resend logic covers it (the loss+// is consumed, not replayed after). At most once per 2 s.static void link_resync(void){static uint32_t seen;- static int64_t last_us = -5000000;+ static int64_t last_us = -2000000;uint32_t corrupt = 0, discarded = 0;cable_link_counters(&corrupt, &discarded);- if (corrupt == seen || !atomic_load(&s_session)) return;+ if ((corrupt == seen && !s_resync_pending) || !atomic_load(&s_session)) return;const int64_t now = esp_timer_get_time();- if (fw_update_active()) { seen = corrupt; return; }- if (now - last_us < 5000000) return; // keep it pending; the next tick after the window answers+ if (fw_update_active()) { seen = corrupt; s_resync_pending = false; return; }+ if (now - last_us < 2000000) return; // keep it pending; the next tick after the window answersseen = corrupt;+ s_resync_pending = false;last_us = now;- send_json(msg("swarms.list"));- send_json(msg("agents.list"));+ if (atomic_load(&s_features) & CABLE_FEATURE_RESYNC) {+ send_json(msg("resync"));+ } else { // a daemon that predates `resync`: the old refresh+ send_json(msg("swarms.list"));+ send_json(msg("agents.list"));+ }}void pro_cable_tick(void *ctx)diff --git a/devices/harness-pro/firmware/main/cable/pro_cable.h b/devices/harness-pro/firmware/main/cable/pro_cable.hindex 8a134cf38..cffe898e7 100644--- a/devices/harness-pro/firmware/main/cable/pro_cable.h+++ b/devices/harness-pro/firmware/main/cable/pro_cable.h@@ -41,6 +41,8 @@ const char *pro_cable_fw_version(void);// ---- seams ----// Messages dropped as malformed / ignored as unknown, cumulative (the heartbeat prints them; the host tests read them).void pro_cable_counters(uint32_t *bad, uint32_t *unknown);+// Frames the daemon's `seq` numbering showed missing (each one asked for a resync), cumulative.+uint32_t pro_cable_seq_gaps(void);// cable_link's callbacks (also what test_pro_cable.c feeds). on_frame runs on the cable_link task.void pro_cable_on_frame(uint8_t version, uint8_t type, const uint8_t *payload, size_t payload_len, void *ctx);void pro_cable_tick(void *ctx);diff --git a/devices/harness-pro/firmware/test/host_esp/driver/usb_serial_jtag.h b/devices/harness-pro/firmware/test/host_esp/driver/usb_serial_jtag.hnew file mode 100644index 000000000..7cde31a98--- /dev/null+++ b/devices/harness-pro/firmware/test/host_esp/driver/usb_serial_jtag.h@@ -0,0 +1,15 @@+// Host-test stand-in for the USB-Serial-JTAG driver header (test_cable_link.c defines the functions).+#pragma once+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>+#include "esp_err.h"+#include "freertos/FreeRTOS.h"+typedef struct { uint32_t tx_buffer_size, rx_buffer_size; } usb_serial_jtag_driver_config_t;+esp_err_t usb_serial_jtag_driver_install(usb_serial_jtag_driver_config_t *cfg);+esp_err_t usb_serial_jtag_driver_uninstall(void);+int usb_serial_jtag_read_bytes(void *buf, uint32_t length, TickType_t ticks);+int usb_serial_jtag_write_bytes(const void *src, size_t size, TickType_t ticks);+bool usb_serial_jtag_is_connected(void);+void usb_serial_jtag_rx_stats(uint32_t *isr_bytes, uint32_t *ring_drops);+const char *esp_err_to_name(esp_err_t e);diff --git a/devices/harness-pro/firmware/test/host_esp/esp_log.h b/devices/harness-pro/firmware/test/host_esp/esp_log.hindex b9f13be68..5963fb1a0 100644--- a/devices/harness-pro/firmware/test/host_esp/esp_log.h+++ b/devices/harness-pro/firmware/test/host_esp/esp_log.h@@ -5,3 +5,6 @@#define ESP_LOGW(tag, ...) ((void)(tag), (void)(0 && printf(__VA_ARGS__)))#define ESP_LOGI(tag, ...) ((void)(tag), (void)(0 && printf(__VA_ARGS__)))#define ESP_LOGD(tag, ...) ((void)(tag), (void)(0 && printf(__VA_ARGS__)))+#include <stdarg.h>+typedef int (*vprintf_like_t)(const char *, va_list);+vprintf_like_t esp_log_set_vprintf(vprintf_like_t func);diff --git a/devices/harness-pro/firmware/test/host_esp/freertos/FreeRTOS.h b/devices/harness-pro/firmware/test/host_esp/freertos/FreeRTOS.hindex 0ae0f846d..f9b6ebda3 100644--- a/devices/harness-pro/firmware/test/host_esp/freertos/FreeRTOS.h+++ b/devices/harness-pro/firmware/test/host_esp/freertos/FreeRTOS.h@@ -13,3 +13,4 @@ typedef struct { int unused; } portMUX_TYPE;#define portMUX_INITIALIZER_UNLOCKED {0}#define portENTER_CRITICAL(m) ((void)(m))#define portEXIT_CRITICAL(m) ((void)(m))+int xPortInIsrContext(void);diff --git a/devices/harness-pro/firmware/test/host_esp/freertos/semphr.h b/devices/harness-pro/firmware/test/host_esp/freertos/semphr.hindex e307c1605..26ecb12c0 100644--- a/devices/harness-pro/firmware/test/host_esp/freertos/semphr.h+++ b/devices/harness-pro/firmware/test/host_esp/freertos/semphr.h@@ -7,3 +7,6 @@ BaseType_t xSemaphoreGive(SemaphoreHandle_t m);SemaphoreHandle_t xSemaphoreCreateRecursiveMutex(void);BaseType_t xSemaphoreTakeRecursive(SemaphoreHandle_t m, TickType_t wait);BaseType_t xSemaphoreGiveRecursive(SemaphoreHandle_t m);+#include "task.h"+TaskHandle_t xSemaphoreGetMutexHolder(SemaphoreHandle_t m);+void vSemaphoreDelete(SemaphoreHandle_t m);diff --git a/devices/harness-pro/firmware/test/host_esp/freertos/task.h b/devices/harness-pro/firmware/test/host_esp/freertos/task.hindex b897f42ee..52b8773a5 100644--- a/devices/harness-pro/firmware/test/host_esp/freertos/task.h+++ b/devices/harness-pro/firmware/test/host_esp/freertos/task.h@@ -11,3 +11,4 @@ BaseType_t xTaskNotifyGive(TaskHandle_t t);BaseType_t xTaskCreatePinnedToCore(TaskFunction_t fn, const char *name, uint32_t stack, void *arg, unsigned prio,TaskHandle_t *out, int core);uint32_t uxTaskGetStackHighWaterMark(TaskHandle_t t);+TaskHandle_t xTaskGetCurrentTaskHandle(void);diff --git a/devices/harness-pro/firmware/test/run.sh b/devices/harness-pro/firmware/test/run.shindex cae11d0f5..45c817048 100755--- a/devices/harness-pro/firmware/test/run.sh+++ b/devices/harness-pro/firmware/test/run.sh@@ -111,6 +111,12 @@ cc "${cc_flags[@]}" -o "$out/test_pro_cable" "$here/test_pro_cable.c" "${cobjs[@-lpthread -lm"$out/test_pro_cable"+# cable_link: the reader's partial-frame timeout and counters. The test includes cable_link.c (to drive its static+# reader step on a fake clock) with the USB driver and FreeRTOS as stubs; the file itself is also built stack-capped.+cc "${cc_flags[@]}" -I"$fw/main/sys" -Wframe-larger-than=1024 -c -o "$out/cable_link.o" "$cable/cable_link.c"+cc "${cc_flags[@]}" -I"$fw/main/sys" -o "$out/test_cable_link" "$here/test_cable_link.c" "$cable/cable_frame.c"+"$out/test_cable_link"+# fw_update: the OTA receiver over an in-memory partition (host_esp has the esp_ota_ops / partition / sha256 stand-ins;# the cable and UI hooks are recorded by the test). Stack-capped like the rest of the cable task's code.cc "${cc_flags[@]}" -DFW_UPDATE_HOST_TEST -Wframe-larger-than=1024 -c -o "$out/fw_update.o" "$fw/main/sys/fw_update.c"diff --git a/devices/harness-pro/firmware/test/stress_pro_app.c b/devices/harness-pro/firmware/test/stress_pro_app.cindex 6fdb56b4c..070d5eceb 100644--- a/devices/harness-pro/firmware/test/stress_pro_app.c+++ b/devices/harness-pro/firmware/test/stress_pro_app.c@@ -65,6 +65,7 @@ static uint32_t lib_req_id;bool pro_cable_request_library(int offset, uint32_t request) { CHECK(LOCK_DEPTH == 0); lib_req_offset = offset; lib_req_id = request; return true; }bool pro_cable_library_supported(void) { return true; }cable_link_stats_t cable_link_stats(void) { return (cable_link_stats_t){0}; }+uint32_t pro_cable_seq_gaps(void) { return 0; }void pro_cable_counters(uint32_t *bad, uint32_t *unknown) { *bad = 0; *unknown = 0; }void pro_voice_begin(const char *agent) { (void)agent; }void pro_voice_end(bool send) { (void)send; }diff --git a/devices/harness-pro/firmware/test/test_cable_link.c b/devices/harness-pro/firmware/test/test_cable_link.cnew file mode 100644index 000000000..fe57d6930--- /dev/null+++ b/devices/harness-pro/firmware/test/test_cable_link.c@@ -0,0 +1,116 @@+// Host test for cable_link.c's reader: the partial-frame timeout and the counters. The source is included so its static+// reader_step() can be driven with a fake clock and a recording frame callback; the USB driver and FreeRTOS are stubs.+#include <assert.h>+#include <stdio.h>+#include <stdlib.h>++#include "cable/cable_link.c"++static int checks;+#define CHECK(c) do { if (!(c)) { fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #c); abort(); } checks++; } while (0)++static int64_t now_us = 1000000;+int64_t esp_timer_get_time(void) { return now_us; }+esp_err_t usb_serial_jtag_driver_install(usb_serial_jtag_driver_config_t *cfg) { (void)cfg; return ESP_OK; }+esp_err_t usb_serial_jtag_driver_uninstall(void) { return ESP_OK; }+int usb_serial_jtag_read_bytes(void *b, uint32_t n, TickType_t t) { (void)b; (void)n; (void)t; return 0; }+int usb_serial_jtag_write_bytes(const void *s, size_t n, TickType_t t) { (void)s; (void)t; return (int)n; }+bool usb_serial_jtag_is_connected(void) { return true; }+static uint32_t stub_isr = 7, stub_drop = 2;+void usb_serial_jtag_rx_stats(uint32_t *a, uint32_t *b) { *a = stub_isr; *b = stub_drop; }+vprintf_like_t esp_log_set_vprintf(vprintf_like_t f) { return f; }+int xPortInIsrContext(void) { return 0; }+TaskHandle_t xTaskGetCurrentTaskHandle(void) { return NULL; }+TaskHandle_t xSemaphoreGetMutexHolder(SemaphoreHandle_t m) { (void)m; return NULL; }+void vSemaphoreDelete(SemaphoreHandle_t m) { (void)m; }+void last_words_add(const char *l, size_t n) { (void)l; (void)n; }+SemaphoreHandle_t xSemaphoreCreateMutex(void) { return NULL; }+BaseType_t xSemaphoreTake(SemaphoreHandle_t m, TickType_t w) { (void)m; (void)w; return pdTRUE; }+BaseType_t xSemaphoreGive(SemaphoreHandle_t m) { (void)m; return pdTRUE; }+BaseType_t xTaskCreate(TaskFunction_t f, const char *n, uint32_t s, void *a, unsigned p, TaskHandle_t *o) { (void)f; (void)n; (void)s; (void)a; (void)p; (void)o; return pdPASS; }+const char *esp_err_to_name(esp_err_t e) { (void)e; return "err"; }++static int got;+static uint8_t got_type[8];+static void on_frame(uint8_t version, uint8_t type, const uint8_t *p, size_t n, void *ctx)+{+ (void)version; (void)p; (void)n; (void)ctx;+ if (got < 8) got_type[got] = type;+ got++;+}++// A frame of `n` payload bytes of 'x' into `out`; returns its length.+static size_t frame(uint8_t *out, size_t n)+{+ uint8_t payload[400];+ memset(payload, 'x', n);+ return (size_t)cable_frame_encode(CABLE_TYPE_JSON, payload, n, out, 1024);+}++int main(void)+{+ s_cb = on_frame;+ cable_decoder_init(&s_decoder);+ uint8_t a[1024], b[1024];+ const size_t la = frame(a, 100), lb = frame(b, 20);++ // Whole frames pass straight through.+ reader_step(a, (int)la);+ CHECK(got == 1 && s_decoder.len == 0);++ // The tail of a frame is lost (a dropped USB packet) and nothing follows: 300 ms later the partial is dropped,+ // counted corrupt, and the next frame decodes at once. Before: it sat there for 15 s.+ reader_step(a, 64);+ CHECK(s_decoder.len == 64);+ now_us += 299 * 1000;+ reader_step(NULL, 0);+ CHECK(s_decoder.len == 64 && s_decoder.corrupt_frames == 0); // not yet+ now_us += 2 * 1000;+ reader_step(NULL, 0);+ CHECK(s_decoder.len == 0 && s_decoder.corrupt_frames == 1);+ reader_step(b, (int)lb);+ CHECK(got == 2);++ // The same loss, but bytes of the next frame arrive after the gap in the same read: the stale partial goes first.+ reader_step(a, 64);+ now_us += 400 * 1000;+ reader_step(b, (int)lb);+ CHECK(got == 3 && s_decoder.corrupt_frames == 2 && s_decoder.len == 0);++ // A whole frame sitting behind the lost tail is salvaged by the resync instead of being thrown away with it.+ uint8_t mix[1024];+ memcpy(mix, a, 30); // 30 bytes of a 100 B frame, then a complete 20 B frame behind a gap+ memcpy(mix + 30, b, lb);+ reader_step(mix, (int)(30 + lb)); // the decoder wants 114 B for the first header: waits+ CHECK(got == 3 && s_decoder.len == 30 + lb);+ now_us += 301 * 1000;+ reader_step(NULL, 0);+ CHECK(got == 4 && s_decoder.len == 0 && s_decoder.corrupt_frames == 3);++ // A partial frame keeps its whole window from the last byte it received: the rest arriving inside it completes it.+ uint8_t two[1024];+ memcpy(two, b, lb);+ memcpy(two + lb, a, 50); // a whole frame, then half of another+ reader_step(two, (int)(lb + 50));+ CHECK(got == 5 && s_decoder.len == 50);+ now_us += 250 * 1000;+ reader_step(NULL, 0);+ CHECK(s_decoder.len == 50); // 250 ms since the last byte: still waiting+ reader_step(a + 50, (int)(la - 50)); // the rest arrives in time+ CHECK(got == 6 && s_decoder.len == 0 && s_decoder.corrupt_frames == 3);++ // A lone trailing magic byte is not a partial frame: dropped quietly, not counted.+ uint8_t lone = CABLE_MAGIC_0;+ reader_step(&lone, 1);+ now_us += 400 * 1000;+ reader_step(NULL, 0);+ CHECK(s_decoder.len == 0 && s_decoder.corrupt_frames == 3);++ // The driver's counters ride the stats.+ cable_link_stats_t st = cable_link_stats();+ CHECK(st.isr_rx == 7 && st.ring_drop == 2 && st.frames_ok == 6);+ CHECK(st.corrupt_frames == 3 && st.rx_bytes > 0);++ printf("test_cable_link: %d checks passed\n", checks);+ return 0;+}diff --git a/devices/harness-pro/firmware/test/test_pro_cable.c b/devices/harness-pro/firmware/test/test_pro_cable.cindex 9e9d38a33..fdc5bf3ad 100644--- a/devices/harness-pro/firmware/test/test_pro_cable.c+++ b/devices/harness-pro/firmware/test/test_pro_cable.c@@ -133,6 +133,8 @@ bool cable_link_send_nowait(uint8_t type, const uint8_t *payload, size_t len)}bool cable_link_start(cable_frame_cb cb, cable_tick_cb tick, void *ctx) { (void)cb; (void)tick; (void)ctx; return true; }void cable_link_set_log_framing(bool on) { (void)on; }+static int decoder_resets;+void cable_link_reset_decoder(void) { decoder_resets++; }static int64_t now_us = 1000000;int64_t esp_timer_get_time(void) { return now_us; }const esp_app_desc_t *esp_app_get_description(void) { static const esp_app_desc_t d = { .version = "0.0.0" }; return &d; }@@ -952,21 +954,71 @@ static void send_shapes(void)CHECK(nsent == 1 && !strcmp(sent[0], "{\"t\":\"fw.progress\",\"written\":4096,\"resend\":true}"));}-// A frame lost on the way in outside a transfer: ask for both lists once, not again within 5 s, never mid-transfer.-static void link_resync(void)+// A frame lost on the way in outside a transfer: ask for the snapshot once, not again within 2 s, never mid-transfer.+// A welcome that advertises `resync` gets the one request; an older daemon's gets the old swarms.list + agents.list.+static void link_resync_with(const char *welcome_json, bool new_daemon){- welcome(); reset();+ feed(welcome_json); reset();+ now_us += 10000 * 1000; // clear the previous windowpro_cable_tick(NULL); CHECK(nsent == 0); // counter unchangedlink_corrupt++; pro_cable_tick(NULL);- CHECK(nsent == 2 && strstr(sent[0], "swarms.list") && strstr(sent[1], "agents.list"));- reset(); link_corrupt++; now_us += 4999 * 1000; pro_cable_tick(NULL); CHECK(nsent == 0);- now_us += 1000 * 1000; pro_cable_tick(NULL); // 5 s on: the pending loss is answered- CHECK(nsent == 2);+ if (new_daemon) CHECK(nsent == 1 && !strcmp(sent[0], "{\"t\":\"resync\"}"));+ else CHECK(nsent == 2 && strstr(sent[0], "swarms.list") && strstr(sent[1], "agents.list"));+ const int per = nsent;+ reset(); link_corrupt++; now_us += 1999 * 1000; pro_cable_tick(NULL); CHECK(nsent == 0);+ now_us += 1000 * 1000; pro_cable_tick(NULL); // past 2 s: the pending loss is answered+ CHECK(nsent == per);reset(); offer_active = true; link_corrupt++; now_us += 6000 * 1000; pro_cable_tick(NULL);CHECK(nsent == 0); // a transfer covers it with resendoffer_active = false; pro_cable_tick(NULL); CHECK(nsent == 0); // and the loss during it is not replayedend_session();}+static void link_resync(void)+{+ link_resync_with("{\"t\":\"welcome\",\"machine\":{\"id\":\"m1\",\"name\":\"Mac\"},\"features\":[\"resync\"]}", true);+ link_resync_with("{\"t\":\"welcome\",\"machine\":{\"id\":\"m1\",\"name\":\"Mac\"},\"features\":[\"player.library\"]}", false);+}++// The daemon's `seq`: contiguous frames are silent; a hole counts and asks for a resync (rate-limited); a welcome+// restarts the count; frames without seq (round-style, old daemon) change nothing; ending the session clears it.+static void seq_gaps(void)+{+ now_us += 10000 * 1000; // clear link_resync's window+ feed("{\"t\":\"welcome\",\"seq\":0,\"machine\":{\"id\":\"m\",\"name\":\"M\"},\"features\":[\"resync\"]}");+ reset();+ const uint32_t g0 = pro_cable_seq_gaps();+ feed("{\"t\":\"ping\",\"seq\":1}"); feed("{\"t\":\"ping\",\"seq\":2}"); feed("{\"t\":\"ping\"}");+ pro_cable_tick(NULL);+ CHECK(pro_cable_seq_gaps() == g0);+ for (int i = 0; i < nsent; i++) CHECK(!strstr(sent[i], "resync"));+ reset();+ feed("{\"t\":\"ping\",\"seq\":4}"); // 3 never arrived+ CHECK(pro_cable_seq_gaps() == g0 + 1);+ reset(); pro_cable_tick(NULL);+ CHECK(nsent == 1 && strstr(sent[0], "resync"));+ reset(); feed("{\"t\":\"ping\",\"seq\":5}"); pro_cable_tick(NULL);+ for (int i = 0; i < nsent; i++) CHECK(!strstr(sent[i], "resync")); // 5 follows 4: back in step+ CHECK(pro_cable_seq_gaps() == g0 + 1);+ reset();+ feed("{\"t\":\"ping\",\"seq\":9}"); pro_cable_tick(NULL); // a second hole inside the 2 s window+ CHECK(pro_cable_seq_gaps() == g0 + 2);+ int resyncs = 0;+ for (int i = 0; i < nsent; i++) resyncs += strstr(sent[i], "resync") != NULL;+ CHECK(resyncs == 0);+ reset(); now_us += 2000 * 1000; pro_cable_tick(NULL);+ CHECK(nsent == 1 && strstr(sent[0], "resync")); // answered once the window passes+ reset();+ feed("{\"t\":\"welcome\",\"seq\":0,\"machine\":{\"id\":\"m\",\"name\":\"M\"},\"features\":[\"resync\"]}"); // the count starts over+ feed("{\"t\":\"ping\",\"seq\":1}");+ CHECK(pro_cable_seq_gaps() == g0 + 2);+ end_session();+ CHECK(decoder_resets >= 1); // the session ended: no half-frame carried over+ reset();+ feed("{\"t\":\"welcome\",\"machine\":{\"id\":\"m\",\"name\":\"M\"}}"); // a daemon without seq+ feed("{\"t\":\"ping\"}"); feed("{\"t\":\"ping\",\"seq\":40}");+ CHECK(pro_cable_seq_gaps() == g0 + 2); // a welcome without seq turns the check off for the session+ end_session();+}int main(void){@@ -990,6 +1042,7 @@ int main(void)session_down_aborts_then_new_offer_ok();send_shapes();link_resync();+ seq_gaps();printf("test_pro_cable: %d checks passed\n", checks);return 0;}