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/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 0fc8a68..de73424 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]
+extends = esp32
+board = esp32-s3-devkitc1-n16r8
+build_type = release
+board_build.partitions = default_8MB.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
+
[env:esp32c3]
extends = esp32
board = esp32-c3-devkitm-1
@@ -155,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
new file mode 100644
index 0000000..ff46c39
--- /dev/null
+++ b/src/BoardProfile.cpp
@@ -0,0 +1,63 @@
+#include "BoardProfile.h"
+#include
+#include
+#if defined(ESPSOMFY_LILYGO_T_EMBED_CC1101)
+#include
+#endif
+
+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) {
+ // 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)) {
+ 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
+ // 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) 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;
+}
+#else
+void begin() {}
+bool prepareRadio(float) { return true; }
+#endif
+}
diff --git a/src/BoardProfile.h b/src/BoardProfile.h
new file mode 100644
index 0000000..877a4be
--- /dev/null
+++ b/src/BoardProfile.h
@@ -0,0 +1,46 @@
+#pragma once
+#include
+
+namespace BoardProfile {
+#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"
+#endif
+constexpr bool integratedRadio = true;
+#else
+constexpr bool integratedRadio = false;
+#endif
+
+// 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;
+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);
+
+// 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/ConfigFile.cpp b/src/ConfigFile.cpp
index 8b8445c..fbd3f4f 100644
--- a/src/ConfigFile.cpp
+++ b/src/ConfigFile.cpp
@@ -287,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) {
- pinMode(shade->gpioUp, OUTPUT);
- pinMode(shade->gpioDown, OUTPUT);
- }
- if(shade->proto == radio_proto::GP_Remote)
- pinMode(shade->gpioMy, OUTPUT);
+ shade->initGPIOs();
}
void ShadeConfigFile::readGroup(SomfyGroup *group) {
group_record_t rec = groupRecord(group);
diff --git a/src/DeviceOps.cpp b/src/DeviceOps.cpp
index d0a60b0..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"
@@ -109,6 +110,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;
}
}
@@ -234,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/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/src/RadioReadiness.cpp b/src/RadioReadiness.cpp
new file mode 100644
index 0000000..4ef8b25
--- /dev/null
+++ b/src/RadioReadiness.cpp
@@ -0,0 +1,31 @@
+#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;
+}
+
+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
new file mode 100644
index 0000000..c3e9dca
--- /dev/null
+++ b/src/RadioReadiness.h
@@ -0,0 +1,58 @@
+#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.
+// 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
+ 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);
+
+// 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/ShadeGpio.cpp b/src/ShadeGpio.cpp
index 0024326..85e48f5 100644
--- a/src/ShadeGpio.cpp
+++ b/src/ShadeGpio.cpp
@@ -1,9 +1,28 @@
#include "esp_log.h"
#include "Somfy.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) {
+ return shadeOutputsUseBoardPins(shade.proto, shade.gpioUp, shade.gpioDown, 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) {
// 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 +84,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/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/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/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..4ead8a0 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,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"];
- pinMode(this->gpioUp, OUTPUT);
- pinMode(this->gpioDown, OUTPUT);
}
if(this->proto == radio_proto::GP_Remote) {
if(!obj["gpioMy"].isNull()) this->gpioMy = obj["gpioMy"];
- pinMode(this->gpioMy, OUTPUT);
}
+ this->initGPIOs();
}
return err;
}
diff --git a/src/Transceiver.cpp b/src/Transceiver.cpp
index 6b09f36..235a203 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"
@@ -101,7 +102,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 +253,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 +273,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 +366,49 @@ 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);
+ if(BoardProfile::integratedRadio) {
+ // 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);
+ return true;
}
void Transceiver::disableReceive(void) {
rxmode = 0;
@@ -396,12 +424,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 +606,39 @@ 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;
+ 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);
+ 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);
+ 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);
+}
+
void transceiver_config_t::apply() {
Preferences pref;
// A transmission in flight stops after its current frame so the radio can
@@ -588,12 +648,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 +721,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);
@@ -752,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);
}
@@ -765,6 +836,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(!radioMayTransmit(BoardProfile::integratedRadio, this->available())) return 0;
uint32_t ticket;
{
TxQueueLock lock;
@@ -838,7 +912,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 = radioMayTransmit(BoardProfile::integratedRadio, this->available()) && this->transmitJob(job);
TxQueueLock qlock;
this->sched.ended(job.ticket, complete, millis());
}
@@ -872,7 +946,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 +954,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/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/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_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();
}
diff --git a/test/test_radioreadiness/test_radioreadiness.cpp b/test/test_radioreadiness/test_radioreadiness.cpp
new file mode 100644
index 0000000..0f2c19c
--- /dev/null
+++ b/test/test_radioreadiness/test_radioreadiness.cpp
@@ -0,0 +1,178 @@
+#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_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() {
+ 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_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();
+}