From c2475536e39dbf6f179fa573e0615fcb5f8e73ac Mon Sep 17 00:00:00 2001 From: Jessica Janiuk Date: Wed, 4 Nov 2026 19:36:21 -0800 Subject: [PATCH] V2 firmware: pin map and XBee over UART Add a V2 build (pio run -e esp32s3_v2, -D SNIPS_BOARD_V2) for the ESP32-S3-MINI-1U board, with its own pin map and the XBee on the optional UART carrier. - pin_assignment.h: V2 map from PCB/v2.x/snips/GPIO_table.md beside the unchanged V1 map. IMU uses V2's mounting table. - XBee transport split: XbeeLink (frame in/out) with XbeeSpi (V1) and XbeeUart (V2) as thin adapters, and the AT/transmit/receive logic moved out of the SPI adapter into the pure, tested XbeeApi. - XbeeFrameReader assembles API frames from the UART byte stream. - XbeeUartSetup gets the carrier's XBee to API mode (AP=1) at 115200 from whatever state it's in (factory transparent 9600, API 9600, or transparent 115200), saving the change with WR. - No carrier: CTS (pulled up) reads high, so the link is skipped and every XBee call fails cleanly. No hardware flow control, so a missing or sleeping module can't block writes. - CI builds both boards. xbee_uart.cpp joins xbee_spi.cpp in the coverage exclusion list as a Serial1 adapter. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 7 +- PCB/v2.x/snips/GPIO_table.md | 2 +- README.md | 5 +- include/pin_assignment.h | 88 +++++++++++- include/xbee_api.h | 42 ++++++ include/xbee_control.h | 31 +++-- include/xbee_frame_reader.h | 37 +++++ include/xbee_link.h | 24 ++++ include/xbee_spi.h | 54 ++------ include/xbee_uart.h | 49 +++++++ include/xbee_uart_setup.h | 49 +++++++ platformio.ini | 16 ++- src/SnipsController.ino | 5 +- src/xbee_api.cpp | 97 +++++++++++++ src/xbee_control.cpp | 31 +++-- src/xbee_frame_reader.cpp | 37 +++++ src/xbee_spi.cpp | 96 +------------ src/xbee_uart.cpp | 144 +++++++++++++++++++ src/xbee_uart_setup.cpp | 52 +++++++ test/test_xbee_api/test_xbee_api.cpp | 183 ++++++++++++++++++++++++ test/test_xbee_uart/test_xbee_uart.cpp | 185 +++++++++++++++++++++++++ 21 files changed, 1069 insertions(+), 165 deletions(-) create mode 100644 include/xbee_api.h create mode 100644 include/xbee_frame_reader.h create mode 100644 include/xbee_link.h create mode 100644 include/xbee_uart.h create mode 100644 include/xbee_uart_setup.h create mode 100644 src/xbee_api.cpp create mode 100644 src/xbee_frame_reader.cpp create mode 100644 src/xbee_uart.cpp create mode 100644 src/xbee_uart_setup.cpp create mode 100644 test/test_xbee_api/test_xbee_api.cpp create mode 100644 test/test_xbee_uart/test_xbee_uart.cpp diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7415f1e..b45edf6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -122,7 +122,7 @@ jobs: - name: Coverage report run: | - output=$(gcovr --root . --filter 'src/' --exclude 'src/SnipsController\.ino' --exclude 'src/oled\.cpp' --exclude 'src/rgb_led\.cpp' --exclude 'src/calibration_store\.cpp' --exclude 'src/droid_persistence\.cpp' --exclude 'src/xbee_spi\.cpp' --exclude 'src/xbee_control\.cpp' --exclude 'src/display_layout_store\.cpp' --exclude 'src/accelerometer\.cpp' --exclude 'src/power_config_store\.cpp' --print-summary --fail-under-line 90) + output=$(gcovr --root . --filter 'src/' --exclude 'src/SnipsController\.ino' --exclude 'src/oled\.cpp' --exclude 'src/rgb_led\.cpp' --exclude 'src/calibration_store\.cpp' --exclude 'src/droid_persistence\.cpp' --exclude 'src/xbee_spi\.cpp' --exclude 'src/xbee_uart\.cpp' --exclude 'src/xbee_control\.cpp' --exclude 'src/display_layout_store\.cpp' --exclude 'src/accelerometer\.cpp' --exclude 'src/power_config_store\.cpp' --print-summary --fail-under-line 90) status=$? { echo '### Coverage (src/, excluding SnipsController.ino and hardware adapters)' @@ -155,5 +155,8 @@ jobs: - name: Install PlatformIO run: pip install --upgrade platformio - - name: Build esp32s3 firmware + - name: Build esp32s3 firmware (V1) run: pio run -e esp32s3 + + - name: Build esp32s3_v2 firmware (V2) + run: pio run -e esp32s3_v2 diff --git a/PCB/v2.x/snips/GPIO_table.md b/PCB/v2.x/snips/GPIO_table.md index 697129a..d942e95 100644 --- a/PCB/v2.x/snips/GPIO_table.md +++ b/PCB/v2.x/snips/GPIO_table.md @@ -25,7 +25,7 @@ Pins are chosen by position, not carried over from V1, so V2 needs its own firmw - **TXD0 (IO43)** prints the boot log, so it stays free for debugging. RGB data has moved off it, so the LED no longer sees that traffic. - **Boot glitches:** the low-level power-up glitches on IO1-IO17 (Table 2-2, where IO15 and IO16 appear as XTAL_32K) are 60 µs. Those pins carry only inputs, except IO1 (SLEEP_RQ, where low means awake). XBee RESET is on IO42, which has no listed glitch. - **IO26 stays unconnected.** It is the PSRAM chip-select, and Arduino runs a PSRAM probe at every boot, so it is driven before `setup()`. The probe fails on the -N8, which has no PSRAM, and boot continues. -- **Do not flash V1 firmware on V2.** It would treat V2 pins as SPI and read the wrong buttons. V2 needs its own pin map. +- **Do not flash V1 firmware on V2.** It would treat V2 pins as SPI and read the wrong buttons. Build V2 firmware with `pio run -e esp32s3_v2`, which uses V2's pin map in `include/pin_assignment.h`. - **EN:** 10 kΩ and 1 µF, as Espressif advises (Peripheral Schematics), so EN crosses 0.75 × VDD about 14 ms after the rail is up. V1 has no capacitor. - **Pad 61:** the thermal pad is 9 segments, soldered to GND. diff --git a/README.md b/README.md index 03d4e9b..da38a68 100644 --- a/README.md +++ b/README.md @@ -75,9 +75,12 @@ This is yet to be determined since we're so early in the prototype stage, but th Requires [PlatformIO](https://platformio.org/) (CLI or IDE extension). ```bash -# Build the firmware +# Build the firmware for V1.x boards (the default) pio run +# Build the firmware for V2 boards +pio run -e esp32s3_v2 + # Run unit tests (no hardware required) pio test -e native ``` diff --git a/include/pin_assignment.h b/include/pin_assignment.h index b3ae089..09e626b 100644 --- a/include/pin_assignment.h +++ b/include/pin_assignment.h @@ -1,15 +1,89 @@ #pragma once -// Raw GPIO pin assignments for the Snips Controller (ESP32-S3-WROOM-1). -// Values here are Arduino GPIO numbers (e.g. 16 means GPIO16), not the -// module's physical pin numbers used in the PCB docs. +// Raw GPIO pin assignments for the Snips Controller. Values here are +// Arduino GPIO numbers (e.g. 16 means GPIO16), not the module's physical +// pin numbers used in the PCB docs. // -// This file is pure reference data — it should stay a 1:1 mirror of -// PCB/v1.x/GPIO_table.md. Cross-reference that file for the physical-pin-to-GPIO -// mapping, reserved pins, and the rationale behind each assignment. +// Two boards, picked at build time: +// - V1.x (ESP32-S3-WROOM-1, `pio run -e esp32s3`): a 1:1 mirror of +// PCB/v1.x/GPIO_table.md. The XBee is on SPI. +// - V2 (ESP32-S3-MINI-1U, `pio run -e esp32s3_v2`, which defines +// SNIPS_BOARD_V2): a 1:1 mirror of PCB/v2.x/snips/GPIO_table.md. The +// XBee is on an optional carrier board, over UART. +// The two maps are not interchangeable: V1 firmware on a V2 board would +// read the wrong buttons. Cross-reference the GPIO tables for the +// physical-pin-to-GPIO mapping, reserved pins, and the rationale behind +// each assignment. namespace PinAssignment { +#if defined(SNIPS_BOARD_V2) + +// ---- UART (XBee carrier, pads 1-6) ---------------------------------------- +// The ESP32 transmits on the XBee's DIN and receives on its DOUT. CTS is +// the XBee's output (low = ready); RTS is its input. With no carrier fitted +// these float, so the transport pulls CTS, DOUT and ON/SLEEP up and treats +// CTS high as "no XBee" (see xbee_uart.h). +constexpr int kXbeeUartTx = 35; // carrier pad 2, XBee DIN +constexpr int kXbeeUartRx = 36; // carrier pad 3, XBee DOUT +constexpr int kXbeeCts = 34; // carrier pad 1 +constexpr int kXbeeRts = 39; // carrier pad 4 +constexpr int kXbeeOnSleep = 41; // carrier pad 5 +// Carrier pad 6. Drive open drain only: low, or released (input). The +// pull-up is on the carrier. +constexpr int kXbeeReset = 42; +// Carrier pad 7, XBee DTR/SLEEP_RQ. Low = stay awake; set it as one of the +// first instructions in setup(), same as on V1. +constexpr int kXbeeSleepRq = 1; + +// ---- I2C (OLED, ICM-42670-P IMU) ------------------------------------------ +constexpr int kI2cSda = 12; +constexpr int kI2cScl = 13; + +// ---- IMU interrupt (ICM-42670-P INT1) -------------------------------------- +// No longer on a strap pin, unlike V1's GPIO46. +constexpr int kAccelInterrupt = 37; + +// ---- ADC1 (analog trigger, thumbstick, battery sense) ----------------------- +constexpr int kAnalogTrigger = 9; +constexpr int kThumbstickX = 7; +constexpr int kThumbstickY = 6; +constexpr int kVsysSense = 10; // divide-by-3, same as V1 + +// ---- Digital buttons ------------------------------------------------------- +// Same names and meanings as V1; only the GPIOs moved. V2 has one bumper. +constexpr int kVolUp = 38; +constexpr int kVolDown = 40; +constexpr int kTriggerUp = 33; +constexpr int kTriggerDown = 18; +constexpr int kDigitalTrigger = 47; // bumper +constexpr int kThumbstickClick = 17; +constexpr int kMacro1 = 16; +constexpr int kMacro2 = 5; +constexpr int kMacro3 = 4; +constexpr int kMacro4 = 11; +constexpr int kMacro5 = 8; +constexpr int kMacro6 = 2; + +// ---- Power ------------------------------------------------------------------- +// RTC-domain pin, like V1's GPIO2. +constexpr int kPowerButtonSense = 21; +// RXD0. Its pull-up holds the latch through any reset or USB upload. +// Firmware drives it high early in boot and low to power off, and must +// never start UART0 receive on it (Serial is native USB, so it doesn't). +constexpr int kPowerLatchHold = 44; + +// ---- Charging (bq25185) ---------------------------------------------------- +constexpr int kChargeStat1 = 15; +constexpr int kChargeStat2 = 14; + +// ---- RGB status LED (SK6812, RMT-driven) ------------------------------------- +// Moved off TXD0, which prints the boot log. +constexpr int kRgbLedData = 48; + +#else // V1.x + + // ---- SPI (XBee) -------------------------------------------------------- constexpr int kXbeeSpiSck = 10; constexpr int kXbeeSpiMosi = 11; @@ -71,4 +145,6 @@ constexpr int kChargeStat2 = 41; // ---- RGB status LED (SK6812/WS2812, RMT-driven) --------------------------- constexpr int kRgbLedData = 43; +#endif // SNIPS_BOARD_V2 + } // namespace PinAssignment diff --git a/include/xbee_api.h b/include/xbee_api.h new file mode 100644 index 0000000..d567c96 --- /dev/null +++ b/include/xbee_api.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +#include "xbee_link.h" + +// The XBee API operations this firmware uses, over any XbeeLink: local AT +// commands, sending our application payload to the coordinator, and +// polling for payloads from it. Pure: the clock and the idle hook are +// passed in, so native tests can drive it with a fake link. +class XbeeApi { + public: + using ClockFn = unsigned long (*)(); + using IdleFn = void (*)(); + + XbeeApi(XbeeLink *link, ClockFn clock, IdleFn idle) + : link_(link), clock_(clock), idle_(idle) {} + + // Sends a local AT command and waits (up to timeoutMs) for the matching + // (by frame ID) AT Command Response. Returns false on a build failure, + // a non-OK status, or timeout. outValue/outValueLength may be null. + bool sendAtCommand(const char *atCmd, const uint8_t *value, + uint8_t valueLength, uint8_t *outValue, + uint8_t outValueCapacity, uint8_t *outValueLength, + unsigned long timeoutMs = 200); + + // Sends our own application payload to the coordinator as a Transmit + // Request (0x10). Fire-and-forget: the XBee's own ACK/retry handles + // reliability at the radio level. + void sendPacket(const uint8_t *payload, uint16_t payloadLength); + + // Reads at most one queued frame, returning the payload of a Receive + // Packet (0x90). Frames of any other type are discarded. Returns false + // if nothing usable was read this call. + bool pollForPacket(uint8_t *outPayload, uint16_t outPayloadCapacity, + uint16_t *outPayloadLength); + + private: + XbeeLink *link_; + ClockFn clock_; + IdleFn idle_; +}; diff --git a/include/xbee_control.h b/include/xbee_control.h index 7aca127..b96ff32 100644 --- a/include/xbee_control.h +++ b/include/xbee_control.h @@ -3,18 +3,26 @@ #include #include "droid_switcher.h" +#include "xbee_api.h" #include "xbee_role.h" +#if defined(SNIPS_BOARD_V2) +#include "xbee_uart.h" +#else #include "xbee_spi.h" +#endif -// Real XbeeTransport (see droid_switcher.h), over the SPI transport in -// xbee_spi.h. Exact AT command sequencing (NR for leave, ID for the new +// Real XbeeTransport (see droid_switcher.h), over the board's XBee link: +// SPI on V1 (xbee_spi.h), UART to the optional carrier on V2 +// (xbee_uart.h). Exact AT command sequencing (NR for leave, ID for the new // PAN, AC to apply and trigger rejoin) is this class's best-effort // reading of Digi's XBee3 manual, not yet validated against real // hardware — confirm during this PR's bring-up and adjust here if the // sequence needs correcting. class XbeeControl : public XbeeTransport, public XbeeRoleTransport { public: - void begin() { spi_.begin(); } + XbeeControl(); + + void begin() { link_.begin(); } bool leaveNetwork() override; bool setPanId(const char *panId) override; @@ -50,18 +58,23 @@ class XbeeControl : public XbeeTransport, public XbeeRoleTransport { // Returns false on query failure, leaving outDbm untouched. bool queryLocalRssiDbm(int *outDbm); - // Passthroughs to the owned XbeeSpi — see xbee_spi.h. XbeeControl is - // kept as the single facade over the one physical XBee connection - // rather than SnipsController.ino owning a second XbeeSpi instance. + // Passthroughs to the API over the owned link — see xbee_api.h. + // XbeeControl is kept as the single facade over the one physical XBee + // connection rather than SnipsController.ino owning a second one. void sendPacket(const uint8_t *payload, uint16_t payloadLength) { - spi_.sendPacket(payload, payloadLength); + api_.sendPacket(payload, payloadLength); } bool pollForPacket(uint8_t *outPayload, uint16_t outPayloadCapacity, uint16_t *outPayloadLength) { - return spi_.pollForPacket(outPayload, outPayloadCapacity, + return api_.pollForPacket(outPayload, outPayloadCapacity, outPayloadLength); } private: - XbeeSpi spi_; +#if defined(SNIPS_BOARD_V2) + XbeeUart link_; +#else + XbeeSpi link_; +#endif + XbeeApi api_; }; diff --git a/include/xbee_frame_reader.h b/include/xbee_frame_reader.h new file mode 100644 index 0000000..3b9a23a --- /dev/null +++ b/include/xbee_frame_reader.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +// Assembles XBee API frames (AP=1, unescaped) from a byte stream, one byte +// at a time, for the UART link (xbee_uart.h), where bytes arrive whenever +// they arrive rather than a frame per SPI read. Pure. Bytes before a 0x7E +// delimiter are skipped; a 0x7E inside a frame is just data, since the +// length says where the frame ends. +class XbeeFrameReader { + public: + static constexpr uint16_t kMaxFrameLength = 128; + + enum class Result { + kNeedMore, // no complete frame yet + kFrame, // frame() / length() hold a frame with a valid checksum + kBadFrame, // a frame ended with a bad checksum, or its length was + // impossible; dropped, and the reader is looking for the + // next delimiter + }; + + Result feed(uint8_t byte); + + // Only meaningful right after feed() returns kFrame. + const uint8_t *frame() const { return data_; } + uint16_t length() const { return length_; } + + // Drops any partial frame, e.g. after changing the baud rate. + void reset() { state_ = State::kDelimiter; } + + private: + enum class State { kDelimiter, kLengthHigh, kLengthLow, kData, kChecksum }; + State state_ = State::kDelimiter; + uint8_t data_[kMaxFrameLength] = {}; + uint16_t length_ = 0; + uint16_t received_ = 0; +}; diff --git a/include/xbee_link.h b/include/xbee_link.h new file mode 100644 index 0000000..185567f --- /dev/null +++ b/include/xbee_link.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +// One complete XBee API frame at a time, over whichever wire the board +// uses: SPI on V1 (xbee_spi.h), UART on V2 (xbee_uart.h). Frame data here +// excludes the 0x7E delimiter, length and checksum; the link adds and +// checks those. XbeeApi (xbee_api.h) builds everything else on top. +class XbeeLink { + public: + virtual ~XbeeLink() = default; + + // True if at least one frame may be waiting to be read. + virtual bool frameAvailable() = 0; + + // Reads one frame's data into buf. Returns its length; -1 if no frame is + // ready after all (the caller should stop draining); or 0 if a frame was + // found but unusable (bad length or checksum), with the stream still in + // sync, so the caller should keep going. + virtual int32_t readFrame(uint8_t *buf, uint16_t maxLen) = 0; + + // Writes one complete frame (delimiter, length, data, checksum). + virtual void writeFrame(const uint8_t *frameData, uint16_t length) = 0; +}; diff --git a/include/xbee_spi.h b/include/xbee_spi.h index 4a348f8..7f4b705 100644 --- a/include/xbee_spi.h +++ b/include/xbee_spi.h @@ -2,50 +2,26 @@ #include +#include "xbee_link.h" + // Thin hardware adapter for the XBee3's SPI interface (AP=1/unescaped API -// mode). Frame envelope/checksum logic lives in xbee_frame.h (pure, -// tested); this file only does real SPI transfers, CS toggling, and ATTN -// polling — mirrors thePunderWoman/Amidala's proven xbee_spi.cpp read -// path (same module family, same SPI settings), extended with a write -// path and a blocking AT-command round trip. Excluded from native -// build/coverage (see platformio.ini's [env:native] build_src_filter). -class XbeeSpi { +// mode), used on V1 boards. Frame envelope/checksum logic lives in +// xbee_frame.h and the API operations in xbee_api.h (both pure, tested); +// this file only does real SPI transfers, CS toggling, and ATTN polling — +// mirrors thePunderWoman/Amidala's proven xbee_spi.cpp read path (same +// module family, same SPI settings), extended with a write path. Excluded +// from native build/coverage (see platformio.ini's [env:native] +// build_src_filter). +class XbeeSpi : public XbeeLink { public: void begin(); // True if the module has at least one frame queued (ATTN asserted). - bool frameAvailable(); - - // Reads one queued frame's data (excludes the 0x7E/length header and - // trailing checksum) into buf. Returns the length on success, -1 if no - // start delimiter was found at all (ATTN may be stuck low with nothing - // actually queued — caller should stop draining), or 0 if a delimiter - // was found but the frame was unusable (bad length or checksum — the - // SPI stream is still in sync, so the caller should keep going). - int32_t readFrame(uint8_t *buf, uint16_t maxLen); - - // Writes one complete frame (0x7E + length + frameData + checksum). - void writeFrame(const uint8_t *frameData, uint16_t length); - - // Sends a local AT command and blocks (up to timeoutMs) reading frames - // until the matching (by frameId) AT Command Response arrives. Returns - // false on send failure, an unmatched/malformed response, or timeout. - bool sendAtCommand(const char *atCmd, const uint8_t *value, - uint8_t valueLength, uint8_t *outValue, - uint8_t outValueCapacity, uint8_t *outValueLength, - unsigned long timeoutMs = 200); + bool frameAvailable() override; - // Sends our own application payload to the coordinator as a Transmit - // Request (0x10) — non-blocking, fire-and-forget (no response is - // expected or waited for; XBee's own ACK/retry handles reliability at - // the radio level). - void sendPacket(const uint8_t *payload, uint16_t payloadLength); + // See XbeeLink. -1 means no start delimiter was found at all (ATTN may be + // stuck low with nothing actually queued). + int32_t readFrame(uint8_t *buf, uint16_t maxLen) override; - // Non-blocking: drains any queued frames, returning the payload of the - // first Receive Packet (0x90) found (frames of any other type are - // silently discarded — this firmware only expects AT Command Responses, - // handled synchronously by sendAtCommand(), or Receive Packets here). - // Returns false if nothing was available this call. - bool pollForPacket(uint8_t *outPayload, uint16_t outPayloadCapacity, - uint16_t *outPayloadLength); + void writeFrame(const uint8_t *frameData, uint16_t length) override; }; diff --git a/include/xbee_uart.h b/include/xbee_uart.h new file mode 100644 index 0000000..bc0ff38 --- /dev/null +++ b/include/xbee_uart.h @@ -0,0 +1,49 @@ +#pragma once + +#include +#include + +#include "xbee_api.h" +#include "xbee_frame_reader.h" +#include "xbee_link.h" +#include "xbee_uart_setup.h" + +// Thin hardware adapter for the V2 board's optional XBee carrier, over +// UART (Serial1) in API mode (AP=1) at 115200 baud. The setup sequence +// (xbee_uart_setup.h), frame assembly (xbee_frame_reader.h) and API +// operations (xbee_api.h) are pure and tested; this file only moves bytes +// and pins. Excluded from native build/coverage (see platformio.ini's +// [env:native] build_src_filter). +// +// No carrier is a supported setup (the ESP32's own radio can be used +// instead, later), so begin() checks for one first: a fitted XBee drives +// CTS low (its default D7=1), while with no carrier the pin floats and its +// pull-up reads high. With no XBee every call is a no-op and AT commands +// fail, which the rest of the firmware already treats as "no XBee". +// +// Hardware flow control is off: traffic is a ~31-byte frame each way every +// 50 ms, far below what 115200 baud and the XBee's buffers handle, and +// enabling it would let a missing or sleeping module block every write. +class XbeeUart : public XbeeLink, public XbeeUartPort { + public: + void begin(); + bool present() const { return present_; } + + bool frameAvailable() override; + int32_t readFrame(uint8_t *buf, uint16_t maxLen) override; + void writeFrame(const uint8_t *frameData, uint16_t length) override; + + void setBaud(uint32_t baud) override; + bool apiAtCommand(const char *cmd, const uint8_t *value, uint8_t valueLength, + uint8_t *outValue, uint8_t outValueCapacity, + uint8_t *outValueLength) override; + bool enterCommandMode() override; + bool commandModeLine(const char *line) override; + + private: + bool readLine(char *out, size_t capacity, unsigned long timeoutMs); + + bool present_ = false; + bool setUp_ = false; // writes allowed during setup, before present_ + XbeeFrameReader reader_; +}; diff --git a/include/xbee_uart_setup.h b/include/xbee_uart_setup.h new file mode 100644 index 0000000..278cca8 --- /dev/null +++ b/include/xbee_uart_setup.h @@ -0,0 +1,49 @@ +#pragma once + +#include + +// Gets the V2 carrier's XBee talking API frames (AP=1) at kApiBaud over +// UART, whatever state it arrives in. Pure: the hardware adapter +// (xbee_uart.h) implements XbeeUartPort, and native tests fake it. +// +// A factory XBee 3 is in transparent mode (AP=0) at 9600 baud. Firmware +// that already set it up finds it in API mode at 115200. In between, a +// module might be in API mode at 9600 (e.g. set up over XCTU). Each is +// tried in that order, and anything not already right is fixed with WR so +// the module keeps the setting across power cycles. +class XbeeUartPort { + public: + virtual ~XbeeUartPort() = default; + + virtual void setBaud(uint32_t baud) = 0; + + // A local AT command as an API frame (see XbeeApi::sendAtCommand()). + // outValue may be null. + virtual bool apiAtCommand(const char *cmd, const uint8_t *value, + uint8_t valueLength, uint8_t *outValue, + uint8_t outValueCapacity, + uint8_t *outValueLength) = 0; + + // Transparent-mode command mode: guard time, "+++", then "OK\r". + virtual bool enterCommandMode() = 0; + + // Sends one command-mode line (e.g. "ATAP1") and expects "OK\r". + virtual bool commandModeLine(const char *line) = 0; +}; + +namespace XbeeUartSetup { + +constexpr uint32_t kApiBaud = 115200; +constexpr uint32_t kFactoryBaud = 9600; +constexpr uint8_t kApiModeUnescaped = 1; // AP=1 +constexpr uint8_t kBaud115200 = 7; // BD=7 + +enum class Result { + kReady, // already in API mode at kApiBaud + kReconfigured, // changed to API mode at kApiBaud and saved + kNotFound, // no XBee answered in any mode +}; + +Result run(XbeeUartPort *port); + +} // namespace XbeeUartSetup diff --git a/platformio.ini b/platformio.ini index 3311a96..d924ce3 100644 --- a/platformio.ini +++ b/platformio.ini @@ -40,6 +40,15 @@ lib_deps = adafruit/Adafruit NeoPixel@^1.15.4 extra_scripts = pre:scripts/firmware_version.py +; V2 board (PCB/v2.x/snips): ESP32-S3-MINI-1U-N8, its own pin map +; (include/pin_assignment.h, PCB/v2.x/snips/GPIO_table.md) and the XBee on +; an optional UART carrier. Same module family as V1, so the same board def +; and settings; the -N8 has no PSRAM, which Arduino's boot-time probe +; handles. Never flash the V1 build onto a V2 board, or vice versa. +[env:esp32s3_v2] +extends = env:esp32s3 +build_flags = ${env:esp32s3.build_flags} -D SNIPS_BOARD_V2 + ; Native (host) environment for unit tests — no hardware required. ; SnipsController.ino pulls in Arduino.h, so it's excluded here; everything ; else in src/ is hardware-agnostic and gets linked into the test binary, @@ -49,12 +58,13 @@ extra_scripts = pre:scripts/firmware_version.py ; Currently: oled.cpp (Adafruit_SSD1306/Wire), rgb_led.cpp ; (Adafruit_NeoPixel/RMT), calibration_store.cpp, droid_persistence.cpp, ; and display_layout_store.cpp (all Preferences/NVS), xbee_spi.cpp -; (SPI) and xbee_control.cpp (calls through to XbeeSpi, hardware-dependent -; now that it's a real transport rather than a stub). +; (SPI, V1) and xbee_uart.cpp (Serial1, V2) — the XBee's API logic is in +; the pure xbee_api.cpp, xbee_frame_reader.cpp and xbee_uart_setup.cpp — +; and xbee_control.cpp (calls through to the board's link). [env:native] platform = native test_build_src = yes -build_src_filter = +<*> -<*.ino> - - - - - - - - - +build_src_filter = +<*> -<*.ino> - - - - - - - - - - test_framework = unity build_flags = --coverage extra_scripts = pre:scripts/native_coverage_linkflags.py \ No newline at end of file diff --git a/src/SnipsController.ino b/src/SnipsController.ino index 9ef214d..40ab28f 100644 --- a/src/SnipsController.ino +++ b/src/SnipsController.ino @@ -787,8 +787,11 @@ void loop() { // imuFlags 0 on boards without the ICM-42670-P. uint8_t imuBytes[Icm42670p::kSampleLength]; if (accelerometer.readSample(imuBytes)) { - // TODO(V2): pick the mounting from the board once V2 firmware lands. +#if defined(SNIPS_BOARD_V2) + ImuSample imu = imuSampleFromRaw(imuBytes, ImuMountings::kV2); +#else ImuSample imu = imuSampleFromRaw(imuBytes, ImuMountings::kV1_2); +#endif gyroBias.update(imu); gyroBias.remove(&imu); fillUplinkImu(imu, &uplink); diff --git a/src/xbee_api.cpp b/src/xbee_api.cpp new file mode 100644 index 0000000..e47f9f5 --- /dev/null +++ b/src/xbee_api.cpp @@ -0,0 +1,97 @@ +#include "xbee_api.h" + +#include "xbee_frame.h" + +bool XbeeApi::sendAtCommand(const char *atCmd, const uint8_t *value, + uint8_t valueLength, uint8_t *outValue, + uint8_t outValueCapacity, + uint8_t *outValueLength, + unsigned long timeoutMs) { + constexpr uint8_t kFrameId = 0x01; + uint8_t requestFrame[64]; + const uint16_t requestLength = XbeeFrame::buildAtCommandFrame( + requestFrame, sizeof(requestFrame), kFrameId, atCmd, value, + valueLength); + if (requestLength == 0) { + return false; + } + link_->writeFrame(requestFrame, requestLength); + + const unsigned long start = clock_(); + uint8_t responseFrame[64]; + while (clock_() - start < timeoutMs) { + if (!link_->frameAvailable()) { + idle_(); // let the ESP32's background tasks/watchdog run + continue; + } + + const int32_t length = link_->readFrame(responseFrame, sizeof(responseFrame)); + if (length <= 0) { + if (length < 0) idle_(); + continue; // nothing complete yet, or a bad frame — keep waiting + } + + XbeeFrame::AtCommandResponse response; + if (!XbeeFrame::parseAtCommandResponse( + responseFrame, static_cast(length), &response)) { + continue; // some other frame type was queued — not our response + } + if (response.frameId != kFrameId) { + continue; + } + if (response.status != XbeeFrame::AtCommandStatus::kOk) { + return false; + } + + const uint8_t copyLength = response.valueLength < outValueCapacity + ? response.valueLength + : outValueCapacity; + for (uint8_t i = 0; i < copyLength; i++) { + outValue[i] = response.value[i]; + } + if (outValueLength != nullptr) { + *outValueLength = copyLength; + } + return true; + } + return false; // timed out +} + +void XbeeApi::sendPacket(const uint8_t *payload, uint16_t payloadLength) { + constexpr uint8_t kFrameId = 0x02; // distinct from sendAtCommand's 0x01 + uint8_t frame[48]; + const uint16_t length = XbeeFrame::buildTransmitRequestFrame( + frame, sizeof(frame), kFrameId, payload, payloadLength); + if (length == 0) { + return; // payload too large for the frame buffer — drop it + } + link_->writeFrame(frame, length); +} + +bool XbeeApi::pollForPacket(uint8_t *outPayload, uint16_t outPayloadCapacity, + uint16_t *outPayloadLength) { + if (!link_->frameAvailable()) { + return false; + } + + uint8_t frame[64]; + const int32_t length = link_->readFrame(frame, sizeof(frame)); + if (length <= 0) { + return false; // nothing complete yet, or a bad frame was drained + } + + XbeeFrame::ReceivePacket packet; + if (!XbeeFrame::parseReceivePacket(frame, static_cast(length), + &packet)) { + return false; // some other frame type — not what we're looking for + } + + const uint16_t copyLength = packet.payloadLength < outPayloadCapacity + ? packet.payloadLength + : outPayloadCapacity; + for (uint16_t i = 0; i < copyLength; i++) { + outPayload[i] = packet.payload[i]; + } + *outPayloadLength = copyLength; + return true; +} diff --git a/src/xbee_control.cpp b/src/xbee_control.cpp index 3ff95cd..c6ffc51 100644 --- a/src/xbee_control.cpp +++ b/src/xbee_control.cpp @@ -1,5 +1,14 @@ #include "xbee_control.h" +#include + +namespace { +unsigned long clockMs() { return millis(); } +void idle() { yield(); } +} // namespace + +XbeeControl::XbeeControl() : api_(&link_, clockMs, idle) {} + namespace { int hexNibble(char c) { @@ -37,7 +46,7 @@ bool XbeeControl::leaveNetwork() { // "NR0": local network reset — forces the module to leave its current // network and search again per its (about-to-change) ID setting. uint8_t value[] = {0}; - return spi_.sendAtCommand("NR", value, sizeof(value), nullptr, 0, nullptr); + return api_.sendAtCommand("NR", value, sizeof(value), nullptr, 0, nullptr); } bool XbeeControl::setPanId(const char *panId) { @@ -45,7 +54,7 @@ bool XbeeControl::setPanId(const char *panId) { if (!hexStringToBytes(panId, panIdBytes, sizeof(panIdBytes))) { return false; } - if (!spi_.sendAtCommand("ID", panIdBytes, sizeof(panIdBytes), nullptr, 0, + if (!api_.sendAtCommand("ID", panIdBytes, sizeof(panIdBytes), nullptr, 0, nullptr)) { return false; } @@ -53,21 +62,21 @@ bool XbeeControl::setPanId(const char *panId) { // remembers this PAN ID across power cycles on its own — nothing needs // to re-apply it at boot, and it never changes again until this method // is called again for a different droid. - return spi_.sendAtCommand("WR", nullptr, 0, nullptr, 0, nullptr); + return api_.sendAtCommand("WR", nullptr, 0, nullptr, 0, nullptr); } bool XbeeControl::rejoinNetwork() { // "AC": apply pending parameter changes now, triggering the module to // act on the new ID and (re)associate rather than waiting for its next // natural re-read of that setting. - return spi_.sendAtCommand("AC", nullptr, 0, nullptr, 0, nullptr); + return api_.sendAtCommand("AC", nullptr, 0, nullptr, 0, nullptr); } bool XbeeControl::queryByteParameter(const char *command, uint8_t *outValue) { uint8_t value[1]; uint8_t valueLength = 0; - if (!spi_.sendAtCommand(command, nullptr, 0, value, sizeof(value), + if (!api_.sendAtCommand(command, nullptr, 0, value, sizeof(value), &valueLength) || valueLength != sizeof(value)) { return false; @@ -77,15 +86,15 @@ bool XbeeControl::queryByteParameter(const char *command, } bool XbeeControl::writeByteParameter(const char *command, uint8_t value) { - return spi_.sendAtCommand(command, &value, sizeof(value), nullptr, 0, + return api_.sendAtCommand(command, &value, sizeof(value), nullptr, 0, nullptr); } bool XbeeControl::commitAndApply() { // "WR" so the settings survive power cycles, "AC" so they take effect // now. - return spi_.sendAtCommand("WR", nullptr, 0, nullptr, 0, nullptr) && - spi_.sendAtCommand("AC", nullptr, 0, nullptr, 0, nullptr); + return api_.sendAtCommand("WR", nullptr, 0, nullptr, 0, nullptr) && + api_.sendAtCommand("AC", nullptr, 0, nullptr, 0, nullptr); } bool XbeeControl::querySerialLow(char *outHex, size_t outHexCapacity) { @@ -94,7 +103,7 @@ bool XbeeControl::querySerialLow(char *outHex, size_t outHexCapacity) { } uint8_t value[4]; uint8_t valueLength = 0; - if (!spi_.sendAtCommand("SL", nullptr, 0, value, sizeof(value), + if (!api_.sendAtCommand("SL", nullptr, 0, value, sizeof(value), &valueLength) || valueLength != sizeof(value)) { return false; @@ -109,7 +118,7 @@ bool XbeeControl::queryPanId(char *outHex, size_t outHexCapacity) { } uint8_t value[8]; uint8_t valueLength = 0; - if (!spi_.sendAtCommand("ID", nullptr, 0, value, sizeof(value), + if (!api_.sendAtCommand("ID", nullptr, 0, value, sizeof(value), &valueLength) || valueLength != sizeof(value)) { return false; @@ -121,7 +130,7 @@ bool XbeeControl::queryPanId(char *outHex, size_t outHexCapacity) { bool XbeeControl::queryLocalRssiDbm(int *outDbm) { uint8_t value[1]; uint8_t valueLength = 0; - if (!spi_.sendAtCommand("DB", nullptr, 0, value, sizeof(value), + if (!api_.sendAtCommand("DB", nullptr, 0, value, sizeof(value), &valueLength) || valueLength != sizeof(value)) { return false; diff --git a/src/xbee_frame_reader.cpp b/src/xbee_frame_reader.cpp new file mode 100644 index 0000000..d89d82e --- /dev/null +++ b/src/xbee_frame_reader.cpp @@ -0,0 +1,37 @@ +#include "xbee_frame_reader.h" + +#include "xbee_frame.h" + +XbeeFrameReader::Result XbeeFrameReader::feed(uint8_t byte) { + switch (state_) { + case State::kDelimiter: + if (byte == 0x7E) state_ = State::kLengthHigh; + return Result::kNeedMore; + + case State::kLengthHigh: + length_ = static_cast(byte) << 8; + state_ = State::kLengthLow; + return Result::kNeedMore; + + case State::kLengthLow: + length_ |= byte; + if (length_ == 0 || length_ > kMaxFrameLength) { + state_ = State::kDelimiter; + return Result::kBadFrame; + } + received_ = 0; + state_ = State::kData; + return Result::kNeedMore; + + case State::kData: + data_[received_++] = byte; + if (received_ == length_) state_ = State::kChecksum; + return Result::kNeedMore; + + case State::kChecksum: + state_ = State::kDelimiter; + return XbeeFrame::checksumValid(data_, length_, byte) ? Result::kFrame + : Result::kBadFrame; + } + return Result::kNeedMore; +} diff --git a/src/xbee_spi.cpp b/src/xbee_spi.cpp index 3ab1bd2..845cef3 100644 --- a/src/xbee_spi.cpp +++ b/src/xbee_spi.cpp @@ -1,5 +1,8 @@ #include "xbee_spi.h" +// V1 boards only; V2 talks to its XBee over UART (xbee_uart.h). +#if !defined(SNIPS_BOARD_V2) + #include #include @@ -87,95 +90,4 @@ void XbeeSpi::writeFrame(const uint8_t *frameData, uint16_t length) { SPI.endTransaction(); } -bool XbeeSpi::sendAtCommand(const char *atCmd, const uint8_t *value, - uint8_t valueLength, uint8_t *outValue, - uint8_t outValueCapacity, - uint8_t *outValueLength, - unsigned long timeoutMs) { - constexpr uint8_t kFrameId = 0x01; - uint8_t requestFrame[64]; - const uint16_t requestLength = XbeeFrame::buildAtCommandFrame( - requestFrame, sizeof(requestFrame), kFrameId, atCmd, value, - valueLength); - if (requestLength == 0) { - return false; - } - writeFrame(requestFrame, requestLength); - - const unsigned long start = millis(); - uint8_t responseFrame[64]; - while (millis() - start < timeoutMs) { - if (!frameAvailable()) { - yield(); // let the ESP32's background tasks/watchdog run - continue; - } - - const int32_t length = readFrame(responseFrame, sizeof(responseFrame)); - if (length <= 0) { - continue; // no delimiter yet, or a bad frame — keep waiting - } - - XbeeFrame::AtCommandResponse response; - if (!XbeeFrame::parseAtCommandResponse( - responseFrame, static_cast(length), &response)) { - continue; // some other frame type was queued — not our response - } - if (response.frameId != kFrameId) { - continue; - } - if (response.status != XbeeFrame::AtCommandStatus::kOk) { - return false; - } - - const uint8_t copyLength = response.valueLength < outValueCapacity - ? response.valueLength - : outValueCapacity; - for (uint8_t i = 0; i < copyLength; i++) { - outValue[i] = response.value[i]; - } - if (outValueLength != nullptr) { - *outValueLength = copyLength; - } - return true; - } - return false; // timed out -} - -void XbeeSpi::sendPacket(const uint8_t *payload, uint16_t payloadLength) { - constexpr uint8_t kFrameId = 0x02; // distinct from sendAtCommand's 0x01 - uint8_t frame[32]; - const uint16_t length = XbeeFrame::buildTransmitRequestFrame( - frame, sizeof(frame), kFrameId, payload, payloadLength); - if (length == 0) { - return; // payload too large for the frame buffer — drop it - } - writeFrame(frame, length); -} - -bool XbeeSpi::pollForPacket(uint8_t *outPayload, uint16_t outPayloadCapacity, - uint16_t *outPayloadLength) { - if (!frameAvailable()) { - return false; - } - - uint8_t frame[64]; - const int32_t length = readFrame(frame, sizeof(frame)); - if (length <= 0) { - return false; // no delimiter yet, or a bad frame was drained - } - - XbeeFrame::ReceivePacket packet; - if (!XbeeFrame::parseReceivePacket(frame, static_cast(length), - &packet)) { - return false; // some other frame type — not what we're looking for - } - - const uint16_t copyLength = packet.payloadLength < outPayloadCapacity - ? packet.payloadLength - : outPayloadCapacity; - for (uint16_t i = 0; i < copyLength; i++) { - outPayload[i] = packet.payload[i]; - } - *outPayloadLength = copyLength; - return true; -} +#endif // !SNIPS_BOARD_V2 diff --git a/src/xbee_uart.cpp b/src/xbee_uart.cpp new file mode 100644 index 0000000..1db87e7 --- /dev/null +++ b/src/xbee_uart.cpp @@ -0,0 +1,144 @@ +#include "xbee_uart.h" + +#include +#include + +#include + +#include "pin_assignment.h" +#include "xbee_frame.h" + +#if defined(SNIPS_BOARD_V2) + +namespace { + +// Command mode needs this much silence before and after "+++" (the +// default GT is 1 s). +constexpr unsigned long kGuardTimeMs = 1100; +constexpr unsigned long kCommandReplyMs = 1500; + +unsigned long clockMs() { return millis(); } +void idle() { yield(); } + +} // namespace + +void XbeeUart::begin() { + // RTS is the XBee's input; it ignores it at the default D6=0, but keep it + // at "clear to send" rather than floating. RESET is open drain with the + // pull-up on the carrier, so leave it released. + pinMode(PinAssignment::kXbeeRts, OUTPUT); + digitalWrite(PinAssignment::kXbeeRts, LOW); + pinMode(PinAssignment::kXbeeReset, INPUT); + pinMode(PinAssignment::kXbeeCts, INPUT_PULLUP); + pinMode(PinAssignment::kXbeeOnSleep, INPUT_PULLUP); + + // Give a module that's still booting time to assert CTS. + delay(20); + if (digitalRead(PinAssignment::kXbeeCts) == HIGH) { + Serial.println("XBee carrier not found (CTS high)."); + return; + } + + Serial1.begin(XbeeUartSetup::kApiBaud, SERIAL_8N1, PinAssignment::kXbeeUartRx, + PinAssignment::kXbeeUartTx); + gpio_pullup_en(static_cast(PinAssignment::kXbeeUartRx)); + setUp_ = true; + switch (XbeeUartSetup::run(this)) { + case XbeeUartSetup::Result::kReady: + present_ = true; + break; + case XbeeUartSetup::Result::kReconfigured: + Serial.println("XBee set to API mode at 115200 baud."); + present_ = true; + break; + case XbeeUartSetup::Result::kNotFound: + Serial.println("XBee carrier fitted but not answering."); + break; + } + setUp_ = false; +} + +bool XbeeUart::frameAvailable() { + return (present_ || setUp_) && Serial1.available() > 0; +} + +int32_t XbeeUart::readFrame(uint8_t *buf, uint16_t maxLen) { + while (Serial1.available() > 0) { + switch (reader_.feed(static_cast(Serial1.read()))) { + case XbeeFrameReader::Result::kNeedMore: + break; + case XbeeFrameReader::Result::kBadFrame: + return 0; + case XbeeFrameReader::Result::kFrame: + if (reader_.length() > maxLen) return 0; + std::memcpy(buf, reader_.frame(), reader_.length()); + return reader_.length(); + } + } + return -1; +} + +void XbeeUart::writeFrame(const uint8_t *frameData, uint16_t length) { + if (!present_ && !setUp_) return; + const size_t total = static_cast(length) + 4; + if (static_cast(Serial1.availableForWrite()) < total) return; + const uint8_t header[3] = {0x7E, static_cast(length >> 8), + static_cast(length & 0xFF)}; + Serial1.write(header, sizeof(header)); + Serial1.write(frameData, length); + Serial1.write(XbeeFrame::computeChecksum(frameData, length)); +} + +void XbeeUart::setBaud(uint32_t baud) { + Serial1.flush(); + Serial1.updateBaudRate(baud); + delay(5); + while (Serial1.available() > 0) Serial1.read(); + reader_.reset(); +} + +bool XbeeUart::apiAtCommand(const char *cmd, const uint8_t *value, + uint8_t valueLength, uint8_t *outValue, + uint8_t outValueCapacity, uint8_t *outValueLength) { + XbeeApi api(this, clockMs, idle); + return api.sendAtCommand(cmd, value, valueLength, outValue, outValueCapacity, + outValueLength, 300); +} + +bool XbeeUart::enterCommandMode() { + delay(kGuardTimeMs); + while (Serial1.available() > 0) Serial1.read(); + Serial1.write(reinterpret_cast("+++"), 3); + char reply[8]; + return readLine(reply, sizeof(reply), kGuardTimeMs + kCommandReplyMs) && + std::strcmp(reply, "OK") == 0; +} + +bool XbeeUart::commandModeLine(const char *line) { + Serial1.write(reinterpret_cast(line), std::strlen(line)); + Serial1.write('\r'); + char reply[8]; + return readLine(reply, sizeof(reply), kCommandReplyMs) && + std::strcmp(reply, "OK") == 0; +} + +// Reads up to a '\r' (command mode's line ending) into `out`. +bool XbeeUart::readLine(char *out, size_t capacity, unsigned long timeoutMs) { + size_t length = 0; + const unsigned long start = millis(); + while (millis() - start < timeoutMs) { + if (Serial1.available() <= 0) { + yield(); + continue; + } + const char c = static_cast(Serial1.read()); + if (c == '\r') { + out[length] = '\0'; + return true; + } + if (length + 1 < capacity) out[length++] = c; + } + return false; +} + +#endif // SNIPS_BOARD_V2 diff --git a/src/xbee_uart_setup.cpp b/src/xbee_uart_setup.cpp new file mode 100644 index 0000000..b2020f4 --- /dev/null +++ b/src/xbee_uart_setup.cpp @@ -0,0 +1,52 @@ +#include "xbee_uart_setup.h" + +namespace XbeeUartSetup { + +namespace { + +bool apiModeIsUnescaped(XbeeUartPort *port) { + uint8_t ap = 0; + uint8_t length = 0; + return port->apiAtCommand("AP", nullptr, 0, &ap, 1, &length) && length == 1 && + ap == kApiModeUnescaped; +} + +bool apiCommand(XbeeUartPort *port, const char *cmd, const uint8_t *value, + uint8_t valueLength) { + return port->apiAtCommand(cmd, value, valueLength, nullptr, 0, nullptr); +} + +} // namespace + +Result run(XbeeUartPort *port) { + port->setBaud(kApiBaud); + if (apiModeIsUnescaped(port)) return Result::kReady; + + // API mode, but at the factory baud: raise it. BD takes effect on AC. + port->setBaud(kFactoryBaud); + if (apiModeIsUnescaped(port)) { + const uint8_t bd = kBaud115200; + if (apiCommand(port, "BD", &bd, 1) && apiCommand(port, "WR", nullptr, 0) && + apiCommand(port, "AC", nullptr, 0)) { + port->setBaud(kApiBaud); + if (apiModeIsUnescaped(port)) return Result::kReconfigured; + } + return Result::kNotFound; + } + + // Transparent mode, the factory state, at either baud. + const uint32_t bauds[] = {kFactoryBaud, kApiBaud}; + for (uint32_t baud : bauds) { + port->setBaud(baud); + if (!port->enterCommandMode()) continue; + if (port->commandModeLine("ATAP1") && port->commandModeLine("ATBD7") && + port->commandModeLine("ATWR") && port->commandModeLine("ATCN")) { + port->setBaud(kApiBaud); + if (apiModeIsUnescaped(port)) return Result::kReconfigured; + } + return Result::kNotFound; + } + return Result::kNotFound; +} + +} // namespace XbeeUartSetup diff --git a/test/test_xbee_api/test_xbee_api.cpp b/test/test_xbee_api/test_xbee_api.cpp new file mode 100644 index 0000000..628897a --- /dev/null +++ b/test/test_xbee_api/test_xbee_api.cpp @@ -0,0 +1,183 @@ +#include + +#include +#include + +#include "xbee_api.h" +#include "xbee_frame.h" + +// A link whose incoming frames are queued by the test and whose outgoing +// frames are recorded. +class FakeLink : public XbeeLink { + public: + std::vector> incoming; + std::vector> written; + int badFrames = 0; // returned as 0 before the queued frames + + bool frameAvailable() override { return badFrames > 0 || !incoming.empty(); } + int32_t readFrame(uint8_t *buf, uint16_t maxLen) override { + if (badFrames > 0) { + --badFrames; + return 0; + } + if (incoming.empty()) return -1; + std::vector f = incoming.front(); + incoming.erase(incoming.begin()); + if (f.size() > maxLen) return 0; + std::memcpy(buf, f.data(), f.size()); + return static_cast(f.size()); + } + void writeFrame(const uint8_t *data, uint16_t length) override { + written.emplace_back(data, data + length); + } +}; + +static unsigned long gNow = 0; +static int gIdles = 0; +unsigned long fakeClock() { return gNow; } +void fakeIdle() { + ++gIdles; + gNow += 10; // time passes while waiting +} + +void setUp(void) { + gNow = 0; + gIdles = 0; +} +void tearDown(void) {} + +std::vector atResponse(uint8_t frameId, const char *cmd, uint8_t status, + std::vector value = {}) { + std::vector f = {XbeeFrame::kFrameTypeAtCommandResponse, frameId, + static_cast(cmd[0]), static_cast(cmd[1]), + status}; + f.insert(f.end(), value.begin(), value.end()); + return f; +} + +std::vector receivePacket(std::vector payload) { + std::vector f = {XbeeFrame::kFrameTypeReceivePacket, 0, 0, 0, 0, 0, 0, 0, 0, + 0xFF, 0xFE, 0x01}; + f.insert(f.end(), payload.begin(), payload.end()); + return f; +} + +// ---- AT commands ------------------------------------------------------------ + +void test_at_command_writes_request_and_returns_value() { + FakeLink link; + link.incoming.push_back(atResponse(0x01, "SL", 0, {0x41, 0x42, 0x43, 0x44})); + XbeeApi api(&link, fakeClock, fakeIdle); + uint8_t value[4]; + uint8_t length = 0; + TEST_ASSERT_TRUE(api.sendAtCommand("SL", nullptr, 0, value, sizeof(value), &length)); + TEST_ASSERT_EQUAL_UINT8(4, length); + TEST_ASSERT_EQUAL_HEX8(0x44, value[3]); + TEST_ASSERT_EQUAL(1, (int)link.written.size()); + TEST_ASSERT_EQUAL_HEX8(XbeeFrame::kFrameTypeAtCommand, link.written[0][0]); + TEST_ASSERT_EQUAL_HEX8('S', link.written[0][2]); +} + +void test_at_command_skips_other_frames_and_ids() { + FakeLink link; + link.badFrames = 1; + link.incoming.push_back(receivePacket({1, 2})); + link.incoming.push_back(atResponse(0x07, "SL", 0, {9})); // someone else's + link.incoming.push_back(atResponse(0x01, "AP", 0, {1})); + XbeeApi api(&link, fakeClock, fakeIdle); + uint8_t value = 0; + TEST_ASSERT_TRUE(api.sendAtCommand("AP", nullptr, 0, &value, 1, nullptr)); + TEST_ASSERT_EQUAL_UINT8(1, value); +} + +void test_at_command_error_status_fails() { + FakeLink link; + link.incoming.push_back(atResponse(0x01, "ID", 2)); + XbeeApi api(&link, fakeClock, fakeIdle); + TEST_ASSERT_FALSE(api.sendAtCommand("ID", nullptr, 0, nullptr, 0, nullptr)); +} + +void test_at_command_times_out_with_no_reply() { + FakeLink link; + XbeeApi api(&link, fakeClock, fakeIdle); + TEST_ASSERT_FALSE(api.sendAtCommand("ID", nullptr, 0, nullptr, 0, nullptr, 200)); + TEST_ASSERT_TRUE(gIdles >= 20); +} + +void test_at_command_truncates_value_to_capacity() { + FakeLink link; + link.incoming.push_back(atResponse(0x01, "ID", 0, {1, 2, 3, 4})); + XbeeApi api(&link, fakeClock, fakeIdle); + uint8_t value[2]; + uint8_t length = 0; + TEST_ASSERT_TRUE(api.sendAtCommand("ID", nullptr, 0, value, sizeof(value), &length)); + TEST_ASSERT_EQUAL_UINT8(2, length); +} + +// ---- packets ------------------------------------------------------------------ + +void test_send_packet_wraps_payload_in_transmit_request() { + FakeLink link; + XbeeApi api(&link, fakeClock, fakeIdle); + uint8_t payload[17] = {}; // today's uplink size + api.sendPacket(payload, sizeof(payload)); + TEST_ASSERT_EQUAL(1, (int)link.written.size()); + TEST_ASSERT_EQUAL_HEX8(XbeeFrame::kFrameTypeTransmitRequest, link.written[0][0]); + TEST_ASSERT_EQUAL(14 + 17, (int)link.written[0].size()); +} + +void test_send_packet_drops_oversized_payload() { + FakeLink link; + XbeeApi api(&link, fakeClock, fakeIdle); + uint8_t payload[64] = {}; + api.sendPacket(payload, sizeof(payload)); + TEST_ASSERT_EQUAL(0, (int)link.written.size()); +} + +void test_poll_returns_receive_packet_payload() { + FakeLink link; + link.incoming.push_back(receivePacket({0x10, 0x20, 0x30})); + XbeeApi api(&link, fakeClock, fakeIdle); + uint8_t out[8]; + uint16_t length = 0; + TEST_ASSERT_TRUE(api.pollForPacket(out, sizeof(out), &length)); + TEST_ASSERT_EQUAL_UINT16(3, length); + TEST_ASSERT_EQUAL_HEX8(0x30, out[2]); +} + +void test_poll_ignores_other_frames_and_empty_link() { + FakeLink link; + XbeeApi api(&link, fakeClock, fakeIdle); + uint8_t out[8]; + uint16_t length = 0; + TEST_ASSERT_FALSE(api.pollForPacket(out, sizeof(out), &length)); + link.incoming.push_back(atResponse(0x01, "AP", 0, {1})); + TEST_ASSERT_FALSE(api.pollForPacket(out, sizeof(out), &length)); + link.badFrames = 1; + TEST_ASSERT_FALSE(api.pollForPacket(out, sizeof(out), &length)); +} + +void test_poll_truncates_to_capacity() { + FakeLink link; + link.incoming.push_back(receivePacket({1, 2, 3, 4, 5})); + XbeeApi api(&link, fakeClock, fakeIdle); + uint8_t out[2]; + uint16_t length = 0; + TEST_ASSERT_TRUE(api.pollForPacket(out, sizeof(out), &length)); + TEST_ASSERT_EQUAL_UINT16(2, length); +} + +int main(int argc, char **argv) { + UNITY_BEGIN(); + RUN_TEST(test_at_command_writes_request_and_returns_value); + RUN_TEST(test_at_command_skips_other_frames_and_ids); + RUN_TEST(test_at_command_error_status_fails); + RUN_TEST(test_at_command_times_out_with_no_reply); + RUN_TEST(test_at_command_truncates_value_to_capacity); + RUN_TEST(test_send_packet_wraps_payload_in_transmit_request); + RUN_TEST(test_send_packet_drops_oversized_payload); + RUN_TEST(test_poll_returns_receive_packet_payload); + RUN_TEST(test_poll_ignores_other_frames_and_empty_link); + RUN_TEST(test_poll_truncates_to_capacity); + return UNITY_END(); +} diff --git a/test/test_xbee_uart/test_xbee_uart.cpp b/test/test_xbee_uart/test_xbee_uart.cpp new file mode 100644 index 0000000..63b3392 --- /dev/null +++ b/test/test_xbee_uart/test_xbee_uart.cpp @@ -0,0 +1,185 @@ +#include + +#include +#include +#include + +#include "xbee_frame.h" +#include "xbee_frame_reader.h" +#include "xbee_uart_setup.h" + +void setUp(void) {} +void tearDown(void) {} + +// ---- frame reader ------------------------------------------------------------- + +std::vector wire(std::vector data) { + std::vector out = {0x7E, static_cast(data.size() >> 8), + static_cast(data.size() & 0xFF)}; + out.insert(out.end(), data.begin(), data.end()); + out.push_back(XbeeFrame::computeChecksum(data.data(), static_cast(data.size()))); + return out; +} + +XbeeFrameReader::Result feedAll(XbeeFrameReader *r, const std::vector &bytes) { + XbeeFrameReader::Result last = XbeeFrameReader::Result::kNeedMore; + for (uint8_t b : bytes) { + last = r->feed(b); + if (last != XbeeFrameReader::Result::kNeedMore) return last; + } + return last; +} + +void test_reader_assembles_frame_after_noise() { + XbeeFrameReader r; + std::vector bytes = {0x00, 0xFF, 0x13}; + auto frame = wire({0x88, 0x01, 'A', 'P', 0x00, 0x7E}); // 0x7E inside is data + bytes.insert(bytes.end(), frame.begin(), frame.end()); + TEST_ASSERT_TRUE(XbeeFrameReader::Result::kFrame == feedAll(&r, bytes)); + TEST_ASSERT_EQUAL_UINT16(6, r.length()); + TEST_ASSERT_EQUAL_HEX8(0x7E, r.frame()[5]); +} + +void test_reader_rejects_bad_checksum_then_recovers() { + XbeeFrameReader r; + auto bad = wire({0x90, 0x01}); + bad.back() ^= 0xFF; + TEST_ASSERT_TRUE(XbeeFrameReader::Result::kBadFrame == feedAll(&r, bad)); + TEST_ASSERT_TRUE(XbeeFrameReader::Result::kFrame == feedAll(&r, wire({0x90, 0x02}))); +} + +void test_reader_rejects_impossible_lengths() { + XbeeFrameReader r; + TEST_ASSERT_TRUE(XbeeFrameReader::Result::kBadFrame == feedAll(&r, {0x7E, 0x00, 0x00})); + TEST_ASSERT_TRUE(XbeeFrameReader::Result::kBadFrame == feedAll(&r, {0x7E, 0x01, 0x00})); + TEST_ASSERT_TRUE(XbeeFrameReader::Result::kFrame == feedAll(&r, wire({0x01}))); +} + +void test_reader_reset_drops_partial_frame() { + XbeeFrameReader r; + feedAll(&r, {0x7E, 0x00, 0x05, 0x01}); + r.reset(); + TEST_ASSERT_TRUE(XbeeFrameReader::Result::kFrame == feedAll(&r, wire({0x42}))); +} + +// ---- setup sequence ------------------------------------------------------------- + +// A pretend XBee: answers API frames only in API mode at its baud, and +// command mode only in transparent mode at its baud. Records what it was +// asked. +class FakePort : public XbeeUartPort { + public: + uint32_t moduleBaud = 9600; + bool moduleApi = false; + bool present = true; + bool failWrite = false; + uint32_t baud = 0; + bool inCommandMode = false; + std::vector log; + + void setBaud(uint32_t b) override { baud = b; } + + bool apiAtCommand(const char *cmd, const uint8_t *value, uint8_t valueLength, + uint8_t *outValue, uint8_t outCapacity, uint8_t *outLength) override { + if (!present || !moduleApi || baud != moduleBaud) return false; + std::string c(cmd, 2); + log.push_back("api " + c); + if (c == "AP") { + if (outValue && outCapacity) outValue[0] = 1; + if (outLength) *outLength = 1; + } else if (c == "BD" && valueLength == 1) { + pendingBaud_ = value[0] == 7 ? 115200 : moduleBaud; + } else if (c == "WR" && failWrite) { + return false; + } else if (c == "AC") { + moduleBaud = pendingBaud_; + } + return true; + } + + bool enterCommandMode() override { + if (!present || moduleApi || baud != moduleBaud) return false; + log.push_back("+++"); + inCommandMode = true; + return true; + } + + bool commandModeLine(const char *line) override { + if (!inCommandMode) return false; + log.push_back(line); + std::string l(line); + if (l == "ATAP1") pendingApi_ = true; + if (l == "ATBD7") pendingBaud_ = 115200; + if (l == "ATCN") { + inCommandMode = false; + moduleApi = pendingApi_; + moduleBaud = pendingBaud_; + } + return true; + } + + private: + uint32_t pendingBaud_ = 9600; + bool pendingApi_ = false; +}; + +void test_setup_already_ready() { + FakePort port; + port.moduleApi = true; + port.moduleBaud = 115200; + TEST_ASSERT_TRUE(XbeeUartSetup::Result::kReady == XbeeUartSetup::run(&port)); + TEST_ASSERT_EQUAL_UINT32(115200, port.baud); +} + +void test_setup_factory_transparent_module() { + FakePort port; // AP=0 at 9600 + TEST_ASSERT_TRUE(XbeeUartSetup::Result::kReconfigured == XbeeUartSetup::run(&port)); + TEST_ASSERT_TRUE(port.moduleApi); + TEST_ASSERT_EQUAL_UINT32(115200, port.moduleBaud); + TEST_ASSERT_EQUAL_UINT32(115200, port.baud); + bool wrote = false; + for (const auto &l : port.log) wrote |= l == "ATWR"; + TEST_ASSERT_TRUE(wrote); +} + +void test_setup_api_mode_at_factory_baud_raises_baud() { + FakePort port; + port.moduleApi = true; // API at 9600 + TEST_ASSERT_TRUE(XbeeUartSetup::Result::kReconfigured == XbeeUartSetup::run(&port)); + TEST_ASSERT_EQUAL_UINT32(115200, port.moduleBaud); +} + +void test_setup_transparent_at_high_baud() { + FakePort port; + port.moduleBaud = 115200; // AP=0 at 115200 + TEST_ASSERT_TRUE(XbeeUartSetup::Result::kReconfigured == XbeeUartSetup::run(&port)); + TEST_ASSERT_TRUE(port.moduleApi); +} + +void test_setup_no_module() { + FakePort port; + port.present = false; + TEST_ASSERT_TRUE(XbeeUartSetup::Result::kNotFound == XbeeUartSetup::run(&port)); +} + +void test_setup_failed_write_is_not_found() { + FakePort port; + port.moduleApi = true; + port.failWrite = true; + TEST_ASSERT_TRUE(XbeeUartSetup::Result::kNotFound == XbeeUartSetup::run(&port)); +} + +int main(int argc, char **argv) { + UNITY_BEGIN(); + RUN_TEST(test_reader_assembles_frame_after_noise); + RUN_TEST(test_reader_rejects_bad_checksum_then_recovers); + RUN_TEST(test_reader_rejects_impossible_lengths); + RUN_TEST(test_reader_reset_drops_partial_frame); + RUN_TEST(test_setup_already_ready); + RUN_TEST(test_setup_factory_transparent_module); + RUN_TEST(test_setup_api_mode_at_factory_baud_raises_baud); + RUN_TEST(test_setup_transparent_at_high_baud); + RUN_TEST(test_setup_no_module); + RUN_TEST(test_setup_failed_write_is_not_found); + return UNITY_END(); +}