From fdf840a236ba9b555f724cfe63438ed9e8a8324e Mon Sep 17 00:00:00 2001 From: "R. Sid Shaytay" <352722946+r-sidshaytay@users.noreply.github.com> Date: Fri, 6 Nov 2026 01:19:31 -0800 Subject: [PATCH 01/10] feat: support headless LILYGO T-Embed CC1101 Plus Configure the integrated radio power, shared SPI selects, RF path and fixed wiring without changing generic boards. Preload output latches for Arduino 3 and publish radio availability only after register and RX checks succeed. Reuse the existing partition table and protect integrated, USB and PSRAM pins across configuration and GPIO output paths. Exercise production setup, RX and queue admission methods in a hardware-boundary host harness, run it in CI and document the opt-in build. Keep restore policy, security corrections and release tooling outside this board-only change. --- .github/workflows/build.yaml | 3 + README.md | 17 +++ platformio.ini | 18 +++ src/BoardProfile.cpp | 70 +++++++++ src/BoardProfile.h | 33 +++++ src/ConfigFile.cpp | 7 +- src/ShadeGpio.cpp | 11 ++ src/SomfyController.cpp | 2 + src/SomfyJson.cpp | 9 +- src/Transceiver.cpp | 109 +++++++++++--- src/Transceiver.h | 10 +- tests/board-profile/Arduino.h | 26 ++++ tests/board-profile/ArduinoJson.h | 2 + tests/board-profile/Preferences.h | 8 + tests/board-profile/SPI.h | 11 ++ tests/board-profile/board-profile-test.cpp | 95 ++++++++++++ tests/board-profile/driver/gpio.h | 4 + tests/board-profile/esp_log.h | 9 ++ tests/board-profile/extract-radio-setup.py | 29 ++++ tests/board-profile/radio-setup-test.cpp | 162 +++++++++++++++++++++ tests/board-profile/shade-gpio-test.cpp | 76 ++++++++++ tools/test-board-profile.sh | 35 +++++ 22 files changed, 715 insertions(+), 31 deletions(-) create mode 100644 src/BoardProfile.cpp create mode 100644 src/BoardProfile.h create mode 100644 tests/board-profile/Arduino.h create mode 100644 tests/board-profile/ArduinoJson.h create mode 100644 tests/board-profile/Preferences.h create mode 100644 tests/board-profile/SPI.h create mode 100644 tests/board-profile/board-profile-test.cpp create mode 100644 tests/board-profile/driver/gpio.h create mode 100644 tests/board-profile/esp_log.h create mode 100644 tests/board-profile/extract-radio-setup.py create mode 100644 tests/board-profile/radio-setup-test.cpp create mode 100644 tests/board-profile/shade-gpio-test.cpp create mode 100755 tools/test-board-profile.sh diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 6d0d1f0..2f8dc1b 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -38,6 +38,9 @@ jobs: - name: Run native unit tests run: pio test -e coverage + - name: Test integrated board GPIO and radio readiness + run: bash tools/test-board-profile.sh + - name: Test the release scripts run: bash test/scripts/test_set_version.sh diff --git a/README.md b/README.md index 70f42e5..019ac0a 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,23 @@ In either mode the socket refuses an upgrade whose `Origin` header doesn't name ## Building The firmware builds on [pioarduino](https://github.com/pioarduino/platform-espressif32) (Arduino 3.x on ESP-IDF 5.5), not the stock PlatformIO platform. In VS Code use the **pioarduino IDE** extension instead of PlatformIO IDE. On the command line, `pip install pioarduino` gives you `pio`. Run the unit tests with `pio test -e native`. [ADR 0003](docs/adr/0003-pioarduino-idf55.md) explains why. +### Build for LILYGO T-Embed CC1101 Plus + +The headless Plus profile uses the board's integrated CC1101 on the 433 MHz RF path, +16 MB flash and 8 MB OPI PSRAM. It fixes the radio pins and reserves the shared +peripheral, USB and flash/PSRAM pins; the display and encoder are not used. +This profile is for the **T-Embed CC1101 Plus**, not the non-Plus board. + +```bash +pio run -e lilygo-t-embed-cc1101-plus +pio run -e lilygo-t-embed-cc1101-plus -t buildfs +``` + +The images are in `.pio/build/lilygo-t-embed-cc1101-plus/`. This environment reuses +`esp32_3MB.csv`. A device with another partition layout needs USB provisioning with +a fresh recovery backup and current rolling codes; firmware-only OTA cannot migrate +the layout. Do not substitute a generic S3 image for this profile. + Bugs and ideas go to the [issues](https://github.com/cjkas/ESPSomfy-RTS/issues); security problems go through [SECURITY.md](SECURITY.md). ## Credits diff --git a/platformio.ini b/platformio.ini index 0fc8a68..8b82071 100644 --- a/platformio.ini +++ b/platformio.ini @@ -98,6 +98,24 @@ build_flags = ${dualcore.build_flags} -DCORE_DEBUG_LEVEL=2 +; Headless LILYGO T-Embed CC1101 Plus with its integrated 433 MHz radio. +[env:lilygo-t-embed-cc1101-plus] +extends = esp32 +board = esp32-s3-devkitc1-n16r8 +build_type = release +board_build.partitions = esp32_3MB.csv +board_build.flash_mode = qio +board_build.f_flash = 80000000L +board_build.arduino.memory_type = qio_opi +board_build.psram_type = opi +board_upload.flash_size = 16MB +build_flags = + ${dualcore.build_flags} + -DCORE_DEBUG_LEVEL=2 + -DARDUINO_USB_MODE=1 + -DARDUINO_USB_CDC_ON_BOOT=1 + -DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS + [env:esp32c3] extends = esp32 board = esp32-c3-devkitm-1 diff --git a/src/BoardProfile.cpp b/src/BoardProfile.cpp new file mode 100644 index 0000000..a920a6b --- /dev/null +++ b/src/BoardProfile.cpp @@ -0,0 +1,70 @@ +#include "BoardProfile.h" +#include +#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS) +#include +#endif + +namespace BoardProfile { +#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS) +static bool initialized = false; + +static void output(uint8_t pin, uint8_t level) { + // Arduino 3 rejects digitalWrite before GPIO ownership is established. + // Preload the hardware latch so active-low selects do not pulse on enable. + gpio_set_level(static_cast(pin), level); + pinMode(pin, OUTPUT); +} + +void begin() { + if(initialized) return; + // Deselect every shared-SPI slave before enabling its power rail. + // https://github.com/Xinyuan-LilyGO/T-Embed-CC1101/blob/c36826e0f91311cb591c4545fccf91e254fc55dc/examples/cc1101_recv_irq/cc1101_recv_irq.ino + output(displayCS, HIGH); + output(sdCS, HIGH); + output(nrfCS, HIGH); + output(cs, HIGH); + output(nrfCE, LOW); + output(backlight, LOW); + output(sw1, HIGH); + output(sw0, HIGH); + output(power, HIGH); + delay(10); // Conservative rail settling; no peripheral drivers are started. + initialized = true; +} + +bool prepareRadio(float frequency) { + begin(); + // This hardware profile selects only the 433 MHz RF filter path. + if(!(frequency >= 387.0f && frequency <= 464.0f)) { + Serial.println("Radio disabled: frequency is outside the selected 433 MHz band"); + return false; + } + // Arduino 3 owns these pads while SPI is active. Release that ownership + // before the GPIO readiness probe, including when reapplying settings. + SPI.end(); + pinMode(miso, INPUT); + output(sck, LOW); + output(mosi, LOW); + digitalWrite(cs, LOW); + unsigned long started = millis(); + while(digitalRead(miso) == HIGH && millis() - started < 20) delay(1); + bool ready = digitalRead(miso) == LOW; + digitalWrite(cs, HIGH); + if(!ready) Serial.println("CC1101 not ready: MISO stayed HIGH; check power/shared SPI before retrying"); + if(ready) SPI.begin(sck, miso, mosi, cs); + return ready; +} + +bool usesPin(uint8_t pin) { + // USB CDC and in-package flash/OPI PSRAM must never become relay outputs. + return pin == 19 || pin == 20 || (pin >= 26 && pin <= 37) || + pin == power || pin == sck || pin == mosi || pin == miso || + pin == cs || pin == tx || pin == rx || pin == sw1 || pin == sw0 || + pin == displayCS || pin == sdCS || pin == nrfCS || pin == nrfCE || pin == backlight; +} +#else +void begin() {} +bool prepareRadio(float) { return true; } +bool usesPin(uint8_t) { return false; } +#endif +} diff --git a/src/BoardProfile.h b/src/BoardProfile.h new file mode 100644 index 0000000..882c0e4 --- /dev/null +++ b/src/BoardProfile.h @@ -0,0 +1,33 @@ +#pragma once +#include + +namespace BoardProfile { +#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS) +#if !defined(CONFIG_IDF_TARGET_ESP32S3) +#error "The LILYGO T-Embed CC1101 Plus profile requires an ESP32-S3 target" +#endif +constexpr bool integratedRadio = true; +#else +constexpr bool integratedRadio = false; +#endif + +// LILYGO T-Embed CC1101 Plus integrated hardware; not the non-Plus board. +constexpr uint8_t power = 15; +constexpr uint8_t sck = 11; +constexpr uint8_t mosi = 9; +constexpr uint8_t miso = 10; +constexpr uint8_t cs = 12; +constexpr uint8_t tx = 3; +constexpr uint8_t rx = 38; +constexpr uint8_t sw1 = 47; +constexpr uint8_t sw0 = 48; +constexpr uint8_t displayCS = 41; +constexpr uint8_t sdCS = 13; +constexpr uint8_t nrfCS = 44; +constexpr uint8_t nrfCE = 43; +constexpr uint8_t backlight = 21; + +void begin(); +bool prepareRadio(float frequency); +bool usesPin(uint8_t pin); +} diff --git a/src/ConfigFile.cpp b/src/ConfigFile.cpp index 8b8445c..6ff02a3 100644 --- a/src/ConfigFile.cpp +++ b/src/ConfigFile.cpp @@ -6,6 +6,7 @@ #include "Utils.h" #include "ConfigSettings.h" #include "RollingCode.h" +#include "BoardProfile.h" static const char *TAG = "ConfigFile"; @@ -288,10 +289,10 @@ void ShadeConfigFile::readShade(SomfyShade *shade) { shade->gpioFlags = rec.gpioFlags; shade->roomId = rec.roomId; if(shade->proto == radio_proto::GP_Relay || shade->proto == radio_proto::GP_Remote) { - pinMode(shade->gpioUp, OUTPUT); - pinMode(shade->gpioDown, OUTPUT); + if(!BoardProfile::usesPin(shade->gpioUp)) pinMode(shade->gpioUp, OUTPUT); + if(!BoardProfile::usesPin(shade->gpioDown)) pinMode(shade->gpioDown, OUTPUT); } - if(shade->proto == radio_proto::GP_Remote) + if(shade->proto == radio_proto::GP_Remote && !BoardProfile::usesPin(shade->gpioMy)) pinMode(shade->gpioMy, OUTPUT); } void ShadeConfigFile::readGroup(SomfyGroup *group) { diff --git a/src/ShadeGpio.cpp b/src/ShadeGpio.cpp index 0024326..bd29617 100644 --- a/src/ShadeGpio.cpp +++ b/src/ShadeGpio.cpp @@ -1,9 +1,19 @@ #include "esp_log.h" #include "Somfy.h" +#include "BoardProfile.h" static const char *TAG = "Somfy"; +// A backup may contain GPIO assignments from another board. Keep its shade +// identity, but never drive a pad used by this board's integrated hardware. +static bool usesBoardGPIOs(const SomfyShade &shade) { + if(shade.proto != radio_proto::GP_Relay && shade.proto != radio_proto::GP_Remote) return false; + return BoardProfile::usesPin(shade.gpioUp) || BoardProfile::usesPin(shade.gpioDown) || + (shade.proto == radio_proto::GP_Remote && BoardProfile::usesPin(shade.gpioMy)); +} + void SomfyShade::setGPIOs() { + if(usesBoardGPIOs(*this)) return; if(this->proto == radio_proto::GP_Relay) { // Determine whether the direction needs to be set. uint8_t p_on = (this->gpioFlags & (uint8_t)gpio_flags_t::LowLevelTrigger) == 0x00 ? HIGH : LOW; @@ -65,6 +75,7 @@ void SomfyShade::setGPIOs() { } void SomfyRemote::triggerGPIOs(somfy_frame_t &frame) { } void SomfyShade::triggerGPIOs(somfy_frame_t &frame) { + if(usesBoardGPIOs(*this)) return; if(this->proto == radio_proto::GP_Remote) { uint8_t p_on = (this->gpioFlags & (uint8_t)gpio_flags_t::LowLevelTrigger) == 0x00 ? HIGH : LOW; uint8_t p_off = (this->gpioFlags & (uint8_t)gpio_flags_t::LowLevelTrigger) == 0x00 ? LOW : HIGH; diff --git a/src/SomfyController.cpp b/src/SomfyController.cpp index bd0024f..f018d1d 100644 --- a/src/SomfyController.cpp +++ b/src/SomfyController.cpp @@ -20,6 +20,7 @@ #include "esp_rom_sys.h" #include #include "Timing.h" +#include "BoardProfile.h" static const char *TAG = "Main"; #define LOOP_SLOW_MS 100 @@ -79,6 +80,7 @@ static void onAllocFailed(size_t size, uint32_t caps, const char *function) { void setup() { Serial.begin(SERIAL_BAUD); + BoardProfile::begin(); heap_caps_register_failed_alloc_callback(onAllocFailed); ESP_LOGI(TAG, "Startup/Boot...."); esp_core_dump_summary_t summary; diff --git a/src/SomfyJson.cpp b/src/SomfyJson.cpp index cd2b493..bac699a 100644 --- a/src/SomfyJson.cpp +++ b/src/SomfyJson.cpp @@ -52,8 +52,7 @@ int8_t SomfyShade::validateJSON(JsonObject &obj) { const uint8_t downPin = !obj["gpioDown"].isNull() ? obj["gpioDown"].as() : this->gpioDown; const uint8_t myPin = !obj["gpioMy"].isNull() ? obj["gpioMy"].as() : this->gpioMy; pin_users_t radio, ethernet, others; - if(somfy.transceiver.config.enabled) - radio.uses = [](uint8_t pin, void *) { return somfy.transceiver.usesPin(pin); }; + radio.uses = [](uint8_t pin, void *) { return somfy.transceiver.usesPin(pin); }; #if HAS_ETHERNET if(settings.connType == conn_types_t::ethernet || settings.connType == conn_types_t::ethernetpref) ethernet.uses = [](uint8_t pin, void *) { return settings.Ethernet.usesPin(pin); }; @@ -158,12 +157,12 @@ int8_t SomfyShade::fromJSON(JsonObject &obj) { if(this->proto == radio_proto::GP_Remote || this->proto == radio_proto::GP_Relay) { if(!obj["gpioUp"].isNull()) this->gpioUp = obj["gpioUp"]; if(!obj["gpioDown"].isNull()) this->gpioDown = obj["gpioDown"]; - pinMode(this->gpioUp, OUTPUT); - pinMode(this->gpioDown, OUTPUT); + if(!BoardProfile::usesPin(this->gpioUp)) pinMode(this->gpioUp, OUTPUT); + if(!BoardProfile::usesPin(this->gpioDown)) pinMode(this->gpioDown, OUTPUT); } if(this->proto == radio_proto::GP_Remote) { if(!obj["gpioMy"].isNull()) this->gpioMy = obj["gpioMy"]; - pinMode(this->gpioMy, OUTPUT); + if(!BoardProfile::usesPin(this->gpioMy)) pinMode(this->gpioMy, OUTPUT); } } return err; diff --git a/src/Transceiver.cpp b/src/Transceiver.cpp index 6b09f36..e341e42 100644 --- a/src/Transceiver.cpp +++ b/src/Transceiver.cpp @@ -101,7 +101,7 @@ bool somfy_rx_queue_t::pop(somfy_rx_t *rx) { return false; } void Transceiver::sendFrame(byte *frame, uint8_t sync, uint8_t bitLength) { - if(!this->config.enabled) return; + if(!this->available()) return; uint32_t pin = 1 << this->config.TXPin; if (sync == 2 || sync == 12) { // Only with the first frame. Repeats do not get a wakeup pulse. // All information online for the wakeup pulse appears to be incorrect. While there is a wakeup @@ -252,9 +252,9 @@ static std::atomic scanEmitPending{false}; void Transceiver::beginFrequencyScan() { // The scan retunes the radio so nothing may transmit until it ends. This // also aborts a transmission in flight so the lock below is never held long. - if(this->config.enabled) this->suspendTx(TX_SUSPEND_SCAN); + if(this->available()) this->suspendTx(TX_SUSPEND_SCAN); RadioLock lock(portMAX_DELAY, true); - if(this->config.enabled) { + if(this->available()) { this->disableReceive(); rxmode = 3; scanStart = millis(); @@ -272,7 +272,7 @@ void Transceiver::beginFrequencyScan() { } void Transceiver::processFrequencyScan(bool received) { RadioLock lock; - if(this->config.enabled && rxmode == 3) { + if(this->available() && rxmode == 3) { if(received) { currRSSI = ELECHOUSE_cc1101.getRssi(); if((long)(markFreq * 100) == (long)(currFreq * 100)) { @@ -365,22 +365,41 @@ void Transceiver::emitFrame(somfy_frame_t *frame, somfy_rx_t *rx) { void Transceiver::clearReceived(void) { //packet_received = false; //memset(receive_buffer, 0x00, sizeof(receive_buffer)); - if(this->config.enabled) + if(this->available()) //attachInterrupt(interruptPin, handleReceive, FALLING); attachInterrupt(interruptPin, handleReceive, CHANGE); } void Transceiver::enableReceive(void) { + if(this->available()) this->startReceive(); +} +bool Transceiver::startReceive() { uint32_t timing = millis(); - if(rxmode > 0) return; - if(this->config.enabled) { - rxmode = 1; - pinMode(this->config.RXPin, INPUT); - interruptPin = digitalPinToInterrupt(this->config.RXPin); - ELECHOUSE_cc1101.SetRx(); - //attachInterrupt(interruptPin, handleReceive, FALLING); - attachInterrupt(interruptPin, handleReceive, CHANGE); - ESP_LOGD(TAG, "Enabled receive on Pin #%d Timing: %ld", this->config.RXPin, millis() - timing); + if(rxmode > 0) return true; + rxmode = 1; + pinMode(this->config.RXPin, INPUT); + interruptPin = digitalPinToInterrupt(this->config.RXPin); + ELECHOUSE_cc1101.SetRx(); + if(BoardProfile::integratedRadio) { + uint8_t state; + do { + delay(1); + state = ELECHOUSE_cc1101.SpiReadStatus(CC1101_MARCSTATE) & 0x1F; + } while(state != 0x0D && millis() - timing < 20); + Serial.printf("CC1101 MARCSTATE=0x%02X (RX=0x0D); RF switch readback SW1=%d SW0=%d\n", + state, digitalRead(BoardProfile::sw1), digitalRead(BoardProfile::sw0)); + if(state != 0x0D) { + Serial.println("CC1101 failed to enter RX; radio unavailable"); + ELECHOUSE_cc1101.setSidle(); + this->config.radioInit = false; + this->_available = false; + rxmode = 0; + return false; + } } + //attachInterrupt(interruptPin, handleReceive, FALLING); + attachInterrupt(interruptPin, handleReceive, CHANGE); + ESP_LOGD(TAG, "Enabled receive on Pin #%d Timing: %ld", this->config.RXPin, millis() - timing); + return true; } void Transceiver::disableReceive(void) { rxmode = 0; @@ -396,12 +415,15 @@ void Transceiver::setConfig(const transceiver_config_t &cfg) { // Saving first means a radio that locks up while applying comes back with // the new config after the reboot. RadioLock lock(portMAX_DELAY, true); - if(this->config.enabled && this->config.TXPin != cfg.TXPin) pinMode(this->config.TXPin, INPUT); - this->config = cfg; + transceiver_config_t next = cfg; + next.applyBoardPins(); + if(this->config.enabled && this->config.TXPin != next.TXPin) pinMode(this->config.TXPin, INPUT); + this->config = next; this->config.save(); this->config.apply(); } bool Transceiver::usesPin(uint8_t pin) { + if(BoardProfile::usesPin(pin)) return true; if(this->config.enabled) { if(this->config.SCKPin == pin || this->config.TXPin == pin || @@ -575,10 +597,41 @@ void transceiver_config_t::load() { pref.end(); //this->printBuffer = somfy.transceiver.printBuffer; } +void transceiver_config_t::applyBoardPins() { + if(!BoardProfile::integratedRadio) return; + this->SCKPin = BoardProfile::sck; + this->MOSIPin = BoardProfile::mosi; + this->MISOPin = BoardProfile::miso; + this->CSNPin = BoardProfile::cs; + this->TXPin = BoardProfile::tx; + this->RXPin = BoardProfile::rx; +} + static void warnBootPin(const char *name, uint8_t pin) { const char *effect = bootPinEffect(pin); if(effect) ESP_LOGW(TAG, "Radio %s is on GPIO%u, a strapping pin the radio can drive at reset. %s", name, pin, effect); } +static bool checkBoardRadio(float frequency) { + if(!BoardProfile::integratedRadio) return true; + uint8_t part = ELECHOUSE_cc1101.SpiReadStatus(CC1101_PARTNUM); + uint8_t version = ELECHOUSE_cc1101.SpiReadStatus(CC1101_VERSION); + uint8_t gdo0 = ELECHOUSE_cc1101.SpiReadReg(CC1101_IOCFG0); + uint8_t gdo2 = ELECHOUSE_cc1101.SpiReadReg(CC1101_IOCFG2); + uint8_t packet = ELECHOUSE_cc1101.SpiReadReg(CC1101_PKTCTRL0); + uint8_t modem = ELECHOUSE_cc1101.SpiReadReg(CC1101_MDMCFG2); + uint32_t word = (static_cast(ELECHOUSE_cc1101.SpiReadReg(CC1101_FREQ2)) << 16) | + (static_cast(ELECHOUSE_cc1101.SpiReadReg(CC1101_FREQ1)) << 8) | + ELECHOUSE_cc1101.SpiReadReg(CC1101_FREQ0); + float actual = word * (26.0f / 65536.0f); + Serial.printf("CC1101 PARTNUM=0x%02X VERSION=0x%02X IOCFG0=0x%02X IOCFG2=0x%02X PKTCTRL0=0x%02X MDMCFG2=0x%02X\n", + part, version, gdo0, gdo2, packet, modem); + Serial.printf("CC1101 frequency requested=%.3f readback=%.3f MHz; GDO0 TX=%u GDO2 RX=%u\n", + frequency, actual, BoardProfile::tx, BoardProfile::rx); + return part == 0 && version != 0 && version != 0xFF && + gdo0 == 0x0D && gdo2 == 0x0D && (packet & 0x30) == 0x30 && + (modem & 0x70) == 0x30 && actual > frequency - 0.01f && actual < frequency + 0.01f; +} + void transceiver_config_t::apply() { Preferences pref; // A transmission in flight stops after its current frame so the radio can @@ -588,12 +641,18 @@ void transceiver_config_t::apply() { // Reconfiguring the radio ends a frequency scan so TX may resume. const bool wasScanning = rxmode == 3; somfy.transceiver.disableReceive(); + // Generic radios retain their enabled-based availability. The integrated + // radio is published ready only after its register/RX checks succeed. + somfy.transceiver._available = false; if(wasScanning) { somfy.transceiver.resumeTx(TX_SUSPEND_SCAN); scanEmitPending = true; } + this->applyBoardPins(); radioBitLength = this->type; if(this->enabled) { + this->radioInit = false; + if(!BoardProfile::prepareRadio(this->frequency)) return; bool radioInit = true; pref.begin("CC1101"); radioInit = pref.getBool("radioInit", true); @@ -655,14 +714,17 @@ void transceiver_config_t::apply() { // 3 = Address check and 0 (0x00) and 255 (0xFF) broadcast. - if (!ELECHOUSE_cc1101.getCC1101()) { + const bool detected = ELECHOUSE_cc1101.getCC1101(); + // Always collect the integrated board readback, even if detection fails. + const bool boardRadioValid = checkBoardRadio(this->frequency); + if (!detected || !boardRadioValid) { ESP_LOGE(TAG, "Error setting up the radio"); this->radioInit = false; } else { ESP_LOGI(TAG, "Successfully set up the radio"); - somfy.transceiver.enableReceive(); - this->radioInit = true; + this->radioInit = somfy.transceiver.startReceive(); + somfy.transceiver._available = this->radioInit; } pref.begin("CC1101"); pref.putBool("radioInit", true); @@ -765,6 +827,9 @@ uint32_t Transceiver::submitTx(somfy_tx_job_t &job, bool priority, uint16_t dela ESP_LOGE(TAG, "Radio task not started, dropping transmission"); return 0; } + // Read published readiness without waiting behind a transmission. A queued + // job checks it again under the radio lock immediately before sending. + if(BoardProfile::integratedRadio && !this->available()) return 0; uint32_t ticket; { TxQueueLock lock; @@ -838,7 +903,7 @@ void Transceiver::runJob(somfy_tx_job_t &job) { start = this->sched.start(job.ticket, millis()); } if(!start) return; - const bool complete = this->transmitJob(job); + const bool complete = (!BoardProfile::integratedRadio || this->available()) && this->transmitJob(job); TxQueueLock qlock; this->sched.ended(job.ticket, complete, millis()); } @@ -872,7 +937,7 @@ void Transceiver::startTxTask() { } somfy_frame_t& Transceiver::lastFrame() { return this->frame; } void Transceiver::beginTransmit() { - if(this->config.enabled) { + if(this->available()) { this->disableReceive(); pinMode(this->config.TXPin, OUTPUT); digitalWrite(this->config.TXPin, 0); @@ -880,7 +945,7 @@ void Transceiver::beginTransmit() { } } void Transceiver::endTransmit() { - if(this->config.enabled) { + if(this->available()) { ELECHOUSE_cc1101.setSidle(); //delay(100); this->enableReceive(); diff --git a/src/Transceiver.h b/src/Transceiver.h index 4c4b17b..0576f55 100644 --- a/src/Transceiver.h +++ b/src/Transceiver.h @@ -1,12 +1,14 @@ #ifndef TRANSCEIVER_H #define TRANSCEIVER_H #include +#include #include #include #include "SomfyFrame.h" #include "TxBuffer.h" #include "RadioScheduler.h" #include "PulseDecoder.h" +#include "BoardProfile.h" // The CC1101 radio: receive decoding, the radio task that transmits radio // jobs, the frequency scan and the radio config. @@ -25,7 +27,7 @@ struct somfy_rx_queue_t { }; struct transceiver_config_t { bool printBuffer = false; - bool enabled = false; + bool enabled = BoardProfile::integratedRadio; uint8_t type = 56; // 56 or 80 bit protocol. radio_proto proto = radio_proto::RTS; uint8_t SCKPin = 18; @@ -44,11 +46,15 @@ struct transceiver_config_t { void save(); void load(); void apply(); + void applyBoardPins(); // Removes a key no longer used from the open CC1101 namespace. void removeNVSKey(Preferences &pref, const char *key); }; class Transceiver { private: + friend struct transceiver_config_t; + // Published under the radio lock; queue producers never wait on SPI. + std::atomic _available{false}; static void handleReceive(); static void txTask(void *arg); bool _received = false; @@ -56,11 +62,13 @@ class Transceiver { // Only touched under the TX queue lock. RadioScheduler sched; void startTxTask(); + bool startReceive(); bool transmitJob(somfy_tx_job_t &job); // Sends a job taken off the queue and leaves a frame beat after it. void runJob(somfy_tx_job_t &job); public: transceiver_config_t config; + bool available() const { return BoardProfile::integratedRadio ? _available.load() : this->config.enabled; } bool printBuffer = false; bool fromJSON(JsonObject& obj); // Swaps in, saves and applies the config. diff --git a/tests/board-profile/Arduino.h b/tests/board-profile/Arduino.h new file mode 100644 index 0000000..b7a69a0 --- /dev/null +++ b/tests/board-profile/Arduino.h @@ -0,0 +1,26 @@ +#pragma once +#include +#include +using byte = uint8_t; +class String; + +constexpr int LOW = 0; +constexpr int HIGH = 1; +constexpr int INPUT = 0x01; +constexpr int OUTPUT = 0x03; +void pinMode(uint8_t pin, uint8_t mode); +void digitalWrite(uint8_t pin, uint8_t value); +int digitalRead(uint8_t pin); +unsigned long millis(); +void delay(unsigned long duration); + +struct TestSerial { + template void printf(const char *, Args...) {} + void println(const char *) {} +}; +extern TestSerial Serial; +struct TestESP { + unsigned int getFlashChipSize() { return 16777216; } + unsigned int getPsramSize() { return 8388608; } +}; +extern TestESP ESP; diff --git a/tests/board-profile/ArduinoJson.h b/tests/board-profile/ArduinoJson.h new file mode 100644 index 0000000..4d66643 --- /dev/null +++ b/tests/board-profile/ArduinoJson.h @@ -0,0 +1,2 @@ +#pragma once +class JsonObject; diff --git a/tests/board-profile/Preferences.h b/tests/board-profile/Preferences.h new file mode 100644 index 0000000..daac39a --- /dev/null +++ b/tests/board-profile/Preferences.h @@ -0,0 +1,8 @@ +#pragma once +extern bool testRadioInit; +struct Preferences { + void begin(const char *) {} + bool getBool(const char *, bool) { return testRadioInit; } + void putBool(const char *, bool value) { testRadioInit = value; } + void end() {} +}; diff --git a/tests/board-profile/SPI.h b/tests/board-profile/SPI.h new file mode 100644 index 0000000..2bc0ca5 --- /dev/null +++ b/tests/board-profile/SPI.h @@ -0,0 +1,11 @@ +#pragma once +#include + +struct TestSPI { + bool active = false; + unsigned int starts = 0; + unsigned int stops = 0; + void begin(int8_t sck, int8_t miso, int8_t mosi, int8_t cs); + void end(); +}; +extern TestSPI SPI; diff --git a/tests/board-profile/board-profile-test.cpp b/tests/board-profile/board-profile-test.cpp new file mode 100644 index 0000000..13f99c8 --- /dev/null +++ b/tests/board-profile/board-profile-test.cpp @@ -0,0 +1,95 @@ +#include +#include +#include "BoardProfile.h" +#include "SPI.h" +#include + +TestSerial Serial; +TestESP ESP; +TestSPI SPI; +void TestSPI::begin(int8_t sck, int8_t miso, int8_t mosi, int8_t cs) { + assert(sck == 11 && miso == 10 && mosi == 9 && cs == 12); + assert(!active); + active = true; + starts++; +} +void TestSPI::end() { active = false; stops++; } +static int levels[49] = {}; +static int modes[49] = {}; +static unsigned long clockMs = 0; +static bool stuckMiso = false; +static unsigned int powerTransitions = 0; + +void pinMode(uint8_t pin, uint8_t mode) { + // Arduino 3 must release SPI ownership before preflight changes its pins. + if(pin == 9 || pin == 10 || pin == 11) assert(!SPI.active); + if(mode == OUTPUT) { + // Initial output enable must already have the safe level latched. + const bool high = pin == 12 || pin == 13 || pin == 15 || pin == 41 || + pin == 44 || pin == 47 || pin == 48; + assert(levels[pin] == (high ? HIGH : LOW)); + } + modes[pin] = mode; +} +int gpio_set_level(gpio_num_t pin, uint32_t value) { + if(pin == 15 && value == HIGH) { + // No other SPI device may drive MISO when the rail comes up. + assert(levels[12] == HIGH && levels[13] == HIGH); + assert(levels[41] == HIGH && levels[44] == HIGH); + assert(levels[43] == LOW && levels[21] == LOW); + assert(levels[47] == HIGH && levels[48] == HIGH); + const uint8_t controls[] = {12, 13, 21, 41, 43, 44, 47, 48}; + for(auto control : controls) assert(modes[control] == OUTPUT); + powerTransitions++; + } + levels[pin] = value; + return 0; +} +void digitalWrite(uint8_t pin, uint8_t value) { + // Arduino 3 only accepts writes after pinMode establishes GPIO ownership. + if(modes[pin] == OUTPUT) gpio_set_level(pin, value); +} +int digitalRead(uint8_t pin) { + if(pin == 10) return stuckMiso ? HIGH : LOW; + return levels[pin]; +} +unsigned long millis() { return clockMs; } +void delay(unsigned long duration) { clockMs += duration; } + +int main() { + BoardProfile::begin(); + if(BoardProfile::integratedRadio) { + assert(powerTransitions == 1); + assert(modes[15] == OUTPUT); + assert(BoardProfile::prepareRadio(433.42f)); + assert(SPI.active && SPI.starts == 1); + assert(modes[10] == INPUT && modes[9] == OUTPUT && modes[11] == OUTPUT); + assert(levels[12] == HIGH); // Release CS after readiness probe. + assert(BoardProfile::prepareRadio(433.42f)); // Reconfigure a running bus safely. + assert(SPI.active && SPI.starts == 2 && SPI.stops == 2); + assert(!BoardProfile::prepareRadio(868.0f)); + assert(!BoardProfile::prepareRadio(0.0f / 0.0f)); + stuckMiso = true; + auto started = millis(); + assert(!BoardProfile::prepareRadio(433.42f)); + assert(millis() - started <= 25); // Fail safely instead of hanging in SmartRC. + assert(levels[12] == HIGH); + assert(!SPI.active); // A failed preflight must not initialize SPI. + stuckMiso = false; + assert(BoardProfile::prepareRadio(433.42f)); + assert(powerTransitions == 1); // Retrying must not power-cycle shared devices. + const uint8_t reserved[] = {3, 9, 10, 11, 12, 13, 15, 21, 38, 41, 43, 44, 47, 48}; + for(auto pin : reserved) assert(BoardProfile::usesPin(pin)); + assert(BoardProfile::usesPin(19) && BoardProfile::usesPin(20)); + for(uint8_t pin = 26; pin <= 37; pin++) assert(BoardProfile::usesPin(pin)); + assert(!BoardProfile::usesPin(255)); + assert(!BoardProfile::usesPin(16)); + } + else { + assert(powerTransitions == 0); + assert(!SPI.active && SPI.starts == 0 && SPI.stops == 0); + assert(BoardProfile::prepareRadio(868.0f)); + for(uint8_t pin = 0; pin < 49; pin++) assert(!BoardProfile::usesPin(pin)); + } + puts("Board profile checks passed"); +} diff --git a/tests/board-profile/driver/gpio.h b/tests/board-profile/driver/gpio.h new file mode 100644 index 0000000..94b03e7 --- /dev/null +++ b/tests/board-profile/driver/gpio.h @@ -0,0 +1,4 @@ +#pragma once +#include +using gpio_num_t = int; +int gpio_set_level(gpio_num_t pin, uint32_t value); diff --git a/tests/board-profile/esp_log.h b/tests/board-profile/esp_log.h new file mode 100644 index 0000000..5ddc030 --- /dev/null +++ b/tests/board-profile/esp_log.h @@ -0,0 +1,9 @@ +#pragma once +// Keep the test logger a function call so unused firmware format arguments are +// still type-checked and the production TAG is referenced. +template inline void testLog(const char *, const char *, Args...) {} +#define ESP_LOGD(...) testLog(__VA_ARGS__) + +#define ESP_LOGE(...) testLog(__VA_ARGS__) +#define ESP_LOGW(...) testLog(__VA_ARGS__) +#define ESP_LOGI(...) testLog(__VA_ARGS__) diff --git a/tests/board-profile/extract-radio-setup.py b/tests/board-profile/extract-radio-setup.py new file mode 100644 index 0000000..845abed --- /dev/null +++ b/tests/board-profile/extract-radio-setup.py @@ -0,0 +1,29 @@ +"""Compile selected production methods without the unrelated RTOS/network code.""" +from pathlib import Path +import sys + +source = Path(sys.argv[1]).read_text() +names = [ + 'static bool checkBoardRadio(', + 'void transceiver_config_t::applyBoardPins(', + 'void transceiver_config_t::apply(', + 'void Transceiver::setConfig(', + 'bool Transceiver::usesPin(', + 'void Transceiver::enableReceive(', + 'bool Transceiver::startReceive(', + 'void Transceiver::disableReceive(', + 'uint32_t Transceiver::submitTx(', +] +methods = [] +for name in names: + assert source.count(name) == 1, f'Production setup method changed: {name}' + start = source.index(name) + brace = source.index('{', start) + depth = 1 + end = brace + 1 + while depth: + assert end < len(source), f'Unterminated method: {name}' + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + methods.append(source[start:end]) +Path(sys.argv[2]).write_text('\n\n'.join(methods) + '\n') diff --git a/tests/board-profile/radio-setup-test.cpp b/tests/board-profile/radio-setup-test.cpp new file mode 100644 index 0000000..c8fbd72 --- /dev/null +++ b/tests/board-profile/radio-setup-test.cpp @@ -0,0 +1,162 @@ +// Exercise the actual radio setup, RX and queue-admission methods, replacing +// only hardware/RTOS boundaries. The script extracts those definitions from +// Transceiver.cpp so the test cannot silently exercise a copy of the logic. +#include +#include +#include +#include +#include "Transceiver.h" +#include "SPI.h" +#include "esp_log.h" +#include +#include + +TestSerial Serial; +TestESP ESP; +TestSPI SPI; +void TestSPI::begin(int8_t, int8_t, int8_t, int8_t) { active = true; } +void TestSPI::end() { active = false; } +static int levels[49] = {}; +static bool stuckMiso; +static unsigned long clockMs; +void pinMode(uint8_t, uint8_t) {} +void digitalWrite(uint8_t pin, uint8_t value) { levels[pin] = value; } +int digitalRead(uint8_t pin) { return pin == 10 && stuckMiso ? HIGH : levels[pin]; } +int gpio_set_level(gpio_num_t pin, uint32_t value) { levels[pin] = value; return 0; } +unsigned long millis() { return clockMs; } +void delay(unsigned long ms) { clockMs += ms; } +static unsigned int attached; +static unsigned int rxStarts; +static unsigned int initializations; +static unsigned int saves; +static bool observedReadyDuringRx; +static uint32_t queuedDuringRx; +int digitalPinToInterrupt(uint8_t pin) { return pin; } +constexpr int CHANGE = 1; +void attachInterrupt(int, void (*)(), int) { attached++; } +void detachInterrupt(int) { attached = 0; } +static const char *TAG = "Somfy"; +static uint8_t rxmode; +static int interruptPin; +uint8_t radioBitLength; +bool testRadioInit = true; +struct { Transceiver transceiver; } somfy; +struct RadioLock { RadioLock(int = 0, bool = false) {} }; +struct TxQueueLock { ~TxQueueLock() {} }; +constexpr int portMAX_DELAY = 0; +static bool scanEmitPending; +static void *txTaskHandle = reinterpret_cast(1); +void xTaskNotifyGive(void *) {} +void Transceiver::handleReceive() {} +void Transceiver::resumeTx(uint8_t) {} +static void warnBootPin(const char *, uint8_t) {} +void transceiver_config_t::save() { + saves++; + if(BoardProfile::integratedRadio) + assert(SCKPin == 11 && MISOPin == 10 && MOSIPin == 9 && CSNPin == 12 && TXPin == 3 && RXPin == 38); +} + +ELECHOUSE_CC1101 ELECHOUSE_cc1101; +static bool detected; +static uint8_t part, version, gdo0, gdo2, packet, modem, rxState; +static uint32_t frequencyWord; +void ELECHOUSE_CC1101::Init() { initializations++; } +bool ELECHOUSE_CC1101::getCC1101() { return detected; } +byte ELECHOUSE_CC1101::SpiReadStatus(byte addr) { + if(addr == CC1101_PARTNUM) return part; + if(addr == CC1101_VERSION) return version; + if(addr == CC1101_MARCSTATE) return rxState; + assert(false); return 0; +} +byte ELECHOUSE_CC1101::SpiReadReg(byte addr) { + if(addr == CC1101_IOCFG0) return gdo0; + if(addr == CC1101_IOCFG2) return gdo2; + if(addr == CC1101_PKTCTRL0) return packet; + if(addr == CC1101_MDMCFG2) return modem; + if(addr == CC1101_FREQ2) return frequencyWord >> 16; + if(addr == CC1101_FREQ1) return frequencyWord >> 8; + if(addr == CC1101_FREQ0) return frequencyWord; + assert(false); return 0; +} +void ELECHOUSE_CC1101::setSpiPin(byte sck, byte miso, byte mosi, byte cs) { + if(BoardProfile::integratedRadio) assert(sck == 11 && miso == 10 && mosi == 9 && cs == 12); +} +void ELECHOUSE_CC1101::SetRx() { + rxStarts++; + observedReadyDuringRx = somfy.transceiver.available(); + somfy_tx_job_t job; + queuedDuringRx = somfy.transceiver.submitTx(job); +} +void ELECHOUSE_CC1101::setSidle() {} +void ELECHOUSE_CC1101::setGDO(byte, byte) {} +void ELECHOUSE_CC1101::setGDO0(byte) {} +#define NOOP(name, type) void ELECHOUSE_CC1101::name(type) {} +NOOP(setCCMode, bool) NOOP(setMHZ, float) NOOP(setRxBW, float) +NOOP(setDeviation, float) NOOP(setPA, int) NOOP(setModulation, byte) +NOOP(setManchester, bool) NOOP(setPktFormat, byte) NOOP(setDcFilterOff, bool) +NOOP(setCrc, bool) NOOP(setCRC_AF, bool) NOOP(setSyncMode, byte) NOOP(setAdrChk, byte) + +#include "radio-setup-methods.inc" + +static void reset() { + somfy.transceiver.~Transceiver(); + new (&somfy.transceiver) Transceiver; + detected = true; part = 0; version = 0x14; + gdo0 = gdo2 = 0x0D; packet = 0x32; modem = 0x3C; + frequencyWord = 0x10AB85; rxState = 0x0D; + attached = rxStarts = initializations = saves = 0; + observedReadyDuringRx = false; queuedDuringRx = 0; + testRadioInit = true; stuckMiso = false; rxmode = 0; clockMs = 0; +} +static void assertUnavailable() { + auto &radio = somfy.transceiver; + assert(!radio.available() && !radio.config.radioInit && attached == 0); + somfy_tx_job_t job; + assert(radio.submitTx(job) == 0); + radio.enableReceive(); + assert(attached == 0); +} +int main() { + reset(); auto &radio = somfy.transceiver; + if(BoardProfile::integratedRadio) { + radio.config.SCKPin = radio.config.TXPin = radio.config.RXPin = 16; + radio.config.apply(); + assert(radio.available() && radio.config.radioInit && attached == 1); + assert(!observedReadyDuringRx && queuedDuringRx == 0); + assert(radio.config.TXPin == 3 && radio.config.RXPin == 38 && radio.config.SCKPin == 11); + somfy_tx_job_t job; assert(radio.submitTx(job) != 0); + stuckMiso = true; radio.config.apply(); assertUnavailable(); + stuckMiso = false; radio.config.apply(); assert(radio.available()); + transceiver_config_t next = radio.config; + next.enabled = false; + next.SCKPin = next.MOSIPin = next.MISOPin = next.CSNPin = next.TXPin = next.RXPin = 16; + radio.setConfig(next); assertUnavailable(); assert(saves == 1); + for(uint8_t pin : {uint8_t(3), uint8_t(12), uint8_t(19), uint8_t(33), uint8_t(48)}) assert(radio.usesPin(pin)); + assert(!radio.usesPin(16)); + reset(); stuckMiso = true; radio.config.apply(); assertUnavailable(); assert(initializations == 0); + reset(); testRadioInit = false; radio.config.apply(); assertUnavailable(); assert(initializations == 0); + reset(); detected = false; radio.config.apply(); assertUnavailable(); assert(rxStarts == 0); + reset(); part = 1; radio.config.apply(); assertUnavailable(); + reset(); version = 0; radio.config.apply(); assertUnavailable(); + reset(); version = 0xFF; radio.config.apply(); assertUnavailable(); assert(rxStarts == 0); + reset(); gdo0 = 0; radio.config.apply(); assertUnavailable(); + reset(); gdo2 = 0; radio.config.apply(); assertUnavailable(); + reset(); packet = 0; radio.config.apply(); assertUnavailable(); + reset(); modem = 0; radio.config.apply(); assertUnavailable(); + reset(); frequencyWord = 0; radio.config.apply(); assertUnavailable(); + reset(); rxState = 0; radio.config.apply(); assertUnavailable(); assert(rxStarts == 1 && millis() <= 25); + rxState = 0x0D; radio.config.apply(); assert(radio.available() && attached == 1); + } else { + // Generic radios retain upstream's enabled-based availability and queue + // admission behavior, including when disabled or detection fails. + radio.config.apply(); + somfy_tx_job_t job; assert(radio.submitTx(job) != 0); + radio.config.enabled = true; detected = false; radio.config.apply(); + assert(radio.available() && !radio.config.radioInit); + radio.config.apply(); // Still no Plus-specific register gating. + detected = true; rxState = 0; radio.config.apply(); + assert(radio.available() && radio.config.radioInit && attached == 1); + assert(observedReadyDuringRx && queuedDuringRx != 0); + } + puts("Radio readiness and RX/queue gating checks passed"); +} diff --git a/tests/board-profile/shade-gpio-test.cpp b/tests/board-profile/shade-gpio-test.cpp new file mode 100644 index 0000000..6cb75a2 --- /dev/null +++ b/tests/board-profile/shade-gpio-test.cpp @@ -0,0 +1,76 @@ +#include +#include +#include "BoardProfile.h" +#include +#include "SomfyFrame.h" +#include "ShadeSettings.h" + +// Substitute only the shade model/storage boundary. The GPIO methods below +// are compiled from the production ShadeGpio.cpp and observe real board policy. +#define SOMFY_H +enum class gpio_flags_t : byte { LowLevelTrigger = 0x01 }; +struct SomfyRemote { + void triggerGPIOs(somfy_frame_t &frame); +}; +struct SomfyShade : SomfyRemote, ShadeSettings { + radio_proto proto = radio_proto::GP_Relay; + uint8_t gpioFlags = 0; + int8_t gpioDir = 0; + uint8_t gpioUp = 16, gpioDown = 17, gpioMy = 18; + uint32_t gpioRelease = 0; + struct State { int8_t direction = -1, tiltDirection = 0; float currentPos = 0; } position; + const State &state() const { return position; } + bool isToggle() { return isToggleShade(shadeType); } + void setGPIOs(); + void triggerGPIOs(somfy_frame_t &frame); + bool usesPin(uint8_t pin); +}; +#include "ShadeGpio.cpp" + +TestSerial Serial; +TestESP ESP; +static unsigned int writes = 0; +static int levels[49] = {}; +int gpio_set_level(gpio_num_t pin, uint32_t value) { levels[pin] = value; return 0; } +void pinMode(uint8_t, uint8_t) {} +void digitalWrite(uint8_t pin, uint8_t value) { writes++; levels[pin] = value; } +int digitalRead(uint8_t pin) { return levels[pin]; } +unsigned long millis() { return 100; } +void delay(unsigned long) {} +// BoardProfile preflight is linked but this test never starts the hardware. +#include "SPI.h" +TestSPI SPI; +void TestSPI::begin(int8_t, int8_t, int8_t, int8_t) {} +void TestSPI::end() {} + +int main() { + SomfyShade shade; + shade.setGPIOs(); + assert(writes == 2 && levels[16] == HIGH && levels[17] == LOW); + somfy_frame_t frame; + frame.cmd = somfy_commands::Down; + frame.repeats = 2; + shade.proto = radio_proto::GP_Remote; + shade.triggerGPIOs(frame); + assert(writes == 5 && levels[17] == HIGH); + const unsigned int before = writes; + // These assignments can arrive from an old backup with the radio disabled. + // Test every reserved pad in each output slot, including USB/flash pads. + for(uint8_t pin = 0; pin < 49; pin++) { + if(!BoardProfile::usesPin(pin)) continue; + for(uint8_t slot = 0; slot < 3; slot++) { + shade.gpioUp = slot == 0 ? pin : 16; + shade.gpioDown = slot == 1 ? pin : 17; + shade.gpioMy = slot == 2 ? pin : 18; + shade.proto = radio_proto::GP_Remote; + shade.triggerGPIOs(frame); + shade.setGPIOs(); + if(slot != 2) { + shade.proto = radio_proto::GP_Relay; + shade.setGPIOs(); + } + assert(writes == before); + } + } + puts("Reserved shade GPIO checks passed"); +} diff --git a/tools/test-board-profile.sh b/tools/test-board-profile.sh new file mode 100755 index 0000000..5810bd7 --- /dev/null +++ b/tools/test-board-profile.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +set -euo pipefail +repo="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +scratch="$(mktemp -d)" +trap 'rm -rf -- "$scratch"' EXIT +compiler="${CXX:-c++}" +common=(-std=c++11 -Wall -Wextra -Werror -Wno-unused-parameter -I"$repo/tests/board-profile" -I"$repo/src") +sources=("$repo/tests/board-profile/board-profile-test.cpp" "$repo/src/BoardProfile.cpp") +"$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS -DCONFIG_IDF_TARGET_ESP32S3 \ + "${sources[@]}" -o "$scratch/lilygo-test" +"$scratch/lilygo-test" +"$compiler" "${common[@]}" "${sources[@]}" -o "$scratch/generic-test" +"$scratch/generic-test" +"$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS -DCONFIG_IDF_TARGET_ESP32S3 \ + "$repo/tests/board-profile/shade-gpio-test.cpp" "$repo/src/BoardProfile.cpp" -o "$scratch/shade-gpio-test" +"$scratch/shade-gpio-test" +if "$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS \ + "${sources[@]}" -o "$scratch/wrong-target" > "$scratch/wrong-target.log" 2>&1; then + echo 'LILYGO profile incorrectly accepted a non-S3 target' >&2 + exit 1 +fi +echo 'Non-S3 LILYGO build rejected as expected' + +# Test production setup/RX/queue methods against register and readiness faults. +python3 "$repo/tests/board-profile/extract-radio-setup.py" "$repo/src/Transceiver.cpp" "$scratch/radio-setup-methods.inc" +for profile in generic lilygo; do + flags=() + if [[ "$profile" == lilygo ]]; then + flags=(-DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS -DCONFIG_IDF_TARGET_ESP32S3) + fi + "$compiler" "${common[@]}" -I"$scratch" -I"$repo/lib/SmartRC-CC1101-Driver-Lib" "${flags[@]}" \ + "$repo/tests/board-profile/radio-setup-test.cpp" "$repo/src/BoardProfile.cpp" \ + "$repo/src/RadioScheduler.cpp" -o "$scratch/radio-$profile" + "$scratch/radio-$profile" +done From a5afcfaceaf59e7ceac0ce8afdfde6ff2045e113 Mon Sep 17 00:00:00 2001 From: "R. Sid Shaytay" <352722946+r-sidshaytay@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:36:18 -0800 Subject: [PATCH 02/10] build: match Plus profile to standard upstream S3 layout --- README.md | 5 +++-- platformio.ini | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 019ac0a..c0451fd 100644 --- a/README.md +++ b/README.md @@ -108,8 +108,9 @@ pio run -e lilygo-t-embed-cc1101-plus -t buildfs ``` The images are in `.pio/build/lilygo-t-embed-cc1101-plus/`. This environment reuses -`esp32_3MB.csv`. A device with another partition layout needs USB provisioning with -a fresh recovery backup and current rolling codes; firmware-only OTA cannot migrate +`default_8MB.csv`, matching the generic S3 release: two 3.1875 MiB firmware slots +and a 1.5 MiB filesystem. The upper 8 MiB stays unallocated. A device with another +partition layout needs USB provisioning with a fresh recovery backup and current rolling codes; firmware-only OTA cannot migrate the layout. Do not substitute a generic S3 image for this profile. Bugs and ideas go to the [issues](https://github.com/cjkas/ESPSomfy-RTS/issues); security problems go through [SECURITY.md](SECURITY.md). diff --git a/platformio.ini b/platformio.ini index 8b82071..385d47a 100644 --- a/platformio.ini +++ b/platformio.ini @@ -103,7 +103,7 @@ build_flags = extends = esp32 board = esp32-s3-devkitc1-n16r8 build_type = release -board_build.partitions = esp32_3MB.csv +board_build.partitions = default_8MB.csv board_build.flash_mode = qio board_build.f_flash = 80000000L board_build.arduino.memory_type = qio_opi From d4c13d51343e54055c3ffe59b957057c9f7b88aa Mon Sep 17 00:00:00 2001 From: "R. Sid Shaytay" <352722946+r-sidshaytay@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:51:36 -0800 Subject: [PATCH 03/10] refactor: centralize shade GPIO initialization and board guards Use one initialization method for saved configuration and JSON updates. Reject the complete output assignment when any pin belongs to integrated board hardware, retaining separate UI validation and runtime output guards. Exercise production GPIO initialization on generic and Plus profiles. --- src/ConfigFile.cpp | 8 +------- src/ShadeGpio.cpp | 11 +++++++++++ src/Somfy.h | 1 + src/SomfyJson.cpp | 4 +--- tests/board-profile/shade-gpio-test.cpp | 19 ++++++++++++++++++- tools/test-board-profile.sh | 12 +++++++++--- 6 files changed, 41 insertions(+), 14 deletions(-) diff --git a/src/ConfigFile.cpp b/src/ConfigFile.cpp index 6ff02a3..fbd3f4f 100644 --- a/src/ConfigFile.cpp +++ b/src/ConfigFile.cpp @@ -6,7 +6,6 @@ #include "Utils.h" #include "ConfigSettings.h" #include "RollingCode.h" -#include "BoardProfile.h" static const char *TAG = "ConfigFile"; @@ -288,12 +287,7 @@ void ShadeConfigFile::readShade(SomfyShade *shade) { shade->gpioMy = rec.gpioMy; shade->gpioFlags = rec.gpioFlags; shade->roomId = rec.roomId; - if(shade->proto == radio_proto::GP_Relay || shade->proto == radio_proto::GP_Remote) { - if(!BoardProfile::usesPin(shade->gpioUp)) pinMode(shade->gpioUp, OUTPUT); - if(!BoardProfile::usesPin(shade->gpioDown)) pinMode(shade->gpioDown, OUTPUT); - } - if(shade->proto == radio_proto::GP_Remote && !BoardProfile::usesPin(shade->gpioMy)) - pinMode(shade->gpioMy, OUTPUT); + shade->initGPIOs(); } void ShadeConfigFile::readGroup(SomfyGroup *group) { group_record_t rec = groupRecord(group); diff --git a/src/ShadeGpio.cpp b/src/ShadeGpio.cpp index bd29617..7085f95 100644 --- a/src/ShadeGpio.cpp +++ b/src/ShadeGpio.cpp @@ -12,6 +12,17 @@ static bool usesBoardGPIOs(const SomfyShade &shade) { (shade.proto == radio_proto::GP_Remote && BoardProfile::usesPin(shade.gpioMy)); } +// Shared by saved/backup configuration loading and JSON updates. Refuse the +// entire assignment if any output belongs to integrated board hardware. +void SomfyShade::initGPIOs() { + if(usesBoardGPIOs(*this)) return; + if(this->proto == radio_proto::GP_Relay || this->proto == radio_proto::GP_Remote) { + pinMode(this->gpioUp, OUTPUT); + pinMode(this->gpioDown, OUTPUT); + } + if(this->proto == radio_proto::GP_Remote) pinMode(this->gpioMy, OUTPUT); +} + void SomfyShade::setGPIOs() { if(usesBoardGPIOs(*this)) return; if(this->proto == radio_proto::GP_Relay) { diff --git a/src/Somfy.h b/src/Somfy.h index d0de9fb..c1df738 100644 --- a/src/Somfy.h +++ b/src/Somfy.h @@ -152,6 +152,7 @@ class SomfyShade : public SomfyRemote, public ShadeSettings, private MotorLink, void commit(); void clear(); int8_t transformPosition(float fpos); + void initGPIOs(); void setGPIOs(); void triggerGPIOs(somfy_frame_t &frame); bool usesPin(uint8_t pin); diff --git a/src/SomfyJson.cpp b/src/SomfyJson.cpp index bac699a..4ead8a0 100644 --- a/src/SomfyJson.cpp +++ b/src/SomfyJson.cpp @@ -157,13 +157,11 @@ int8_t SomfyShade::fromJSON(JsonObject &obj) { if(this->proto == radio_proto::GP_Remote || this->proto == radio_proto::GP_Relay) { if(!obj["gpioUp"].isNull()) this->gpioUp = obj["gpioUp"]; if(!obj["gpioDown"].isNull()) this->gpioDown = obj["gpioDown"]; - if(!BoardProfile::usesPin(this->gpioUp)) pinMode(this->gpioUp, OUTPUT); - if(!BoardProfile::usesPin(this->gpioDown)) pinMode(this->gpioDown, OUTPUT); } if(this->proto == radio_proto::GP_Remote) { if(!obj["gpioMy"].isNull()) this->gpioMy = obj["gpioMy"]; - if(!BoardProfile::usesPin(this->gpioMy)) pinMode(this->gpioMy, OUTPUT); } + this->initGPIOs(); } return err; } diff --git a/tests/board-profile/shade-gpio-test.cpp b/tests/board-profile/shade-gpio-test.cpp index 6cb75a2..2c46ed8 100644 --- a/tests/board-profile/shade-gpio-test.cpp +++ b/tests/board-profile/shade-gpio-test.cpp @@ -21,6 +21,7 @@ struct SomfyShade : SomfyRemote, ShadeSettings { struct State { int8_t direction = -1, tiltDirection = 0; float currentPos = 0; } position; const State &state() const { return position; } bool isToggle() { return isToggleShade(shadeType); } + void initGPIOs(); void setGPIOs(); void triggerGPIOs(somfy_frame_t &frame); bool usesPin(uint8_t pin); @@ -30,9 +31,11 @@ struct SomfyShade : SomfyRemote, ShadeSettings { TestSerial Serial; TestESP ESP; static unsigned int writes = 0; +static unsigned int modes = 0; +static int pinModes[49] = {}; static int levels[49] = {}; int gpio_set_level(gpio_num_t pin, uint32_t value) { levels[pin] = value; return 0; } -void pinMode(uint8_t, uint8_t) {} +void pinMode(uint8_t pin, uint8_t mode) { modes++; pinModes[pin] = mode; } void digitalWrite(uint8_t pin, uint8_t value) { writes++; levels[pin] = value; } int digitalRead(uint8_t pin) { return levels[pin]; } unsigned long millis() { return 100; } @@ -45,6 +48,15 @@ void TestSPI::end() {} int main() { SomfyShade shade; + shade.initGPIOs(); + assert(modes == 2 && pinModes[16] == OUTPUT && pinModes[17] == OUTPUT); + shade.proto = radio_proto::GP_Remote; + shade.initGPIOs(); + assert(modes == 5 && pinModes[18] == OUTPUT); + shade.proto = radio_proto::RTS; + shade.initGPIOs(); + assert(modes == 5); + shade.proto = radio_proto::GP_Relay; shade.setGPIOs(); assert(writes == 2 && levels[16] == HIGH && levels[17] == LOW); somfy_frame_t frame; @@ -63,10 +75,15 @@ int main() { shade.gpioDown = slot == 1 ? pin : 17; shade.gpioMy = slot == 2 ? pin : 18; shade.proto = radio_proto::GP_Remote; + const unsigned int beforeModes = modes; + shade.initGPIOs(); + assert(modes == beforeModes); shade.triggerGPIOs(frame); shade.setGPIOs(); if(slot != 2) { shade.proto = radio_proto::GP_Relay; + shade.initGPIOs(); + assert(modes == beforeModes); shade.setGPIOs(); } assert(writes == before); diff --git a/tools/test-board-profile.sh b/tools/test-board-profile.sh index 5810bd7..cbeb336 100755 --- a/tools/test-board-profile.sh +++ b/tools/test-board-profile.sh @@ -11,9 +11,15 @@ sources=("$repo/tests/board-profile/board-profile-test.cpp" "$repo/src/BoardProf "$scratch/lilygo-test" "$compiler" "${common[@]}" "${sources[@]}" -o "$scratch/generic-test" "$scratch/generic-test" -"$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS -DCONFIG_IDF_TARGET_ESP32S3 \ - "$repo/tests/board-profile/shade-gpio-test.cpp" "$repo/src/BoardProfile.cpp" -o "$scratch/shade-gpio-test" -"$scratch/shade-gpio-test" +for profile in generic lilygo; do + flags=() + if [[ "$profile" == lilygo ]]; then + flags=(-DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS -DCONFIG_IDF_TARGET_ESP32S3) + fi + "$compiler" "${common[@]}" "${flags[@]}" \ + "$repo/tests/board-profile/shade-gpio-test.cpp" "$repo/src/BoardProfile.cpp" -o "$scratch/shade-gpio-$profile" + "$scratch/shade-gpio-$profile" +done if "$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS \ "${sources[@]}" -o "$scratch/wrong-target" > "$scratch/wrong-target.log" 2>&1; then echo 'LILYGO profile incorrectly accepted a non-S3 target' >&2 From 9b75bd61f44ee8e485b95a286b7ad77b9035c655 Mon Sep 17 00:00:00 2001 From: "R. Sid Shaytay" <352722946+r-sidshaytay@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:02:32 -0800 Subject: [PATCH 04/10] ci: build and publish LILYGO Plus release files --- .github/workflows/build.yaml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 2f8dc1b..5f8bda1 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -168,7 +168,7 @@ jobs: # for flashing a new chip via USB/serial # addr_bootloader: chip-dependent (ESP32: 0x1000, S3/C3/C6: 0x0, C5/P4: 0x2000) # addr_fs: must match the spiffs offset in the env's partition table - # (0x310000 in both esp32_3MB.csv and esp32_huge_app.csv) + # (0x310000 in esp32_3MB.csv/esp32_huge_app.csv, 0x670000 in default_8MB.csv) include: - env: esp32dev name: ESP32 @@ -188,6 +188,15 @@ jobs: elfname: SomfyController.ino.esp32s3.elf fsname: SomfyController.littlefs.esp32s3.bin obname: SomfyController.onboard.esp32s3.bin + - env: lilygo-t-embed-cc1101-plus + name: LILYGO T-Embed CC1101 Plus + chip: ESP32-S3 + addr_bootloader: "0x0" + addr_fs: "0x670000" + fwname: SomfyController.ino.lilygo-t-embed-cc1101-plus.bin + elfname: SomfyController.ino.lilygo-t-embed-cc1101-plus.elf + fsname: SomfyController.littlefs.lilygo-t-embed-cc1101-plus.bin + obname: SomfyController.onboard.lilygo-t-embed-cc1101-plus.bin - env: esp32c3 name: ESP32-C3 chip: ESP32-C3 From fce6f0cb6e594f326f3abc8600c9e93616eecd65 Mon Sep 17 00:00:00 2001 From: "R. Sid Shaytay" <352722946+r-sidshaytay@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:37:46 -0800 Subject: [PATCH 05/10] docs: distinguish expected CC1101 compatibility from Plus testing --- README.md | 7 ++++++- src/BoardProfile.h | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c0451fd..b6b2775 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,12 @@ The firmware builds on [pioarduino](https://github.com/pioarduino/platform-espre The headless Plus profile uses the board's integrated CC1101 on the 433 MHz RF path, 16 MB flash and 8 MB OPI PSRAM. It fixes the radio pins and reserves the shared peripheral, USB and flash/PSRAM pins; the display and encoder are not used. -This profile is for the **T-Embed CC1101 Plus**, not the non-Plus board. +Hardware testing was performed on the **T-Embed CC1101 Plus**. The standard +**T-Embed CC1101** is expected to work with the same profile: [LILYGO describes the +Plus](https://lilygo.cc/products/t-embed-cc1101-plus) as that board with an added +nRF24L01, and its [documented radio/power pins](https://github.com/Xinyuan-LilyGO/T-Embed-CC1101/blob/master/examples/utilities.h) +match this profile. The non-Plus CC1101 model has not been tested here. This does +not cover the plain T-Embed without a CC1101. ```bash pio run -e lilygo-t-embed-cc1101-plus diff --git a/src/BoardProfile.h b/src/BoardProfile.h index 882c0e4..cce53dc 100644 --- a/src/BoardProfile.h +++ b/src/BoardProfile.h @@ -11,7 +11,7 @@ constexpr bool integratedRadio = true; constexpr bool integratedRadio = false; #endif -// LILYGO T-Embed CC1101 Plus integrated hardware; not the non-Plus board. +// LILYGO T-Embed CC1101 wiring, hardware-tested on the Plus model. constexpr uint8_t power = 15; constexpr uint8_t sck = 11; constexpr uint8_t mosi = 9; From bfd8c1c7b4a5a12aea0dc1d90748b8939c11178c Mon Sep 17 00:00:00 2001 From: "R. Sid Shaytay" <352722946+r-sidshaytay@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:49:39 -0800 Subject: [PATCH 06/10] docs: invite testing of expected non-Plus CC1101 compatibility --- README.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b6b2775..6ce10a5 100644 --- a/README.md +++ b/README.md @@ -100,12 +100,14 @@ The firmware builds on [pioarduino](https://github.com/pioarduino/platform-espre The headless Plus profile uses the board's integrated CC1101 on the 433 MHz RF path, 16 MB flash and 8 MB OPI PSRAM. It fixes the radio pins and reserves the shared peripheral, USB and flash/PSRAM pins; the display and encoder are not used. -Hardware testing was performed on the **T-Embed CC1101 Plus**. The standard -**T-Embed CC1101** is expected to work with the same profile: [LILYGO describes the -Plus](https://lilygo.cc/products/t-embed-cc1101-plus) as that board with an added -nRF24L01, and its [documented radio/power pins](https://github.com/Xinyuan-LilyGO/T-Embed-CC1101/blob/master/examples/utilities.h) -match this profile. The non-Plus CC1101 model has not been tested here. This does -not cover the plain T-Embed without a CC1101. + +The standard T-Embed CC1101 is expected to work with the same firmware profile. Its +documented radio wiring and memory configuration match, and we haven’t identified a +reason it would need different firmware. We’ve tested only the Plus ourselves. If you +have the standard CC1101 model, please try it and report whether it works, including +your board revision and any problems. + +This refers to the T-Embed CC1101, not the plain T-Embed without the radio. ```bash pio run -e lilygo-t-embed-cc1101-plus From 31eda550b95434277e3f148db31d153a55e13d1f Mon Sep 17 00:00:00 2001 From: "R. Sid Shaytay" <352722946+r-sidshaytay@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:35:23 -0800 Subject: [PATCH 07/10] Rename the Plus-only LILYGO profile to the T-Embed CC1101 names The profile was named for the Plus model only, but the standard T-Embed CC1101 is expected to run the same firmware. Rename the macro to ESPSOMFY_LILYGO_T_EMBED_CC1101, the PlatformIO environment to lilygo-t-embed-cc1101, and the release files to SomfyController.{ino,littlefs,onboard}.lilygo-t-embed-cc1101.*, so later merges with downstream builds match by name. The matrix entry reads "LILYGO T-Embed CC1101 / Plus". Behavior and partitions are unchanged. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/build.yaml | 12 ++++++------ README.md | 10 +++++----- platformio.ini | 6 +++--- src/BoardProfile.cpp | 4 ++-- src/BoardProfile.h | 6 +++--- tools/test-board-profile.sh | 8 ++++---- 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 5f8bda1..827205e 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -188,15 +188,15 @@ jobs: elfname: SomfyController.ino.esp32s3.elf fsname: SomfyController.littlefs.esp32s3.bin obname: SomfyController.onboard.esp32s3.bin - - env: lilygo-t-embed-cc1101-plus - name: LILYGO T-Embed CC1101 Plus + - env: lilygo-t-embed-cc1101 + name: LILYGO T-Embed CC1101 / Plus chip: ESP32-S3 addr_bootloader: "0x0" addr_fs: "0x670000" - fwname: SomfyController.ino.lilygo-t-embed-cc1101-plus.bin - elfname: SomfyController.ino.lilygo-t-embed-cc1101-plus.elf - fsname: SomfyController.littlefs.lilygo-t-embed-cc1101-plus.bin - obname: SomfyController.onboard.lilygo-t-embed-cc1101-plus.bin + fwname: SomfyController.ino.lilygo-t-embed-cc1101.bin + elfname: SomfyController.ino.lilygo-t-embed-cc1101.elf + fsname: SomfyController.littlefs.lilygo-t-embed-cc1101.bin + obname: SomfyController.onboard.lilygo-t-embed-cc1101.bin - env: esp32c3 name: ESP32-C3 chip: ESP32-C3 diff --git a/README.md b/README.md index 6ce10a5..dc13adc 100644 --- a/README.md +++ b/README.md @@ -95,9 +95,9 @@ In either mode the socket refuses an upgrade whose `Origin` header doesn't name ## Building The firmware builds on [pioarduino](https://github.com/pioarduino/platform-espressif32) (Arduino 3.x on ESP-IDF 5.5), not the stock PlatformIO platform. In VS Code use the **pioarduino IDE** extension instead of PlatformIO IDE. On the command line, `pip install pioarduino` gives you `pio`. Run the unit tests with `pio test -e native`. [ADR 0003](docs/adr/0003-pioarduino-idf55.md) explains why. -### Build for LILYGO T-Embed CC1101 Plus +### Build for LILYGO T-Embed CC1101 / Plus -The headless Plus profile uses the board's integrated CC1101 on the 433 MHz RF path, +The headless T-Embed CC1101 profile, for both the Plus and the standard model, uses the board's integrated CC1101 on the 433 MHz RF path, 16 MB flash and 8 MB OPI PSRAM. It fixes the radio pins and reserves the shared peripheral, USB and flash/PSRAM pins; the display and encoder are not used. @@ -110,11 +110,11 @@ your board revision and any problems. This refers to the T-Embed CC1101, not the plain T-Embed without the radio. ```bash -pio run -e lilygo-t-embed-cc1101-plus -pio run -e lilygo-t-embed-cc1101-plus -t buildfs +pio run -e lilygo-t-embed-cc1101 +pio run -e lilygo-t-embed-cc1101 -t buildfs ``` -The images are in `.pio/build/lilygo-t-embed-cc1101-plus/`. This environment reuses +The images are in `.pio/build/lilygo-t-embed-cc1101/`. This environment reuses `default_8MB.csv`, matching the generic S3 release: two 3.1875 MiB firmware slots and a 1.5 MiB filesystem. The upper 8 MiB stays unallocated. A device with another partition layout needs USB provisioning with a fresh recovery backup and current rolling codes; firmware-only OTA cannot migrate diff --git a/platformio.ini b/platformio.ini index 385d47a..df35719 100644 --- a/platformio.ini +++ b/platformio.ini @@ -98,8 +98,8 @@ build_flags = ${dualcore.build_flags} -DCORE_DEBUG_LEVEL=2 -; Headless LILYGO T-Embed CC1101 Plus with its integrated 433 MHz radio. -[env:lilygo-t-embed-cc1101-plus] +; Headless LILYGO T-Embed CC1101 / Plus with its integrated 433 MHz radio. +[env:lilygo-t-embed-cc1101] extends = esp32 board = esp32-s3-devkitc1-n16r8 build_type = release @@ -114,7 +114,7 @@ build_flags = -DCORE_DEBUG_LEVEL=2 -DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT=1 - -DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS + -DESPSOMFY_LILYGO_T_EMBED_CC1101 [env:esp32c3] extends = esp32 diff --git a/src/BoardProfile.cpp b/src/BoardProfile.cpp index a920a6b..802e715 100644 --- a/src/BoardProfile.cpp +++ b/src/BoardProfile.cpp @@ -1,11 +1,11 @@ #include "BoardProfile.h" #include -#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS) +#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101) #include #endif namespace BoardProfile { -#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS) +#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101) static bool initialized = false; static void output(uint8_t pin, uint8_t level) { diff --git a/src/BoardProfile.h b/src/BoardProfile.h index cce53dc..0e547e6 100644 --- a/src/BoardProfile.h +++ b/src/BoardProfile.h @@ -2,16 +2,16 @@ #include namespace BoardProfile { -#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS) +#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101) #if !defined(CONFIG_IDF_TARGET_ESP32S3) -#error "The LILYGO T-Embed CC1101 Plus profile requires an ESP32-S3 target" +#error "The LILYGO T-Embed CC1101 / Plus profile requires an ESP32-S3 target" #endif constexpr bool integratedRadio = true; #else constexpr bool integratedRadio = false; #endif -// LILYGO T-Embed CC1101 wiring, hardware-tested on the Plus model. +// LILYGO T-Embed CC1101 wiring, hardware-tested on the Plus model; the standard model is expected to match. constexpr uint8_t power = 15; constexpr uint8_t sck = 11; constexpr uint8_t mosi = 9; diff --git a/tools/test-board-profile.sh b/tools/test-board-profile.sh index cbeb336..748eab0 100755 --- a/tools/test-board-profile.sh +++ b/tools/test-board-profile.sh @@ -6,7 +6,7 @@ trap 'rm -rf -- "$scratch"' EXIT compiler="${CXX:-c++}" common=(-std=c++11 -Wall -Wextra -Werror -Wno-unused-parameter -I"$repo/tests/board-profile" -I"$repo/src") sources=("$repo/tests/board-profile/board-profile-test.cpp" "$repo/src/BoardProfile.cpp") -"$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS -DCONFIG_IDF_TARGET_ESP32S3 \ +"$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101 -DCONFIG_IDF_TARGET_ESP32S3 \ "${sources[@]}" -o "$scratch/lilygo-test" "$scratch/lilygo-test" "$compiler" "${common[@]}" "${sources[@]}" -o "$scratch/generic-test" @@ -14,13 +14,13 @@ sources=("$repo/tests/board-profile/board-profile-test.cpp" "$repo/src/BoardProf for profile in generic lilygo; do flags=() if [[ "$profile" == lilygo ]]; then - flags=(-DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS -DCONFIG_IDF_TARGET_ESP32S3) + flags=(-DESPSOMFY_LILYGO_T_EMBED_CC1101 -DCONFIG_IDF_TARGET_ESP32S3) fi "$compiler" "${common[@]}" "${flags[@]}" \ "$repo/tests/board-profile/shade-gpio-test.cpp" "$repo/src/BoardProfile.cpp" -o "$scratch/shade-gpio-$profile" "$scratch/shade-gpio-$profile" done -if "$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS \ +if "$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101 \ "${sources[@]}" -o "$scratch/wrong-target" > "$scratch/wrong-target.log" 2>&1; then echo 'LILYGO profile incorrectly accepted a non-S3 target' >&2 exit 1 @@ -32,7 +32,7 @@ python3 "$repo/tests/board-profile/extract-radio-setup.py" "$repo/src/Transceive for profile in generic lilygo; do flags=() if [[ "$profile" == lilygo ]]; then - flags=(-DESPSOMFY_LILYGO_T_EMBED_CC1101_PLUS -DCONFIG_IDF_TARGET_ESP32S3) + flags=(-DESPSOMFY_LILYGO_T_EMBED_CC1101 -DCONFIG_IDF_TARGET_ESP32S3) fi "$compiler" "${common[@]}" -I"$scratch" -I"$repo/lib/SmartRC-CC1101-Driver-Lib" "${flags[@]}" \ "$repo/tests/board-profile/radio-setup-test.cpp" "$repo/src/BoardProfile.cpp" \ From 2b3d5567292d380741fffcece88d0cb502b5f936 Mon Sep 17 00:00:00 2001 From: "R. Sid Shaytay" <352722946+r-sidshaytay@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:41:27 -0800 Subject: [PATCH 08/10] Show the fixed radio pins as read-only in the web UI On the integrated-radio board the firmware replaces any radio pins a client saves with the board's wiring, yet the web UI let the user edit them and reported success. The radio settings now carry fixedPins (wire key fx), sent only where the radio is wired to the board. The web UI disables the six pin selects, shows "Radio wiring is fixed on this board." and skips the pin duplicate and boot-pin checks for them. Generic builds do not send the field, so their behaviour is unchanged, and applyBoardPins() stays as the safety net for old configs and imports. Co-Authored-By: Claude Sonnet 5.5 --- data-src/index.html | 1 + data-src/index.js | 19 +++++++----- data-src/js/views.js | 18 +++++++++-- docs/PROTOCOL.md | 4 +-- src/DeviceOps.cpp | 1 + src/ProtoSchema.h | 1 + src/ProtoSettings.cpp | 6 +++- src/ProtoSettings.h | 5 +++ test/fixtures/proto2/hello.json | 2 +- test/fixtures/proto2/schema.json | 7 ++++- test/fixtures/proto2/sync.json | 6 ++++ test/js/views.test.js | 31 +++++++++++++++++++ .../test_protosettings/test_protosettings.cpp | 23 ++++++++++++++ 13 files changed, 109 insertions(+), 15 deletions(-) diff --git a/data-src/index.html b/data-src/index.html index 6b3a4b5..0e8f13e 100644 --- a/data-src/index.html +++ b/data-src/index.html @@ -933,6 +933,7 @@ +
diff --git a/data-src/index.js b/data-src/index.js index f30f830a..636c659 100644 --- a/data-src/index.js +++ b/data-src/index.js @@ -1973,13 +1973,16 @@ class Somfy { let config = ProtoViews.radio(proto.schema, radio); ui.toElement(document.getElementById('divTransceiverSettings'), { transceiver: { config: config } }); document.getElementById('divRadioError').style.display = config.radioInit ? 'none' : ''; + this.radioPinsFixed = !!config.fixedPins; + ProtoViews.showRadioPins(document, this.radioPinsFixed); this.checkBootPins(); }); } // Warns of radio pins that can stop the board booting (issue #34). checkBootPins() { let trans = ui.fromElement(document.getElementById('divTransceiverSettings')).transceiver; - let warnings = BootPins.radioWarnings(chipModel(), trans.config); + // The board's wiring is not the user's to move, so there is nothing to warn of. + let warnings = this.radioPinsFixed ? [] : BootPins.radioWarnings(chipModel(), trans.config); let div = document.getElementById('divRadioBootPins'); div.innerText = warnings.join('\n'); div.style.display = warnings.length > 0 ? '' : 'none'; @@ -1993,7 +1996,7 @@ class Somfy { ui.errorMessage('You must select a radio type.'); valid = false; } - // Check to make sure no pins were duplicated and defined + // Check to make sure no pins were duplicated and defined. The board's own wiring is not checked. if (valid) { let fnValDup = (o, name) => { let val = o[name]; @@ -2022,12 +2025,12 @@ class Somfy { } return true; }; - if (valid) valid = fnValDup(trans.config, 'SCKPin'); - if (valid) valid = fnValDup(trans.config, 'CSNPin'); - if (valid) valid = fnValDup(trans.config, 'MOSIPin'); - if (valid) valid = fnValDup(trans.config, 'MISOPin'); - if (valid) valid = fnValDup(trans.config, 'TXPin'); - if (valid) valid = fnValDup(trans.config, 'RXPin'); + if (valid && !this.radioPinsFixed) valid = fnValDup(trans.config, 'SCKPin'); + if (valid && !this.radioPinsFixed) valid = fnValDup(trans.config, 'CSNPin'); + if (valid && !this.radioPinsFixed) valid = fnValDup(trans.config, 'MOSIPin'); + if (valid && !this.radioPinsFixed) valid = fnValDup(trans.config, 'MISOPin'); + if (valid && !this.radioPinsFixed) valid = fnValDup(trans.config, 'TXPin'); + if (valid && !this.radioPinsFixed) valid = fnValDup(trans.config, 'RXPin'); if (valid) { sendOp('saveSettings', ProtoViews.radioSave(trans.config), (err) => { if (err) ui.serviceError(err); diff --git a/data-src/js/views.js b/data-src/js/views.js index e1719b6..85b1b7e 100644 --- a/data-src/js/views.js +++ b/data-src/js/views.js @@ -51,10 +51,20 @@ class ProtoViews { static radioSave(config) { const fields = { section: 'radio', bitLength: config.type }; for (const name of ProtoViews.SETTINGS.radio) { - if (name !== 'bitLength' && name !== 'radioInit') fields[name] = config[name]; + if (name !== 'bitLength' && !ProtoViews.RADIO_SHOWN.includes(name)) fields[name] = config[name]; } return fields; } + // Where the radio is wired to the board (config.fixedPins) its six pins + // can't be changed: the pin selects are disabled and the note shown. + static showRadioPins(doc, fixed) { + for (const id of ProtoViews.RADIO_PIN_SELECTS) { + const el = doc.getElementById(id); + if (el) el.disabled = !!fixed; + } + const note = doc.getElementById(ProtoViews.RADIO_PINS_NOTE); + if (note) note.style.display = fixed ? '' : 'none'; + } // An op's refusal as the UI's error box shows it. A shade whose settings // don't add up carries the reason's number, which the errors table // describes. @@ -66,6 +76,10 @@ class ProtoViews { } ProtoViews.WIFI = ['ssid', 'hasPassphrase', 'roaming', 'hidden']; ProtoViews.ETHERNET = ['boardType', 'phyType', 'CLKMode', 'phyAddress', 'PWRPin', 'MDCPin', 'MDIOPin']; +// The radio fields the device only sends. +ProtoViews.RADIO_SHOWN = ['radioInit', 'fixedPins']; +ProtoViews.RADIO_PIN_SELECTS = ['selTransSCKPin', 'selTransCSNPin', 'selTransMOSIPin', 'selTransMISOPin', 'selTransTXPin', 'selTransRXPin']; +ProtoViews.RADIO_PINS_NOTE = 'divRadioPinsFixed'; ProtoViews.IP = ['dhcp', 'ip', 'gateway', 'subnet', 'dns1', 'dns2']; // The fields of each settings section, as getSettings sends them // (src/DeviceOps.cpp). @@ -75,6 +89,6 @@ ProtoViews.SETTINGS = { mqtt: ['enabled', 'pubDisco', 'protocol', 'hostname', 'port', 'username', 'hasPassword', 'rootTopic', 'discoTopic'], security: ['securityType', 'username', 'hasPassword', 'hasPin'], radio: ['bitLength', 'proto', 'enabled', 'TXPin', 'RXPin', 'SCKPin', 'MOSIPin', 'MISOPin', 'CSNPin', 'frequency', 'rxBandwidth', - 'deviation', 'txPower', 'noiseDetection', 'radioInit'] + 'deviation', 'txPower', 'noiseDetection', 'radioInit', 'fixedPins'] }; if (typeof module !== 'undefined' && module.exports) module.exports = { ProtoViews }; diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 0f27463..32b540c 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -139,7 +139,7 @@ The settings are in five sections. `getSettings` and `saveSettings` name one in | `security` | `securityType`, `username`, `password`, `pin` | `/getSecurity`, `/saveSecurity` | | `radio` | `bitLength`, `proto`, `enabled`, `TXPin`, `RXPin`, `SCKPin`, `MOSIPin`, `MISOPin`, `CSNPin`, `frequency`, `rxBandwidth`, `deviation`, `txPower`, `noiseDetection` | `/getRadio`, `/saveRadio` | -- **Reading.** `getSettings` replies with the section's fields. A secret is never sent: `hasPassphrase`, `hasPassword` and `hasPin` say whether one is set. `network` also has `hasEthernet`, and has the Ethernet fields only on a device with Ethernet. `radio` also has `radioInit`. +- **Reading.** `getSettings` replies with the section's fields. A secret is never sent: `hasPassphrase`, `hasPassword` and `hasPin` say whether one is set. `network` also has `hasEthernet`, and has the Ethernet fields only on a device with Ethernet. `radio` also has `radioInit`, and `fixedPins` where the radio is wired to the board (the LILYGO T-Embed CC1101), left out on every other build. `fixedPins` means the six pins in the section are the board's and a client should show them as read-only: a save of other pins is applied with the board's pins and still replies as saved. Older clients and Home Assistant ignore the field. - `connMode` is the connection the settings ask for: 1 WiFi, 2 Ethernet, 3 Ethernet with WiFi as the fallback. The header's `connType` is the connection in use. - **Saving.** `saveSettings` takes the section and the fields to change. As with every op, a field left out stays as it is. A secret sent empty keeps the stored one, except alongside a new `ssid` or MQTT `username`, as on the routes. - Every field is checked before anything is saved: @@ -148,7 +148,7 @@ The settings are in five sections. `getSettings` and `saveSettings` name one in - a string's length, which is what the setting holds: `hostname` 31, `pin` 4, and so on; - an address: four numbers 0–255, or `""` for none. - A bad request also comes for a field the section doesn't save (a `has*` field, `radioInit`, a field of another section, Ethernet on a device without it), and for a save with no fields. + A bad request also comes for a field the section doesn't save (a `has*` field, `radioInit`, `fixedPins`, a field of another section, Ethernet on a device without it), and for a save with no fields. - One save runs at a time, whichever client sent it: while one is waiting, another gets busy. - The reply comes once the settings are saved and applied, as their route applies them. A saved time zone takes effect at once, where the route waited for a reboot. - `rebooting` 1 means the device restarts a second later for them. That happens for a new `connMode`, for a new SSID or passphrase while on WiFi with nobody on the soft AP, and for Ethernet settings while on Ethernet. diff --git a/src/DeviceOps.cpp b/src/DeviceOps.cpp index d0a60b0..9b2a834 100644 --- a/src/DeviceOps.cpp +++ b/src/DeviceOps.cpp @@ -109,6 +109,7 @@ static void writeSettings(ProtoWriter &w, settings_section_t section) { w.add(proto_field_t::txPower, cfg.txPower); w.add(proto_field_t::noiseDetection, cfg.noiseDetection); w.add(proto_field_t::radioInit, cfg.radioInit); + writeRadioBoardFields(w, BoardProfile::integratedRadio); break; } } diff --git a/src/ProtoSchema.h b/src/ProtoSchema.h index 85ae094..20637dd 100644 --- a/src/ProtoSchema.h +++ b/src/ProtoSchema.h @@ -251,6 +251,7 @@ FIELD(txPower, "tp", 'i', 0) \ FIELD(noiseDetection, "nd", 'b', 0) \ FIELD(radioInit, "ri", 'b', 0) \ + FIELD(fixedPins, "fx", 'b', 0) \ /* wifiNetworks: each network has ssid, channel and strength as above */ \ FIELD(networks, "nw", 'l', 0) \ FIELD(macAddress, "ma", 's', 0) diff --git a/src/ProtoSettings.cpp b/src/ProtoSettings.cpp index 0cec9da..42435fc 100644 --- a/src/ProtoSettings.cpp +++ b/src/ProtoSettings.cpp @@ -25,7 +25,7 @@ static settings_section_t sectionOf(settings_part_t part) { // What a save may set. lo..hi is a whole number's range, a number's in // hundredths, and hi a string's longest length: what the setting holds, so the // route's fromJSON neither cuts it short nor wraps it. The has* fields and -// radioInit are only ever sent. +// radioInit and fixedPins are only ever sent. struct settings_field_t { settings_part_t part; proto_field_t field; @@ -97,6 +97,10 @@ static const settings_field_t *saved(settings_section_t section, proto_field_t f return nullptr; } +void writeRadioBoardFields(ProtoWriter &w, bool pinsFixed) { + w.add(proto_field_t::fixedPins, pinsFixed); +} + const char *parseSettingsSection(JsonObjectConst d, settings_section_t §ion) { const char *name = protoString(d, proto_field_t::section); if(!name) return "section is missing"; diff --git a/src/ProtoSettings.h b/src/ProtoSettings.h index 8b4aa71..a57e923 100644 --- a/src/ProtoSettings.h +++ b/src/ProtoSettings.h @@ -32,6 +32,11 @@ enum class settings_part_t : uint8_t { radio // transceiver_config_t }; const char *settingsSectionName(settings_section_t section); +// What the radio section says about the board rather than the config: +// fixedPins is set where the radio is wired to the board, so the six pins in +// the section are the board's and a save can't change them. Left out +// otherwise, so a client that doesn't know it never sees it. +void writeRadioBoardFields(ProtoWriter &w, bool pinsFixed); // The section that payload d names in section. nullptr when it is good; // otherwise what is wrong with it, for a bad request reply. const char *parseSettingsSection(JsonObjectConst d, settings_section_t §ion); diff --git a/test/fixtures/proto2/hello.json b/test/fixtures/proto2/hello.json index 9f18062..03f0de3 100644 --- a/test/fixtures/proto2/hello.json +++ b/test/fixtures/proto2/hello.json @@ -3,6 +3,6 @@ "t": 1, "d": { "fw": "v3.0.14", - "sh": "16fdffc7" + "sh": "422f9a6e" } } \ No newline at end of file diff --git a/test/fixtures/proto2/schema.json b/test/fixtures/proto2/schema.json index ce9a228..513c9d2 100644 --- a/test/fixtures/proto2/schema.json +++ b/test/fixtures/proto2/schema.json @@ -1,5 +1,5 @@ { - "hash": "16fdffc7", + "hash": "422f9a6e", "types": { "1": "hello", "2": "reply", @@ -294,6 +294,11 @@ "kind": "s", "default": 0 }, + "fx": { + "name": "fixedPins", + "kind": "b", + "default": 0 + }, "g": { "name": "groupId", "kind": "i", diff --git a/test/fixtures/proto2/sync.json b/test/fixtures/proto2/sync.json index 86fecdc..6147ff3 100644 --- a/test/fixtures/proto2/sync.json +++ b/test/fixtures/proto2/sync.json @@ -1148,6 +1148,12 @@ "b", 0 ], + [ + "fx", + "fixedPins", + "b", + 0 + ], [ "nw", "networks", diff --git a/test/js/views.test.js b/test/js/views.test.js index 30e1775..c30f4a1 100644 --- a/test/js/views.test.js +++ b/test/js/views.test.js @@ -71,9 +71,40 @@ test('the radio section as the panel binds it, and back', () => { assert.equal(save.frequency, 433.42); // Only shown, never saved. assert.equal('radioInit' in save, false); + assert.equal('fixedPins' in save, false); assert.equal('type' in save, false); }); +function fakeDocument() { + const els = {}; + for (const id of ProtoViews.RADIO_PIN_SELECTS) els[id] = { disabled: false }; + els[ProtoViews.RADIO_PINS_NOTE] = { style: { display: 'none' } }; + return { els, getElementById: (id) => els[id] || null }; +} + +test('the radio pins are fixed only where the device says so', () => { + assert.equal(ProtoViews.radio(schema, { bitLength: 80 }).fixedPins, false); + assert.equal(ProtoViews.radio(schema, { bitLength: 80, fixedPins: true }).fixedPins, true); + + const fixed = fakeDocument(); + ProtoViews.showRadioPins(fixed, ProtoViews.radio(schema, { fixedPins: true }).fixedPins); + assert.equal(ProtoViews.RADIO_PIN_SELECTS.length, 6); + for (const id of ProtoViews.RADIO_PIN_SELECTS) assert.equal(fixed.els[id].disabled, true, id); + assert.equal(fixed.els[ProtoViews.RADIO_PINS_NOTE].style.display, ''); + + // Without the flag they are editable, and a page that was fixed becomes editable again. + const free = fakeDocument(); + ProtoViews.showRadioPins(free, true); + ProtoViews.showRadioPins(free, ProtoViews.radio(schema, {}).fixedPins); + for (const id of ProtoViews.RADIO_PIN_SELECTS) assert.equal(free.els[id].disabled, false, id); + assert.equal(free.els[ProtoViews.RADIO_PINS_NOTE].style.display, 'none'); +}); + +test('every pin select and the note are in the page', () => { + const html = require('node:fs').readFileSync(require('node:path').join(__dirname, '../../data-src/index.html'), 'utf8'); + for (const id of ProtoViews.RADIO_PIN_SELECTS.concat(ProtoViews.RADIO_PINS_NOTE)) assert.ok(html.includes(`id="${id}"`), id); +}); + test('an op refusal for the error box, with a shade validation code', () => { assert.deepEqual(ProtoViews.opError('saveShade', { code: 'badRequest', desc: 'Pin in use', data: { validation: -10 } }), { htmlError: 'badRequest', service: 'saveShade', desc: 'Pin in use', code: -10 }); diff --git a/test/test_protosettings/test_protosettings.cpp b/test/test_protosettings/test_protosettings.cpp index 9e6acb3..668ce9b 100644 --- a/test/test_protosettings/test_protosettings.cpp +++ b/test/test_protosettings/test_protosettings.cpp @@ -2,6 +2,7 @@ #include #include #include "ProtoSettings.h" +#include "JsonFormatter.h" // Socket protocol 2's settings ops: the sections, and the settings route's // request that a save's payload becomes (docs/PROTOCOL.md). @@ -161,6 +162,7 @@ static void test_what_is_only_sent_is_refused() { TEST_ASSERT_EQUAL_STRING("hasPassphrase can't be saved in network", expand(R"({"se":"network","hq":1})")); TEST_ASSERT_EQUAL_STRING("hasEthernet can't be saved in network", expand(R"({"se":"network","he":1})")); TEST_ASSERT_EQUAL_STRING("radioInit can't be saved in radio", expand(R"({"se":"radio","ri":1})")); + TEST_ASSERT_EQUAL_STRING("fixedPins can't be saved in radio", expand(R"({"se":"radio","fx":1})")); } static void test_a_field_of_another_section_is_refused() { TEST_ASSERT_EQUAL_STRING("ssid can't be saved in general", expand(R"({"se":"general","sd":"home"})")); @@ -202,6 +204,26 @@ static void test_a_route_name_belongs_to_its_section() { TEST_ASSERT_EQUAL_UINT16(bit(settings_part_t::security), parts()); } +/********************************************************************* + * What the radio section says about the board + ********************************************************************/ +static std::string boardFields(bool pinsFixed) { + static BufferedJsonFormatter fmt; + static char buff[64]; + fmt.setBuffer(buff, sizeof(buff)); + ProtoWriter w(fmt); + fmt.beginObject(); + writeRadioBoardFields(w, pinsFixed); + fmt.endObject(); + return buff; +} +static void test_the_radio_pins_are_fixed_only_where_the_board_wires_them() { + TEST_ASSERT_EQUAL_STRING("{\"fx\":1}", boardFields(true).c_str()); + // A generic board leaves it out, which is false to a client that knows it. + TEST_ASSERT_EQUAL_STRING("{}", boardFields(false).c_str()); + TEST_ASSERT_EQUAL_STRING("fixedPins", protoFieldByKey("fx")->name); +} + int main(int argc, char **argv) { UNITY_BEGIN(); RUN_TEST(test_every_section_by_its_name); @@ -226,5 +248,6 @@ int main(int argc, char **argv) { RUN_TEST(test_ethernet_needs_a_chip_with_it); RUN_TEST(test_a_save_sets_the_parts_it_has_fields_of); RUN_TEST(test_a_route_name_belongs_to_its_section); + RUN_TEST(test_the_radio_pins_are_fixed_only_where_the_board_wires_them); return UNITY_END(); } From 28af01195a60e8b8d69b7791d5b6dcc25f48bf62 Mon Sep 17 00:00:00 2001 From: "R. Sid Shaytay" <352722946+r-sidshaytay@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:46:33 -0800 Subject: [PATCH 09/10] Move the board profile tests into the native Unity suite The board tests ran through tools/test-board-profile.sh with their own stubs, assert() and a script that copied nine method bodies out of Transceiver.cpp, so they were outside pio test -e native and the coverage report. Pure decisions now live in units the native env builds: BoardProfile::usesPin is constexpr, RadioReadiness decides register validity, the receive-state outcome (ready, retry or unavailable, with one try today) and whether a queued job may transmit, and ShadeGpioGuard decides whether a shade's outputs touch a board pad. Transceiver and ShadeGpio call them with identical behaviour. New Unity suites cover the generic and LILYGO profiles (reserved pads, startup order, radio bring-up) and the readiness unit; the old harness, its script, CI step and stubs are deleted. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/build.yaml | 3 - gcovr.cfg | 3 + platformio.ini | 2 +- src/BoardProfile.cpp | 9 - src/BoardProfile.h | 15 +- src/RadioReadiness.cpp | 21 ++ src/RadioReadiness.h | 46 ++++ src/ShadeGpio.cpp | 6 +- src/ShadeGpioGuard.h | 14 ++ src/Transceiver.cpp | 33 ++- test/stubs/Arduino.h | 56 ++++- test/stubs/SPI.h | 19 ++ test/stubs/driver/gpio.h | 8 + test/test_boardprofile/test_boardprofile.cpp | 47 ++++ .../test_boardprofile_plus.cpp | 221 ++++++++++++++++++ .../test_radioreadiness.cpp | 129 ++++++++++ tests/board-profile/Arduino.h | 26 --- tests/board-profile/ArduinoJson.h | 2 - tests/board-profile/Preferences.h | 8 - tests/board-profile/SPI.h | 11 - tests/board-profile/board-profile-test.cpp | 95 -------- tests/board-profile/driver/gpio.h | 4 - tests/board-profile/esp_log.h | 9 - tests/board-profile/extract-radio-setup.py | 29 --- tests/board-profile/radio-setup-test.cpp | 162 ------------- tests/board-profile/shade-gpio-test.cpp | 93 -------- tools/test-board-profile.sh | 41 ---- 27 files changed, 595 insertions(+), 517 deletions(-) create mode 100644 src/RadioReadiness.cpp create mode 100644 src/RadioReadiness.h create mode 100644 src/ShadeGpioGuard.h create mode 100644 test/stubs/SPI.h create mode 100644 test/stubs/driver/gpio.h create mode 100644 test/test_boardprofile/test_boardprofile.cpp create mode 100644 test/test_boardprofile_plus/test_boardprofile_plus.cpp create mode 100644 test/test_radioreadiness/test_radioreadiness.cpp delete mode 100644 tests/board-profile/Arduino.h delete mode 100644 tests/board-profile/ArduinoJson.h delete mode 100644 tests/board-profile/Preferences.h delete mode 100644 tests/board-profile/SPI.h delete mode 100644 tests/board-profile/board-profile-test.cpp delete mode 100644 tests/board-profile/driver/gpio.h delete mode 100644 tests/board-profile/esp_log.h delete mode 100644 tests/board-profile/extract-radio-setup.py delete mode 100644 tests/board-profile/radio-setup-test.cpp delete mode 100644 tests/board-profile/shade-gpio-test.cpp delete mode 100755 tools/test-board-profile.sh diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 827205e..470a42c 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -38,9 +38,6 @@ jobs: - name: Run native unit tests run: pio test -e coverage - - name: Test integrated board GPIO and radio readiness - run: bash tools/test-board-profile.sh - - name: Test the release scripts run: bash test/scripts/test_set_version.sh diff --git a/gcovr.cfg b/gcovr.cfg index 04fd331..acf69d3 100644 --- a/gcovr.cfg +++ b/gcovr.cfg @@ -7,3 +7,6 @@ sort = uncovered-percent print-summary = yes html-title = ESPSomfy-RTS native tests html-details = coverage/ +# BoardProfile.cpp is built once per board by the board profile tests, so the +# same function sits on different lines in each build. +merge-mode-functions = merge-use-line-min diff --git a/platformio.ini b/platformio.ini index df35719..de73424 100644 --- a/platformio.ini +++ b/platformio.ini @@ -173,7 +173,7 @@ build_flags = platform = native test_framework = unity test_build_src = yes -build_src_filter = -<*> + + + + + + + + + + + + + + + + + + + + + + + + + +build_src_filter = -<*> + + + + + + + + + + + + + + + + + + + + + + + + + + lib_deps = bblanchon/ArduinoJson@7.4.3 build_flags = diff --git a/src/BoardProfile.cpp b/src/BoardProfile.cpp index 802e715..1aad81d 100644 --- a/src/BoardProfile.cpp +++ b/src/BoardProfile.cpp @@ -54,17 +54,8 @@ bool prepareRadio(float frequency) { if(ready) SPI.begin(sck, miso, mosi, cs); return ready; } - -bool usesPin(uint8_t pin) { - // USB CDC and in-package flash/OPI PSRAM must never become relay outputs. - return pin == 19 || pin == 20 || (pin >= 26 && pin <= 37) || - pin == power || pin == sck || pin == mosi || pin == miso || - pin == cs || pin == tx || pin == rx || pin == sw1 || pin == sw0 || - pin == displayCS || pin == sdCS || pin == nrfCS || pin == nrfCE || pin == backlight; -} #else void begin() {} bool prepareRadio(float) { return true; } -bool usesPin(uint8_t) { return false; } #endif } diff --git a/src/BoardProfile.h b/src/BoardProfile.h index 0e547e6..877a4be 100644 --- a/src/BoardProfile.h +++ b/src/BoardProfile.h @@ -29,5 +29,18 @@ constexpr uint8_t backlight = 21; void begin(); bool prepareRadio(float frequency); -bool usesPin(uint8_t pin); + +// Whether the board's own hardware uses this pad. Pure, so it is unit tested +// on the PC (pio test -e native). +#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101) +constexpr bool usesPin(uint8_t pin) { + // USB CDC and in-package flash/OPI PSRAM must never become relay outputs. + return pin == 19 || pin == 20 || (pin >= 26 && pin <= 37) || + pin == power || pin == sck || pin == mosi || pin == miso || + pin == cs || pin == tx || pin == rx || pin == sw1 || pin == sw0 || + pin == displayCS || pin == sdCS || pin == nrfCS || pin == nrfCE || pin == backlight; +} +#else +constexpr bool usesPin(uint8_t) { return false; } +#endif } diff --git a/src/RadioReadiness.cpp b/src/RadioReadiness.cpp new file mode 100644 index 0000000..d2ac7ef --- /dev/null +++ b/src/RadioReadiness.cpp @@ -0,0 +1,21 @@ +#include "RadioReadiness.h" + +float radioFrequencyMHz(uint32_t freqWord) { + return freqWord * (26.0f / 65536.0f); +} + +bool radioRegistersReady(const radio_readings_t &r, float requestedMHz) { + const float actual = radioFrequencyMHz(r.freqWord); + return r.partnum == 0 && r.version != 0 && r.version != 0xFF && + r.iocfg0 == 0x0D && r.iocfg2 == 0x0D && (r.pktctrl0 & 0x30) == 0x30 && + (r.mdmcfg2 & 0x70) == 0x30 && actual > requestedMHz - 0.01f && actual < requestedMHz + 0.01f; +} + +rx_outcome_t radioRxOutcome(uint8_t marcstate, uint8_t attempt, uint8_t maxAttempts) { + if((marcstate & 0x1F) == RADIO_MARCSTATE_RX) return rx_outcome_t::ready; + return attempt + 1 < maxAttempts ? rx_outcome_t::retry : rx_outcome_t::unavailable; +} + +bool radioMayTransmit(bool integratedRadio, bool radioAvailable) { + return !integratedRadio || radioAvailable; +} diff --git a/src/RadioReadiness.h b/src/RadioReadiness.h new file mode 100644 index 0000000..9c2ff82 --- /dev/null +++ b/src/RadioReadiness.h @@ -0,0 +1,46 @@ +#ifndef RADIO_READINESS_H +#define RADIO_READINESS_H +#include + +// Whether the integrated CC1101 is fit to use, and whether a queued job may +// still go on air. Every register is read in Transceiver.cpp and passed in, +// so this is free of SPI and the RTOS and can be unit tested on the PC +// (pio test -e native). + +// What the radio reported after it was set up. +struct radio_readings_t { + uint8_t partnum = 0; // CC1101_PARTNUM, 0 for a CC1101 + uint8_t version = 0; // CC1101_VERSION, 0 and 0xFF mean no chip answered + uint8_t iocfg0 = 0; // GDO0, TX data + uint8_t iocfg2 = 0; // GDO2, RX data + uint8_t pktctrl0 = 0; + uint8_t mdmcfg2 = 0; + uint32_t freqWord = 0; // FREQ2:FREQ1:FREQ0 +}; + +// The carrier in MHz that FREQ2:FREQ1:FREQ0 selects with the 26 MHz crystal. +float radioFrequencyMHz(uint32_t freqWord); +// True when the registers say a CC1101 is wired up and configured for async +// OOK/ASK on the pins and frequency (MHz) we asked for. +bool radioRegistersReady(const radio_readings_t &r, float requestedMHz); + +// CC1101_MARCSTATE value while receiving. +#define RADIO_MARCSTATE_RX 0x0D +// Tries at entering receive before the radio is given up as unavailable. +#define RADIO_RX_ATTEMPTS 1 + +enum class rx_outcome_t : uint8_t { + ready, // the radio is receiving + retry, // not receiving yet, and another try is allowed + unavailable // not receiving and no tries are left +}; +// What to do after try number `attempt` (counting from 0) at entering receive +// left the radio in `marcstate`. Only the 5 state bits are looked at. A +// caller allowed N tries passes maxAttempts = N. +rx_outcome_t radioRxOutcome(uint8_t marcstate, uint8_t attempt, uint8_t maxAttempts); + +// Whether a job for the radio may be queued or sent. A generic radio is +// always allowed, as before; the integrated one only once it is ready. +bool radioMayTransmit(bool integratedRadio, bool radioAvailable); + +#endif diff --git a/src/ShadeGpio.cpp b/src/ShadeGpio.cpp index 7085f95..85e48f5 100644 --- a/src/ShadeGpio.cpp +++ b/src/ShadeGpio.cpp @@ -1,15 +1,13 @@ #include "esp_log.h" #include "Somfy.h" -#include "BoardProfile.h" +#include "ShadeGpioGuard.h" static const char *TAG = "Somfy"; // A backup may contain GPIO assignments from another board. Keep its shade // identity, but never drive a pad used by this board's integrated hardware. static bool usesBoardGPIOs(const SomfyShade &shade) { - if(shade.proto != radio_proto::GP_Relay && shade.proto != radio_proto::GP_Remote) return false; - return BoardProfile::usesPin(shade.gpioUp) || BoardProfile::usesPin(shade.gpioDown) || - (shade.proto == radio_proto::GP_Remote && BoardProfile::usesPin(shade.gpioMy)); + return shadeOutputsUseBoardPins(shade.proto, shade.gpioUp, shade.gpioDown, shade.gpioMy); } // Shared by saved/backup configuration loading and JSON updates. Refuse the diff --git a/src/ShadeGpioGuard.h b/src/ShadeGpioGuard.h new file mode 100644 index 0000000..b8b9a4e --- /dev/null +++ b/src/ShadeGpioGuard.h @@ -0,0 +1,14 @@ +#ifndef SHADE_GPIO_GUARD_H +#define SHADE_GPIO_GUARD_H +#include "BoardProfile.h" +#include "SomfyFrame.h" + +// A backup may carry GPIO assignments from another board. Whether a shade's +// outputs would drive a pad the board's own hardware uses. Header only so the +// native tests can build it for a given board; free of the shade model. +inline bool shadeOutputsUseBoardPins(radio_proto proto, uint8_t up, uint8_t down, uint8_t my) { + if(proto != radio_proto::GP_Relay && proto != radio_proto::GP_Remote) return false; + return BoardProfile::usesPin(up) || BoardProfile::usesPin(down) || + (proto == radio_proto::GP_Remote && BoardProfile::usesPin(my)); +} +#endif diff --git a/src/Transceiver.cpp b/src/Transceiver.cpp index e341e42..b3f04de 100644 --- a/src/Transceiver.cpp +++ b/src/Transceiver.cpp @@ -8,6 +8,7 @@ #include "driver/gpio.h" #include "esp_log.h" #include "Utils.h" +#include "RadioReadiness.h" #include "BootPins.h" #include "ConfigSettings.h" #include "Somfy.h" @@ -384,10 +385,10 @@ bool Transceiver::startReceive() { do { delay(1); state = ELECHOUSE_cc1101.SpiReadStatus(CC1101_MARCSTATE) & 0x1F; - } while(state != 0x0D && millis() - timing < 20); + } while(state != RADIO_MARCSTATE_RX && millis() - timing < 20); Serial.printf("CC1101 MARCSTATE=0x%02X (RX=0x0D); RF switch readback SW1=%d SW0=%d\n", state, digitalRead(BoardProfile::sw1), digitalRead(BoardProfile::sw0)); - if(state != 0x0D) { + if(radioRxOutcome(state, 0, RADIO_RX_ATTEMPTS) != rx_outcome_t::ready) { Serial.println("CC1101 failed to enter RX; radio unavailable"); ELECHOUSE_cc1101.setSidle(); this->config.radioInit = false; @@ -613,23 +614,21 @@ static void warnBootPin(const char *name, uint8_t pin) { } static bool checkBoardRadio(float frequency) { if(!BoardProfile::integratedRadio) return true; - uint8_t part = ELECHOUSE_cc1101.SpiReadStatus(CC1101_PARTNUM); - uint8_t version = ELECHOUSE_cc1101.SpiReadStatus(CC1101_VERSION); - uint8_t gdo0 = ELECHOUSE_cc1101.SpiReadReg(CC1101_IOCFG0); - uint8_t gdo2 = ELECHOUSE_cc1101.SpiReadReg(CC1101_IOCFG2); - uint8_t packet = ELECHOUSE_cc1101.SpiReadReg(CC1101_PKTCTRL0); - uint8_t modem = ELECHOUSE_cc1101.SpiReadReg(CC1101_MDMCFG2); - uint32_t word = (static_cast(ELECHOUSE_cc1101.SpiReadReg(CC1101_FREQ2)) << 16) | + radio_readings_t r; + r.partnum = ELECHOUSE_cc1101.SpiReadStatus(CC1101_PARTNUM); + r.version = ELECHOUSE_cc1101.SpiReadStatus(CC1101_VERSION); + r.iocfg0 = ELECHOUSE_cc1101.SpiReadReg(CC1101_IOCFG0); + r.iocfg2 = ELECHOUSE_cc1101.SpiReadReg(CC1101_IOCFG2); + r.pktctrl0 = ELECHOUSE_cc1101.SpiReadReg(CC1101_PKTCTRL0); + r.mdmcfg2 = ELECHOUSE_cc1101.SpiReadReg(CC1101_MDMCFG2); + r.freqWord = (static_cast(ELECHOUSE_cc1101.SpiReadReg(CC1101_FREQ2)) << 16) | (static_cast(ELECHOUSE_cc1101.SpiReadReg(CC1101_FREQ1)) << 8) | ELECHOUSE_cc1101.SpiReadReg(CC1101_FREQ0); - float actual = word * (26.0f / 65536.0f); Serial.printf("CC1101 PARTNUM=0x%02X VERSION=0x%02X IOCFG0=0x%02X IOCFG2=0x%02X PKTCTRL0=0x%02X MDMCFG2=0x%02X\n", - part, version, gdo0, gdo2, packet, modem); + r.partnum, r.version, r.iocfg0, r.iocfg2, r.pktctrl0, r.mdmcfg2); Serial.printf("CC1101 frequency requested=%.3f readback=%.3f MHz; GDO0 TX=%u GDO2 RX=%u\n", - frequency, actual, BoardProfile::tx, BoardProfile::rx); - return part == 0 && version != 0 && version != 0xFF && - gdo0 == 0x0D && gdo2 == 0x0D && (packet & 0x30) == 0x30 && - (modem & 0x70) == 0x30 && actual > frequency - 0.01f && actual < frequency + 0.01f; + frequency, radioFrequencyMHz(r.freqWord), BoardProfile::tx, BoardProfile::rx); + return radioRegistersReady(r, frequency); } void transceiver_config_t::apply() { @@ -829,7 +828,7 @@ uint32_t Transceiver::submitTx(somfy_tx_job_t &job, bool priority, uint16_t dela } // Read published readiness without waiting behind a transmission. A queued // job checks it again under the radio lock immediately before sending. - if(BoardProfile::integratedRadio && !this->available()) return 0; + if(!radioMayTransmit(BoardProfile::integratedRadio, this->available())) return 0; uint32_t ticket; { TxQueueLock lock; @@ -903,7 +902,7 @@ void Transceiver::runJob(somfy_tx_job_t &job) { start = this->sched.start(job.ticket, millis()); } if(!start) return; - const bool complete = (!BoardProfile::integratedRadio || this->available()) && this->transmitJob(job); + const bool complete = radioMayTransmit(BoardProfile::integratedRadio, this->available()) && this->transmitJob(job); TxQueueLock qlock; this->sched.ended(job.ticket, complete, millis()); } diff --git a/test/stubs/Arduino.h b/test/stubs/Arduino.h index f247c50..9607a85 100644 --- a/test/stubs/Arduino.h +++ b/test/stubs/Arduino.h @@ -10,12 +10,64 @@ #include #include #include +#include #include typedef uint8_t byte; -// Fixed so anything formatted from it is deterministic. -inline unsigned long millis() { return 0; } +// Starts at 0 and only moves when a test calls delay() or sets it, so anything +// formatted from it is deterministic. +inline unsigned long stubMillis = 0; +inline unsigned long millis() { return stubMillis; } +inline void delay(unsigned long ms) { stubMillis += ms; } + +// A fake GPIO bank for board code. Every pin call is also logged in order +// so tests can check the startup sequence, not only the final levels. +constexpr int LOW = 0; +constexpr int HIGH = 1; +constexpr int INPUT = 0x01; +constexpr int OUTPUT = 0x03; +struct StubGpioEvent { + enum Kind : char { Mode = 'M', Level = 'L', Write = 'W', SpiBegin = 'B', SpiEnd = 'E' }; + Kind kind; + uint8_t pin; + int value; +}; +inline std::vector stubGpioLog; +inline int stubPinLevel[64] = {}; +inline int stubPinMode[64] = {}; +inline int stubPinReadOverride[64] = {}; // -1 for none, set by stubGpioReset() +inline void stubGpioReset() { + stubGpioLog.clear(); + for(int i = 0; i < 64; i++) { stubPinLevel[i] = 0; stubPinMode[i] = 0; stubPinReadOverride[i] = -1; } + stubMillis = 0; +} +// The ESP-IDF call that sets the output latch whatever the pin mode is. +inline void stubSetLatch(uint8_t pin, int level) { + stubPinLevel[pin] = level; + stubGpioLog.push_back({StubGpioEvent::Level, pin, level}); +} +inline void pinMode(uint8_t pin, uint8_t mode) { + stubPinMode[pin] = mode; + stubGpioLog.push_back({StubGpioEvent::Mode, pin, mode}); +} +// Arduino 3 only accepts writes once pinMode has made the pin an output. +inline void digitalWrite(uint8_t pin, uint8_t level) { + if(stubPinMode[pin] != OUTPUT) return; + stubPinLevel[pin] = level; + stubGpioLog.push_back({StubGpioEvent::Write, pin, level}); +} +inline int digitalRead(uint8_t pin) { + return stubPinReadOverride[pin] >= 0 ? stubPinReadOverride[pin] : stubPinLevel[pin]; +} + +// Serial output is discarded. +struct StubSerial { + template void printf(const char *, Args...) {} + void println(const char *) {} +}; +inline StubSerial Serial; + // Tests that measure time set this. inline unsigned long stubMicros = 0; inline unsigned long micros() { return stubMicros; } diff --git a/test/stubs/SPI.h b/test/stubs/SPI.h new file mode 100644 index 0000000..ef813fe --- /dev/null +++ b/test/stubs/SPI.h @@ -0,0 +1,19 @@ +// Arduino SPI stand-in for the native test env: remembers whether the bus is +// up and logs begin/end in order with the pin calls (see Arduino.h). +#pragma once +#include +struct StubSPI { + bool active = false; + unsigned int begins = 0; + unsigned int ends = 0; + int8_t sck = -1, miso = -1, mosi = -1, cs = -1; + void begin(int8_t s, int8_t mi, int8_t mo, int8_t c) { + active = true; begins++; sck = s; miso = mi; mosi = mo; cs = c; + stubGpioLog.push_back({StubGpioEvent::SpiBegin, 0, 0}); + } + void end() { + active = false; ends++; + stubGpioLog.push_back({StubGpioEvent::SpiEnd, 0, 0}); + } +}; +inline StubSPI SPI; diff --git a/test/stubs/driver/gpio.h b/test/stubs/driver/gpio.h new file mode 100644 index 0000000..c4da958 --- /dev/null +++ b/test/stubs/driver/gpio.h @@ -0,0 +1,8 @@ +// ESP-IDF gpio_set_level stand-in for the native test env; see Arduino.h. +#pragma once +#include +using gpio_num_t = int; +inline int gpio_set_level(gpio_num_t pin, uint32_t level) { + stubSetLatch(static_cast(pin), static_cast(level)); + return 0; +} diff --git a/test/test_boardprofile/test_boardprofile.cpp b/test/test_boardprofile/test_boardprofile.cpp new file mode 100644 index 0000000..bf8c915 --- /dev/null +++ b/test/test_boardprofile/test_boardprofile.cpp @@ -0,0 +1,47 @@ +// A generic board: the profile reserves nothing and does nothing. +#include +#include "BoardProfile.cpp" +#include "ShadeGpioGuard.h" + +void setUp() { + stubGpioReset(); + SPI = StubSPI(); +} +void tearDown() {} + +static void test_there_is_no_integrated_radio() { + TEST_ASSERT_FALSE(BoardProfile::integratedRadio); +} +static void test_no_pad_is_reserved() { + for(unsigned pin = 0; pin < 256; pin++) TEST_ASSERT_FALSE(BoardProfile::usesPin((uint8_t)pin)); +} +static void test_begin_leaves_the_hardware_alone() { + BoardProfile::begin(); + TEST_ASSERT_EQUAL_UINT(0, stubGpioLog.size()); + TEST_ASSERT_FALSE(SPI.active); + TEST_ASSERT_EQUAL_UINT(0, SPI.begins); +} +static void test_any_frequency_is_accepted_without_touching_the_bus() { + TEST_ASSERT_TRUE(BoardProfile::prepareRadio(868.0f)); + TEST_ASSERT_TRUE(BoardProfile::prepareRadio(433.42f)); + TEST_ASSERT_EQUAL_UINT(0, stubGpioLog.size()); + TEST_ASSERT_EQUAL_UINT(0, SPI.begins); + TEST_ASSERT_EQUAL_UINT(0, SPI.ends); +} +static void test_shade_outputs_may_use_any_pad() { + for(unsigned pin = 0; pin < 256; pin++) { + const uint8_t p = (uint8_t)pin; + TEST_ASSERT_FALSE(shadeOutputsUseBoardPins(radio_proto::GP_Relay, p, p, p)); + TEST_ASSERT_FALSE(shadeOutputsUseBoardPins(radio_proto::GP_Remote, p, p, p)); + } +} + +int main(int, char **) { + UNITY_BEGIN(); + RUN_TEST(test_there_is_no_integrated_radio); + RUN_TEST(test_no_pad_is_reserved); + RUN_TEST(test_begin_leaves_the_hardware_alone); + RUN_TEST(test_any_frequency_is_accepted_without_touching_the_bus); + RUN_TEST(test_shade_outputs_may_use_any_pad); + return UNITY_END(); +} diff --git a/test/test_boardprofile_plus/test_boardprofile_plus.cpp b/test/test_boardprofile_plus/test_boardprofile_plus.cpp new file mode 100644 index 0000000..7c84caf --- /dev/null +++ b/test/test_boardprofile_plus/test_boardprofile_plus.cpp @@ -0,0 +1,221 @@ +// The LILYGO T-Embed CC1101 profile: which pads the board owns, the hardware +// startup order and the radio bring-up. BoardProfile.cpp is included so it +// is built for this board whatever the env's flags are. +#include +#include +#define ESPSOMFY_LILYGO_T_EMBED_CC1101 1 +#define CONFIG_IDF_TARGET_ESP32S3 1 +#include "BoardProfile.cpp" +#include "ShadeGpioGuard.h" + +using E = StubGpioEvent; +static const uint8_t RESERVED[] = {3, 9, 10, 11, 12, 13, 15, 21, 38, 41, 43, 44, 47, 48}; + +void setUp() { + // begin() runs once per boot, so what it set up stays between tests. + int modes[64]; + memcpy(modes, stubPinMode, sizeof(modes)); + stubGpioReset(); + memcpy(stubPinMode, modes, sizeof(modes)); + SPI = StubSPI(); +} +void tearDown() {} + +static unsigned countEvents(E::Kind kind, uint8_t pin, int value) { + unsigned n = 0; + for(const auto &e : stubGpioLog) if(e.kind == kind && e.pin == pin && e.value == value) n++; + return n; +} +static int firstEvent(E::Kind kind, uint8_t pin) { + for(size_t i = 0; i < stubGpioLog.size(); i++) + if(stubGpioLog[i].kind == kind && stubGpioLog[i].pin == pin) return (int)i; + return -1; +} + +// --- reserved pads --- + +static void test_profile_has_an_integrated_radio() { + TEST_ASSERT_TRUE(BoardProfile::integratedRadio); +} +static void test_the_wiring_is_the_lilygo_one() { + TEST_ASSERT_EQUAL(15, BoardProfile::power); + TEST_ASSERT_EQUAL(11, BoardProfile::sck); + TEST_ASSERT_EQUAL(9, BoardProfile::mosi); + TEST_ASSERT_EQUAL(10, BoardProfile::miso); + TEST_ASSERT_EQUAL(12, BoardProfile::cs); + TEST_ASSERT_EQUAL(3, BoardProfile::tx); + TEST_ASSERT_EQUAL(38, BoardProfile::rx); +} +static void test_every_board_pad_is_reserved() { + for(uint8_t pin : RESERVED) TEST_ASSERT_TRUE_MESSAGE(BoardProfile::usesPin(pin), "pad not reserved"); +} +static void test_usb_and_flash_pads_are_reserved() { + TEST_ASSERT_TRUE(BoardProfile::usesPin(19)); + TEST_ASSERT_TRUE(BoardProfile::usesPin(20)); + for(uint8_t pin = 26; pin <= 37; pin++) TEST_ASSERT_TRUE(BoardProfile::usesPin(pin)); +} +static void test_other_pads_are_free() { + TEST_ASSERT_FALSE(BoardProfile::usesPin(0)); + TEST_ASSERT_FALSE(BoardProfile::usesPin(16)); + TEST_ASSERT_FALSE(BoardProfile::usesPin(18)); + TEST_ASSERT_FALSE(BoardProfile::usesPin(25)); + TEST_ASSERT_FALSE(BoardProfile::usesPin(39)); + TEST_ASSERT_FALSE(BoardProfile::usesPin(46)); + TEST_ASSERT_FALSE(BoardProfile::usesPin(255)); +} + +// --- shade outputs on board pads (a backup may carry another board's pins) --- + +static void test_a_relay_output_on_any_board_pad_is_refused() { + for(uint8_t pin = 0; pin < 64; pin++) { + if(!BoardProfile::usesPin(pin)) continue; + TEST_ASSERT_TRUE(shadeOutputsUseBoardPins(radio_proto::GP_Relay, pin, 17, 18)); + TEST_ASSERT_TRUE(shadeOutputsUseBoardPins(radio_proto::GP_Relay, 16, pin, 18)); + TEST_ASSERT_TRUE(shadeOutputsUseBoardPins(radio_proto::GP_Remote, pin, 17, 18)); + TEST_ASSERT_TRUE(shadeOutputsUseBoardPins(radio_proto::GP_Remote, 16, pin, 18)); + TEST_ASSERT_TRUE(shadeOutputsUseBoardPins(radio_proto::GP_Remote, 16, 17, pin)); + } +} +static void test_a_relay_has_no_my_output() { + for(uint8_t pin = 0; pin < 64; pin++) + if(BoardProfile::usesPin(pin)) + TEST_ASSERT_FALSE(shadeOutputsUseBoardPins(radio_proto::GP_Relay, 16, 17, pin)); +} +static void test_free_pads_are_allowed() { + TEST_ASSERT_FALSE(shadeOutputsUseBoardPins(radio_proto::GP_Relay, 16, 17, 18)); + TEST_ASSERT_FALSE(shadeOutputsUseBoardPins(radio_proto::GP_Remote, 16, 17, 18)); +} +static void test_radio_shades_have_no_gpio_outputs() { + TEST_ASSERT_FALSE(shadeOutputsUseBoardPins(radio_proto::RTS, 3, 9, 10)); + TEST_ASSERT_FALSE(shadeOutputsUseBoardPins(radio_proto::RTW, 3, 9, 10)); + TEST_ASSERT_FALSE(shadeOutputsUseBoardPins(radio_proto::RTV, 3, 9, 10)); +} + +// --- startup order; this runs first as begin() only acts once --- + +static void test_begin_deselects_every_slave_before_the_power_rail() { + BoardProfile::begin(); + const int power = firstEvent(E::Level, BoardProfile::power); + TEST_ASSERT_TRUE(power >= 0); + TEST_ASSERT_EQUAL_UINT(1, countEvents(E::Level, BoardProfile::power, HIGH)); + // Nothing happens after the rail comes up except settling. + TEST_ASSERT_EQUAL((int)stubGpioLog.size() - 2, power); // then its own pinMode + TEST_ASSERT_EQUAL(E::Mode, stubGpioLog.back().kind); + TEST_ASSERT_EQUAL(BoardProfile::power, stubGpioLog.back().pin); + const uint8_t high[] = {BoardProfile::cs, BoardProfile::sdCS, BoardProfile::displayCS, + BoardProfile::nrfCS, BoardProfile::sw1, BoardProfile::sw0}; + const uint8_t low[] = {BoardProfile::nrfCE, BoardProfile::backlight}; + for(uint8_t pin : high) { + TEST_ASSERT_TRUE(firstEvent(E::Level, pin) < power); + TEST_ASSERT_EQUAL_UINT(1, countEvents(E::Level, pin, HIGH)); + TEST_ASSERT_EQUAL(OUTPUT, stubPinMode[pin]); + } + for(uint8_t pin : low) { + TEST_ASSERT_TRUE(firstEvent(E::Level, pin) < power); + TEST_ASSERT_EQUAL_UINT(1, countEvents(E::Level, pin, LOW)); + TEST_ASSERT_EQUAL(OUTPUT, stubPinMode[pin]); + } + TEST_ASSERT_EQUAL(OUTPUT, stubPinMode[BoardProfile::power]); + TEST_ASSERT_EQUAL(10, (int)stubMillis); // rail settling + // Each pin's safe level is latched before it is made an output. + for(const auto &e : stubGpioLog) { + if(e.kind != E::Mode) continue; + TEST_ASSERT_EQUAL(OUTPUT, e.value); + int latch = -1, mode = -1; + for(size_t i = 0; i < stubGpioLog.size(); i++) { + if(stubGpioLog[i].pin != e.pin) continue; + if(stubGpioLog[i].kind == E::Level && latch < 0) latch = (int)i; + if(stubGpioLog[i].kind == E::Mode && mode < 0) mode = (int)i; + } + TEST_ASSERT_TRUE_MESSAGE(latch >= 0 && latch < mode, "pin became an output before its level was latched"); + } + // The shared SPI pads are left alone until the radio is prepared. + for(uint8_t pin : {BoardProfile::sck, BoardProfile::mosi, BoardProfile::miso}) + TEST_ASSERT_EQUAL(-1, firstEvent(E::Mode, pin)); + TEST_ASSERT_FALSE(SPI.active); +} +static void test_a_second_begin_does_nothing() { + // begin() ran in the previous test; starting again changes nothing. + stubGpioLog.clear(); + BoardProfile::begin(); + TEST_ASSERT_EQUAL_UINT(0, stubGpioLog.size()); +} + +// --- radio bring-up --- + +static void test_prepare_releases_spi_before_it_probes_the_pads() { + TEST_ASSERT_TRUE(BoardProfile::prepareRadio(433.42f)); + const int end = firstEvent(E::SpiEnd, 0); + TEST_ASSERT_TRUE(end >= 0); + for(uint8_t pin : {BoardProfile::sck, BoardProfile::mosi, BoardProfile::miso}) + TEST_ASSERT_TRUE(firstEvent(E::Mode, pin) > end); + TEST_ASSERT_EQUAL(INPUT, stubPinMode[BoardProfile::miso]); + TEST_ASSERT_EQUAL(OUTPUT, stubPinMode[BoardProfile::mosi]); + TEST_ASSERT_EQUAL(OUTPUT, stubPinMode[BoardProfile::sck]); + TEST_ASSERT_EQUAL(HIGH, stubPinLevel[BoardProfile::cs]); // released after the probe + TEST_ASSERT_TRUE(SPI.active); + TEST_ASSERT_EQUAL_UINT(1, SPI.begins); + TEST_ASSERT_EQUAL(11, SPI.sck); + TEST_ASSERT_EQUAL(10, SPI.miso); + TEST_ASSERT_EQUAL(9, SPI.mosi); + TEST_ASSERT_EQUAL(12, SPI.cs); +} +static void test_prepare_can_run_again_on_a_running_bus() { + TEST_ASSERT_TRUE(BoardProfile::prepareRadio(433.42f)); + TEST_ASSERT_TRUE(BoardProfile::prepareRadio(433.42f)); + TEST_ASSERT_EQUAL_UINT(2, SPI.begins); + TEST_ASSERT_EQUAL_UINT(2, SPI.ends); + TEST_ASSERT_TRUE(SPI.active); +} +static void test_prepare_refuses_a_frequency_outside_the_433_band() { + TEST_ASSERT_FALSE(BoardProfile::prepareRadio(868.0f)); + TEST_ASSERT_FALSE(BoardProfile::prepareRadio(386.9f)); + TEST_ASSERT_FALSE(BoardProfile::prepareRadio(464.1f)); + TEST_ASSERT_FALSE(BoardProfile::prepareRadio(0.0f)); + TEST_ASSERT_FALSE(BoardProfile::prepareRadio(NAN)); + TEST_ASSERT_TRUE(BoardProfile::prepareRadio(387.0f)); + TEST_ASSERT_TRUE(BoardProfile::prepareRadio(464.0f)); +} +static void test_a_rejected_frequency_leaves_the_bus_alone() { + BoardProfile::prepareRadio(868.0f); + TEST_ASSERT_EQUAL_UINT(0, stubGpioLog.size()); + TEST_ASSERT_EQUAL_UINT(0, SPI.begins); +} +static void test_prepare_fails_fast_when_the_radio_holds_miso_high() { + stubPinReadOverride[BoardProfile::miso] = HIGH; + TEST_ASSERT_FALSE(BoardProfile::prepareRadio(433.42f)); + TEST_ASSERT_TRUE(stubMillis <= 25); // not a hang inside the radio driver + TEST_ASSERT_EQUAL(HIGH, stubPinLevel[BoardProfile::cs]); + TEST_ASSERT_FALSE(SPI.active); + TEST_ASSERT_EQUAL_UINT(0, SPI.begins); +} +static void test_a_retry_after_a_fault_does_not_power_cycle_the_board() { + stubPinReadOverride[BoardProfile::miso] = HIGH; + TEST_ASSERT_FALSE(BoardProfile::prepareRadio(433.42f)); + stubPinReadOverride[BoardProfile::miso] = -1; + TEST_ASSERT_TRUE(BoardProfile::prepareRadio(433.42f)); + TEST_ASSERT_EQUAL_UINT(0, countEvents(E::Level, BoardProfile::power, HIGH)); + TEST_ASSERT_EQUAL_UINT(0, countEvents(E::Level, BoardProfile::power, LOW)); +} + +int main(int, char **) { + UNITY_BEGIN(); + RUN_TEST(test_begin_deselects_every_slave_before_the_power_rail); + RUN_TEST(test_a_second_begin_does_nothing); + RUN_TEST(test_profile_has_an_integrated_radio); + RUN_TEST(test_the_wiring_is_the_lilygo_one); + RUN_TEST(test_every_board_pad_is_reserved); + RUN_TEST(test_usb_and_flash_pads_are_reserved); + RUN_TEST(test_other_pads_are_free); + RUN_TEST(test_a_relay_output_on_any_board_pad_is_refused); + RUN_TEST(test_a_relay_has_no_my_output); + RUN_TEST(test_free_pads_are_allowed); + RUN_TEST(test_radio_shades_have_no_gpio_outputs); + RUN_TEST(test_prepare_releases_spi_before_it_probes_the_pads); + RUN_TEST(test_prepare_can_run_again_on_a_running_bus); + RUN_TEST(test_prepare_refuses_a_frequency_outside_the_433_band); + RUN_TEST(test_a_rejected_frequency_leaves_the_bus_alone); + RUN_TEST(test_prepare_fails_fast_when_the_radio_holds_miso_high); + RUN_TEST(test_a_retry_after_a_fault_does_not_power_cycle_the_board); + return UNITY_END(); +} diff --git a/test/test_radioreadiness/test_radioreadiness.cpp b/test/test_radioreadiness/test_radioreadiness.cpp new file mode 100644 index 0000000..0c44edb --- /dev/null +++ b/test/test_radioreadiness/test_radioreadiness.cpp @@ -0,0 +1,129 @@ +#include +#include +#include "RadioReadiness.h" + +void setUp() {} +void tearDown() {} + +// What a healthy CC1101 reports when set up for 433.42 MHz async OOK. +static radio_readings_t healthy() { + radio_readings_t r; + r.partnum = 0; + r.version = 0x14; + r.iocfg0 = 0x0D; + r.iocfg2 = 0x0D; + r.pktctrl0 = 0x32; + r.mdmcfg2 = 0x3C; + r.freqWord = 0x10AB85; + return r; +} +static const float MHZ = 433.42f; + +static void test_frequency_word_converts_to_mhz() { + TEST_ASSERT_FLOAT_WITHIN(0.01f, 433.42f, radioFrequencyMHz(0x10AB85)); + TEST_ASSERT_EQUAL_FLOAT(0.0f, radioFrequencyMHz(0)); +} +static void test_a_healthy_radio_is_ready() { + TEST_ASSERT_TRUE(radioRegistersReady(healthy(), MHZ)); +} +static void test_a_part_that_is_not_a_cc1101_is_refused() { + radio_readings_t r = healthy(); + r.partnum = 1; + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); + r.partnum = 0xFF; + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); +} +static void test_no_chip_answering_is_refused() { + radio_readings_t r = healthy(); + r.version = 0; + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); + r.version = 0xFF; + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); +} +static void test_gdo_pins_must_carry_the_async_data() { + radio_readings_t r = healthy(); + r.iocfg0 = 0; + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); + r = healthy(); + r.iocfg2 = 0; + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); +} +static void test_packet_format_and_modulation_must_be_set() { + radio_readings_t r = healthy(); + r.pktctrl0 = 0; + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); + r = healthy(); + r.pktctrl0 = 0x10; // only part of the async format bits + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); + r = healthy(); + r.mdmcfg2 = 0; + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); + r = healthy(); + r.mdmcfg2 = 0x0C; // 2-FSK instead of OOK + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); +} +static void test_unrelated_register_bits_are_ignored() { + radio_readings_t r = healthy(); + r.pktctrl0 = 0x3F; + r.mdmcfg2 = 0xBF; + TEST_ASSERT_TRUE(radioRegistersReady(r, MHZ)); +} +static void test_the_frequency_readback_must_match_the_request() { + radio_readings_t r = healthy(); + r.freqWord = 0; + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); + r.freqWord = 0x10AB85 + 100; // 0.04 MHz away + TEST_ASSERT_FALSE(radioRegistersReady(r, MHZ)); + TEST_ASSERT_FALSE(radioRegistersReady(healthy(), 433.92f)); + TEST_ASSERT_FALSE(radioRegistersReady(healthy(), NAN)); +} + +static void test_rx_state_ready() { + TEST_ASSERT_EQUAL(rx_outcome_t::ready, radioRxOutcome(RADIO_MARCSTATE_RX, 0, 1)); + TEST_ASSERT_EQUAL(rx_outcome_t::ready, radioRxOutcome(0xED, 0, 1)); // upper bits are not state +} +static void test_a_radio_not_in_rx_is_unavailable_with_one_try() { + TEST_ASSERT_EQUAL(rx_outcome_t::unavailable, radioRxOutcome(0x00, 0, 1)); + TEST_ASSERT_EQUAL(rx_outcome_t::unavailable, radioRxOutcome(0x01, 0, 1)); // IDLE + TEST_ASSERT_EQUAL(rx_outcome_t::unavailable, radioRxOutcome(0x11, 0, 1)); // RXFIFO_OVERFLOW +} +static void test_a_radio_not_in_rx_may_retry_while_tries_are_left() { + TEST_ASSERT_EQUAL(rx_outcome_t::retry, radioRxOutcome(0x01, 0, 2)); + TEST_ASSERT_EQUAL(rx_outcome_t::unavailable, radioRxOutcome(0x01, 1, 2)); + TEST_ASSERT_EQUAL(rx_outcome_t::ready, radioRxOutcome(RADIO_MARCSTATE_RX, 1, 2)); +} +static void test_zero_tries_never_retry() { + TEST_ASSERT_EQUAL(rx_outcome_t::unavailable, radioRxOutcome(0x01, 0, 0)); +} +static void test_the_firmware_makes_one_try_for_now() { + TEST_ASSERT_EQUAL(1, RADIO_RX_ATTEMPTS); +} + +static void test_a_generic_radio_may_always_queue_and_send() { + TEST_ASSERT_TRUE(radioMayTransmit(false, false)); + TEST_ASSERT_TRUE(radioMayTransmit(false, true)); +} +static void test_the_integrated_radio_transmits_only_when_ready() { + TEST_ASSERT_TRUE(radioMayTransmit(true, true)); + TEST_ASSERT_FALSE(radioMayTransmit(true, false)); +} + +int main(int, char **) { + UNITY_BEGIN(); + RUN_TEST(test_frequency_word_converts_to_mhz); + RUN_TEST(test_a_healthy_radio_is_ready); + RUN_TEST(test_a_part_that_is_not_a_cc1101_is_refused); + RUN_TEST(test_no_chip_answering_is_refused); + RUN_TEST(test_gdo_pins_must_carry_the_async_data); + RUN_TEST(test_packet_format_and_modulation_must_be_set); + RUN_TEST(test_unrelated_register_bits_are_ignored); + RUN_TEST(test_the_frequency_readback_must_match_the_request); + RUN_TEST(test_rx_state_ready); + RUN_TEST(test_a_radio_not_in_rx_is_unavailable_with_one_try); + RUN_TEST(test_a_radio_not_in_rx_may_retry_while_tries_are_left); + RUN_TEST(test_zero_tries_never_retry); + RUN_TEST(test_the_firmware_makes_one_try_for_now); + RUN_TEST(test_a_generic_radio_may_always_queue_and_send); + RUN_TEST(test_the_integrated_radio_transmits_only_when_ready); + return UNITY_END(); +} diff --git a/tests/board-profile/Arduino.h b/tests/board-profile/Arduino.h deleted file mode 100644 index b7a69a0..0000000 --- a/tests/board-profile/Arduino.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -#include -#include -using byte = uint8_t; -class String; - -constexpr int LOW = 0; -constexpr int HIGH = 1; -constexpr int INPUT = 0x01; -constexpr int OUTPUT = 0x03; -void pinMode(uint8_t pin, uint8_t mode); -void digitalWrite(uint8_t pin, uint8_t value); -int digitalRead(uint8_t pin); -unsigned long millis(); -void delay(unsigned long duration); - -struct TestSerial { - template void printf(const char *, Args...) {} - void println(const char *) {} -}; -extern TestSerial Serial; -struct TestESP { - unsigned int getFlashChipSize() { return 16777216; } - unsigned int getPsramSize() { return 8388608; } -}; -extern TestESP ESP; diff --git a/tests/board-profile/ArduinoJson.h b/tests/board-profile/ArduinoJson.h deleted file mode 100644 index 4d66643..0000000 --- a/tests/board-profile/ArduinoJson.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -class JsonObject; diff --git a/tests/board-profile/Preferences.h b/tests/board-profile/Preferences.h deleted file mode 100644 index daac39a..0000000 --- a/tests/board-profile/Preferences.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once -extern bool testRadioInit; -struct Preferences { - void begin(const char *) {} - bool getBool(const char *, bool) { return testRadioInit; } - void putBool(const char *, bool value) { testRadioInit = value; } - void end() {} -}; diff --git a/tests/board-profile/SPI.h b/tests/board-profile/SPI.h deleted file mode 100644 index 2bc0ca5..0000000 --- a/tests/board-profile/SPI.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#include - -struct TestSPI { - bool active = false; - unsigned int starts = 0; - unsigned int stops = 0; - void begin(int8_t sck, int8_t miso, int8_t mosi, int8_t cs); - void end(); -}; -extern TestSPI SPI; diff --git a/tests/board-profile/board-profile-test.cpp b/tests/board-profile/board-profile-test.cpp deleted file mode 100644 index 13f99c8..0000000 --- a/tests/board-profile/board-profile-test.cpp +++ /dev/null @@ -1,95 +0,0 @@ -#include -#include -#include "BoardProfile.h" -#include "SPI.h" -#include - -TestSerial Serial; -TestESP ESP; -TestSPI SPI; -void TestSPI::begin(int8_t sck, int8_t miso, int8_t mosi, int8_t cs) { - assert(sck == 11 && miso == 10 && mosi == 9 && cs == 12); - assert(!active); - active = true; - starts++; -} -void TestSPI::end() { active = false; stops++; } -static int levels[49] = {}; -static int modes[49] = {}; -static unsigned long clockMs = 0; -static bool stuckMiso = false; -static unsigned int powerTransitions = 0; - -void pinMode(uint8_t pin, uint8_t mode) { - // Arduino 3 must release SPI ownership before preflight changes its pins. - if(pin == 9 || pin == 10 || pin == 11) assert(!SPI.active); - if(mode == OUTPUT) { - // Initial output enable must already have the safe level latched. - const bool high = pin == 12 || pin == 13 || pin == 15 || pin == 41 || - pin == 44 || pin == 47 || pin == 48; - assert(levels[pin] == (high ? HIGH : LOW)); - } - modes[pin] = mode; -} -int gpio_set_level(gpio_num_t pin, uint32_t value) { - if(pin == 15 && value == HIGH) { - // No other SPI device may drive MISO when the rail comes up. - assert(levels[12] == HIGH && levels[13] == HIGH); - assert(levels[41] == HIGH && levels[44] == HIGH); - assert(levels[43] == LOW && levels[21] == LOW); - assert(levels[47] == HIGH && levels[48] == HIGH); - const uint8_t controls[] = {12, 13, 21, 41, 43, 44, 47, 48}; - for(auto control : controls) assert(modes[control] == OUTPUT); - powerTransitions++; - } - levels[pin] = value; - return 0; -} -void digitalWrite(uint8_t pin, uint8_t value) { - // Arduino 3 only accepts writes after pinMode establishes GPIO ownership. - if(modes[pin] == OUTPUT) gpio_set_level(pin, value); -} -int digitalRead(uint8_t pin) { - if(pin == 10) return stuckMiso ? HIGH : LOW; - return levels[pin]; -} -unsigned long millis() { return clockMs; } -void delay(unsigned long duration) { clockMs += duration; } - -int main() { - BoardProfile::begin(); - if(BoardProfile::integratedRadio) { - assert(powerTransitions == 1); - assert(modes[15] == OUTPUT); - assert(BoardProfile::prepareRadio(433.42f)); - assert(SPI.active && SPI.starts == 1); - assert(modes[10] == INPUT && modes[9] == OUTPUT && modes[11] == OUTPUT); - assert(levels[12] == HIGH); // Release CS after readiness probe. - assert(BoardProfile::prepareRadio(433.42f)); // Reconfigure a running bus safely. - assert(SPI.active && SPI.starts == 2 && SPI.stops == 2); - assert(!BoardProfile::prepareRadio(868.0f)); - assert(!BoardProfile::prepareRadio(0.0f / 0.0f)); - stuckMiso = true; - auto started = millis(); - assert(!BoardProfile::prepareRadio(433.42f)); - assert(millis() - started <= 25); // Fail safely instead of hanging in SmartRC. - assert(levels[12] == HIGH); - assert(!SPI.active); // A failed preflight must not initialize SPI. - stuckMiso = false; - assert(BoardProfile::prepareRadio(433.42f)); - assert(powerTransitions == 1); // Retrying must not power-cycle shared devices. - const uint8_t reserved[] = {3, 9, 10, 11, 12, 13, 15, 21, 38, 41, 43, 44, 47, 48}; - for(auto pin : reserved) assert(BoardProfile::usesPin(pin)); - assert(BoardProfile::usesPin(19) && BoardProfile::usesPin(20)); - for(uint8_t pin = 26; pin <= 37; pin++) assert(BoardProfile::usesPin(pin)); - assert(!BoardProfile::usesPin(255)); - assert(!BoardProfile::usesPin(16)); - } - else { - assert(powerTransitions == 0); - assert(!SPI.active && SPI.starts == 0 && SPI.stops == 0); - assert(BoardProfile::prepareRadio(868.0f)); - for(uint8_t pin = 0; pin < 49; pin++) assert(!BoardProfile::usesPin(pin)); - } - puts("Board profile checks passed"); -} diff --git a/tests/board-profile/driver/gpio.h b/tests/board-profile/driver/gpio.h deleted file mode 100644 index 94b03e7..0000000 --- a/tests/board-profile/driver/gpio.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once -#include -using gpio_num_t = int; -int gpio_set_level(gpio_num_t pin, uint32_t value); diff --git a/tests/board-profile/esp_log.h b/tests/board-profile/esp_log.h deleted file mode 100644 index 5ddc030..0000000 --- a/tests/board-profile/esp_log.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once -// Keep the test logger a function call so unused firmware format arguments are -// still type-checked and the production TAG is referenced. -template inline void testLog(const char *, const char *, Args...) {} -#define ESP_LOGD(...) testLog(__VA_ARGS__) - -#define ESP_LOGE(...) testLog(__VA_ARGS__) -#define ESP_LOGW(...) testLog(__VA_ARGS__) -#define ESP_LOGI(...) testLog(__VA_ARGS__) diff --git a/tests/board-profile/extract-radio-setup.py b/tests/board-profile/extract-radio-setup.py deleted file mode 100644 index 845abed..0000000 --- a/tests/board-profile/extract-radio-setup.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Compile selected production methods without the unrelated RTOS/network code.""" -from pathlib import Path -import sys - -source = Path(sys.argv[1]).read_text() -names = [ - 'static bool checkBoardRadio(', - 'void transceiver_config_t::applyBoardPins(', - 'void transceiver_config_t::apply(', - 'void Transceiver::setConfig(', - 'bool Transceiver::usesPin(', - 'void Transceiver::enableReceive(', - 'bool Transceiver::startReceive(', - 'void Transceiver::disableReceive(', - 'uint32_t Transceiver::submitTx(', -] -methods = [] -for name in names: - assert source.count(name) == 1, f'Production setup method changed: {name}' - start = source.index(name) - brace = source.index('{', start) - depth = 1 - end = brace + 1 - while depth: - assert end < len(source), f'Unterminated method: {name}' - depth += (source[end] == '{') - (source[end] == '}') - end += 1 - methods.append(source[start:end]) -Path(sys.argv[2]).write_text('\n\n'.join(methods) + '\n') diff --git a/tests/board-profile/radio-setup-test.cpp b/tests/board-profile/radio-setup-test.cpp deleted file mode 100644 index c8fbd72..0000000 --- a/tests/board-profile/radio-setup-test.cpp +++ /dev/null @@ -1,162 +0,0 @@ -// Exercise the actual radio setup, RX and queue-admission methods, replacing -// only hardware/RTOS boundaries. The script extracts those definitions from -// Transceiver.cpp so the test cannot silently exercise a copy of the logic. -#include -#include -#include -#include -#include "Transceiver.h" -#include "SPI.h" -#include "esp_log.h" -#include -#include - -TestSerial Serial; -TestESP ESP; -TestSPI SPI; -void TestSPI::begin(int8_t, int8_t, int8_t, int8_t) { active = true; } -void TestSPI::end() { active = false; } -static int levels[49] = {}; -static bool stuckMiso; -static unsigned long clockMs; -void pinMode(uint8_t, uint8_t) {} -void digitalWrite(uint8_t pin, uint8_t value) { levels[pin] = value; } -int digitalRead(uint8_t pin) { return pin == 10 && stuckMiso ? HIGH : levels[pin]; } -int gpio_set_level(gpio_num_t pin, uint32_t value) { levels[pin] = value; return 0; } -unsigned long millis() { return clockMs; } -void delay(unsigned long ms) { clockMs += ms; } -static unsigned int attached; -static unsigned int rxStarts; -static unsigned int initializations; -static unsigned int saves; -static bool observedReadyDuringRx; -static uint32_t queuedDuringRx; -int digitalPinToInterrupt(uint8_t pin) { return pin; } -constexpr int CHANGE = 1; -void attachInterrupt(int, void (*)(), int) { attached++; } -void detachInterrupt(int) { attached = 0; } -static const char *TAG = "Somfy"; -static uint8_t rxmode; -static int interruptPin; -uint8_t radioBitLength; -bool testRadioInit = true; -struct { Transceiver transceiver; } somfy; -struct RadioLock { RadioLock(int = 0, bool = false) {} }; -struct TxQueueLock { ~TxQueueLock() {} }; -constexpr int portMAX_DELAY = 0; -static bool scanEmitPending; -static void *txTaskHandle = reinterpret_cast(1); -void xTaskNotifyGive(void *) {} -void Transceiver::handleReceive() {} -void Transceiver::resumeTx(uint8_t) {} -static void warnBootPin(const char *, uint8_t) {} -void transceiver_config_t::save() { - saves++; - if(BoardProfile::integratedRadio) - assert(SCKPin == 11 && MISOPin == 10 && MOSIPin == 9 && CSNPin == 12 && TXPin == 3 && RXPin == 38); -} - -ELECHOUSE_CC1101 ELECHOUSE_cc1101; -static bool detected; -static uint8_t part, version, gdo0, gdo2, packet, modem, rxState; -static uint32_t frequencyWord; -void ELECHOUSE_CC1101::Init() { initializations++; } -bool ELECHOUSE_CC1101::getCC1101() { return detected; } -byte ELECHOUSE_CC1101::SpiReadStatus(byte addr) { - if(addr == CC1101_PARTNUM) return part; - if(addr == CC1101_VERSION) return version; - if(addr == CC1101_MARCSTATE) return rxState; - assert(false); return 0; -} -byte ELECHOUSE_CC1101::SpiReadReg(byte addr) { - if(addr == CC1101_IOCFG0) return gdo0; - if(addr == CC1101_IOCFG2) return gdo2; - if(addr == CC1101_PKTCTRL0) return packet; - if(addr == CC1101_MDMCFG2) return modem; - if(addr == CC1101_FREQ2) return frequencyWord >> 16; - if(addr == CC1101_FREQ1) return frequencyWord >> 8; - if(addr == CC1101_FREQ0) return frequencyWord; - assert(false); return 0; -} -void ELECHOUSE_CC1101::setSpiPin(byte sck, byte miso, byte mosi, byte cs) { - if(BoardProfile::integratedRadio) assert(sck == 11 && miso == 10 && mosi == 9 && cs == 12); -} -void ELECHOUSE_CC1101::SetRx() { - rxStarts++; - observedReadyDuringRx = somfy.transceiver.available(); - somfy_tx_job_t job; - queuedDuringRx = somfy.transceiver.submitTx(job); -} -void ELECHOUSE_CC1101::setSidle() {} -void ELECHOUSE_CC1101::setGDO(byte, byte) {} -void ELECHOUSE_CC1101::setGDO0(byte) {} -#define NOOP(name, type) void ELECHOUSE_CC1101::name(type) {} -NOOP(setCCMode, bool) NOOP(setMHZ, float) NOOP(setRxBW, float) -NOOP(setDeviation, float) NOOP(setPA, int) NOOP(setModulation, byte) -NOOP(setManchester, bool) NOOP(setPktFormat, byte) NOOP(setDcFilterOff, bool) -NOOP(setCrc, bool) NOOP(setCRC_AF, bool) NOOP(setSyncMode, byte) NOOP(setAdrChk, byte) - -#include "radio-setup-methods.inc" - -static void reset() { - somfy.transceiver.~Transceiver(); - new (&somfy.transceiver) Transceiver; - detected = true; part = 0; version = 0x14; - gdo0 = gdo2 = 0x0D; packet = 0x32; modem = 0x3C; - frequencyWord = 0x10AB85; rxState = 0x0D; - attached = rxStarts = initializations = saves = 0; - observedReadyDuringRx = false; queuedDuringRx = 0; - testRadioInit = true; stuckMiso = false; rxmode = 0; clockMs = 0; -} -static void assertUnavailable() { - auto &radio = somfy.transceiver; - assert(!radio.available() && !radio.config.radioInit && attached == 0); - somfy_tx_job_t job; - assert(radio.submitTx(job) == 0); - radio.enableReceive(); - assert(attached == 0); -} -int main() { - reset(); auto &radio = somfy.transceiver; - if(BoardProfile::integratedRadio) { - radio.config.SCKPin = radio.config.TXPin = radio.config.RXPin = 16; - radio.config.apply(); - assert(radio.available() && radio.config.radioInit && attached == 1); - assert(!observedReadyDuringRx && queuedDuringRx == 0); - assert(radio.config.TXPin == 3 && radio.config.RXPin == 38 && radio.config.SCKPin == 11); - somfy_tx_job_t job; assert(radio.submitTx(job) != 0); - stuckMiso = true; radio.config.apply(); assertUnavailable(); - stuckMiso = false; radio.config.apply(); assert(radio.available()); - transceiver_config_t next = radio.config; - next.enabled = false; - next.SCKPin = next.MOSIPin = next.MISOPin = next.CSNPin = next.TXPin = next.RXPin = 16; - radio.setConfig(next); assertUnavailable(); assert(saves == 1); - for(uint8_t pin : {uint8_t(3), uint8_t(12), uint8_t(19), uint8_t(33), uint8_t(48)}) assert(radio.usesPin(pin)); - assert(!radio.usesPin(16)); - reset(); stuckMiso = true; radio.config.apply(); assertUnavailable(); assert(initializations == 0); - reset(); testRadioInit = false; radio.config.apply(); assertUnavailable(); assert(initializations == 0); - reset(); detected = false; radio.config.apply(); assertUnavailable(); assert(rxStarts == 0); - reset(); part = 1; radio.config.apply(); assertUnavailable(); - reset(); version = 0; radio.config.apply(); assertUnavailable(); - reset(); version = 0xFF; radio.config.apply(); assertUnavailable(); assert(rxStarts == 0); - reset(); gdo0 = 0; radio.config.apply(); assertUnavailable(); - reset(); gdo2 = 0; radio.config.apply(); assertUnavailable(); - reset(); packet = 0; radio.config.apply(); assertUnavailable(); - reset(); modem = 0; radio.config.apply(); assertUnavailable(); - reset(); frequencyWord = 0; radio.config.apply(); assertUnavailable(); - reset(); rxState = 0; radio.config.apply(); assertUnavailable(); assert(rxStarts == 1 && millis() <= 25); - rxState = 0x0D; radio.config.apply(); assert(radio.available() && attached == 1); - } else { - // Generic radios retain upstream's enabled-based availability and queue - // admission behavior, including when disabled or detection fails. - radio.config.apply(); - somfy_tx_job_t job; assert(radio.submitTx(job) != 0); - radio.config.enabled = true; detected = false; radio.config.apply(); - assert(radio.available() && !radio.config.radioInit); - radio.config.apply(); // Still no Plus-specific register gating. - detected = true; rxState = 0; radio.config.apply(); - assert(radio.available() && radio.config.radioInit && attached == 1); - assert(observedReadyDuringRx && queuedDuringRx != 0); - } - puts("Radio readiness and RX/queue gating checks passed"); -} diff --git a/tests/board-profile/shade-gpio-test.cpp b/tests/board-profile/shade-gpio-test.cpp deleted file mode 100644 index 2c46ed8..0000000 --- a/tests/board-profile/shade-gpio-test.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include -#include -#include "BoardProfile.h" -#include -#include "SomfyFrame.h" -#include "ShadeSettings.h" - -// Substitute only the shade model/storage boundary. The GPIO methods below -// are compiled from the production ShadeGpio.cpp and observe real board policy. -#define SOMFY_H -enum class gpio_flags_t : byte { LowLevelTrigger = 0x01 }; -struct SomfyRemote { - void triggerGPIOs(somfy_frame_t &frame); -}; -struct SomfyShade : SomfyRemote, ShadeSettings { - radio_proto proto = radio_proto::GP_Relay; - uint8_t gpioFlags = 0; - int8_t gpioDir = 0; - uint8_t gpioUp = 16, gpioDown = 17, gpioMy = 18; - uint32_t gpioRelease = 0; - struct State { int8_t direction = -1, tiltDirection = 0; float currentPos = 0; } position; - const State &state() const { return position; } - bool isToggle() { return isToggleShade(shadeType); } - void initGPIOs(); - void setGPIOs(); - void triggerGPIOs(somfy_frame_t &frame); - bool usesPin(uint8_t pin); -}; -#include "ShadeGpio.cpp" - -TestSerial Serial; -TestESP ESP; -static unsigned int writes = 0; -static unsigned int modes = 0; -static int pinModes[49] = {}; -static int levels[49] = {}; -int gpio_set_level(gpio_num_t pin, uint32_t value) { levels[pin] = value; return 0; } -void pinMode(uint8_t pin, uint8_t mode) { modes++; pinModes[pin] = mode; } -void digitalWrite(uint8_t pin, uint8_t value) { writes++; levels[pin] = value; } -int digitalRead(uint8_t pin) { return levels[pin]; } -unsigned long millis() { return 100; } -void delay(unsigned long) {} -// BoardProfile preflight is linked but this test never starts the hardware. -#include "SPI.h" -TestSPI SPI; -void TestSPI::begin(int8_t, int8_t, int8_t, int8_t) {} -void TestSPI::end() {} - -int main() { - SomfyShade shade; - shade.initGPIOs(); - assert(modes == 2 && pinModes[16] == OUTPUT && pinModes[17] == OUTPUT); - shade.proto = radio_proto::GP_Remote; - shade.initGPIOs(); - assert(modes == 5 && pinModes[18] == OUTPUT); - shade.proto = radio_proto::RTS; - shade.initGPIOs(); - assert(modes == 5); - shade.proto = radio_proto::GP_Relay; - shade.setGPIOs(); - assert(writes == 2 && levels[16] == HIGH && levels[17] == LOW); - somfy_frame_t frame; - frame.cmd = somfy_commands::Down; - frame.repeats = 2; - shade.proto = radio_proto::GP_Remote; - shade.triggerGPIOs(frame); - assert(writes == 5 && levels[17] == HIGH); - const unsigned int before = writes; - // These assignments can arrive from an old backup with the radio disabled. - // Test every reserved pad in each output slot, including USB/flash pads. - for(uint8_t pin = 0; pin < 49; pin++) { - if(!BoardProfile::usesPin(pin)) continue; - for(uint8_t slot = 0; slot < 3; slot++) { - shade.gpioUp = slot == 0 ? pin : 16; - shade.gpioDown = slot == 1 ? pin : 17; - shade.gpioMy = slot == 2 ? pin : 18; - shade.proto = radio_proto::GP_Remote; - const unsigned int beforeModes = modes; - shade.initGPIOs(); - assert(modes == beforeModes); - shade.triggerGPIOs(frame); - shade.setGPIOs(); - if(slot != 2) { - shade.proto = radio_proto::GP_Relay; - shade.initGPIOs(); - assert(modes == beforeModes); - shade.setGPIOs(); - } - assert(writes == before); - } - } - puts("Reserved shade GPIO checks passed"); -} diff --git a/tools/test-board-profile.sh b/tools/test-board-profile.sh deleted file mode 100755 index 748eab0..0000000 --- a/tools/test-board-profile.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -repo="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" -scratch="$(mktemp -d)" -trap 'rm -rf -- "$scratch"' EXIT -compiler="${CXX:-c++}" -common=(-std=c++11 -Wall -Wextra -Werror -Wno-unused-parameter -I"$repo/tests/board-profile" -I"$repo/src") -sources=("$repo/tests/board-profile/board-profile-test.cpp" "$repo/src/BoardProfile.cpp") -"$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101 -DCONFIG_IDF_TARGET_ESP32S3 \ - "${sources[@]}" -o "$scratch/lilygo-test" -"$scratch/lilygo-test" -"$compiler" "${common[@]}" "${sources[@]}" -o "$scratch/generic-test" -"$scratch/generic-test" -for profile in generic lilygo; do - flags=() - if [[ "$profile" == lilygo ]]; then - flags=(-DESPSOMFY_LILYGO_T_EMBED_CC1101 -DCONFIG_IDF_TARGET_ESP32S3) - fi - "$compiler" "${common[@]}" "${flags[@]}" \ - "$repo/tests/board-profile/shade-gpio-test.cpp" "$repo/src/BoardProfile.cpp" -o "$scratch/shade-gpio-$profile" - "$scratch/shade-gpio-$profile" -done -if "$compiler" "${common[@]}" -DESPSOMFY_LILYGO_T_EMBED_CC1101 \ - "${sources[@]}" -o "$scratch/wrong-target" > "$scratch/wrong-target.log" 2>&1; then - echo 'LILYGO profile incorrectly accepted a non-S3 target' >&2 - exit 1 -fi -echo 'Non-S3 LILYGO build rejected as expected' - -# Test production setup/RX/queue methods against register and readiness faults. -python3 "$repo/tests/board-profile/extract-radio-setup.py" "$repo/src/Transceiver.cpp" "$scratch/radio-setup-methods.inc" -for profile in generic lilygo; do - flags=() - if [[ "$profile" == lilygo ]]; then - flags=(-DESPSOMFY_LILYGO_T_EMBED_CC1101 -DCONFIG_IDF_TARGET_ESP32S3) - fi - "$compiler" "${common[@]}" -I"$scratch" -I"$repo/lib/SmartRC-CC1101-Driver-Lib" "${flags[@]}" \ - "$repo/tests/board-profile/radio-setup-test.cpp" "$repo/src/BoardProfile.cpp" \ - "$repo/src/RadioScheduler.cpp" -o "$scratch/radio-$profile" - "$scratch/radio-$profile" -done From 60d1872f35fdb5d13e235e5e7364f7b03a23325f Mon Sep 17 00:00:00 2001 From: "R. Sid Shaytay" <352722946+r-sidshaytay@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:50:41 -0800 Subject: [PATCH 10/10] Report a dead radio clearly, retry receive once and drop stale repeats A frequency scan was accepted when the radio was enabled but had failed its checks, and the client waited for results that never came. It is now refused with radioUnavailable: "The radio is disabled" or "The radio did not respond". Generic boards are unchanged (available() equals config.enabled). One missed switch into RX after a transmission or scan used to disable the radio until reboot. startReceive() now goes idle and calls SetRx once more (RADIO_RX_ATTEMPTS = 2, decided by radioRxOutcome) and gives up only after that. Repeater frames are dropped while the integrated radio is unavailable instead of being retried and sent stale later. Serial output in startReceive(), checkBoardRadio() and BoardProfile moves to ESP_LOG*, and the per-transmission RF switch readback is gone. Co-Authored-By: Claude Sonnet 5.5 --- src/BoardProfile.cpp | 6 +- src/DeviceOps.cpp | 5 +- src/RadioReadiness.cpp | 10 ++++ src/RadioReadiness.h | 14 ++++- src/Transceiver.cpp | 36 +++++++----- .../test_radioreadiness.cpp | 55 ++++++++++++++++++- 6 files changed, 105 insertions(+), 21 deletions(-) diff --git a/src/BoardProfile.cpp b/src/BoardProfile.cpp index 1aad81d..ff46c39 100644 --- a/src/BoardProfile.cpp +++ b/src/BoardProfile.cpp @@ -1,4 +1,5 @@ #include "BoardProfile.h" +#include #include #if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101) #include @@ -6,6 +7,7 @@ namespace BoardProfile { #if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101) +static const char *TAG = "Somfy"; static bool initialized = false; static void output(uint8_t pin, uint8_t level) { @@ -36,7 +38,7 @@ bool prepareRadio(float frequency) { begin(); // This hardware profile selects only the 433 MHz RF filter path. if(!(frequency >= 387.0f && frequency <= 464.0f)) { - Serial.println("Radio disabled: frequency is outside the selected 433 MHz band"); + ESP_LOGW(TAG, "Radio disabled: frequency is outside the selected 433 MHz band"); return false; } // Arduino 3 owns these pads while SPI is active. Release that ownership @@ -50,7 +52,7 @@ bool prepareRadio(float frequency) { while(digitalRead(miso) == HIGH && millis() - started < 20) delay(1); bool ready = digitalRead(miso) == LOW; digitalWrite(cs, HIGH); - if(!ready) Serial.println("CC1101 not ready: MISO stayed HIGH; check power/shared SPI before retrying"); + if(!ready) ESP_LOGW(TAG, "CC1101 not ready: MISO stayed HIGH; check power/shared SPI before retrying"); if(ready) SPI.begin(sck, miso, mosi, cs); return ready; } diff --git a/src/DeviceOps.cpp b/src/DeviceOps.cpp index 9b2a834..fe3b59d 100644 --- a/src/DeviceOps.cpp +++ b/src/DeviceOps.cpp @@ -2,6 +2,7 @@ #include #include #include +#include "RadioReadiness.h" #include "esp_log.h" #include "DeviceOps.h" #include "ConfigSettings.h" @@ -235,8 +236,8 @@ void runDeviceOp(const loop_item_t &item) { protoSocket.endReply(item.replyTo); break; case proto_type_t::beginFrequencyScan: - if(!somfy.transceiver.config.enabled) { - protoSocket.replyRefused(item.replyTo, proto_error_t::radioUnavailable, "The radio is disabled"); + if(const char *why = radioRefusalReason(somfy.transceiver.config.enabled, somfy.transceiver.available())) { + protoSocket.replyRefused(item.replyTo, proto_error_t::radioUnavailable, why); break; } somfy.transceiver.beginFrequencyScan(); diff --git a/src/RadioReadiness.cpp b/src/RadioReadiness.cpp index d2ac7ef..4ef8b25 100644 --- a/src/RadioReadiness.cpp +++ b/src/RadioReadiness.cpp @@ -19,3 +19,13 @@ rx_outcome_t radioRxOutcome(uint8_t marcstate, uint8_t attempt, uint8_t maxAttem bool radioMayTransmit(bool integratedRadio, bool radioAvailable) { return !integratedRadio || radioAvailable; } + +const char *radioRefusalReason(bool enabled, bool radioAvailable) { + if(!enabled) return "The radio is disabled"; + if(!radioAvailable) return "The radio did not respond"; + return nullptr; +} + +bool repeaterFrameDropped(bool txSuspended, bool integratedRadio, bool radioAvailable) { + return txSuspended || !radioMayTransmit(integratedRadio, radioAvailable); +} diff --git a/src/RadioReadiness.h b/src/RadioReadiness.h index 9c2ff82..c3e9dca 100644 --- a/src/RadioReadiness.h +++ b/src/RadioReadiness.h @@ -27,7 +27,9 @@ bool radioRegistersReady(const radio_readings_t &r, float requestedMHz); // CC1101_MARCSTATE value while receiving. #define RADIO_MARCSTATE_RX 0x0D // Tries at entering receive before the radio is given up as unavailable. -#define RADIO_RX_ATTEMPTS 1 +// One retry: go idle and call SetRx again, so a single missed switch after a +// transmission does not disable the radio until reboot. +#define RADIO_RX_ATTEMPTS 2 enum class rx_outcome_t : uint8_t { ready, // the radio is receiving @@ -43,4 +45,14 @@ rx_outcome_t radioRxOutcome(uint8_t marcstate, uint8_t attempt, uint8_t maxAttem // always allowed, as before; the integrated one only once it is ready. bool radioMayTransmit(bool integratedRadio, bool radioAvailable); +// Why a request that needs the radio (a frequency scan) is refused, or nullptr +// when it may go ahead. Texts are the ones clients show. A generic radio is +// available exactly when it is enabled, so it only ever gets the first one. +const char *radioRefusalReason(bool enabled, bool radioAvailable); + +// Whether a queued repeater frame is discarded instead of kept for another +// try: while transmitting is suspended, or the integrated radio is unavailable +// (a stale repeat must not go out when the radio comes back). +bool repeaterFrameDropped(bool txSuspended, bool integratedRadio, bool radioAvailable); + #endif diff --git a/src/Transceiver.cpp b/src/Transceiver.cpp index b3f04de..235a203 100644 --- a/src/Transceiver.cpp +++ b/src/Transceiver.cpp @@ -379,24 +379,32 @@ bool Transceiver::startReceive() { rxmode = 1; pinMode(this->config.RXPin, INPUT); interruptPin = digitalPinToInterrupt(this->config.RXPin); - ELECHOUSE_cc1101.SetRx(); if(BoardProfile::integratedRadio) { - uint8_t state; - do { - delay(1); - state = ELECHOUSE_cc1101.SpiReadStatus(CC1101_MARCSTATE) & 0x1F; - } while(state != RADIO_MARCSTATE_RX && millis() - timing < 20); - Serial.printf("CC1101 MARCSTATE=0x%02X (RX=0x0D); RF switch readback SW1=%d SW0=%d\n", - state, digitalRead(BoardProfile::sw1), digitalRead(BoardProfile::sw0)); - if(radioRxOutcome(state, 0, RADIO_RX_ATTEMPTS) != rx_outcome_t::ready) { - Serial.println("CC1101 failed to enter RX; radio unavailable"); + // One missed switch into RX is retried from idle before the radio is + // given up as unavailable. + for(uint8_t attempt = 0;; attempt++) { + ELECHOUSE_cc1101.SetRx(); + const uint32_t tried = millis(); + uint8_t state; + do { + delay(1); + state = ELECHOUSE_cc1101.SpiReadStatus(CC1101_MARCSTATE) & 0x1F; + } while(state != RADIO_MARCSTATE_RX && millis() - tried < 20); + const rx_outcome_t outcome = radioRxOutcome(state, attempt, RADIO_RX_ATTEMPTS); + if(outcome == rx_outcome_t::ready) break; ELECHOUSE_cc1101.setSidle(); + if(outcome == rx_outcome_t::retry) { + ESP_LOGW(TAG, "CC1101 MARCSTATE=0x%02X, not RX; trying again", state); + continue; + } + ESP_LOGW(TAG, "CC1101 MARCSTATE=0x%02X, failed to enter RX; radio unavailable", state); this->config.radioInit = false; this->_available = false; rxmode = 0; return false; } } + else ELECHOUSE_cc1101.SetRx(); //attachInterrupt(interruptPin, handleReceive, FALLING); attachInterrupt(interruptPin, handleReceive, CHANGE); ESP_LOGD(TAG, "Enabled receive on Pin #%d Timing: %ld", this->config.RXPin, millis() - timing); @@ -624,9 +632,9 @@ static bool checkBoardRadio(float frequency) { r.freqWord = (static_cast(ELECHOUSE_cc1101.SpiReadReg(CC1101_FREQ2)) << 16) | (static_cast(ELECHOUSE_cc1101.SpiReadReg(CC1101_FREQ1)) << 8) | ELECHOUSE_cc1101.SpiReadReg(CC1101_FREQ0); - Serial.printf("CC1101 PARTNUM=0x%02X VERSION=0x%02X IOCFG0=0x%02X IOCFG2=0x%02X PKTCTRL0=0x%02X MDMCFG2=0x%02X\n", + ESP_LOGD(TAG, "CC1101 PARTNUM=0x%02X VERSION=0x%02X IOCFG0=0x%02X IOCFG2=0x%02X PKTCTRL0=0x%02X MDMCFG2=0x%02X", r.partnum, r.version, r.iocfg0, r.iocfg2, r.pktctrl0, r.mdmcfg2); - Serial.printf("CC1101 frequency requested=%.3f readback=%.3f MHz; GDO0 TX=%u GDO2 RX=%u\n", + ESP_LOGD(TAG, "CC1101 frequency requested=%.3f readback=%.3f MHz; GDO0 TX=%u GDO2 RX=%u", frequency, radioFrequencyMHz(r.freqWord), BoardProfile::tx, BoardProfile::rx); return radioRegistersReady(r, frequency); } @@ -813,7 +821,9 @@ void Transceiver::loop() { snprintf(frame_buf + fpos, sizeof(frame_buf) - fpos, "]"); ESP_LOGD(TAG, "%s", frame_buf); } - if(this->submitTx(job) || this->txSuspended()) { + // Drop the frame rather than keep retrying it while the radio cannot + // send: a stale repeat must not go out when the radio comes back. + if(repeaterFrameDropped(this->txSuspended(), BoardProfile::integratedRadio, this->available()) || this->submitTx(job)) { somfy_tx_t sent; tx_queue.pop(&sent); } diff --git a/test/test_radioreadiness/test_radioreadiness.cpp b/test/test_radioreadiness/test_radioreadiness.cpp index 0c44edb..0f2c19c 100644 --- a/test/test_radioreadiness/test_radioreadiness.cpp +++ b/test/test_radioreadiness/test_radioreadiness.cpp @@ -95,8 +95,47 @@ static void test_a_radio_not_in_rx_may_retry_while_tries_are_left() { static void test_zero_tries_never_retry() { TEST_ASSERT_EQUAL(rx_outcome_t::unavailable, radioRxOutcome(0x01, 0, 0)); } -static void test_the_firmware_makes_one_try_for_now() { - TEST_ASSERT_EQUAL(1, RADIO_RX_ATTEMPTS); +static void test_the_firmware_retries_receive_once() { + TEST_ASSERT_EQUAL(2, RADIO_RX_ATTEMPTS); +} +static void test_receive_retry_succeeds_on_the_second_try() { + TEST_ASSERT_EQUAL(rx_outcome_t::retry, radioRxOutcome(0x01, 0, RADIO_RX_ATTEMPTS)); + TEST_ASSERT_EQUAL(rx_outcome_t::ready, radioRxOutcome(RADIO_MARCSTATE_RX, 1, RADIO_RX_ATTEMPTS)); +} +static void test_receive_retry_fails_after_the_second_try() { + TEST_ASSERT_EQUAL(rx_outcome_t::retry, radioRxOutcome(0x01, 0, RADIO_RX_ATTEMPTS)); + TEST_ASSERT_EQUAL(rx_outcome_t::unavailable, radioRxOutcome(0x01, 1, RADIO_RX_ATTEMPTS)); +} + +static void test_refusal_text_for_a_disabled_radio() { + TEST_ASSERT_EQUAL_STRING("The radio is disabled", radioRefusalReason(false, false)); + TEST_ASSERT_EQUAL_STRING("The radio is disabled", radioRefusalReason(false, true)); +} +static void test_refusal_text_for_a_radio_that_did_not_respond() { + TEST_ASSERT_EQUAL_STRING("The radio did not respond", radioRefusalReason(true, false)); +} +static void test_a_working_radio_is_not_refused() { + TEST_ASSERT_NULL(radioRefusalReason(true, true)); +} +static void test_a_generic_radio_is_refused_only_when_disabled() { + // A generic radio is available exactly when enabled. + TEST_ASSERT_NULL(radioRefusalReason(true, true)); + TEST_ASSERT_EQUAL_STRING("The radio is disabled", radioRefusalReason(false, false)); +} + +static void test_repeater_frame_is_dropped_while_the_integrated_radio_is_unavailable() { + TEST_ASSERT_TRUE(repeaterFrameDropped(false, true, false)); +} +static void test_repeater_frame_is_kept_for_a_ready_radio() { + TEST_ASSERT_FALSE(repeaterFrameDropped(false, true, true)); + TEST_ASSERT_FALSE(repeaterFrameDropped(false, false, true)); +} +static void test_repeater_frame_is_dropped_while_tx_is_suspended() { + TEST_ASSERT_TRUE(repeaterFrameDropped(true, true, true)); + TEST_ASSERT_TRUE(repeaterFrameDropped(true, false, true)); +} +static void test_a_generic_radio_never_drops_a_repeat_for_availability() { + TEST_ASSERT_FALSE(repeaterFrameDropped(false, false, false)); } static void test_a_generic_radio_may_always_queue_and_send() { @@ -122,7 +161,17 @@ int main(int, char **) { RUN_TEST(test_a_radio_not_in_rx_is_unavailable_with_one_try); RUN_TEST(test_a_radio_not_in_rx_may_retry_while_tries_are_left); RUN_TEST(test_zero_tries_never_retry); - RUN_TEST(test_the_firmware_makes_one_try_for_now); + RUN_TEST(test_the_firmware_retries_receive_once); + RUN_TEST(test_receive_retry_succeeds_on_the_second_try); + RUN_TEST(test_receive_retry_fails_after_the_second_try); + RUN_TEST(test_refusal_text_for_a_disabled_radio); + RUN_TEST(test_refusal_text_for_a_radio_that_did_not_respond); + RUN_TEST(test_a_working_radio_is_not_refused); + RUN_TEST(test_a_generic_radio_is_refused_only_when_disabled); + RUN_TEST(test_repeater_frame_is_dropped_while_the_integrated_radio_is_unavailable); + RUN_TEST(test_repeater_frame_is_kept_for_a_ready_radio); + RUN_TEST(test_repeater_frame_is_dropped_while_tx_is_suspended); + RUN_TEST(test_a_generic_radio_never_drops_a_repeat_for_availability); RUN_TEST(test_a_generic_radio_may_always_queue_and_send); RUN_TEST(test_the_integrated_radio_transmits_only_when_ready); return UNITY_END();