Files
MicrOBU/obu-firmware/main/serial_link.h
T
Ashin WalpolaandClaude Opus 5 528637dab6 Fix UPER encoding of CurvatureCalculationMode; verified on hardware
CurvatureCalculationMode is the one extensible ENUMERATED in CAM:
  ENUMERATED {yawRateUsed(0), yawRateNotUsed(1), unavailable(2), ...}
UPER encodes an extensible ENUMERATED as an extension bit followed by the root
index - 1 + 2 = 3 bits. All three of our encoders wrote only the 2-bit index,
shifting yawRate and the entire low-frequency container one bit early for any
standards-compliant receiver.

It went unnoticed because every end of this project shared the mistake: the
Kotlin codec was ported bit-for-bit from cam.c, so phone and ESP32 agreed
perfectly with each other and with nothing else. Confirmed against the ETSI
ASN.1 in the C-ITS-Parser checkout, where rasn marks this type - and only this
type - #[non_exhaustive].

Fixed in all three copies of the encoder (app CamUperCodec.kt,
obu-firmware/main/cam.c, obu-cam-transmistter/main/cam.c) plus the decoder,
which now rejects rather than misreads a set extension bit. Frame size is
unchanged at 43 bytes. Transmitter reflashed and the phone decodes its CAMs.

Also in this change:

- serial_link: skip send_frame entirely when no USB host is attached, and raise
  the tx mutex timeout above the worst-case hold. With the phone unplugged every
  write blocked its full timeout while holding the lock, so forwarded CAM_RX
  traffic starved the 1 Hz heartbeat - observed as "tx mutex timeout, dropping
  frame" on the console, and it would have tripped the phone's link watchdog.
  Verified gone on hardware.
- Log decoded and failed CAMs in CamUseCaseRepository. "The app shows nothing"
  had two indistinguishable causes; a silent `?: return` made this bug much
  harder to find than it needed to be.
- Remove the ESP32 send-only/send-and-receive toggle. Reception can't be
  disabled in firmware (raw TX only works while promiscuous), so it was an
  app-side filter pretending to be a radio control.
- V2X monitor follows the serial link state on the ESP32 path instead of MQTT,
  which is permanently disconnected there; CAM intake is gated on the link being
  up, and engine state is cleared when it drops.
