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