From f4bab463d157c3344a4e713b1390782b78954e87 Mon Sep 17 00:00:00 2001 From: "Rich O." Date: Sun, 1 Nov 2026 11:46:04 -0500 Subject: [PATCH] palm-client: USB bench link works end to end Query radio on the Visor Neo got DEVICE_INFO from the XIAO via USB cradle -> visor_bridge.py -> FTDI -> D6/D7 UART. The app's HsUd driver sends on the Visor's HOTSYNC USB port (2), not GENERIC, so the bridge listens on every port and replies on the one in use; stalled endpoints are cleared instead of ending the session. The app waits after SrmOpen and retries sends that time out while the bridge attaches. make install stops the bridge, which would otherwise grab the Visor during HotSync. --- docs/progress.md | 2 + palm-client/Makefile | 3 + palm-client/README.md | 18 ++++ palm-client/src/main.c | 12 ++- .../__pycache__/visor_bridge.cpython-315.pyc | Bin 13816 -> 16372 bytes palm-client/tools/visor_bridge.py | 83 +++++++++++++----- 6 files changed, 96 insertions(+), 22 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index a3c29c7..9fd092c 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -29,6 +29,7 @@ - [ ] Original Handspring SDK headers (Springboard `HsCard*` APIs; the PalmOne `HsExt.h` lacks them), needed for module-ROM work only - [ ] Port springSD bus routines; SC16IS740 driver - [x] Companion protocol: framing, builders (DEVICE_QUERY, APP_START, GET_CONTACTS, SYNC_NEXT_MESSAGE), parsers (SELF_INFO, contacts, v3 contact/channel messages); host tests from real captures + MeshCore layouts +- [x] USB bench link: app (`HsUd`) → Visor USB cradle → `tools/visor_bridge.py` → FTDI → XIAO D6/D7. Query radio shows `Reply 0x000D, 82 bytes` on the Visor - [ ] Wire the protocol into the app: connect sequence, contact list, message sync on PUSH_MSG_WAITING - [ ] UI: contacts, DMs, channels - [x] Install method confirmed: HotSync over the USB cradle from the dev Mac (`make install`) @@ -59,3 +60,4 @@ - Firmware builds and runs. Fixed the patch's I2C override (`-U` flags broke Wire under PlatformIO; now `build_unflags`). Pinned native GCC 14 on Apple Silicon. Enabled the USB companion link alongside the UART. The XIAO answers DEVICE_QUERY over USB, and that real frame is now a Palm host test. - UART path verified: FT232R on D6/D7 at 115200 8N1 gets the same DEVICE_INFO as USB. The radio side of SB-LoRa is proven; what remains is the carrier board (SC16IS740 + bus) and the Palm transport for it. - Protocol layer for the read-only commands, built against MeshCore's MyMesh.cpp and captured replies (DEVICE_QUERY, APP_START → SELF_INFO, GET_CONTACTS with 0 contacts, SYNC → NO_MORE_MESSAGES). LE fields are assembled byte by byte for the big-endian 68k. The radio is on MeshCore factory defaults (869.618 MHz / 62.5 kHz / SF8, 22 dBm, no name). +- **First end-to-end round trip from the Visor:** DEVICE_QUERY from VisorMesh on the Neo went over USB, through the Mac bridge and the FTDI adapter, into the XIAO's UART, and DEVICE_INFO came back and decoded on the Visor. `HsUd` turned out to use the Visor's HOTSYNC USB port (2); the endpoints stall around open/close and need clear-halt. diff --git a/palm-client/Makefile b/palm-client/Makefile index 94a4c87..2e970d5 100644 --- a/palm-client/Makefile +++ b/palm-client/Makefile @@ -61,6 +61,9 @@ build: endif install: all + @if pgrep -f tools/visor_bridge.py >/dev/null; then \ + echo "Stopping visor_bridge.py (it would grab the Visor during HotSync)"; \ + pkill -f tools/visor_bridge.py; sleep 1; fi @echo "Press the HotSync button on the Visor cradle..." $(PILOT_XFER) -p $(PORT) -i build/$(APP).prc diff --git a/palm-client/README.md b/palm-client/README.md index e5bbd34..fe7cef6 100644 --- a/palm-client/README.md +++ b/palm-client/README.md @@ -53,6 +53,24 @@ The Makefile uses `~/.local/bin/pilot-xfer` when it exists. On Linux, use the ke Verified: `pilot-xfer -p usb: -l` lists the Visor Neo's databases from macOS on Apple Silicon. The Visor is behind a USB hub, so a hub works. +## Testing against a real radio over USB (before the boards arrive) + +`tools/visor_bridge.py` connects the app to a MeshCore companion radio through the Visor's USB cradle: + +```sh +tools/visor_bridge.py /dev/cu.usbserial-XXXX # radio's D6/D7 UART on a 3.3 V USB-TTL adapter +tools/visor_bridge.py /dev/cu.usbmodemXXXX # or the XIAO's own USB companion link +``` + +In VisorMesh, set **Link** to **USB** and tap **Query radio**. The app opens the Neo's `'HsUd'` Serial Manager driver, so the Visor appears on USB. The bridge reads the Visor's port list (vendor request `0x03`), forwards bytes to the radio, and logs every companion frame in both directions. What we found while getting it working: + +- `HsUd` sends on the Visor's HOTSYNC USB port (2), not GENERIC (1). The bridge listens on every port and replies on whichever one the Visor used. +- The endpoints stall briefly around open and close, so the bridge clears them (`libusb_clear_halt`) and carries on. +- The Visor only appears on USB after `SrmOpen`. The app waits a second, then retries sends that time out (`serErrTimeOut`, 0x0305) while the bridge attaches. +- The bridge grabs the Visor during a HotSync too, so `make install` stops it first. + +The Ports screen lists the Neo's Serial Manager drivers: `A8xZ` Serial, `HaSA` USB/Serial, `HsUc` USB Console, `HsUd` USB, `HsUr` USB RemoteFS, and more. + ## Testing without hardware The Visor can't be emulated on a Mac: CloudpilotEmu doesn't support Handspring devices. Use CloudpilotEmu (https://cloudpilot-emu.github.io/app) with a Palm OS 3.5 device ROM, such as a Palm IIIx or m100. The OS APIs match the Neo's. In the emulator, "Query radio" should report "No reply" or an open error, since there's no radio attached. diff --git a/palm-client/src/main.c b/palm-client/src/main.c index 42d000c..ceb70fd 100644 --- a/palm-client/src/main.c +++ b/palm-client/src/main.c @@ -53,8 +53,18 @@ static void QueryRadio(void) frameLen = VmBuildDeviceQuery(frame, sizeof(frame)); VmDecoderReset(&gDecoder); + /* Over USB the Visor only appears to the host after SrmOpen; give the bridge time to attach. */ + if (TransportGetPort() == VM_PORT_USB) + SysTaskDelay(SysTicksPerSecond()); + for (attempt = 1; attempt <= VM_QUERY_ATTEMPTS; attempt++) { err = TransportSend(frame, frameLen); + if (err == serErrTimeOut) { + /* Nobody reading yet (host still attaching): try again next attempt. */ + StrPrintF(msg, "Host not ready (%u)...", attempt); + SetStatus(msg); + continue; + } if (err != errNone) { StrPrintF(msg, "Send failed (0x%x)", err); SetStatus(msg); @@ -78,7 +88,7 @@ static void QueryRadio(void) } } } - SetStatus("No reply"); + SetStatus(err == serErrTimeOut ? "Send timed out" : "No reply"); TransportClose(); } diff --git a/palm-client/tools/__pycache__/visor_bridge.cpython-315.pyc b/palm-client/tools/__pycache__/visor_bridge.cpython-315.pyc index 3b8c0a34ebcae0f6b9cfa82d10de0de0dcfcb7d9..a2895a8f938bc77af094b5cb1c26a5a8fd71c9c8 100644 GIT binary patch delta 5665 zcmb7Idr(~0c|Uh|@4lbxgEw42EG*(FAt8e-8S$tjV^+Ixkz|CH6?=gduos=XNEWfZ zICWbj*%tVWMl?-lNZTa1PRFQtY8)qxq)M?m%`{8F1@AENc*ZlW{)=RHlz5V%-?_UB za%M8q9){nZ$9LY}_xrwce>3t`%OCd-tq4i#aq~c17hYlQL!(a~b>W zFPe@ye0feJIeqznE;}kjz5*xm74A{cjtEJaJ`P&4d_{oSzGA=}UkPCDnLOXF{ihHb zfGKj&nOt&$ajMFL8A=jnexl^Njx0T+Xk}vE!vYr^A1{-*vZE3oD&s;pd{Mw$bOJ{t zPMnBxQIV5`NQe_7ToivU%eH!k8RSH8zn$w{J~3Y^2?&=3qdDv8_> z4xW>Cx^bZi9F7ceLGGv+?YbNpXgthGQE{9LN4aytpoj&oe=Im6aN&p)4UUfX>&xkg zFF@5`cvRp*qCiIrOB~2@m&FOs(zlfV%qVWN#Ax2N6kso?$ZbuXx>CV2-f~i;wv$D* zgT!?%rUFW3WJ=>;8EB&=+NL8d`YJCq3q`mYXns_ZpY@#fMGO}mse z^&p&342BYHFdD^@q=d4Y(spr)04ZN1GLARpN(8Sm16+iID@ z6HtwP6#Nvr03;T`O%vWv8tf&EpY+;mm;+1K?7vrfs08K#5~{&)BqaAuu<||<%26Sb zV9#BS3KI5{TbZR=I=n}Vd&sXc_vg!tQVj}1C}C~K!7-sj92ydEHLdAcs>=#9c?YOG zE02%mrERYY`^Z0Kx2jLl=`XyU(`KQg;m$O8Nq0`Mns&#XOE2eW6-*Hq2N*BeYB1lPB4Ll0uM+kD8ebGj?sK67>))&BLWwx zZsOOWb&OQzznej)8%S9SWD(LYJlc3*1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z{2Ve^pk6vR+ Q|Hkr<_HQtN^{8w92V-_8?f?J) diff --git a/palm-client/tools/visor_bridge.py b/palm-client/tools/visor_bridge.py index d84d630..4e81325 100755 --- a/palm-client/tools/visor_bridge.py +++ b/palm-client/tools/visor_bridge.py @@ -2,13 +2,16 @@ """Bridge the Visor's USB data port to a MeshCore radio's serial port. For testing the Palm client before the SB-LoRa boards exist: the app opens the -Visor's 'HsUd' Serial Manager driver (the USB GENERIC port) and this forwards +Visor's 'HsUd' Serial Manager driver (USB) and this forwards bytes between it and the radio, logging each companion frame. visor_bridge.py /dev/cu.usbserial-XXXX # radio on a USB-TTL adapter (D6/D7) visor_bridge.py /dev/cu.usbmodemXXXX # radio's own USB companion link Then put the Visor in its USB cradle and tap "Query radio" with Link = USB. +The app's 'HsUd' driver turns out to send on the Visor's HOTSYNC port (2), so +the bridge also grabs the Visor during a HotSync: stop it before `make install` +(the Makefile does this for you). Needs libusb-1.0 (brew install libusb); everything else is the standard library. """ import argparse @@ -31,6 +34,7 @@ FUNCTIONS = {0: 'GENERIC', 1: 'DEBUGGER', 2: 'HOTSYNC', 3: 'CONSOLE', 4: 'REMOTE LIBUSB_ERROR_TIMEOUT = -7 LIBUSB_ERROR_NO_DEVICE = -4 +LIBUSB_ERROR_PIPE = -9 CODES_TO_RADIO = {1: 'APP_START', 2: 'SEND_TXT_MSG', 3: 'SEND_CHANNEL_TXT_MSG', 4: 'GET_CONTACTS', 10: 'SYNC_NEXT_MESSAGE', 22: 'DEVICE_QUERY'} @@ -53,6 +57,7 @@ def load_libusb(): ctypes.c_uint16, ctypes.c_char_p, ctypes.c_uint16, ctypes.c_uint] lib.libusb_bulk_transfer.argtypes = [ctypes.c_void_p, ctypes.c_uint8, ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(ctypes.c_int), ctypes.c_uint] + lib.libusb_clear_halt.argtypes = [ctypes.c_void_p, ctypes.c_uint8] lib.libusb_error_name.restype = ctypes.c_char_p lib.libusb_error_name.argtypes = [ctypes.c_int] if lib.libusb_init(None) != 0: @@ -117,8 +122,8 @@ def wait_for_visor(lib): time.sleep(0.1) -def generic_port(lib, h): - """Asks the Visor which USB port number carries each function; returns the GENERIC one.""" +def connection_ports(lib, h): + """Asks the Visor which USB port number carries each function. Returns {port: function name}.""" buf = ctypes.create_string_buffer(0x12) n = lib.libusb_control_transfer(h, VISOR_REQ_TYPE_IN, VISOR_GET_CONNECTION_INFORMATION, 0, 0, buf, 0x12, 2000) if n < 2: @@ -130,35 +135,63 @@ def generic_port(lib, h): if 2 + 2 * k + 1 >= n: break func, port = raw[2 + 2 * k], raw[3 + 2 * k] - ports[func] = port - print(f' port {port}: {FUNCTIONS.get(func, hex(func))}', flush=True) + ports[port] = FUNCTIONS.get(func, hex(func)) + print(f' port {port}: {ports[port]}', flush=True) avail = ctypes.create_string_buffer(2) lib.libusb_control_transfer(h, VISOR_REQ_TYPE_IN, VISOR_REQUEST_BYTES_AVAILABLE, 0, 0, avail, 2, 2000) - if 0 not in ports: - raise RuntimeError('Visor did not offer a GENERIC port (is the app using the HsUd driver?)') - return ports[0] + if not ports: + raise RuntimeError('Visor reported no ports') + return ports -def bridge(lib, h, port, serial_fd, quiet): - ep_in, ep_out = 0x80 | port, port +def bridge(lib, h, ports, serial_fd, quiet): + """ + Listens on every port's IN endpoint, since which one the app's driver uses + isn't documented. Radio replies go out on the port the Visor last sent on. + Stalled endpoints are cleared and retried rather than ending the session. + """ to_radio = FrameLogger('visor->radio', b'<', CODES_TO_RADIO, quiet) to_visor = FrameLogger('radio->visor', b'>', CODES_FROM_RADIO, quiet) gone = threading.Event() + lock = threading.Lock() + active = {'port': None} - def usb_to_serial(): + for port in ports: + lib.libusb_clear_halt(h, 0x80 | port) + lib.libusb_clear_halt(h, port) + + def stop(where, rc): + with lock: + if not gone.is_set() and rc != LIBUSB_ERROR_NO_DEVICE: + print(f'{where}: {lib.libusb_error_name(rc).decode()} ({rc})', flush=True) + gone.set() + + def usb_to_serial(port): + ep_in = 0x80 | port buf = ctypes.create_string_buffer(512) got = ctypes.c_int(0) + stalls = 0 while not gone.is_set(): rc = lib.libusb_bulk_transfer(h, ep_in, buf, len(buf), ctypes.byref(got), 200) if got.value: + if active['port'] != port: + active['port'] = port + print(f'Visor is sending on port {port} ({ports[port]})', flush=True) data = buf.raw[:got.value] os.write(serial_fd, data) to_radio.feed(data) - if rc not in (0, LIBUSB_ERROR_TIMEOUT): - gone.set() + if rc == LIBUSB_ERROR_PIPE: + stalls += 1 + if stalls in (10, 100): + print(f'bulk read 0x{ep_in:02x} stalled ({stalls}x), clearing', flush=True) + lib.libusb_clear_halt(h, ep_in) + time.sleep(0.05) + elif rc not in (0, LIBUSB_ERROR_TIMEOUT): + stop(f'bulk read 0x{ep_in:02x}', rc) - t = threading.Thread(target=usb_to_serial, daemon=True) - t.start() + readers = [threading.Thread(target=usb_to_serial, args=(p,), daemon=True) for p in ports] + for t in readers: + t.start() got = ctypes.c_int(0) while not gone.is_set(): r, _, _ = select.select([serial_fd], [], [], 0.2) @@ -166,10 +199,18 @@ def bridge(lib, h, port, serial_fd, quiet): continue data = os.read(serial_fd, 512) to_visor.feed(data) - rc = lib.libusb_bulk_transfer(h, ep_out, data, len(data), ctypes.byref(got), 2000) + port = active['port'] + if port is None: + print('radio sent data before the Visor did; dropped', flush=True) + continue + rc = lib.libusb_bulk_transfer(h, port, data, len(data), ctypes.byref(got), 2000) + if rc == LIBUSB_ERROR_PIPE: + lib.libusb_clear_halt(h, port) + rc = lib.libusb_bulk_transfer(h, port, data, len(data), ctypes.byref(got), 2000) if rc != 0: - gone.set() - t.join(1) + stop(f'bulk write 0x{port:02x}', rc) + for t in readers: + t.join(1) def main(): @@ -185,9 +226,9 @@ def main(): h = wait_for_visor(lib) print('Visor connected', flush=True) try: - port = generic_port(lib, h) - print(f'Bridging Visor USB port {port} <-> {args.radio}', flush=True) - bridge(lib, h, port, serial_fd, args.quiet) + ports = connection_ports(lib, h) + print(f'Bridging Visor USB ports {sorted(ports)} <-> {args.radio}', flush=True) + bridge(lib, h, ports, serial_fd, args.quiet) except RuntimeError as e: print(e, flush=True) finally: