Add opt-in combined RAK4631 Ethernet test image

Keep Full sensors, UART2, adaptive OTA storage and the 8 KiB loop stack. Arbitrate shared SPI and OTA workspace ownership, move network waits into a worker, and use bounded queued TCP operations. Add reproducible test configs, RAM checks and regression coverage. Validated the Full build, UF2 layout and 29 sanitizer runtime scenarios.
This commit is contained in:
mikecarper committed 2026-10-08 13:53:31 -07:00
1 parent 57036b1d66
commit df88a6ef95
31 files changed
+3581 -8

No files matched your search

+5
View File
@@ -10,6 +10,11 @@
// allocation even when a combined Full image starts with the UART disabled.
static_assert(sizeof(RS232Bridge) <= 4096, "Update the ESP32 UART heap budget");
#endif
#if defined(NRF52_PLATFORM) && defined(RAK4631_COMBINED_ETHERNET)
// The combined RAK RAM policy reserves this object plus allocator metadata
// and the UART driver's TX semaphore. Its RX/TX arrays are linked globals.
static_assert(sizeof(RS232Bridge) <= 2304, "Update the combined RAK UART heap budget");
#endif
RS232Bridge::RS232Bridge(NodePrefs *prefs, Stream &serial, int16_t rx_pin,
int16_t tx_pin, mesh::PacketManager *mgr,
+187
View File
@@ -7,6 +7,9 @@
#include <RAK13800_W5100S.h>
#include <helpers/nrf52/EthernetMac.h>
#include <helpers/UsbLogging.h>
#if defined(RAK4631_COMBINED_ETHERNET)
#include <atomic>
#endif
// Ethernet startup runs on a FreeRTOS task, and client acceptance runs in the
// mesh loop. Never let either path wait on a CDC host which stopped reading.
@@ -38,15 +41,37 @@ static SPIClass ETHERNET_SPI_PORT(NRF_SPIM1, PIN_SPI1_MISO, PIN_SPI1_SCK, PIN_SP
#define ETHERNET_RETRY_INTERVAL_MS 30000
static EthernetServer ethernet_server(ETHERNET_TCP_PORT);
#if !defined(RAK4631_COMBINED_ETHERNET)
static EthernetClient ethernet_client;
#endif
#if defined(RAK4631_COMBINED_ETHERNET)
static std::atomic<bool> ethernet_running{false};
#else
static volatile bool ethernet_running = false;
#endif
#if defined(RAK4631_COMBINED_ETHERNET)
static std::atomic<bool> ethernet_session_reset{false};
static bool ethernet_line_discarding = false; // Main-thread framing state.
#else
static bool ethernet_session_reset = false;
#endif
static bool ethernet_take_session_reset() {
#if defined(RAK4631_COMBINED_ETHERNET)
const bool changed = ethernet_session_reset.exchange(false);
if (changed) ethernet_line_discarding = false;
return changed;
#else
const bool changed = ethernet_session_reset;
ethernet_session_reset = false;
return changed;
#endif
}
#if defined(RAK4631_COMBINED_ETHERNET)
static void ethernet_check_client();
#include "EthernetCliRuntime.h"
#else
// FreeRTOS task: handles hw init, DHCP, and retries in the background
static void ethernet_task(void* param) {
(void)param;
@@ -99,10 +124,48 @@ static void ethernet_task(void* param) {
static void ethernet_start_task() {
xTaskCreate(ethernet_task, "eth_init", 1024, NULL, 1, NULL);
}
#endif
// Format ethernet status into reply buffer. Returns true if command was handled.
static bool ethernet_handle_command(const char* command, char* reply) {
#if defined(RAK4631_COMBINED_ETHERNET)
if (strcmp(command, "eth on") == 0 || strcmp(command, "set eth on") == 0) {
(void)ethernet_request_start(reply, true);
return true;
}
if (strcmp(command, "eth off") == 0 || strcmp(command, "set eth off") == 0) {
(void)ethernet_request_stop(reply);
return true;
}
if (strcmp(command, "get eth") == 0) {
strcpy(reply, ethernet_enabled.load() ? "> on" : "> off");
return true;
}
if (strncmp(command, "eth ", 4) == 0 || strncmp(command, "set eth ", 8) == 0) {
strcpy(reply, "Error: Ethernet mode must be on or off");
return true;
}
#endif
if (strcmp(command, "eth.status") == 0) {
#if defined(RAK4631_COMBINED_ETHERNET)
const EthernetCliState state = ethernet_state.load();
if (state != EthernetCliState::Online) {
const char* status = state == EthernetCliState::Off ? "off" :
state == EthernetCliState::Starting ? "starting" :
state == EthernetCliState::Retrying ? "waiting for DHCP" :
state == EthernetCliState::Maintaining ? "renewing DHCP" :
state == EthernetCliState::Stopping ? "stopping" :
state == EthernetCliState::NoHardware ? "hardware not found" :
state == EthernetCliState::Faulted ? "controller stalled; turn Ethernet off/on" : "start failed";
snprintf(reply, 160, "ETH: %s", status);
return true;
}
const uint32_t ip = ethernet_cached_ip.load();
snprintf(reply, 160, "ETH: %u.%u.%u.%u:%d", (unsigned)(ip & 255),
(unsigned)((ip >> 8) & 255), (unsigned)((ip >> 16) & 255),
(unsigned)((ip >> 24) & 255), ETHERNET_TCP_PORT);
return true;
#endif
if (!ethernet_running) {
strcpy(reply, "ETH: not connected");
} else {
@@ -119,6 +182,36 @@ static bool ethernet_handle_command(const char* command, char* reply) {
// available() also returns existing connected sockets that have data, which
// would force us to disambiguate every inbound packet from a real new client.
static void ethernet_check_client() {
#if defined(RAK4631_COMBINED_ETHERNET)
// Combined accept/relisten can call vendor controller commands; run only
// in the background worker while the mesh-facing Stream is gated.
auto newClient = ethernet_server.accept();
if (newClient) {
ethernet_session_generation.fetch_add(1);
if (ethernet_raw_client && ethernet_raw_client.getSocketNumber() != newClient.getSocketNumber()) {
(void)mesh::nrf52::EthernetCliTransmit::close(ethernet_raw_client.getSocketNumber());
ethernet_require_command_check();
}
ethernet_queue_clear();
ethernet_transmit.reset();
ethernet_raw_client = newClient;
ethernet_client_attached.store(true);
ethernet_session_reset = true;
static const char banner[] = ETHERNET_CLI_BANNER "\r\n";
(void)ethernet_queue_write(reinterpret_cast<const uint8_t*>(banner), sizeof(banner) - 1);
}
if (ethernet_raw_client &&
!mesh::nrf52::EthernetCliTransmit::connected(ethernet_raw_client.getSocketNumber())) {
ethernet_session_generation.fetch_add(1);
(void)mesh::nrf52::EthernetCliTransmit::close(ethernet_raw_client.getSocketNumber());
ethernet_require_command_check();
ethernet_raw_client = EthernetClient();
ethernet_client_attached.store(false);
ethernet_queue_clear();
ethernet_transmit.reset();
ethernet_session_reset = true;
}
#else
auto newClient = ethernet_server.accept();
if (newClient) {
if (ethernet_client) ethernet_client.stop();
@@ -128,20 +221,102 @@ static void ethernet_check_client() {
ETHERNET_CLI_LOG("Client connected from %u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
ethernet_client.println(ETHERNET_CLI_BANNER);
}
#endif
}
// Call from loop() to maintain DHCP and check for new clients
static void ethernet_loop_maintain() {
#if defined(RAK4631_COMBINED_ETHERNET)
if (ethernet_state.load() == EthernetCliState::Stopping) {
if (ethernet_worker_active.load() && !ethernet_worker_stopped.load()) {
EthernetSpiAccess expected = EthernetSpiAccess::Idle;
if (ethernet_spi_access.compare_exchange_strong(expected, EthernetSpiAccess::Worker)) {
ethernet_running.store(false);
}
if (ethernet_spi_access.load() == EthernetSpiAccess::Worker) ethernet_notify_worker();
return;
}
if (ethernet_complete_release()) {
ethernet_state.store(EthernetCliState::Off);
}
return;
}
if (!ethernet_running.load() && ethernet_bus_reserved &&
(!ethernet_worker_active.load() || ethernet_worker_stopped.load())) {
(void)ethernet_complete_release();
return;
}
if (ethernet_running.load()) {
if (static_cast<uint32_t>(millis() - ethernet_last_maintain.load()) >= 1000) {
ethernet_request_maintenance();
}
}
#else
if (ethernet_running) {
ethernet_check_client();
Ethernet.maintain();
}
#endif
}
// Read a line from the Ethernet client into the command buffer.
// Returns true when a complete line is ready to process (command is null-terminated).
// The caller should process the command and then reset ethernet_command[0] = 0.
static bool ethernet_read_line(char* ethernet_command, size_t buf_size) {
#if defined(RAK4631_COMBINED_ETHERNET)
if (buf_size < 2) return false;
EthernetClientAccess access;
if (!access || !ethernet_client_attached.load()) return false;
const uint32_t generation = ethernet_session_generation.load();
if (ethernet_session_reset.load() ||
((ethernet_command[0] || ethernet_line_discarding) && ethernet_line_generation != generation)) {
ethernet_command[0] = 0;
ethernet_line_discarding = false;
return false;
}
ethernet_line_generation = generation;
const uint8_t socket = ethernet_raw_client.getSocketNumber();
if (!mesh::nrf52::EthernetCliTransmit::connected(socket)) return false;
// Reserve one complete synchronous CLI reply before dispatching a command;
// Print's component writes cannot otherwise retain a partially queued reply.
if (ethernet_queue_capacity() < 170) return false;
size_t length = strlen(ethernet_command);
// One gate covers this bounded turn, so a worker cannot replace the peer
// between bytes or between the terminal byte and reply-owner publication.
for (unsigned consumed = 0; consumed < 128 &&
mesh::nrf52::EthernetCliTransmit::available(socket); ++consumed) {
const int next = mesh::nrf52::EthernetCliTransmit::read(socket);
if (!mesh::nrf52::EthernetCliTransmit::commandReady(socket)) ethernet_require_command_check();
if (next < 0) break;
const char c = static_cast<char>(next);
if (c == '\r' || c == '\n') {
if (ethernet_line_discarding) {
ethernet_line_discarding = false;
ethernet_command[0] = 0;
static const char error[] = "Error: invalid or oversized command; discarded\r\n";
(void)ethernet_queue_write(reinterpret_cast<const uint8_t*>(error), sizeof(error) - 1);
ethernet_session_reset.store(true);
return false;
}
if (length == 0) continue;
ethernet_command[length] = 0;
ethernet_reply_generation = generation;
static const uint8_t newline[] = {'\r', '\n'};
(void)ethernet_queue_write(newline, sizeof(newline));
return true;
}
if (ethernet_line_discarding) continue;
if (c == '\0' || length == buf_size - 1) {
ethernet_line_discarding = true;
ethernet_command[0] = 0;
length = 0;
continue;
}
ethernet_command[length++] = c;
ethernet_command[length] = 0;
}
return false;
#else
if (!ethernet_running || !ethernet_client || !ethernet_client.connected()) return false;
int elen = strlen(ethernet_command);
@@ -162,12 +337,24 @@ static bool ethernet_read_line(char* ethernet_command, size_t buf_size) {
return true;
}
return false;
#endif
}
// Send a reply to the Ethernet client
static void ethernet_send_reply(const char* reply) {
if (reply[0]) {
#if defined(RAK4631_COMBINED_ETHERNET)
// One RAM-only enqueue keeps a synchronous command's complete reply even
// if the worker begins renewal between command dispatch and this call.
char frame[170];
const int length = snprintf(frame, sizeof(frame), " -> %s\r\n", reply);
if (length > 0 && static_cast<size_t>(length) < sizeof(frame)) {
(void)ethernet_queue_write(reinterpret_cast<const uint8_t*>(frame), static_cast<size_t>(length),
true, ethernet_reply_generation);
}
#else
ethernet_client.print(" -> "); ethernet_client.println(reply);
#endif
}
}
+544
View File
@@ -0,0 +1,544 @@
#pragma once
#include <cstdlib>
#include "EthernetCliTransmit.h"
// Included by EthernetCLI.h only for the opt-in combined RAK4631 prototype.
// Legacy Ethernet profiles retain their established implementation.
struct EthernetCliHooks {
bool (*prepare)(void*, char*, size_t) = nullptr;
bool (*can_release)(void*) = nullptr;
bool (*released)(void*) = nullptr;
bool (*save)(void*, bool) = nullptr;
void* context = nullptr;
};
enum class EthernetCliState : uint8_t {
Off, Starting, Retrying, Online, Maintaining, Stopping, NoHardware, StartFailed, Faulted
};
enum class EthernetSpiAccess : uint8_t { Idle, Client, Worker };
static EthernetCliHooks ethernet_hooks;
static std::atomic<bool> ethernet_enabled{false};
static std::atomic<bool> ethernet_worker_active{false};
static std::atomic<bool> ethernet_worker_stopped{false};
static std::atomic<EthernetCliState> ethernet_state{EthernetCliState::Off};
static std::atomic<EthernetSpiAccess> ethernet_spi_access{EthernetSpiAccess::Worker};
static std::atomic<bool> ethernet_maintain_requested{false};
static std::atomic<uint32_t> ethernet_cached_ip{0};
static std::atomic<uint32_t> ethernet_last_maintain{0};
// Only scheduler-critical sections access the handle. OTA context callbacks
// and bus reservation changes run exclusively on the main thread.
static TaskHandle_t ethernet_task_handle = nullptr;
static bool ethernet_bus_reserved = false;
static bool ethernet_spi_started = false;
static bool ethernet_hardware_found = false;
static EthernetClient ethernet_raw_client;
static std::atomic<bool> ethernet_client_attached{false};
static std::atomic<uint32_t> ethernet_session_generation{0};
static uint32_t ethernet_reply_generation = 0; // Main-thread command owner.
static uint32_t ethernet_line_generation = 0; // Main-thread partial input owner.
static std::atomic<bool> ethernet_command_check_requested{false};
static std::atomic<uint32_t> ethernet_command_check_started{0};
static bool ethernet_controller_faulted = false;
static mesh::nrf52::EthernetCliTransmit ethernet_transmit;
#ifndef ETHERNET_CLI_TX_BUFFER_BYTES
#define ETHERNET_CLI_TX_BUFFER_BYTES 512
#endif
static_assert(ETHERNET_CLI_TX_BUFFER_BYTES >= 512 && ETHERNET_CLI_TX_BUFFER_BYTES <= 2048,
"Ethernet queue capacity must match its qualified RAM budget");
// This queue exists only while Ethernet owns SPI. Free it and synchronously
// reclaim the worker before external OTA allocates its mutually exclusive RAM.
static uint8_t* ethernet_tx_queue = nullptr;
static size_t ethernet_tx_head = 0;
static size_t ethernet_tx_count = 0;
#ifndef RAK4631_ETHERNET_TASK_STACK_WORDS
#define RAK4631_ETHERNET_TASK_STACK_WORDS 1024
#endif
static_assert(RAK4631_ETHERNET_TASK_STACK_WORDS >= 1024,
"Ethernet worker requires its qualified stack budget");
static_assert(sizeof(StaticTask_t) + 32 <= 256,
"Ethernet task metadata exceeds its qualified RAM allowance");
static bool ethernet_is_running() { return ethernet_running.load(); }
static bool ethernet_get_enabled() { return ethernet_enabled.load(); }
static void ethernet_notify_worker() {
taskENTER_CRITICAL();
if (ethernet_task_handle != nullptr) xTaskNotifyGive(ethernet_task_handle);
taskEXIT_CRITICAL();
}
static void ethernet_queue_clear() {
taskENTER_CRITICAL();
ethernet_tx_head = 0;
ethernet_tx_count = 0;
taskEXIT_CRITICAL();
}
static size_t ethernet_queue_capacity() {
taskENTER_CRITICAL();
const size_t free = ethernet_tx_queue ? ETHERNET_CLI_TX_BUFFER_BYTES - ethernet_tx_count : 0;
taskEXIT_CRITICAL();
return free;
}
static size_t ethernet_queue_write(const uint8_t* data, size_t size,
bool bind_session = false, uint32_t generation = 0) {
taskENTER_CRITICAL();
if (!ethernet_tx_queue || !ethernet_client_attached.load() ||
(bind_session && generation != ethernet_session_generation.load())) {
taskEXIT_CRITICAL();
return 0;
}
const size_t free = ETHERNET_CLI_TX_BUFFER_BYTES - ethernet_tx_count;
if (size > free) size = free;
const size_t tail = (ethernet_tx_head + ethernet_tx_count) % ETHERNET_CLI_TX_BUFFER_BYTES;
const size_t first = size < ETHERNET_CLI_TX_BUFFER_BYTES - tail ? size : ETHERNET_CLI_TX_BUFFER_BYTES - tail;
memcpy(ethernet_tx_queue + tail, data, first);
memcpy(ethernet_tx_queue, data + first, size - first);
ethernet_tx_count += size;
taskEXIT_CRITICAL();
if (size) ethernet_notify_worker();
return size;
}
static void ethernet_require_command_check() {
ethernet_running.store(false);
ethernet_command_check_started.store(millis());
ethernet_command_check_requested.store(true);
ethernet_notify_worker();
}
class EthernetClientAccess {
bool acquired = false;
public:
EthernetClientAccess() {
if (!ethernet_running.load()) return;
EthernetSpiAccess expected = EthernetSpiAccess::Idle;
acquired = ethernet_spi_access.compare_exchange_strong(expected, EthernetSpiAccess::Client);
if (acquired && !ethernet_running.load()) {
ethernet_spi_access.store(EthernetSpiAccess::Idle);
acquired = false;
}
}
~EthernetClientAccess() {
if (!acquired) return;
ethernet_spi_access.store(EthernetSpiAccess::Idle);
}
explicit operator bool() const { return acquired; }
};
// MyMesh retains this Stream for asynchronous replies. It must never expose
// the raw client while DHCP initialization/renewal owns the SPI bus. Busy
// methods yield immediately so radio, USB and UART service can continue.
class EthernetCliClient : public Stream {
public:
int available() override {
EthernetClientAccess access;
if (!access || !ethernet_client_attached.load()) return 0;
const uint8_t socket = ethernet_raw_client.getSocketNumber();
const int available = mesh::nrf52::EthernetCliTransmit::available(socket);
if (!mesh::nrf52::EthernetCliTransmit::commandReady(socket)) ethernet_require_command_check();
return available;
}
int read() override {
EthernetClientAccess access;
if (!access || !ethernet_client_attached.load()) return -1;
const uint8_t socket = ethernet_raw_client.getSocketNumber();
const int value = mesh::nrf52::EthernetCliTransmit::read(socket);
if (!mesh::nrf52::EthernetCliTransmit::commandReady(socket)) ethernet_require_command_check();
return value;
}
int peek() override {
EthernetClientAccess access;
if (!access || !ethernet_client_attached.load()) return -1;
const uint8_t socket = ethernet_raw_client.getSocketNumber();
const int value = mesh::nrf52::EthernetCliTransmit::peek(socket);
if (!mesh::nrf52::EthernetCliTransmit::commandReady(socket)) ethernet_require_command_check();
return value;
}
int availableForWrite() override {
EthernetClientAccess access;
return access && ethernet_client_attached.load() ? static_cast<int>(ethernet_queue_capacity()) : 0;
}
size_t write(uint8_t value) override { return write(&value, 1); }
size_t write(const uint8_t* data, size_t size) override {
EthernetClientAccess access;
if (!access || ethernet_session_reset.load()) return 0;
return ethernet_queue_write(data, size);
}
void flush() override {} // Never wait for a remote TCP host.
bool connected() {
EthernetClientAccess access;
return access && ethernet_client_attached.load() &&
mesh::nrf52::EthernetCliTransmit::connected(ethernet_raw_client.getSocketNumber());
}
explicit operator bool() { return connected(); }
void stop() {
EthernetClientAccess access;
if (!access) return;
if (ethernet_raw_client) {
(void)mesh::nrf52::EthernetCliTransmit::close(ethernet_raw_client.getSocketNumber());
ethernet_require_command_check();
}
ethernet_raw_client = EthernetClient();
ethernet_client_attached.store(false);
ethernet_session_generation.fetch_add(1);
ethernet_queue_clear();
ethernet_transmit.reset();
ethernet_line_discarding = false;
ethernet_session_reset.store(true);
}
using Print::write;
};
static EthernetCliClient ethernet_client;
static bool ethernet_configure(const EthernetCliHooks& hooks, bool saved_enabled = false) {
if (ethernet_bus_reserved || ethernet_worker_active.load()) return false;
ethernet_hooks = hooks;
ethernet_enabled.store(saved_enabled);
ethernet_state.store(EthernetCliState::Off);
return true;
}
static void ethernet_stop_hardware() {
// The W5100S has four sockets; there is no EthernetServer::end() in the
// library. Stop listener, accepted-client and DHCP sockets before SPI.end.
// Never toggle the PHY reset or shared WisBlock supply during shutdown.
if (ethernet_spi_started && ethernet_hardware_found) {
for (uint8_t index = 0; index < 4; ++index) {
(void)mesh::nrf52::EthernetCliTransmit::close(index);
}
}
ethernet_raw_client = EthernetClient();
ethernet_client_attached.store(false);
ethernet_session_generation.fetch_add(1);
ethernet_running.store(false);
if (ethernet_spi_started) {
ETHERNET_SPI_PORT.end();
digitalWrite(PIN_ETHERNET_SS, HIGH);
ethernet_spi_started = false;
}
ethernet_hardware_found = false;
ethernet_transmit.reset();
ethernet_queue_clear();
ethernet_command_check_requested.store(false);
}
static bool ethernet_complete_release() {
// Main-thread only. A stopped worker parks with its handle intact. Deleting
// that other task reclaims its stack synchronously; self-deletion would
// defer reclamation to the idle task and overlap the external OTA workspace.
if (ethernet_worker_active.load()) {
if (!ethernet_worker_stopped.load()) return false;
taskENTER_CRITICAL();
TaskHandle_t stopped = ethernet_task_handle;
ethernet_task_handle = nullptr;
taskEXIT_CRITICAL();
if (stopped != nullptr) vTaskDelete(stopped);
ethernet_worker_active.store(false);
ethernet_worker_stopped.store(false);
}
ethernet_stop_hardware();
free(ethernet_tx_queue);
ethernet_tx_queue = nullptr;
ethernet_line_discarding = false;
if (ethernet_bus_reserved) {
if (!ethernet_hooks.released(ethernet_hooks.context)) return false;
ethernet_bus_reserved = false;
ethernet_session_reset = true;
}
return true;
}
static void ethernet_worker_take_access() {
while (ethernet_spi_access.load() != EthernetSpiAccess::Worker) {
EthernetSpiAccess expected = EthernetSpiAccess::Idle;
if (ethernet_spi_access.compare_exchange_strong(expected, EthernetSpiAccess::Worker)) break;
vTaskDelay(pdMS_TO_TICKS(1));
}
ethernet_running.store(false);
}
static void ethernet_finish_task(EthernetCliState state) {
// No hardware operation follows this publication. Keep the handle and park
// until the main thread deletes this task before handing SPI back to OTA.
taskENTER_CRITICAL();
ethernet_state.store(state);
ethernet_running.store(false);
ethernet_worker_stopped.store(true);
taskEXIT_CRITICAL();
for (;;) vTaskDelay(portMAX_DELAY);
}
static bool ethernet_publish_online() {
taskENTER_CRITICAL();
const bool enabled = ethernet_enabled.load();
if (enabled) {
ethernet_state.store(EthernetCliState::Online);
ethernet_spi_access.store(EthernetSpiAccess::Idle);
ethernet_running.store(true);
}
taskEXIT_CRITICAL();
return enabled;
}
static void ethernet_cache_ip() {
const IPAddress ip = Ethernet.localIP();
ethernet_cached_ip.store(static_cast<uint32_t>(ip[0]) |
(static_cast<uint32_t>(ip[1]) << 8) |
(static_cast<uint32_t>(ip[2]) << 16) |
(static_cast<uint32_t>(ip[3]) << 24));
}
static bool ethernet_has_tx_work() {
taskENTER_CRITICAL();
const bool queued = ethernet_tx_count != 0;
taskEXIT_CRITICAL();
return queued || ethernet_transmit.pending();
}
static bool ethernet_controller_commands_idle() {
SPIClass* spi = W5100.getSPI();
if (!spi) return false;
spi->beginTransaction(SPI_ETHERNET_SETTINGS);
bool idle = true;
for (uint8_t socket = 0; socket < 4; ++socket) {
if (W5100.readSnCR(socket) != 0) idle = false;
}
spi->endTransaction();
return idle;
}
static void ethernet_poll_command_check() {
if (!ethernet_command_check_requested.load()) return;
if (ethernet_controller_commands_idle()) {
ethernet_command_check_requested.store(false);
} else if (static_cast<uint32_t>(millis() - ethernet_command_check_started.load()) >= 250) {
ethernet_controller_faulted = true;
ethernet_state.store(EthernetCliState::Faulted);
ethernet_session_reset.store(true);
}
}
// Worker-only, while SPI access is Worker. No library socketSend/execCmdSn
// calls: stalled TCP acknowledgement must never hold the mesh loop.
static void ethernet_pump_tx() {
ethernet_transmit.poll(millis());
if (ethernet_transmit.failed()) {
if (ethernet_raw_client) {
if (!mesh::nrf52::EthernetCliTransmit::close(ethernet_raw_client.getSocketNumber())) {
ethernet_controller_faulted = true;
ethernet_state.store(EthernetCliState::Faulted);
} else {
ethernet_require_command_check();
}
}
ethernet_raw_client = EthernetClient();
ethernet_client_attached.store(false);
ethernet_session_generation.fetch_add(1);
ethernet_queue_clear();
ethernet_transmit.reset();
ethernet_session_reset.store(true);
return;
}
if (!ethernet_raw_client) { ethernet_queue_clear(); return; }
// Main-loop accesses are excluded by the SPI gate while this worker owns it.
taskENTER_CRITICAL();
const size_t head = ethernet_tx_head;
const size_t count = ethernet_tx_count;
taskEXIT_CRITICAL();
if (count == 0) return;
const size_t contiguous = count < ETHERNET_CLI_TX_BUFFER_BYTES - head
? count : ETHERNET_CLI_TX_BUFFER_BYTES - head;
const size_t written = ethernet_transmit.write(ethernet_raw_client.getSocketNumber(),
ethernet_tx_queue + head, contiguous, millis());
taskENTER_CRITICAL();
ethernet_tx_head = (ethernet_tx_head + written) % ETHERNET_CLI_TX_BUFFER_BYTES;
ethernet_tx_count -= written;
taskEXIT_CRITICAL();
}
static void ethernet_drain_before_stop() {
if (!ethernet_spi_started || !ethernet_hardware_found) return;
const uint32_t started = millis();
while (ethernet_has_tx_work() && static_cast<uint32_t>(millis() - started) < 250) {
ethernet_pump_tx();
if (!ethernet_has_tx_work()) break;
(void)ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(10));
}
}
// Persistent background worker: both initial DHCP and renewal may wait for
// network responses. Main-loop Stream operations yield while it owns SPI.
// OFF interrupts retry waits, then lets an in-progress library call finish;
// never delete another task in the middle of its SPI transaction.
static void ethernet_task(void*) {
if (ethernet_enabled.load()) {
pinMode(PIN_ETHERNET_RESET, OUTPUT);
digitalWrite(PIN_ETHERNET_RESET, HIGH);
ETHERNET_SPI_PORT.begin();
ethernet_spi_started = true;
Ethernet.init(ETHERNET_SPI_PORT, PIN_ETHERNET_SS);
uint8_t mac[6];
generateEthernetMac(mac);
while (ethernet_enabled.load()) {
const bool connected = Ethernet.begin(mac, 10000, 2000) != 0;
ethernet_hardware_found = Ethernet.hardwareStatus() != EthernetNoHardware;
if (!ethernet_enabled.load()) break;
if (!ethernet_hardware_found) {
ethernet_stop_hardware();
ethernet_finish_task(EthernetCliState::NoHardware);
return;
}
if (connected) {
ethernet_server.begin();
ethernet_cache_ip();
ethernet_last_maintain.store(millis());
if (!ethernet_publish_online()) break;
for (;;) {
// An online OFF is notified by the next mesh-loop maintain call,
// allowing a command received over Ethernet to send its reply first.
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(20));
if (!ethernet_enabled.load()) break;
if (ethernet_controller_faulted) continue;
const bool maintain = ethernet_maintain_requested.exchange(false);
ethernet_worker_take_access();
ethernet_poll_command_check();
if (ethernet_controller_faulted || ethernet_command_check_requested.load()) {
// Preserve the maintenance request while command checking yields.
if (maintain) ethernet_maintain_requested.store(true);
continue;
}
if (maintain) (void)Ethernet.maintain();
if (!ethernet_enabled.load()) break;
if (maintain) ethernet_last_maintain.store(millis());
// Do not enter vendor accept/relisten while SEND/RECV is pending.
if (!ethernet_transmit.pending()) ethernet_check_client();
ethernet_pump_tx();
if (ethernet_controller_faulted || ethernet_transmit.pending() ||
ethernet_command_check_requested.load()) continue;
ethernet_cache_ip();
if (!ethernet_publish_online()) break;
}
break;
}
ethernet_state.store(EthernetCliState::Retrying);
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(ETHERNET_RETRY_INTERVAL_MS));
}
}
ethernet_worker_take_access();
ethernet_drain_before_stop();
ethernet_stop_hardware();
ethernet_finish_task(EthernetCliState::Stopping);
}
static bool ethernet_request_start(char* reply, bool persist) {
if (ethernet_state.load() == EthernetCliState::Stopping) {
strcpy(reply, "Error: Ethernet is still stopping");
return false;
}
if (ethernet_worker_stopped.load() && !ethernet_complete_release()) {
strcpy(reply, "Error: Ethernet bus release is still pending");
return false;
}
if (ethernet_worker_active.load() || ethernet_running.load()) {
strcpy(reply, "OK - Ethernet already on");
return true;
}
if (ethernet_bus_reserved && !ethernet_complete_release()) {
strcpy(reply, "Error: Ethernet bus release is still pending");
return false;
}
if (!ethernet_hooks.prepare || !ethernet_hooks.can_release || !ethernet_hooks.released) {
strcpy(reply, "Error: Ethernet bus safety hooks unavailable");
return false;
}
reply[0] = 0;
if (!ethernet_hooks.prepare(ethernet_hooks.context, reply, 160)) {
if (!reply[0]) strcpy(reply, "Error: Ethernet bus is busy");
return false;
}
ethernet_bus_reserved = true;
ethernet_tx_queue = static_cast<uint8_t*>(malloc(ETHERNET_CLI_TX_BUFFER_BYTES));
if (!ethernet_tx_queue) {
(void)ethernet_complete_release();
ethernet_state.store(EthernetCliState::StartFailed);
strcpy(reply, "Error: Ethernet queue allocation failed");
return false;
}
ethernet_queue_clear();
if (persist && ethernet_hooks.save && !ethernet_hooks.save(ethernet_hooks.context, true)) {
(void)ethernet_complete_release();
strcpy(reply, "Error: cannot save Ethernet mode");
return false;
}
ethernet_enabled.store(true);
ethernet_controller_faulted = false;
ethernet_command_check_requested.store(false);
ethernet_maintain_requested.store(false);
ethernet_spi_access.store(EthernetSpiAccess::Worker);
ethernet_state.store(EthernetCliState::Starting);
ethernet_worker_stopped.store(false);
ethernet_worker_active.store(true);
// Ensure a fast worker cannot clear the output handle before creation has
// finished publishing it. Handle notification/clearing use the same guard.
taskENTER_CRITICAL();
const BaseType_t created = xTaskCreate(ethernet_task, "eth_init",
RAK4631_ETHERNET_TASK_STACK_WORDS, nullptr, 1, &ethernet_task_handle);
taskEXIT_CRITICAL();
if (created != pdPASS) {
ethernet_task_handle = nullptr;
ethernet_enabled.store(false);
ethernet_worker_active.store(false);
(void)ethernet_complete_release();
ethernet_state.store(EthernetCliState::StartFailed);
strcpy(reply, "Error: Ethernet task allocation failed");
return false;
}
strcpy(reply, ethernet_hooks.save
? "OK - Ethernet starting; use eth.status"
: "OK - Ethernet starting until restart; use eth.status");
return true;
}
static bool ethernet_request_stop(char* reply) {
if (ethernet_bus_reserved && !ethernet_hooks.can_release(ethernet_hooks.context)) {
strcpy(reply, "Error: Ethernet mode is locked by OTA activity or staged data");
return false;
}
if (ethernet_hooks.save && !ethernet_hooks.save(ethernet_hooks.context, false)) {
strcpy(reply, "Error: cannot save Ethernet mode");
return false;
}
taskENTER_CRITICAL();
ethernet_enabled.store(false);
const bool active = ethernet_worker_active.load() || ethernet_bus_reserved;
ethernet_state.store(active ? EthernetCliState::Stopping : EthernetCliState::Off);
taskEXIT_CRITICAL();
// Startup/renewal already owns SPI, so wake cancellation immediately.
// Online OFF waits for the next main-loop maintain to preserve its reply.
if (ethernet_spi_access.load() == EthernetSpiAccess::Worker) ethernet_notify_worker();
strcpy(reply, active
? (ethernet_hooks.save ? "OK - Ethernet stopping" : "OK - Ethernet stopping until restart")
: (ethernet_hooks.save ? "OK - Ethernet off" : "OK - Ethernet off until restart"));
return true;
}
static void ethernet_start_task() {
if (!ethernet_enabled.load()) return;
char reply[160];
(void)ethernet_request_start(reply, false);
}
static void ethernet_request_maintenance() {
EthernetSpiAccess expected = EthernetSpiAccess::Idle;
if (!ethernet_spi_access.compare_exchange_strong(expected, EthernetSpiAccess::Worker)) return;
ethernet_running.store(false);
ethernet_state.store(EthernetCliState::Maintaining);
ethernet_last_maintain.store(millis());
ethernet_maintain_requested.store(true);
ethernet_notify_worker();
}
+219
View File
@@ -0,0 +1,219 @@
#pragma once
#include <RAK13800_W5100S.h>
#include <w5100.h>
#include <stddef.h>
#include <stdint.h>
namespace mesh {
namespace nrf52 {
#ifndef RAK4631_ETHERNET_SEND_TIMEOUT_MS
#define RAK4631_ETHERNET_SEND_TIMEOUT_MS 250u
#endif
static_assert(RAK4631_ETHERNET_SEND_TIMEOUT_MS > 0u &&
RAK4631_ETHERNET_SEND_TIMEOUT_MS < 0x80000000u,
"Ethernet send deadline must support wrap-safe elapsed time");
// The vendor socketSend()/execCmdSn() wait for ACK/command completion without
// a software deadline. Queue one SEND directly in the controller, then inspect
// its completion on later worker turns. Every method has a finite number of
// register transfers and never owns heap storage or waits for network traffic.
class EthernetCliTransmit {
static constexpr uint8_t NO_SOCKET = 0xFFu;
static constexpr uint8_t SOCKET_COUNT = 4u; // RAK13800's exact W5100S
static constexpr uint8_t FREE_SIZE_READS = 4u;
uint8_t _socket = NO_SOCKET;
bool _pending = false;
bool _failed = false;
bool _waiting_command = false;
uint32_t _started = 0;
class Transaction {
SPIClass* _spi;
public:
Transaction() : _spi(W5100.getSPI()) {
if (_spi) _spi->beginTransaction(SPI_ETHERNET_SETTINGS);
}
~Transaction() { if (_spi) _spi->endTransaction(); }
explicit operator bool() const { return _spi != nullptr; }
};
static bool usableStatus(uint8_t status) {
return status == SnSR::ESTABLISHED || status == SnSR::CLOSE_WAIT;
}
static bool socketValid(uint8_t socket) {
return socket < SOCKET_COUNT && W5100.getChip() == 51u;
}
static bool receiveSize(uint8_t socket, uint16_t& size) {
uint16_t previous = W5100.readSnRX_RSR(socket);
for (uint8_t count = 1u; count < FREE_SIZE_READS; ++count) {
const uint16_t current = W5100.readSnRX_RSR(socket);
if (current == previous) {
size = current;
return current <= W5100.SSIZE;
}
previous = current;
}
return false;
}
static int receiveByte(uint8_t socket, bool consume) {
if (!socketValid(socket)) return -1;
Transaction transaction;
if (!transaction || !usableStatus(W5100.readSnSR(socket)) ||
W5100.readSnCR(socket) != 0u) return -1;
uint16_t size = 0u;
if (!receiveSize(socket, size) || !size) return -1;
const uint16_t pointer = W5100.readSnRX_RD(socket);
uint8_t value = 0u;
if (W5100.read(static_cast<uint16_t>(W5100.RBASE(socket) + (pointer & W5100.SMASK)),
&value, 1u) != 1u) return -1;
if (consume) {
W5100.writeSnRX_RD(socket, static_cast<uint16_t>(pointer + 1u));
W5100.writeSnCR(socket, Sock_RECV);
}
return value;
}
bool expired(uint32_t now) const {
return static_cast<uint32_t>(now - _started) >= RAK4631_ETHERNET_SEND_TIMEOUT_MS;
}
void fail() {
_failed = true;
_pending = false;
_waiting_command = false;
}
public:
bool pending() const { return _pending || _waiting_command; }
bool failed() const { return _failed; }
void reset() {
_socket = NO_SOCKET;
_pending = _failed = _waiting_command = false;
_started = 0;
}
void poll(uint32_t now) {
if (_failed || (!_pending && !_waiting_command)) return;
Transaction transaction;
if (!transaction) { fail(); return; }
if (!usableStatus(W5100.readSnSR(_socket))) { fail(); return; }
const uint8_t interrupt = W5100.readSnIR(_socket);
if (interrupt & SnIR::TIMEOUT) {
W5100.writeSnIR(_socket, SnIR::TIMEOUT | SnIR::SEND_OK);
fail();
return;
}
const uint8_t command = W5100.readSnCR(_socket);
if (_pending && (interrupt & SnIR::SEND_OK) && command == 0u) {
W5100.writeSnIR(_socket, SnIR::SEND_OK);
_pending = false;
return;
}
if (_waiting_command && command == 0u) {
_waiting_command = false;
return;
}
if (expired(now)) fail();
}
size_t write(uint8_t socket, const uint8_t* data, size_t length, uint32_t now) {
if (!data || !length || _failed) return 0u;
if (socket >= SOCKET_COUNT || W5100.getChip() != 51u) { fail(); return 0u; }
if (_socket != NO_SOCKET && _socket != socket) { fail(); return 0u; }
_socket = socket;
poll(now);
if (_failed || _pending || _waiting_command) return 0u;
Transaction transaction;
if (!transaction) { fail(); return 0u; }
if (!usableStatus(W5100.readSnSR(socket))) { fail(); return 0u; }
if (W5100.readSnCR(socket) != 0u) {
_waiting_command = true;
_started = now;
return 0u;
}
if (!W5100.SSIZE || W5100.SMASK != W5100.SSIZE - 1u) { fail(); return 0u; }
// A 16-bit free-size register can change between byte reads. The vendor
// retries forever for a matching pair; retain backpressure after at most
// four reads and try again on a later worker turn instead.
uint16_t previous = W5100.readSnTX_FSR(socket);
uint16_t available = 0u;
bool stable = false;
for (uint8_t count = 1u; count < FREE_SIZE_READS; ++count) {
const uint16_t current = W5100.readSnTX_FSR(socket);
if (current == previous) { available = current; stable = true; break; }
previous = current;
}
if (!stable || !available) return 0u;
if (available > W5100.SSIZE) { fail(); return 0u; }
if (length > available) length = available;
const uint16_t count = static_cast<uint16_t>(length);
const uint16_t pointer = W5100.readSnTX_WR(socket);
const uint16_t offset = pointer & W5100.SMASK;
const uint16_t first = count <= W5100.SSIZE - offset
? count : static_cast<uint16_t>(W5100.SSIZE - offset);
if (W5100.write(static_cast<uint16_t>(W5100.SBASE(socket) + offset), data, first) != first) {
fail();
return 0u;
}
if (first < count && W5100.write(W5100.SBASE(socket), data + first,
static_cast<uint16_t>(count - first)) != count - first) {
fail();
return 0u;
}
W5100.writeSnTX_WR(socket, static_cast<uint16_t>(pointer + count));
W5100.writeSnIR(socket, SnIR::SEND_OK | SnIR::TIMEOUT); // revoke stale completion
W5100.writeSnCR(socket, Sock_SEND); // deliberately do not call execCmdSn()
_started = now;
_pending = true;
return count;
}
static bool close(uint8_t socket) {
if (socket >= SOCKET_COUNT || W5100.getChip() != 51u) return false;
Transaction transaction;
if (!transaction || W5100.readSnCR(socket) != 0u) return false;
W5100.writeSnCR(socket, Sock_CLOSE);
return true;
}
static bool commandReady(uint8_t socket) {
if (!socketValid(socket)) return false;
Transaction transaction;
return transaction && W5100.readSnCR(socket) == 0u;
}
static int available(uint8_t socket) {
if (!socketValid(socket)) return 0;
Transaction transaction;
if (!transaction || !usableStatus(W5100.readSnSR(socket)) ||
W5100.readSnCR(socket) != 0u) return 0;
uint16_t size = 0u;
return receiveSize(socket, size) ? size : 0;
}
static int peek(uint8_t socket) { return receiveByte(socket, false); }
static int read(uint8_t socket) { return receiveByte(socket, true); }
static bool connected(uint8_t socket) {
if (!socketValid(socket)) return false;
Transaction transaction;
if (!transaction) return false;
const uint8_t status = W5100.readSnSR(socket);
if (status == SnSR::ESTABLISHED) return true;
if (status != SnSR::CLOSE_WAIT) return false;
uint16_t size = 0u;
// An unstable size snapshot is backpressure, not proof of EOF. Retain
// the client until a stable zero proves its final bytes were consumed.
return !receiveSize(socket, size) || size != 0u;
}
};
} // namespace nrf52
} // namespace mesh
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#if defined(RAK4631_COMBINED_ETHERNET)
#include <atomic>
namespace mesh {
namespace ota {
// The combined RAK4631 image gives the WisBlock clock/data pins to one
// controller at a time. Reserve them before starting Ethernet's DHCP task;
// release them only after that task and every Ethernet socket have stopped.
// NOR discovery and QSPI staging must never touch these pins while reserved.
inline std::atomic<bool>& rak4631_ethernet_spi_owner() {
static std::atomic<bool> owner{false};
return owner;
}
inline bool rak4631_ethernet_owns_spi() {
return rak4631_ethernet_spi_owner().load(std::memory_order_acquire);
}
inline void rak4631_set_ethernet_spi_owner(bool ethernet) {
rak4631_ethernet_spi_owner().store(ethernet, std::memory_order_release);
}
} // namespace ota
} // namespace mesh
#endif
+114
View File
@@ -137,6 +137,9 @@ struct OtaContext {
// store. A failed allocation is reported by the CLI before any write.
uint8_t* serve_buf = nullptr;
bool ensureServeBuffer() {
#if defined(RAK4631_COMBINED_ETHERNET)
if (rak4631_ethernet_owns_spi()) return false;
#endif
if (!serve_buf) serve_buf = static_cast<uint8_t*>(malloc(OTA_SERVE_BUF_SIZE));
return serve_buf != nullptr;
}
@@ -470,6 +473,12 @@ struct OtaContext {
bool attach_folder_source(MotaSource* source, FolderLink link, const char* label,
char* msg, size_t cap) {
if (!msg || cap == 0) return false;
#if defined(RAK4631_COMBINED_ETHERNET)
if (rak4631_ethernet_owns_spi()) {
snprintf(msg, cap, "ERR turn Ethernet off before attaching an OTA folder");
return false;
}
#endif
if (!source || link == FOLDER_LINK_NONE) {
strncpy(msg, "ERR invalid folder source", cap);
msg[cap - 1] = 0;
@@ -564,6 +573,111 @@ struct OtaContext {
}
}
#if defined(RAK4631_COMBINED_ETHERNET)
// Only the main thread may change ownership. No allocation or SPI access in
// the DHCP worker is allowed until prepareRakEthernet() has finished.
bool canReleaseRakEthernet() const {
const bool own_image = manager.servingPrimaryManifest(serve_self_manifest);
return manager.fetchState() == OtaManager::IDLE &&
fetch_store.staged_size() == 0u && !apply_pending && !bootloader_apply_pending &&
!manager.pendingServeJobs() && !manager.pendingManifestJobs() &&
(!serving || own_image) && manager.servedCount() <= (own_image ? 1u : 0u) &&
serve_expected == 0u && !folder_active && !_folder_source && !folder_dest &&
!disconnected_folder_dest && !fetch_to_folder;
}
void refreshRakStorageCapabilities() {
const bool external = !rak4631_ethernet_owns_spi() && fetch_store.usesExternal();
manager.set_accept_full(external);
manager.set_accept_bootloader(
ota_bootloader_self_update_caps_valid(bootloaderUpdateCaps()));
manager.set_apply_codec(CODEC_DETOOLS_INPLACE);
manager.set_fetch_store(&fetch_store);
manager.set_archive_interest(false);
self_serve_supported = ota_self_serve_supported(external);
#if MESHCORE_OTA_DEVICE_DEFLATE
manager.set_transport_deflate_encoder(self_serve_supported ? ota_transport_deflate : nullptr);
#endif
}
void releaseRakIdleServingBuffers() {
// The idle preflight admits only our automatic own-image view, never a
// manual or folder source. Revoke it before freeing the caller-owned RAM.
manager.clear_primary();
serving = false;
free(serve_self_leaves); free(serve_self_proof);
serve_self_leaves = serve_self_proof = nullptr;
releaseServeBuffer();
serve_expected = 0u;
}
bool prepareRakEthernet(char* error, size_t cap) {
if (!error || !cap) return false;
error[0] = 0;
if (rak4631_ethernet_owns_spi()) {
snprintf(error, cap, "ERR Ethernet already owns WisBlock SPI");
return false;
}
if (!canReleaseRakEthernet()) {
snprintf(error, cap, "ERR OTA busy; cancel transfer, clear manual serve and detach folder first");
return false;
}
const uint8_t detected = OtaStoreQspiNrf52::autoDetect();
uint32_t rak_id = 0, w25_id = 0;
OtaStoreQspiNrf52::autoProbeIds(rak_id, w25_id);
(void)w25_id;
if (detected == 1u || detected == 3u) {
snprintf(error, cap, "ERR RAK15001 and Ethernet share chip-select 26; remove RAK15001 first");
return false;
}
if (rak_id != 0u && rak_id != 0xFFFFFFu) {
snprintf(error, cap, "ERR unknown SPI device on Ethernet chip-select 26 (%06lX)",
(unsigned long)rak_id);
return false;
}
const OtaBlCaps& caps = bootloaderAppCaps();
const bool qspi_bootloader = caps.present && (caps.storage_flags & OTA_BL_STORAGE_QSPI);
const OtaBootloaderIdentity& identity = bootloaderIdentity();
if (rak_storage_choice(0u, qspi_bootloader, identity.present && identity.crc_ok,
identity.device_name, false,
caps.optional_app_storage ==
(OTA_BL_STORAGE_QSPI | OTA_BL_STORAGE_HEADER_W25)) !=
RakStorageChoice::Internal) {
snprintf(error, cap, "ERR installed bootloader cannot use internal OTA with Ethernet");
return false;
}
if (!fetch_store.resetSelection()) {
snprintf(error, cap, "ERR staged OTA data must be cancelled before enabling Ethernet");
return false;
}
releaseRakIdleServingBuffers();
rak4631_set_ethernet_spi_owner(true);
refreshRakStorageCapabilities();
// The policy check above and the adaptive store must agree before the
// caller allocates a worker or lets the Ethernet library touch hardware.
if (!fetch_store.usesInternal()) {
rak4631_set_ethernet_spi_owner(false);
fetch_store.resetSelection();
refreshRakStorageCapabilities();
snprintf(error, cap, "ERR internal OTA selection failed; Ethernet remains off");
return false;
}
return true;
}
bool releaseRakEthernet() {
if (!rak4631_ethernet_owns_spi()) return true;
// OFF is cooperative. A transfer can start after its first preflight;
// keep the safe internal backend pinned and let the main loop retry after
// cancellation/completion. The Ethernet worker and SPI are already gone.
if (!canReleaseRakEthernet() || !fetch_store.resetSelection()) return false;
releaseRakIdleServingBuffers();
rak4631_set_ethernet_spi_owner(false);
refreshRakStorageCapabilities();
return true;
}
#endif
#if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
OtaStoreSdNrf52& sdStagingStore() {
#if defined(OTA_TOWER_AUTO_STORE)
+8
View File
@@ -1,4 +1,7 @@
#include "OtaDeflate.h"
#if defined(RAK4631_COMBINED_ETHERNET)
#include "../nrf52/Rak4631SharedSpi.h"
#endif
#if defined(ENABLE_OTA) || defined(OTA_TRANSPORT_DEFLATE_TEST)
@@ -30,6 +33,11 @@ bool ota_transport_deflate(void* context, const uint8_t* src, uint16_t src_len,
uint8_t* dst, uint16_t dst_cap, uint16_t* dst_len) {
(void)context;
if (dst_len) *dst_len = 0;
#if defined(RAK4631_COMBINED_ETHERNET)
// The Ethernet worker and encoder workspace share the combined image's
// runtime RAM allowance. Refuse before tinydeflate can allocate its table.
if (rak4631_ethernet_owns_spi()) return false;
#endif
if (!src || src_len < 3 || src_len > MESHCORE_OTA_DEFLATE_BLOCK_MAX ||
!dst || !dst_cap || !dst_len) return false;
// Proof/output scratch is disjoint from the manager's raw input. Reject
+5
View File
@@ -198,6 +198,11 @@ static uint32_t parse_fw_version(const char* s) {
}
bool ota_serve_self(OtaContext& c, uint32_t fw_version) {
#if defined(RAK4631_COMBINED_ETHERNET)
// Also cover diagnostic `ota dev serve self`, which bypasses the public
// default-self-serve gate. Ethernet owns the alternative RAM workspace.
if (rak4631_ethernet_owns_spi()) return false;
#endif
// Derive our version from the build string when the caller didn't supply one, so the mOTA we advertise
// carries a real version (was hard-coded 0 -> peers saw "v0.0.0"). A dev build with no dotted number
// still reads 0 - the self-describing EndF identity (docs) is the durable fix for that.
+44
View File
@@ -8,6 +8,9 @@
#include "OtaStoreFlashNrf52.h"
#include "OtaStoreQspiNrf52.h"
#include "OtaRakStoragePolicy.h"
#if defined(RAK4631_COMBINED_ETHERNET)
#include "../nrf52/Rak4631SharedSpi.h"
#endif
#include <new>
namespace mesh {
@@ -63,7 +66,12 @@ class OtaStoreAdaptiveNrf52 : public OtaStore {
void select() const {
if (_mode != UNSELECTED) return;
#if defined(RAK4631_COMBINED_ETHERNET)
const bool ethernet = rak4631_ethernet_owns_spi();
const uint8_t detected = ethernet ? 0u : OtaStoreQspiNrf52::autoDetect();
#else
const uint8_t detected = OtaStoreQspiNrf52::autoDetect();
#endif
const OtaBlCaps caps = ota_bootloader_app_caps();
if (detected == 3u) {
_mode = UNSAFE;
@@ -92,6 +100,12 @@ class OtaStoreAdaptiveNrf52 : public OtaStore {
caps.optional_app_storage == (OTA_BL_STORAGE_QSPI | OTA_BL_STORAGE_HEADER_W25));
if (choice == RakStorageChoice::Internal) {
activateInternal();
#if defined(RAK4631_COMBINED_ETHERNET)
if (ethernet) {
_reason = "Ethernet active; internal application deltas only";
return;
}
#endif
_reason = detected == 0u ? "no external NOR" :
"external NOR fitted; internal bootloader";
return;
@@ -103,6 +117,12 @@ class OtaStoreAdaptiveNrf52 : public OtaStore {
return;
}
_mode = UNSAFE;
#if defined(RAK4631_COMBINED_ETHERNET)
if (ethernet) {
_reason = "Ethernet active; bootloader lacks internal OTA";
return;
}
#endif
if (detected == 0u) {
_reason = "QSPI bootloader but no matched external NOR";
} else if (!identity_valid) {
@@ -114,16 +134,40 @@ class OtaStoreAdaptiveNrf52 : public OtaStore {
OtaStore* active() {
select();
#if defined(RAK4631_COMBINED_ETHERNET)
if (_mode == QSPI_MODE && rak4631_ethernet_owns_spi()) return nullptr;
#endif
return _mode == QSPI_MODE ? static_cast<OtaStore*>(&_storage.external) :
_mode == INTERNAL_MODE ? static_cast<OtaStore*>(&_storage.internal) : nullptr;
}
const OtaStore* active() const {
select();
#if defined(RAK4631_COMBINED_ETHERNET)
if (_mode == QSPI_MODE && rak4631_ethernet_owns_spi()) return nullptr;
#endif
return _mode == QSPI_MODE ? static_cast<const OtaStore*>(&_storage.external) :
_mode == INTERNAL_MODE ? static_cast<const OtaStore*>(&_storage.internal) : nullptr;
}
public:
#if defined(RAK4631_COMBINED_ETHERNET)
// Only the main-loop handoff may reset the selection, after OtaContext has
// proved that no receive/apply session is active. Never discard staged data
// as a side effect of changing a network setting.
bool resetSelection() {
if (_mode == QSPI_MODE) {
if (_storage.external.staged_size() != 0u) return false;
_storage.external.~OtaStoreQspiNrf52();
} else if (_mode == INTERNAL_MODE) {
if (_storage.internal.staged_size() != 0u) return false;
_storage.internal.~OtaStoreFlashNrf52();
}
_mode = UNSELECTED;
_reason = "not probed";
_bootloader_store = false;
return true;
}
#endif
~OtaStoreAdaptiveNrf52() override {
if (_mode == QSPI_MODE) _storage.external.~OtaStoreQspiNrf52();
else if (_mode == INTERNAL_MODE) _storage.internal.~OtaStoreFlashNrf52();
+28 -3
View File
@@ -13,6 +13,9 @@
#include <SPI.h>
#endif
#include <string.h>
#if defined(RAK4631_COMBINED_ETHERNET)
#include "../nrf52/Rak4631SharedSpi.h"
#endif
namespace mesh {
namespace ota {
@@ -324,6 +327,11 @@ static uint32_t probe_nor(uint8_t cs) {
#if defined(OTA_RAK_AUTO_STORE)
uint8_t OtaStoreQspiNrf52::autoDetect() {
#if defined(RAK4631_COMBINED_ETHERNET)
// Do not even bit-bang a JEDEC probe while the Ethernet task owns SPI.
// Leave the cached physical discovery unchanged for the next idle handoff.
if (rak4631_ethernet_owns_spi()) return 0u;
#endif
if (auto_detection != 0xFFu) return auto_detection;
const uint8_t w25_cs = arduino_to_physical(31);
@@ -479,6 +487,12 @@ bool OtaStoreQspiNrf52::waitMemoryReady(uint32_t timeout_ms) {
}
bool OtaStoreQspiNrf52::ensureFlash() {
#if defined(RAK4631_COMBINED_ETHERNET)
if (rak4631_ethernet_owns_spi()) {
fail("Ethernet owns WisBlock SPI; external OTA unavailable");
return false;
}
#endif
if (_qspi_ready) return true;
#if defined(OTA_QSPI_RAK3401_RADIO_BUS_HANDOFF)
@@ -613,7 +627,11 @@ bool OtaStoreQspiNrf52::ensureFlash() {
}
void OtaStoreQspiNrf52::releaseFlash() {
if (_qspi_awake && !_memory_operation_pending) {
bool send_power_down = _qspi_awake && !_memory_operation_pending;
#if defined(RAK4631_COMBINED_ETHERNET)
send_power_down = send_power_down && !rak4631_ethernet_owns_spi();
#endif
if (send_power_down) {
// The repeater can remain idle for hours after a capacity/status probe or
// a completed checkpoint. Put the NOR into deep power-down before
// releasing the nRF QSPI peripheral instead of leaving both active for
@@ -632,7 +650,14 @@ void OtaStoreQspiNrf52::releaseFlash() {
// disabling the peripheral. Trigger it after every successful ENABLE, even
// when wake or JEDEC identification failed before _qspi_ready was set.
if (_qspi_active) {
if (_memory_operation_pending) {
#if defined(RAK4631_COMBINED_ETHERNET)
// Also release the QSPI pin assignments after a successful operation so
// the Ethernet SPIM can safely acquire the same pads at an idle handoff.
const bool disconnect_pins = true;
#else
const bool disconnect_pins = _memory_operation_pending;
#endif
if (disconnect_pins) {
// QSPI owns pin direction while enabled. Preload and configure CS# high
// before releasing the peripheral so an unresolved NOR operation cannot
// see a floating or asserted chip select during the handoff.
@@ -645,7 +670,7 @@ void OtaStoreQspiNrf52::releaseFlash() {
nrf_qspi_task_trigger(NRF_QSPI, NRF_QSPI_TASK_DEACTIVATE);
nrf_qspi_disable(NRF_QSPI);
nrf_qspi_event_clear(NRF_QSPI, NRF_QSPI_EVENT_READY);
if (_memory_operation_pending) {
if (disconnect_pins) {
#if defined(OTA_QSPI_RAK3401_RADIO_BUS_HANDOFF)
disconnect_qspi_pins();
#else
+8 -1
View File
@@ -6,10 +6,17 @@
#error "OTA_QSPI_STORE raw staging cannot share a QSPI chip with QSPIFLASH"
#endif
#if defined(OTA_QSPI_SHARED_WISBLOCK_SPI) && defined(ETHERNET_ENABLED)
#if defined(OTA_QSPI_SHARED_WISBLOCK_SPI) && defined(ETHERNET_ENABLED) && \
!defined(RAK4631_COMBINED_ETHERNET)
#error "WisBlock SPI OTA staging cannot share the bus/chip-select with Ethernet"
#endif
#if defined(RAK4631_COMBINED_ETHERNET) && \
(!defined(NRF52_PLATFORM) || !defined(RAK_4631) || !defined(OTA_RAK_AUTO_STORE) || \
!defined(OTA_QSPI_SHARED_WISBLOCK_SPI) || !defined(ETHERNET_ENABLED))
#error "Combined RAK4631 Ethernet requires its adaptive OTA and shared-SPI ownership contract"
#endif
#if defined(OTA_QSPI_SHARED_WISBLOCK_SPI) && defined(OTA_SD_STORE)
#error "WisBlock SPI OTA staging cannot share the bus/chip-select with SD staging"
#endif
+11
View File
@@ -1,5 +1,16 @@
#include "SSD1306Display.h"
#if defined(NRF52_PLATFORM) && defined(RAK4631_COMBINED_ETHERNET)
// Adafruit_SSD1306::begin allocates WIDTH * ((HEIGHT + 7) / 8) once and
// reuses that framebuffer on later begin calls. The driver itself is embedded
// in the linked global display, not allocated on the heap. Even including
// that object again plus allocator overhead fits the combined 2 KiB bound.
static_assert(SSD1306Display::FRAMEBUFFER_BYTES == 1024,
"Update the combined RAK OLED framebuffer budget");
static_assert(sizeof(SSD1306Display) + SSD1306Display::FRAMEBUFFER_BYTES + 32 <= 2048,
"Update the combined RAK OLED runtime budget");
#endif
bool SSD1306Display::i2c_probe(TwoWire& wire, uint8_t addr) {
wire.beginTransmission(addr);
uint8_t error = wire.endTransmission();
+7 -2
View File
@@ -16,6 +16,11 @@
#endif
class SSD1306Display : public DisplayDriver {
public:
static constexpr int16_t PANEL_WIDTH = 128;
static constexpr int16_t PANEL_HEIGHT = 64;
static constexpr size_t FRAMEBUFFER_BYTES = PANEL_WIDTH * ((PANEL_HEIGHT + 7) / 8);
private:
Adafruit_SSD1306 display;
bool _isOn;
bool _panel_ready = false;
@@ -32,8 +37,8 @@ class SSD1306Display : public DisplayDriver {
bool i2c_probe(TwoWire& wire, uint8_t addr);
void applyRotation();
public:
SSD1306Display(RefCountedDigitalPin* peripher_power=NULL) : DisplayDriver(128, 64),
display(128, 64, &Wire, PIN_OLED_RESET),
SSD1306Display(RefCountedDigitalPin* peripher_power=NULL) : DisplayDriver(PANEL_WIDTH, PANEL_HEIGHT),
display(PANEL_WIDTH, PANEL_HEIGHT, &Wire, PIN_OLED_RESET),
_peripher_power(peripher_power)
{
_isOn = false;