- About screen: 0.5.0, Phase 03.
- Track obu-cam-transmistter, the bench CAM transmitter. Its cam.c is compiled
  (unlike obu-firmware's reference copy) and must stay bit-identical to the other
  two - this commit is what that coupling costs when it's broken.
- Document the two-toolchain split: this project builds on IDF 5.5.4, obu-firmware
  on the pinned 6.1. Exporting both in one shell fails confusingly.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 14:50:35 +02:00

94 lines
6.0 KiB
C

#ifndef SERIAL_LINK_H
#define SERIAL_LINK_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
// Binary framing for the phone <-> ESP32-C5 link (Phase 03). This runs over the ESP32-C5's
// native USB Serial/JTAG peripheral (driver/usb_serial_jtag.h) - the same physical USB-C port
// used for JTAG, exposed to the host as a fixed-VID/PID (0x303A/0x1001) USB CDC-ACM device.
// Deliberately NOT the same wire as the ESP-IDF console/ESP_LOG output, which stays on the
// OTHER USB-C port (the UART-bridge one, UART0, see sdkconfig CONFIG_ESP_CONSOLE_UART_NUM=0) -
// mixing binary frames with human-readable log text on one wire would corrupt both, and this
// way they're physically separate ports so there's no risk of that regardless.
//
// On the Android side, connect the phone (via USB-OTG) to the board's NATIVE USB-C port, not
// the UART-bridge/flashing port. The usb-serial-for-android library's default prober doesn't
// know Espressif's 0x303A/0x1001 VID/PID, so UsbSerialTransport.kt registers it manually via a
// custom ProbeTable pointed at CdcAcmSerialDriver - see that file's KDoc.
//
// Frame format (both directions, symmetric):
// [0xAA][0x55][type:1][length:2 LE][payload: length bytes][crc16:2 LE]
// CRC16 is CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, no reflect, no xorout), computed over
// type + length + payload only (not the two sync bytes). Same algorithm must be used on the
// Kotlin side (see app SerialFrame.kt) - frames that don't checksum are silently dropped.
//
// Direction / types:
// SERIAL_MSG_CAM_TX (0x01), phone -> ESP32: payload is a raw CAM UPER byte string, already
// built by the phone (position/speed/heading/yaw rate baked in). On receipt the ESP32
// immediately GeoNetworking-wraps and transmits it - this IS the transmit clock now, there
// is no independent on-chip timer. See main.c's rx-driven tx path.
// SERIAL_MSG_CAM_RX (0x02), ESP32 -> phone: payload is [rssi:1 signed][CAM UPER bytes...] - a
// CAM received over the air, already stripped of its 802.11/LLC-SNAP/GeoNetworking/BTP-B
// framing by gn_unwrap.c. The phone never sees raw 802.11 frames. No station id is carried
// separately - CAM's own ItsPduHeader.stationID (the first field inside the UPER bytes) is
// already the meaningful identifier; see gn_unwrap.h for why a second one isn't added here.
// SERIAL_MSG_STATUS (0x03), ESP32 -> phone: heartbeat + counters, sent at 1 Hz so the phone can
// distinguish "link idle" from "link dead" independent of CAM traffic (the app's watchdog in
// UsbSerialTransport.kt declares the link dead after 3 missed beats). Payload is 7 bytes:
// [status:1][oversize_drops:2 LE][tx_failures:2 LE][rx_crc_errors:2 LE]
// status 0 = ok. The counters are free-running totals since boot, saturating at 0xFFFF.
// They exist because the alternative - ESP_LOGW on the flashing port - is invisible to the
// phone, which is the only thing watching during a bench session. Mirrored by EspLinkStatus
// in the app's SerialFrame.kt.
#define SERIAL_MSG_CAM_TX 0x01
#define SERIAL_MSG_CAM_RX 0x02
#define SERIAL_MSG_STATUS 0x03
// USB Serial/JTAG has no baud rate or GPIO pins to configure - it's a fixed on-chip USB device
// controller wired directly to the native USB-C port's D+/D- lines in silicon. RX/TX buffer
// sizes for usb_serial_jtag_driver_install() (see serial_link.c) are sized generously relative
// to SERIAL_LINK_MAX_PAYLOAD below.
#define SERIAL_LINK_USB_BUF_SIZE 1024
// Per-write block ceiling, and the mutex acquire timeout that must comfortably exceed the
// worst case of one frame (4 writes: sync, head, payload, crc). Keep that relationship if you
// change either number - a lock timeout below the max hold turns normal contention into
// dropped frames, which is how the heartbeat was being starved by forwarded CAM_RX traffic.
#define SERIAL_LINK_WRITE_TIMEOUT_MS 100
#define SERIAL_LINK_TX_LOCK_TIMEOUT_MS 600
// Max CAM payload this link will carry. MUST match SERIAL_LINK_MAX_PAYLOAD in the app's
// SerialFrame.kt - a mismatch means every frame above the smaller of the two is rejected by that
// side's "length exceeds max, resync" branch, silently.
//
// Raised from 160 to 512: 160 was reasoned from cam.c's 96-byte encode buffer, which only ever
// described OUR OWN minimal CAM. A third-party CAM off the air carrying a path-history or
// special-vehicle container comfortably exceeds it, and those stations would then never reach the
// phone at all. 512 clears any realistic CAM; the real upstream ceiling on the RX path is
// rx_item_t.data (400 bytes) in main.c, so nothing larger can get here anyway.
#define SERIAL_LINK_MAX_PAYLOAD 512
// Initializes the USB Serial/JTAG driver and its background RX-framing and 1 Hz heartbeat tasks.
// Call once from app_main, after nvs/event loop init. `on_cam_tx` is invoked (from the RX task's
// context - keep it fast, it blocks the next frame's parsing) whenever a complete, checksummed
// SERIAL_MSG_CAM_TX frame arrives from the phone.
typedef void (*serial_link_cam_tx_cb_t)(const uint8_t *cam_uper, int cam_len);
void serial_link_init(serial_link_cam_tx_cb_t on_cam_tx);
// Sends a SERIAL_MSG_CAM_RX frame to the phone: rssi + the CAM UPER bytes gn_unwrap.c extracted
// from an over-the-air frame. Returns true if the frame was written to the UART (not an
// end-to-end ack - the phone may still drop it, e.g. serial buffer overrun).
bool serial_link_send_cam_rx(int8_t rssi, const uint8_t *cam_uper, int cam_len);
// Sends one SERIAL_MSG_STATUS heartbeat frame immediately (status byte + the current counters).
// Normally unnecessary to call by hand - serial_link_init() starts a task that does this at 1 Hz.
bool serial_link_send_status(uint8_t status);
// Records a failed esp_wifi_80211_tx() so it shows up in the next heartbeat's tx_failures
// counter. Called from main.c's tx_radio_task - a CAM that reached the radio but didn't go out is
// otherwise indistinguishable, from the phone's side, from one that transmitted fine.
void serial_link_note_tx_failure(void);
#endif