Harden nRF52 OTA, USB sessions, and T096 controls

Bind Companion replies to request transports, make dual-CDC USB sessions nonblocking and reconnect-safe, and harden nRF52 watchdog/OTA storage paths. Fix T096 button debounce, display wake, sleep races, and the compact message layout; add exact WisBlock OTA profiles plus expanded native/static/HIL documentation.
This commit is contained in:
mikecarper committed 2026-09-01 20:51:43 -07:00
1 parent fcd1f8cc6c
commit ecaa5ac2a0
61 files changed
+4446 -226

No files matched your search

+30 -4
View File
@@ -45,7 +45,8 @@ void Dispatcher::setRadioAvailable(bool available) {
const unsigned long now = _ms->getMillis();
radio_nonrx_start = now;
next_floor_calib_time = now;
next_agc_reset_time = now;
armed_agc_reset_interval = 0;
agc_reset_armed = false;
_radio->begin();
prev_isrecv_mode = _radio->isInRecvMode();
last_observed_radio_irq = _radio->getLastRadioInterruptMillis();
@@ -73,6 +74,8 @@ void Dispatcher::begin() {
last_budget_update = _ms->getMillis();
const unsigned long now = _ms->getMillis();
armed_agc_reset_interval = 0;
agc_reset_armed = false;
dispatcher_started = true;
if (radio_available) {
_radio->begin();
@@ -461,12 +464,35 @@ void Dispatcher::loop() {
}
// going back into receive mode now...
next_agc_reset_time = futureMillis(getAGCResetInterval());
const int agc_interval = getAGCResetInterval();
if (agc_interval > 0) {
next_agc_reset_time = futureMillis(agc_interval);
armed_agc_reset_interval = agc_interval;
agc_reset_armed = true;
} else {
armed_agc_reset_interval = 0;
agc_reset_armed = false;
}
}
if (getAGCResetInterval() > 0 && millisHasNowPassed(next_agc_reset_time)) {
const int agc_interval = getAGCResetInterval();
if (agc_interval <= 0) {
armed_agc_reset_interval = 0;
agc_reset_armed = false;
} else if (!agc_reset_armed
|| agc_interval != armed_agc_reset_interval) {
// MyMesh loads persisted preferences after Dispatcher::begin(). Arm from
// the first loop so the real configured interval is used, and so a freshly
// initialized radio/frontend gets one full settle interval before the
// first warm-sleep AGC reset. A live interval change also gets a complete
// new interval instead of inheriting the old setting's deadline.
next_agc_reset_time = futureMillis(agc_interval);
armed_agc_reset_interval = agc_interval;
agc_reset_armed = true;
} else if (millisHasNowPassed(next_agc_reset_time)) {
_radio->resetAGC();
next_agc_reset_time = futureMillis(getAGCResetInterval());
next_agc_reset_time = futureMillis(agc_interval);
armed_agc_reset_interval = agc_interval;
}
// check inbound (delayed) queue
+4
View File
@@ -250,6 +250,8 @@ class Dispatcher {
unsigned long cad_busy_start;
unsigned long radio_nonrx_start;
unsigned long next_floor_calib_time, next_agc_reset_time;
int armed_agc_reset_interval;
bool agc_reset_armed;
bool prev_isrecv_mode;
bool radio_available;
bool dispatcher_started;
@@ -290,6 +292,8 @@ protected:
next_tx_time = ms.getMillis();
cad_busy_start = 0;
next_floor_calib_time = next_agc_reset_time = 0;
armed_agc_reset_interval = 0;
agc_reset_armed = false;
_err_flags = 0;
radio_nonrx_start = 0;
prev_isrecv_mode = true;
+14
View File
@@ -25,6 +25,20 @@ public:
// Returns true once for each pending Bluetooth pairing prompt. Non-BLE
// transports keep the default implementation so UI code can poll safely.
virtual bool takePairingRequest() { return false; }
// Capture and later address the transport which supplied the current
// command. Multi-transport implementations override these so asynchronous
// replies do not follow a newer client's command or fall back to broadcast.
virtual BaseSerialInterface* captureReplyRoute() { return this; }
virtual bool isReplyRouteAvailable(BaseSerialInterface* route) const {
return route == this && isEnabled() && isConnected();
}
virtual bool isReplyRouteWriteBusy(BaseSerialInterface* route) const {
return !isReplyRouteAvailable(route) || isWriteBusy();
}
virtual size_t writeFrameToRoute(BaseSerialInterface* route,
const uint8_t src[], size_t len) {
return route == this ? writeFrame(src, len) : 0;
}
// Multi-transport implementations can pin a sequence of response frames to
// the interface which supplied the current command. Single transports have
// nothing to route, so their default implementations are no-ops.
+25
View File
@@ -44,6 +44,31 @@ inline bool companionFrameRequiresDelivery(const uint8_t* frame, size_t len) {
return companionFrameClass(frame, len) != COMPANION_BEST_EFFORT_PUSH;
}
// Queue priority and transport ownership are separate. Some required pushes
// (MSG_WAITING, control data, and contact-capacity notifications) are
// unsolicited state changes which every connected app should observe. Only
// direct command responses and known asynchronous command completions inherit
// the requester's route. New push codes default to broadcast, which is safer
// than exposing one client's completion to whichever client spoke last.
inline bool companionFrameUsesRequesterRoute(const uint8_t* frame,
size_t len) {
if (frame == NULL || len == 0) return false;
if (!isCompanionPushFrame(frame, len)) return true;
switch (frame[0]) {
case 0x82: // SEND_CONFIRMED
case 0x85: // LOGIN_SUCCESS
case 0x86: // LOGIN_FAIL
case 0x87: // STATUS_RESPONSE
case 0x89: // TRACE_DATA
case 0x8B: // TELEMETRY_RESPONSE
case 0x8C: // BINARY_RESPONSE
case 0x8D: // PATH_DISCOVERY_RESPONSE
return true;
default:
return false;
}
}
/**
* Add a frame to a companion transport's contiguous outbound queue.
*
+3
View File
@@ -2,6 +2,7 @@
#include <stddef.h>
#include <stdint.h>
#include "UsbAsciiBinarySwitch.h"
namespace mesh {
namespace companion {
@@ -80,6 +81,8 @@ inline bool isBleOtaControlCommandAllowed(const uint8_t* command,
if (exact("tempradio", 9)) return true;
if (token("tempradio", 9)) return length > 10;
if (!token("ota", 3)) return false;
if (mesh::isUsbMotaOwnerTransitionCommand(
reinterpret_cast<const char*>(command), length)) return false;
if (token("ota folder", 10)) return false;
return true;
}
+43 -4
View File
@@ -247,6 +247,45 @@ public:
return false;
}
// Exact transport-session resets can arrive independently of
// isConnected() polling (for example, a close/reopen between two loop
// iterations). Let the application abort only work which belongs to that
// transport, without disturbing an active BLE/WiFi response transaction.
bool isReplyRouteFor(BaseSerialInterface* target) const {
return target != nullptr && replyTarget() == target;
}
BaseSerialInterface* captureReplyRoute() override {
return replyTarget();
}
bool isReplyRouteAvailable(BaseSerialInterface* route) const override {
return _enabled && isAvailableReplyTarget(route);
}
bool isReplyRouteWriteBusy(BaseSerialInterface* route) const override {
return !_enabled || !isAvailableReplyTarget(route)
|| route->isWriteBusy();
}
size_t writeFrameToRoute(BaseSerialInterface* route,
const uint8_t src[], size_t len) override {
if (!_enabled || src == nullptr || len == 0
|| !isAvailableReplyTarget(route)) {
return 0;
}
return route->writeFrame(src, len);
}
// Call this only after the response producer for target has been stopped.
// Forgetting both pointers prevents a new host on the same transport from
// inheriting the prior host's reply destination.
void forgetReplyRouteForDisconnected(BaseSerialInterface* target) {
if (target == nullptr) return;
if (_lockedReplyInterface == target) _lockedReplyInterface = nullptr;
if (_lastRxInterface == target) _lastRxInterface = nullptr;
}
void lockReplyRoute() override {
if (isAvailableReplyTarget(_lastRxInterface)) {
_lockedReplyInterface = _lastRxInterface;
@@ -263,10 +302,10 @@ public:
return 0;
}
// Responses and delivery-required completion pushes belong to the client
// which supplied the latest command. Best-effort asynchronous observations
// remain broadcast so passive connected apps can keep their view fresh.
if (mesh::companionFrameRequiresDelivery(src, len)) {
// Responses and command-completion pushes belong to their requester.
// Unsolicited pushes remain broadcast regardless of queue priority so
// passive connected apps can keep their view fresh.
if (mesh::companionFrameUsesRequesterRoute(src, len)) {
BaseSerialInterface* target = replyTarget();
if (target != nullptr) {
if (!isAvailableReplyTarget(target)) return 0;
+6 -2
View File
@@ -459,9 +459,13 @@ void NRF52Board::sleep(uint32_t secs) {
// flag or BLE queue before sleeping again.
sd_app_evt_wait();
} else {
// softdevice is disabled, use raw WFE
__SEV();
// SoftDevice is disabled. Match the Adafruit core's race-preserving
// waitForEvent() sequence: the first WFE sleeps or consumes an already-
// pending event, then SEV/WFE reliably clears the event register before
// returning. SEV/WFE/WFE can erase the only GPIO edge that arrived between
// the caller's predicate and here.
__WFE();
__SEV();
__WFE();
}
}
+370
View File
@@ -2,11 +2,373 @@
#include <Arduino.h>
#include <atomic>
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
// A Stream facade for transports which provide a genuinely nonblocking write
// primitive separate from Stream::write(). Adafruit_USBD_CDC::write() loops
// and yields until it has queued the complete request; TinyUSB's lower-level
// tud_cdc_n_write() instead returns after one FIFO attempt. Keeping the
// single-attempt policy here makes the primary Companion CDC and the dedicated
// logging CDC share the same reentrancy guard without changing other targets.
class SingleAttemptNonBlockingStream : public Stream {
public:
using TryWrite = size_t (*)(void* context, const uint8_t* data,
size_t size);
using CanAccess = bool (*)(void* context);
using ExclusiveOperation = void (*)(void* context);
SingleAttemptNonBlockingStream(Stream& delegate, TryWrite try_write,
void* context = nullptr,
CanAccess can_access = nullptr)
: _delegate(delegate), _try_write(try_write), _context(context),
_can_access(can_access) {}
int available() override {
if (!canAccess()) return 0;
const int count = _delegate.available();
return canAccess() ? count : 0;
}
int read() override {
if (!canAccess()) return -1;
const int value = _delegate.read();
// If the host changed while read() was in flight, consume/drop that byte
// instead of handing it to the next session's protocol parser.
return canAccess() ? value : -1;
}
int peek() override {
if (!canAccess()) return -1;
const int value = _delegate.peek();
return canAccess() ? value : -1;
}
// The delegate's flush may wait forever while a CDC host keeps DTR asserted
// but stops reading. A single-attempt facade must keep every operation
// single-attempt, including flush.
void flush() override {}
int availableForWrite() override {
return canAccess() ? _delegate.availableForWrite() : 0;
}
size_t write(uint8_t value) override { return write(&value, 1); }
size_t write(const uint8_t* data, size_t size) override {
if (data == nullptr || size == 0 || _try_write == nullptr) return 0;
if (_writer_busy.test_and_set(std::memory_order_acquire)) return 0;
if (!canAccess()) {
_writer_busy.clear(std::memory_order_release);
return 0;
}
size_t written = _try_write(_context, data, size);
if (written > size) written = size;
_writer_busy.clear(std::memory_order_release);
return written;
}
// Check capacity and perform the sole write under the same producer gate.
// A separate outer preflight is insufficient: another writer over this
// shared CDC can otherwise consume capacity between check and write.
size_t writeWholeRecord(const uint8_t* data, size_t size) {
if (data == nullptr || size == 0 || _try_write == nullptr) return 0;
if (_writer_busy.test_and_set(std::memory_order_acquire)) return 0;
if (!canAccess()) {
_writer_busy.clear(std::memory_order_release);
return 0;
}
size_t written = 0;
const int available = _delegate.availableForWrite();
if (available >= 0 && static_cast<size_t>(available) >= size) {
written = _try_write(_context, data, size);
if (written > size) written = size;
}
_writer_busy.clear(std::memory_order_release);
return written;
}
// Run a short transport/session operation only when no application writer
// is in flight. The caller retries later on false; this never waits.
bool tryRunExclusive(ExclusiveOperation operation, void* context = nullptr) {
if (operation == nullptr
|| _writer_busy.test_and_set(std::memory_order_acquire)) {
return false;
}
operation(context);
_writer_busy.clear(std::memory_order_release);
return true;
}
private:
bool canAccess() const {
return _can_access == nullptr || _can_access(_context);
}
Stream& _delegate;
TryWrite _try_write;
void* _context;
CanAccess _can_access;
std::atomic_flag _writer_busy = ATOMIC_FLAG_INIT;
};
// A whole-record view over a shared SingleAttemptNonBlockingStream. Unlike a
// generic wrapper, its capacity preflight uses the delegate's own writer gate,
// so Binary, terminal, logging, and mOTA producers cannot interleave between
// the capacity sample and the one low-level write.
template <size_t MAX_WRITE_SIZE = 256>
class AtomicWholeRecordNonBlockingStream : public Stream {
public:
explicit AtomicWholeRecordNonBlockingStream(
SingleAttemptNonBlockingStream& delegate) : _delegate(delegate) {}
int available() override { return _delegate.available(); }
int read() override { return _delegate.read(); }
int peek() override { return _delegate.peek(); }
void flush() override {}
int availableForWrite() override { return _delegate.availableForWrite(); }
size_t write(uint8_t value) override { return write(&value, 1); }
size_t write(const uint8_t* data, size_t size) override {
if (data == nullptr || size == 0 || size > MAX_WRITE_SIZE) return 0;
constexpr size_t PRINTF_SCRATCH_SIZE = 256;
if (size == PRINTF_SCRATCH_SIZE && data[size - 1] == '\0') return 0;
return _delegate.writeWholeRecord(data, size);
}
private:
SingleAttemptNonBlockingStream& _delegate;
};
// A bounded byte queue for functional text written through a single-attempt
// transport. Producer calls are admitted whole and never wait; service() keeps
// a byte offset across short delegate writes so an ordinary draining host sees
// the exact ordered stream. Once the queue fills, later records are dropped as
// a whole rather than blocking the application loop.
//
// Adafruit nRF52 Print::printf() formats into a 256-byte scratch buffer but can
// pass vsnprintf()'s larger required length to write(). The NUL at byte 255 is
// the only safe signal that such a record was truncated before this facade.
template <size_t CAPACITY = 4096, size_t PRINTF_SCRATCH_SIZE = 256>
class BufferedNonBlockingWriteStream : public Stream {
public:
static_assert(CAPACITY > 1, "byte queue needs at least two bytes");
static_assert(PRINTF_SCRATCH_SIZE > 1,
"printf scratch size needs at least two bytes");
explicit BufferedNonBlockingWriteStream(Stream& delegate)
: _delegate(delegate) {}
int available() override { return _delegate.available(); }
int read() override { return _delegate.read(); }
int peek() override { return _delegate.peek(); }
// Drain only currently available capacity. Never forward a potentially
// blocking delegate flush from the application loop.
void flush() override { service(); }
int availableForWrite() override {
if (_busy.test_and_set(std::memory_order_acquire)) return 0;
const size_t free = CAPACITY - _count;
_busy.clear(std::memory_order_release);
return free > static_cast<size_t>(INT_MAX)
? INT_MAX
: static_cast<int>(free);
}
size_t write(uint8_t value) override { return write(&value, 1); }
size_t write(const uint8_t* data, size_t size) override {
if (data == nullptr || size == 0 || size > CAPACITY) return 0;
if (size >= PRINTF_SCRATCH_SIZE
&& data[PRINTF_SCRATCH_SIZE - 1] == '\0') {
return 0;
}
if (_busy.test_and_set(std::memory_order_acquire)) return 0;
drainUnlocked();
if (size > CAPACITY - _count) {
_busy.clear(std::memory_order_release);
return 0;
}
const size_t first = size < CAPACITY - _head
? size
: CAPACITY - _head;
memcpy(&_buffer[_head], data, first);
if (first < size) memcpy(_buffer, data + first, size - first);
_head = (_head + size) % CAPACITY;
_count += size;
drainUnlocked();
_busy.clear(std::memory_order_release);
return size;
}
// Called from the application loop. Retains every unwritten suffix for the
// next call and stops immediately when the delegate reports no progress.
size_t service() {
if (_busy.test_and_set(std::memory_order_acquire)) return 0;
const size_t written = drainUnlocked();
_busy.clear(std::memory_order_release);
return written;
}
void discardPending() {
if (_busy.test_and_set(std::memory_order_acquire)) return;
_head = 0;
_tail = 0;
_count = 0;
_busy.clear(std::memory_order_release);
}
size_t queuedByteCount() {
if (_busy.test_and_set(std::memory_order_acquire)) return CAPACITY;
const size_t count = _count;
_busy.clear(std::memory_order_release);
return count;
}
private:
size_t drainUnlocked() {
size_t total = 0;
while (_count > 0) {
const int available = _delegate.availableForWrite();
if (available <= 0) break;
size_t attempt = _count < CAPACITY - _tail
? _count
: CAPACITY - _tail;
if (attempt > static_cast<size_t>(available)) {
attempt = static_cast<size_t>(available);
}
size_t written = _delegate.write(&_buffer[_tail], attempt);
if (written > attempt) written = attempt;
if (written == 0) break;
_tail = (_tail + written) % CAPACITY;
_count -= written;
total += written;
if (written < attempt) break;
}
return total;
}
Stream& _delegate;
uint8_t _buffer[CAPACITY]{};
size_t _head = 0;
size_t _tail = 0;
size_t _count = 0;
std::atomic_flag _busy = ATOMIC_FLAG_INIT;
};
// A bounded, lossy record queue for transports whose low-level write must run
// in one owner task. Producers only copy complete records into this queue; they
// never touch the delegate. The owner calls drainOne() from its own task. This
// is particularly important for nRF52 TinyUSB: starting a CDC transfer from an
// application task can race control transfers handled by TinyUSB's high-
// priority task, while an unread host can leave that race armed indefinitely.
template <size_t SLOT_COUNT = 8, size_t MAX_WRITE_SIZE = 256>
class TaskOwnedWriteStream : public Stream {
public:
static_assert(SLOT_COUNT >= 2, "record queue needs at least two slots");
explicit TaskOwnedWriteStream(Stream& delegate) : _delegate(delegate) {}
int available() override { return _delegate.available(); }
int read() override { return _delegate.read(); }
int peek() override { return _delegate.peek(); }
// Flushing is owned by the transport task. A producer must never re-enter
// the delegate through this facade.
void flush() override {}
int availableForWrite() override {
const size_t head = _head.load(std::memory_order_relaxed);
const size_t next = increment(head);
return next == _tail.load(std::memory_order_acquire)
? 0
: static_cast<int>(MAX_WRITE_SIZE);
}
size_t write(uint8_t value) override { return write(&value, 1); }
size_t write(const uint8_t* data, size_t size) override {
if (data == nullptr || size == 0 || size > MAX_WRITE_SIZE) return 0;
if (_producer_busy.test_and_set(std::memory_order_acquire)) return 0;
const size_t head = _head.load(std::memory_order_relaxed);
const size_t next = increment(head);
if (next == _tail.load(std::memory_order_acquire)) {
_producer_busy.clear(std::memory_order_release);
return 0;
}
Record& record = _records[head];
memcpy(record.data, data, size);
record.size = size;
_head.store(next, std::memory_order_release);
_producer_busy.clear(std::memory_order_release);
return size;
}
// Called only by the delegate's owner task. A short delegate write is
// discarded rather than retried, because replaying a prefix would duplicate
// bytes and diagnostics are intentionally best effort.
size_t drainOne() {
const size_t tail = _tail.load(std::memory_order_relaxed);
if (tail == _head.load(std::memory_order_acquire)) return 0;
const Record& record = _records[tail];
const int available = _delegate.availableForWrite();
if (available < 0 || static_cast<size_t>(available) < record.size) return 0;
size_t written = _delegate.write(record.data, record.size);
if (written > record.size) written = record.size;
if (written > 0) {
_tail.store(increment(tail), std::memory_order_release);
}
return written;
}
// Called by the owner task, or after its transport callback has been disabled
// so no consumer can race this cursor. Producers may publish concurrently;
// loading head before storing tail preserves that newly published record.
void discardPending() {
_tail.store(_head.load(std::memory_order_acquire),
std::memory_order_release);
}
size_t queuedRecordCount() const {
const size_t head = _head.load(std::memory_order_acquire);
const size_t tail = _tail.load(std::memory_order_acquire);
return head >= tail ? head - tail : SLOT_COUNT - tail + head;
}
private:
struct Record {
size_t size = 0;
uint8_t data[MAX_WRITE_SIZE]{};
};
static constexpr size_t increment(size_t value) {
return value + 1 == SLOT_COUNT ? 0 : value + 1;
}
Stream& _delegate;
Record _records[SLOT_COUNT];
std::atomic<size_t> _head{0};
std::atomic<size_t> _tail{0};
std::atomic_flag _producer_busy = ATOMIC_FLAG_INIT;
};
// A Stream facade for a transport whose underlying write() may wait for FIFO
// space. It never retries or forwards a write larger than one nRF52 TinyUSB TX
// FIFO. Print::printf() can report a length larger than its 256-byte scratch
@@ -31,6 +393,14 @@ class WholeRecordNonBlockingStream : public Stream {
size_t write(const uint8_t* data, size_t size) override {
if (data == nullptr || size == 0 || size > MAX_WRITE_SIZE) return 0;
// Adafruit nRF52 Print::printf() formats into char[256], then forwards
// vsnprintf()'s required length without clamping it to that buffer. An
// exactly 256-character result therefore arrives here as 255 characters
// plus the formatter's trailing NUL. Drop that truncated record as a
// whole, just as we do for reported lengths greater than the buffer.
constexpr size_t PRINTF_SCRATCH_SIZE = 256;
if (size == PRINTF_SCRATCH_SIZE && data[size - 1] == '\0') return 0;
// Never wait for another application writer. All diagnostic access to the
// delegate is routed through this facade; the USB task can only drain the
// TX FIFO, so free capacity cannot shrink while this gate is held.
+36
View File
@@ -1,9 +1,45 @@
#pragma once
#include <stdint.h>
#include <string.h>
namespace mesh {
// OtaCli accepts both `folder` and `fold`, and collapses repeated ASCII spaces
// between its words. Recognize that same mutating command surface here so no
// alias can attach/detach the CDC0-backed folder outside the USB owner state
// machine. Status/list commands deliberately remain ordinary OTA CLI queries.
inline bool isUsbMotaOwnerTransitionCommand(const char* command,
size_t length) {
if (command == nullptr) return false;
size_t pos = 0;
while (pos < length && (command[pos] == ' ' || command[pos] == '\t')) ++pos;
if (length - pos < 3 || memcmp(command + pos, "ota", 3) != 0) return false;
pos += 3;
if (pos < length && command[pos] != ' ') return false;
while (pos < length && command[pos] == ' ') ++pos;
const size_t noun_start = pos;
while (pos < length && command[pos] != ' ') ++pos;
const size_t noun_len = pos - noun_start;
if (!((noun_len == 6
&& memcmp(command + noun_start, "folder", 6) == 0)
|| (noun_len == 4
&& memcmp(command + noun_start, "fold", 4) == 0))) {
return false;
}
while (pos < length && command[pos] == ' ') ++pos;
const size_t action_len = length - pos;
return (action_len == 2 && memcmp(command + pos, "on", 2) == 0)
|| (action_len == 3 && memcmp(command + pos, "off", 3) == 0);
}
inline bool isUsbMotaOwnerTransitionCommand(const char* command) {
return command != nullptr
&& isUsbMotaOwnerTransitionCommand(command, strlen(command));
}
// Coordinates the Full Companion USB startup handoff without consuming the
// '<' byte. ArduinoSerialInterface remains the only binary protocol parser.
class UsbBinaryStartupProbe {
+521 -17
View File
@@ -8,6 +8,17 @@
#include "NonBlockingWriteStream.h"
#endif
#if defined(NRF52_PLATFORM) && \
(defined(ENABLE_USB_INTERFACE) || defined(OTA_FOLDER_SERIAL))
#define MESH_NRF52_PRIMARY_USB_NONBLOCKING 1
#include <Adafruit_TinyUSB.h>
#if !defined(CFG_TUD_CDC) || CFG_TUD_CDC < 1
#error "nRF52 USB Companion/mOTA requires CFG_TUD_CDC >= 1"
#endif
#else
#define MESH_NRF52_PRIMARY_USB_NONBLOCKING 0
#endif
#if defined(MESH_DUAL_CDC_LOGGING)
#if !defined(COMPANION_FEATURE_DEDICATED_USB_LOGGING) || \
!COMPANION_FEATURE_DEDICATED_USB_LOGGING
@@ -16,7 +27,9 @@
#if !defined(NRF52_PLATFORM)
#error "MESH_DUAL_CDC_LOGGING is supported only by nRF52 Full Companion"
#endif
#include <Adafruit_TinyUSB.h>
#if !defined(ENABLE_USB_INTERFACE)
#error "MESH_DUAL_CDC_LOGGING requires ENABLE_USB_INTERFACE"
#endif
#if !defined(CFG_TUD_CDC) || CFG_TUD_CDC < 2
#error "MESH_DUAL_CDC_LOGGING requires CFG_TUD_CDC >= 2"
#endif
@@ -46,6 +59,100 @@ class NullUsbLoggingStream : public Stream {
static NullUsbLoggingStream null_usb_logging_stream;
#if MESH_NRF52_PRIMARY_USB_NONBLOCKING
#if defined(ENABLE_USB_INTERFACE)
// Writers/readers may access CDC0 only when DTR is high and the application has
// completed the current close epoch. Incrementing reset_generation therefore
// closes the transport atomically; an older completion can publish only its
// older epoch and can never reopen across a newer close.
static std::atomic<uint32_t> primary_usb_reset_generation{0};
static std::atomic<uint32_t> primary_usb_allowed_generation{0};
static std::atomic<bool> primary_usb_line_state_dtr{false};
static constexpr uint32_t primary_usb_session_settle_millis = 8;
static std::atomic<uint32_t> primary_usb_reset_settle_until{0};
static uint32_t primaryUsbSessionGeneration() {
return primary_usb_reset_generation.load(std::memory_order_acquire);
}
static bool canAccessPrimaryUsbSession(void*) {
return primary_usb_line_state_dtr.load(std::memory_order_acquire)
&& primary_usb_allowed_generation.load(std::memory_order_acquire)
== primary_usb_reset_generation.load(std::memory_order_acquire);
}
static void endPrimaryUsbHostSession(bool clear_cdc_fifos) {
const bool previous = primary_usb_line_state_dtr.exchange(
false, std::memory_order_acq_rel);
if (!previous) return;
// Publish a short quiescence deadline before closing the generation gate.
// TinyUSB's TX clear does not cancel an endpoint transfer already in its
// class buffer, so the later final TX purge catches a racing old-session
// write. RX is purged synchronously below; bytes sent by a reopened host
// during the settle interval remain queued until the gate reopens.
primary_usb_reset_settle_until.store(
millis() + primary_usb_session_settle_millis,
std::memory_order_release);
primary_usb_reset_generation.fetch_add(1, std::memory_order_acq_rel);
if (clear_cdc_fifos) {
// The line-state callback runs before TinyUSB resets the device. A device
// unmount/remount boundary has already reset these class FIFOs.
tud_cdc_n_read_flush(0);
(void)tud_cdc_n_write_clear(0);
}
}
#endif
// Adafruit_USBD_CDC::write() retries from a yield loop until it has queued the
// complete request. A CDC host can change DTR or stop draining between the
// caller's availableForWrite() sample and that loop. Use TinyUSB's native
// single-attempt primitive so both Companion CDCs return short immediately and
// let their existing queue/whole-record policy decide what to retry.
static size_t writeTinyUsbCdcOnce(void* context, const uint8_t* data,
size_t size) {
const uint8_t instance = static_cast<uint8_t>(
reinterpret_cast<uintptr_t>(context));
if (data == nullptr || size == 0 || instance >= CFG_TUD_CDC) {
return 0;
}
#if defined(ENABLE_USB_INTERFACE)
if (instance == 0 && !canAccessPrimaryUsbSession(nullptr)) {
return 0;
}
#endif
if (!tud_cdc_n_connected(instance)) return 0;
const size_t available = tud_cdc_n_write_available(instance);
const size_t attempt = size < available ? size : available;
if (attempt == 0) return 0;
return tud_cdc_n_write(instance, data, attempt);
}
static SingleAttemptNonBlockingStream nonblocking_primary_usb_companion_port(
Serial, writeTinyUsbCdcOnce, reinterpret_cast<void*>(uintptr_t{0})
#if defined(ENABLE_USB_INTERFACE)
, canAccessPrimaryUsbSession
#endif
);
// SerialMotaSource emits one contiguous request whose largest valid frame is
// 11 bytes. Preflight that entire record before the sole TinyUSB write attempt;
// a busy FIFO drops the request cleanly and lets the transaction retry later.
static AtomicWholeRecordNonBlockingStream<11>
nonblocking_primary_usb_mota_port(
nonblocking_primary_usb_companion_port);
#if defined(ENABLE_USB_INTERFACE)
// Unlike Binary Companion frames, a terminal reply is produced as many Print
// calls whose return values are not consumed by the CLI. Retain one complete
// multi-line response while a normal host drains CDC0, but bound the memory and
// drop later records instead of ever waiting on an unread endpoint.
static BufferedNonBlockingWriteStream<4096>
buffered_primary_usb_terminal_port(
nonblocking_primary_usb_companion_port);
static uint32_t primary_usb_terminal_seen_reset_generation = 0;
static uint32_t primary_usb_terminal_taken_reset_generation = 0;
#endif
#endif
static void setPlatformDebugOutputEnabled(bool enabled) {
#if defined(ESP32_PLATFORM) && defined(ENABLE_USB_INTERFACE)
// Arduino-ESP32 log_e()/ESP-IDF diagnostics otherwise write straight to
@@ -60,16 +167,210 @@ static void setPlatformDebugOutputEnabled(bool enabled) {
#if defined(MESH_DUAL_CDC_LOGGING)
static bool dedicated_usb_logging_port_configured = false;
static bool dedicated_usb_logging_port_started = false;
static bool dedicated_usb_logging_port_connected = false;
static Adafruit_USBD_CDC dedicated_usb_logging_port;
static std::atomic<bool> dedicated_usb_logging_port_connected{false};
static bool dedicated_usb_logging_sof_enabled = false;
static constexpr char dedicated_usb_logging_descriptor[] =
"MeshCore Logging";
// Adafruit_USBD_CDC::begin() assigns "TinyUSB Serial" and immediately copies
// the interface descriptor into TinyUSBDevice's configuration buffer. Calling
// setStringDescriptor() after begin() therefore cannot rename that copied
// descriptor. Assign our string while the virtual descriptor builder is
// running, immediately before the core copies it instead.
class DedicatedUsbLoggingCdc : public Adafruit_USBD_CDC {
public:
uint16_t getInterfaceDescriptor(uint8_t itfnum_deprecated, uint8_t* buf,
uint16_t bufsize) override {
if (buf != nullptr) {
setStringDescriptor(dedicated_usb_logging_descriptor);
}
return Adafruit_USBD_CDC::getInterfaceDescriptor(
itfnum_deprecated, buf, bufsize);
}
};
static DedicatedUsbLoggingCdc dedicated_usb_logging_port;
static SingleAttemptNonBlockingStream single_attempt_dedicated_usb_logging_port(
dedicated_usb_logging_port, writeTinyUsbCdcOnce,
reinterpret_cast<void*>(uintptr_t{1}));
static TaskOwnedWriteStream<> usb_task_dedicated_usb_logging_port(
single_attempt_dedicated_usb_logging_port);
static WholeRecordNonBlockingStream<>
nonblocking_dedicated_usb_logging_port(dedicated_usb_logging_port);
nonblocking_dedicated_usb_logging_port(
usb_task_dedicated_usb_logging_port);
static constexpr char dedicated_usb_logging_identity[] =
"MeshCore USB logging port\r\n"
"USB CDC 1; interface 02; Linux stable suffix: -if02\r\n";
static constexpr size_t dedicated_usb_logging_identity_size =
sizeof(dedicated_usb_logging_identity) - 1;
static_assert(dedicated_usb_logging_identity_size <= 256,
"USB identity marker exceeds the nonblocking record limit");
static_assert(dedicated_usb_logging_identity_size
<= CFG_TUD_CDC_TX_BUFSIZE,
"USB identity marker exceeds the TinyUSB CDC TX FIFO");
static std::atomic<uint32_t> dedicated_usb_logging_reset_generation{0};
static uint32_t dedicated_usb_logging_seen_reset_generation = 0;
// TinyUSB reports SET_CONTROL_LINE_STATE from its owner task. Keep the last
// DTR value independently of main-loop polling so a close/reopen cannot be
// collapsed into one continuously connected sample.
static std::atomic<bool> dedicated_usb_logging_line_state_dtr{false};
static bool dedicated_usb_logging_usb_task_connected = false;
static size_t dedicated_usb_logging_identity_offset = 0;
// Windows configures line coding and then purges its COM buffers. Keep CDC1
// silent for more than one Windows scheduling quantum so that purge cannot
// discard the identity marker and expose a later diagnostic as byte zero.
static constexpr uint8_t dedicated_usb_logging_host_settle_sofs = 50;
static uint8_t dedicated_usb_logging_quiet_sofs = 0;
static void resetDedicatedUsbLoggingIdentity() {
dedicated_usb_logging_identity_offset = 0;
}
static void resetDedicatedUsbLoggingUsbTaskState() {
dedicated_usb_logging_usb_task_connected = false;
resetDedicatedUsbLoggingIdentity();
usb_task_dedicated_usb_logging_port.discardPending();
}
static void restartDedicatedUsbLoggingHostSession() {
// This callback and the SOF drain both run in TinyUSB's task. Gate producers
// before clearing both queues, then publish a generation so the next SOF
// repeats the reset after any producer which was already in flight. Clearing
// here also prevents bytes left in TinyUSB's TX FIFO from preceding the
// identity marker after a rapid reopen.
dedicated_usb_logging_port_connected.store(false,
std::memory_order_release);
(void)tud_cdc_n_write_clear(1);
resetDedicatedUsbLoggingUsbTaskState();
dedicated_usb_logging_quiet_sofs =
dedicated_usb_logging_host_settle_sofs;
dedicated_usb_logging_reset_generation.fetch_add(
1, std::memory_order_acq_rel);
}
static void handleDedicatedUsbLoggingLineState(bool dtr) {
const bool previous = dedicated_usb_logging_line_state_dtr.exchange(
dtr, std::memory_order_acq_rel);
if (previous == dtr) return;
restartDedicatedUsbLoggingHostSession();
// TinyUSB clears its SOF-consumer bits on every USB bus reset. A rapid
// reset/re-enumeration can leave the main loop's requested-state cache true
// throughout, so it would otherwise never ask TinyUSB to restore this
// callback. SET_CONTROL_LINE_STATE runs in TinyUSB's owner task after the
// new configuration is active, making the fresh DTR edge the exact place
// to rearm (or disable) CDC1's sole drain tick.
tud_sof_cb_enable(dtr && isUsbLoggingEnabled());
}
static void handleDedicatedUsbLoggingLineCoding() {
// Windows can close and immediately reopen a COM handle without exposing a
// distinct DTR-low interval to the device. It still configures line coding
// for the newly opened handle. Treat that owner-task callback as a fresh
// CDC1 host session only when DTR is already asserted; if it is not, the
// subsequent DTR-high edge performs the reset instead.
if (tud_cdc_n_connected(1)) {
restartDedicatedUsbLoggingHostSession();
}
}
// Called by TinyUSB's own high-priority task through tud_sof_cb(). Application
// writers only copy complete records into the queue above, so every CDC1 FIFO
// and endpoint operation happens in the same task as control transfers. The
// identity marker bypasses that producer queue: its cursor advances from the
// actual TinyUSB write result, not from queue acceptance. Sampling DTR here at
// 1 kHz also catches a close/reopen that occurs entirely between main-loop
// service calls.
void serviceDedicatedUsbLoggingFromUsbTask() {
const uint32_t reset_generation =
dedicated_usb_logging_reset_generation.load(std::memory_order_acquire);
if (reset_generation != dedicated_usb_logging_seen_reset_generation) {
resetDedicatedUsbLoggingUsbTaskState();
dedicated_usb_logging_seen_reset_generation = reset_generation;
}
const bool physical_connected = tud_cdc_n_connected(1);
const bool connected = isUsbLoggingEnabled() && physical_connected;
if (!physical_connected) {
// A bus reset need not deliver an explicit DTR-low request. Make the next
// DTR-high callback an edge even when the previous host vanished abruptly.
dedicated_usb_logging_line_state_dtr.store(
false, std::memory_order_release);
}
if (!connected) {
dedicated_usb_logging_port_connected.store(
false, std::memory_order_release);
resetDedicatedUsbLoggingUsbTaskState();
return;
}
if (dedicated_usb_logging_quiet_sofs > 0) {
dedicated_usb_logging_port_connected.store(
false, std::memory_order_release);
// Drop anything already in flight from the prior session and anything a
// producer raced into the owner queue before the callback gated it.
(void)tud_cdc_n_write_clear(1);
resetDedicatedUsbLoggingUsbTaskState();
--dedicated_usb_logging_quiet_sofs;
return;
}
dedicated_usb_logging_port_connected.store(
true, std::memory_order_release);
if (!dedicated_usb_logging_usb_task_connected) {
// Drop diagnostics from the prior host before sending byte zero of the
// marker to the new host.
usb_task_dedicated_usb_logging_port.discardPending();
resetDedicatedUsbLoggingIdentity();
dedicated_usb_logging_usb_task_connected = true;
}
if (dedicated_usb_logging_identity_offset
< dedicated_usb_logging_identity_size) {
// This direct single-attempt call runs in the sole CDC1 endpoint owner.
// With the complete marker fitting in one TX FIFO, a short result can only
// occur around a connection transition; restart from byte zero for the
// next observed host instead of delivering only a suffix.
const size_t remaining = dedicated_usb_logging_identity_size
- dedicated_usb_logging_identity_offset;
if (single_attempt_dedicated_usb_logging_port.availableForWrite()
< static_cast<int>(remaining)) {
(void)tud_cdc_n_write_flush(1);
return;
}
const size_t written = single_attempt_dedicated_usb_logging_port.write(
reinterpret_cast<const uint8_t*>(
dedicated_usb_logging_identity
+ dedicated_usb_logging_identity_offset),
remaining);
dedicated_usb_logging_identity_offset =
detail::nextUsbLoggingIdentityOffset(
dedicated_usb_logging_identity_offset, remaining, written);
(void)tud_cdc_n_write_flush(1);
return;
}
// If the host stops reading, the TinyUSB FIFO and this queue simply fill and
// later diagnostics are dropped without blocking either task.
usb_task_dedicated_usb_logging_port.drainOne();
(void)tud_cdc_n_write_flush(1);
}
#elif defined(NRF52_PLATFORM)
// Single-CDC nRF52 roles need the same protection. In particular, BLE debug
// callbacks and packet logging write through usbLoggingPort() without going
// through MeshCore's formatted-debug helper.
#if MESH_NRF52_PRIMARY_USB_NONBLOCKING
static AtomicWholeRecordNonBlockingStream<>
nonblocking_primary_usb_logging_port(
nonblocking_primary_usb_companion_port);
#else
static WholeRecordNonBlockingStream<>
nonblocking_primary_usb_logging_port(Serial);
#endif
#endif
bool isUsbLoggingEnabled() {
@@ -101,9 +402,6 @@ void beginUsbLoggingPort() {
}
dedicated_usb_logging_port.begin(115200);
// `begin()` installs the core's generic "TinyUSB Serial" name. Replace it
// before (re-)enumeration so host USB tools can distinguish the log endpoint.
dedicated_usb_logging_port.setStringDescriptor("MeshCore Logging");
dedicated_usb_logging_port_configured = true;
dedicated_usb_logging_port_started = true;
@@ -121,23 +419,50 @@ void beginUsbLoggingPort() {
void serviceUsbLoggingPort() {
#if defined(MESH_DUAL_CDC_LOGGING)
bool connected = false;
connected = dedicated_usb_logging_port_started
const bool connected = dedicated_usb_logging_port_started
&& dedicated_usb_logging_port.dtr();
if (connected && !dedicated_usb_logging_port_connected
&& isUsbLoggingEnabled()) {
Stream& port = usbLoggingPort();
port.println("MeshCore USB logging port");
port.println("USB CDC 1; interface 02; Linux stable suffix: -if02");
const bool should_service = connected && isUsbLoggingEnabled();
// Only the TinyUSB owner task publishes a positive producer gate. The main
// loop may close it, but must not bypass the post-open quiet window.
if (!should_service) {
dedicated_usb_logging_port_connected.store(
false, std::memory_order_release);
}
if (!connected) {
dedicated_usb_logging_line_state_dtr.store(
false, std::memory_order_release);
}
// SOF callbacks execute in TinyUSB's task and provide the bounded owner-task
// drain tick. This cached requested state converges ordinary opens/closes
// and runtime logging changes. TinyUSB clears the actual SOF-consumer bit on
// bus reset, so the owner-task DTR callback above also rearms it after each
// re-enumeration even when this sampled state never changed. Queue cursor
// mutation remains in TinyUSB's owner task, and the reset generation stays
// pending until a later reopen lets that callback reset before its first
// drain.
if (should_service != dedicated_usb_logging_sof_enabled) {
if (should_service) {
// Publish the new generation before the callback can run.
dedicated_usb_logging_reset_generation.fetch_add(
1, std::memory_order_acq_rel);
tud_sof_cb_enable(true);
} else {
// Stop the consumer before publishing the next reset generation. The
// generation remains pending until a later reopen enables the callback.
tud_sof_cb_enable(false);
dedicated_usb_logging_reset_generation.fetch_add(
1, std::memory_order_acq_rel);
}
dedicated_usb_logging_sof_enabled = should_service;
}
dedicated_usb_logging_port_connected = connected;
#endif
}
Stream& usbLoggingPort() {
#if defined(MESH_DUAL_CDC_LOGGING)
if (isUsbLoggingEnabled() && dedicated_usb_logging_port_started) {
if (isUsbLoggingEnabled() && dedicated_usb_logging_port_started
&& dedicated_usb_logging_port_connected.load(std::memory_order_acquire)) {
return nonblocking_dedicated_usb_logging_port;
}
return null_usb_logging_stream;
@@ -151,6 +476,98 @@ Stream& usbLoggingPort() {
#endif
}
Stream& usbCompanionPort() {
#if MESH_NRF52_PRIMARY_USB_NONBLOCKING
return nonblocking_primary_usb_companion_port;
#else
return Serial;
#endif
}
Stream& usbMotaPort() {
#if MESH_NRF52_PRIMARY_USB_NONBLOCKING
return nonblocking_primary_usb_mota_port;
#else
return usbCompanionPort();
#endif
}
Stream& usbTerminalPort() {
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
return buffered_primary_usb_terminal_port;
#else
return usbCompanionPort();
#endif
}
void serviceUsbTerminalPort() {
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
const uint32_t reset_generation =
primaryUsbSessionGeneration();
if (reset_generation != primary_usb_terminal_seen_reset_generation) {
buffered_primary_usb_terminal_port.discardPending();
primary_usb_terminal_seen_reset_generation = reset_generation;
}
buffered_primary_usb_terminal_port.service();
#endif
}
void discardUsbTerminalOutput() {
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
buffered_primary_usb_terminal_port.discardPending();
#endif
}
bool hasPendingUsbTerminalOutput() {
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
return buffered_primary_usb_terminal_port.queuedByteCount() != 0;
#else
return false;
#endif
}
bool takeUsbTerminalSessionReset() {
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
const uint32_t reset_generation =
primaryUsbSessionGeneration();
if (reset_generation == primary_usb_terminal_taken_reset_generation) {
return false;
}
primary_usb_terminal_taken_reset_generation = reset_generation;
return true;
#else
return false;
#endif
}
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
static void completePrimaryUsbSessionReset(void*) {
// This runs under the primary SingleAttempt stream's producer gate. It
// removes a write that raced the owner-task close callback before allowing
// any producer to address the reopened handle. RX was already purged when
// the close/line-coding boundary was captured. Do not purge it again here:
// hosts such as meshcli send APP_START immediately after opening the port,
// while this generation gate is deliberately settling.
(void)tud_cdc_n_write_clear(0);
const uint32_t cleaned_generation =
primary_usb_terminal_taken_reset_generation;
primary_usb_allowed_generation.store(cleaned_generation,
std::memory_order_release);
}
#endif
bool tryCompleteUsbTerminalSessionReset() {
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
const uint32_t settle_until =
primary_usb_reset_settle_until.load(std::memory_order_acquire);
if ((int32_t)(millis() - settle_until) < 0) return false;
return nonblocking_primary_usb_companion_port.tryRunExclusive(
completePrimaryUsbSessionReset);
#else
return true;
#endif
}
bool hasDedicatedUsbLoggingPort() {
#if defined(MESH_DUAL_CDC_LOGGING)
return true;
@@ -184,4 +601,91 @@ const char* usbLoggingPortDescription() {
}
} // namespace mesh
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
// A protocol-only, weak-declaration-free translation unit supplies strong
// versions of TinyUSB's callbacks and forwards here. Preserve Adafruit's CDC0
// 1200-baud touch behavior exactly, capture every CDC0 host-session close and
// USB device boundary, and give an optional CDC1 logging endpoint its exact
// reconnect edges.
extern "C" void meshTinyUsbCdcLineStateChanged(uint8_t instance, bool dtr,
bool rts) {
(void)rts;
#if defined(MESH_DUAL_CDC_LOGGING)
if (instance == 1) {
mesh::handleDedicatedUsbLoggingLineState(dtr);
return;
}
#endif
if (instance == 0 && !dtr) {
// Discard raw input/output already admitted to TinyUSB. The generation
// change keeps every facade closed until the application resets its
// protocol owner and performs the final exclusive TX purge.
mesh::endPrimaryUsbHostSession(true);
cdc_line_coding_t coding;
tud_cdc_get_line_coding(&coding);
if (coding.bit_rate == 1200) {
TinyUSB_Port_EnterDFU();
}
} else if (instance == 0) {
const bool was_open = mesh::primary_usb_line_state_dtr.load(
std::memory_order_acquire);
if (!was_open) {
// Purge any late bytes from the closed owner before publishing the fresh
// session. New-host input sent after SET_CONTROL_LINE_STATE completes is
// then retained while the application-side generation gate settles.
tud_cdc_n_read_flush(0);
mesh::primary_usb_line_state_dtr.store(
true, std::memory_order_release);
}
}
}
extern "C" void meshTinyUsbDeviceSessionBoundary() {
// TinyUSB does not issue SET_CONTROL_LINE_STATE(DTR=0) for a hard unplug or
// bus reset. An unmount catches the former; the following mount catches a
// reset/reconfigure whose old DTR state survived in this application. The
// helper is edge-sensitive, so initial enumeration and the mount following
// an already observed unmount do not create a false reset.
mesh::endPrimaryUsbHostSession(false);
#if defined(MESH_DUAL_CDC_LOGGING)
mesh::handleDedicatedUsbLoggingLineState(false);
#endif
}
extern "C" void meshTinyUsbCdcLineCodingChanged(uint8_t instance) {
if (instance == 0) {
// Windows may close/reopen a COM handle without presenting a distinct
// DTR-low interval to the device, but it configures line coding for the
// new handle. If CDC0 still appears open, treat this as a protocol-session
// boundary. Restore the physical DTR sample after closing the epoch so an
// intentional baud change on a continuously open handle recovers as soon
// as the application has reset its parsers.
if (mesh::primary_usb_line_state_dtr.load(std::memory_order_acquire)) {
mesh::endPrimaryUsbHostSession(true);
mesh::primary_usb_line_state_dtr.store(
tud_cdc_n_connected(0), std::memory_order_release);
}
return;
}
#if defined(MESH_DUAL_CDC_LOGGING)
if (instance == 1) {
mesh::handleDedicatedUsbLoggingLineCoding();
}
#else
(void)instance;
#endif
}
#if defined(MESH_DUAL_CDC_LOGGING)
// The weak-declaration-free bridge lives in UsbLoggingLineStateOverride.cpp.
// This forwarding target runs in TinyUSB's task, making CDC1 endpoint
// ownership explicit without inheriting TinyUSB's weak callback attribute.
extern "C" void meshTinyUsbStartOfFrame(uint32_t frame_count) {
(void)frame_count;
mesh::serviceDedicatedUsbLoggingFromUsbTask();
}
#endif
#endif
#endif
+43 -3
View File
@@ -16,6 +16,20 @@
namespace mesh {
namespace detail {
// Keep the identity-marker reconnect rule pure so host tests can exercise the
// DTR edge case without a TinyUSB device. The USB owner task passes the actual
// TinyUSB write result here. A short write means the old connection vanished
// mid-record; byte zero is the only safe starting point for the next host.
inline size_t nextUsbLoggingIdentityOffset(size_t current_offset,
size_t requested,
size_t written) {
return written == requested ? current_offset + written : 0;
}
} // namespace detail
// Ordinary merged images start enabled. USB/Full Companion starts disabled to
// protect framed traffic and restores its saved choice after preferences load.
bool isUsbLoggingEnabled();
@@ -29,11 +43,37 @@ bool saveUsbLoggingBootPreference(bool enabled);
// Start the optional dedicated USB logging interface. Ordinary and single-TTY
// builds use Serial; nRF52 Full Companion uses a second CDC ACM port.
void beginUsbLoggingPort();
// Emit a short identity marker whenever a host opens the dedicated logging
// endpoint. The device can report its USB interface, but the host alone chooses
// names such as /dev/ttyACM1 or COM7.
// Enable owner-task service when a host opens the dedicated logging endpoint.
// That task emits the identity marker from the actual TinyUSB write result and
// retries a busy CDC TX FIFO without waiting.
// The device can report its USB interface, but the host alone chooses names
// such as /dev/ttyACM1 or COM7.
void serviceUsbLoggingPort();
Stream& usbLoggingPort();
// Primary USB Companion data stream. On nRF52 this uses one direct TinyUSB
// FIFO attempt per write so a host-side open/close race cannot trap the main
// loop in Adafruit_USBD_CDC::write(). Other platforms retain Serial.
Stream& usbCompanionPort();
// Serial mOTA requests are binary records of at most 11 bytes. On nRF52 this
// facade admits a request only when the complete record fits in CDC0's current
// TX capacity, so a retry can never append to a prefix from the prior attempt.
Stream& usbMotaPort();
// Functional ASCII output needs the same zero-wait USB primitive plus a
// bounded queue so a normal host receives complete multi-line replies. Service
// it from the application loop; discard it before changing the CDC protocol or
// after a host disconnect so stale text cannot prefix a later Binary session.
Stream& usbTerminalPort();
void serviceUsbTerminalPort();
void discardUsbTerminalOutput();
bool hasPendingUsbTerminalOutput();
// Consume an exact CDC0 DTR-low edge captured in TinyUSB's owner task. This is
// separate from polling the current DTR value: Windows can close and reopen a
// COM handle between two application-loop iterations.
bool takeUsbTerminalSessionReset();
// After the application has reset its protocol state, atomically purge any
// CDC0 writer that raced the close callback and reopen the producer gate. A
// false result is a zero-wait busy indication; retry it next loop.
bool tryCompleteUsbTerminalSessionReset();
bool hasDedicatedUsbLoggingPort();
bool isDedicatedUsbLoggingPortConfigured();
bool usbLoggingInterfaceRestartRequired();
@@ -0,0 +1,58 @@
// Include only TinyUSB's CDC protocol types here. cdc_device.h and the Arduino
// TinyUSB headers declare these callbacks weak, and that attribute would carry
// onto our definitions. This translation unit intentionally supplies the
// strong callbacks which override Adafruit's weak defaults for nRF52 USB
// Companion builds. CDC0 needs exact close events even on single-CDC targets;
// dual-CDC builds additionally forward CDC1 reconnect events.
#if defined(ARDUINO) && defined(NRF52_PLATFORM) \
&& defined(ENABLE_USB_INTERFACE)
#include <class/cdc/cdc.h>
extern "C" void meshTinyUsbCdcLineStateChanged(uint8_t instance, bool dtr,
bool rts);
extern "C" void meshTinyUsbCdcLineCodingChanged(uint8_t instance);
extern "C" void meshTinyUsbDeviceSessionBoundary();
#if defined(MESH_DUAL_CDC_LOGGING)
extern "C" void meshTinyUsbStartOfFrame(uint32_t frame_count);
// cdc_device.h would attach TinyUSB's weak callback declarations to the strong
// overrides in this translation unit. Declare only the non-callback API used
// below, retaining the exact TinyUSB signature without importing that header.
extern "C" uint32_t tud_cdc_n_write_flush(uint8_t itf);
// The nRF core calls this weak hook from both the application task and the
// TinyUSB task. Never let those application-side yield()/delay() calls touch
// CDC1; its SOF bridge below is the sole endpoint owner. CDC0 retains the
// framework's ordinary opportunistic flush behavior.
extern "C" void TinyUSB_Device_FlushCDC(void) {
(void)tud_cdc_n_write_flush(0);
}
#endif
// TinyUSB calls unmount for a hard unplug/configuration loss, but not for an
// ordinary bus-reset event. The subsequent mount is therefore also a session
// boundary; the forwarded handler is edge-sensitive so initial enumeration
// and an unmount/mount pair count at most once.
extern "C" void tud_mount_cb(void) {
meshTinyUsbDeviceSessionBoundary();
}
extern "C" void tud_umount_cb(void) {
meshTinyUsbDeviceSessionBoundary();
}
extern "C" void tud_cdc_line_state_cb(uint8_t instance, bool dtr, bool rts) {
meshTinyUsbCdcLineStateChanged(instance, dtr, rts);
}
extern "C" void tud_cdc_line_coding_cb(uint8_t instance,
cdc_line_coding_t const* line_coding) {
(void)line_coding;
meshTinyUsbCdcLineCodingChanged(instance);
}
#if defined(MESH_DUAL_CDC_LOGGING)
extern "C" void tud_sof_cb(uint32_t frame_count) {
meshTinyUsbStartOfFrame(frame_count);
}
#endif
#endif
+18 -2
View File
@@ -23,11 +23,27 @@
#if defined(OTA_FOLDER_SERIAL)
#include "MotaSourceSerial.h" // relay an external folder served by a host daemon over the USB serial
#ifndef OTA_FOLDER_SERIAL_STREAM
#define OTA_FOLDER_SERIAL_STREAM Serial // default: the same USB console the CLI uses (no extra HW)
#if defined(NRF52_PLATFORM)
// Adafruit's CDC write waits while an open host stops reading. Every
// default nRF52 serial-folder request uses a whole-record facade over one
// TinyUSB attempt; dedicated-UART overrides retain their normal stream.
#include "../UsbLogging.h"
#define OTA_FOLDER_SERIAL_STREAM ::mesh::usbMotaPort()
#define MESH_OTA_FOLDER_SERIAL_NONBLOCKING_USB 1
#else
#define OTA_FOLDER_SERIAL_STREAM Serial // default: shared USB console
#endif
#endif
#ifndef OTA_FOLDER_SERIAL_BAUD
#define OTA_FOLDER_SERIAL_BAUD 115200
#endif
#ifndef OTA_FOLDER_SERIAL_WRITE_POLICY
#if defined(MESH_OTA_FOLDER_SERIAL_NONBLOCKING_USB)
#define OTA_FOLDER_SERIAL_WRITE_POLICY MotaStreamWritePolicy::NoFlush
#else
#define OTA_FOLDER_SERIAL_WRITE_POLICY MotaStreamWritePolicy::FlushTransmit
#endif
#endif
// The console Serial is already begun by the example; a DEDICATED UART (override the stream) needs init,
// so define OTA_FOLDER_SERIAL_BEGIN to have attach_folder() call .begin(baud) on it.
#endif
@@ -394,7 +410,7 @@ struct OtaContext {
#if defined(OTA_FOLDER_SERIAL)
bool attach_folder(char* msg, size_t cap) {
static SerialMotaSource src(OTA_FOLDER_SERIAL_STREAM,
MotaStreamWritePolicy::FlushTransmit, 600);
OTA_FOLDER_SERIAL_WRITE_POLICY, 600);
#ifdef OTA_FOLDER_SERIAL_BEGIN
OTA_FOLDER_SERIAL_STREAM.begin(OTA_FOLDER_SERIAL_BAUD); // dedicated UART; console is already up
#endif
+57
View File
@@ -9,6 +9,9 @@
#include "nrf.h"
#include <Arduino.h>
#if defined(OTA_QSPI_RAK3401_RADIO_BUS_HANDOFF)
#include <SPI.h>
#endif
#include <string.h>
namespace mesh {
@@ -162,6 +165,43 @@ static void configure_qspi_gpio(const nrf_qspi_pins_t& pins) {
NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_H0H1, NRF_GPIO_PIN_NOSENSE);
}
#if defined(OTA_QSPI_RAK3401_RADIO_BUS_HANDOFF)
static void disconnect_qspi_pins() {
const nrf_qspi_pins_t disconnected = {
NRF_QSPI_PIN_NOT_CONNECTED, NRF_QSPI_PIN_NOT_CONNECTED,
NRF_QSPI_PIN_NOT_CONNECTED, NRF_QSPI_PIN_NOT_CONNECTED,
NRF_QSPI_PIN_NOT_CONNECTED, NRF_QSPI_PIN_NOT_CONNECTED
};
nrf_qspi_pins_set(NRF_QSPI, &disconnected);
}
static void acquire_rak3401_radio_bus() {
// RadioLib transactions are synchronous in the main loop and its DIO1 ISR
// only records state, so no radio SPI transfer can overlap this handoff.
// The SX1262 may remain in autonomous RX while its distinct NSS is high.
// Reinitializing SPI1 after QSPI releases the pads is necessary because the
// QSPI GPIO setup changes their direction and drive configuration.
const uint8_t flash_cs = qspi_cs_pin();
nrf_gpio_pin_set(flash_cs);
nrf_gpio_cfg(flash_cs, NRF_GPIO_PIN_DIR_OUTPUT, NRF_GPIO_PIN_INPUT_DISCONNECT,
NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_H0H1, NRF_GPIO_PIN_NOSENSE);
pinMode(P_LORA_NSS, OUTPUT);
digitalWrite(P_LORA_NSS, HIGH);
SPI1.end();
}
static void release_rak3401_radio_bus() {
const uint8_t flash_cs = qspi_cs_pin();
nrf_gpio_pin_set(flash_cs);
nrf_gpio_cfg(flash_cs, NRF_GPIO_PIN_DIR_OUTPUT, NRF_GPIO_PIN_INPUT_DISCONNECT,
NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_H0H1, NRF_GPIO_PIN_NOSENSE);
disconnect_qspi_pins();
SPI1.begin();
pinMode(P_LORA_NSS, OUTPUT);
digitalWrite(P_LORA_NSS, HIGH);
}
#endif
static void wake_qspi_flash_before_activate(const nrf_qspi_pins_t& pins) {
// nRF52840 TASKS_ACTIVATE communicates with the NOR before CINSTR is
// available. A flash put to sleep by our preceding 0xB9 ignores that
@@ -297,6 +337,13 @@ bool OtaStoreQspiNrf52::waitMemoryReady(uint32_t timeout_ms) {
bool OtaStoreQspiNrf52::ensureFlash() {
if (_qspi_ready) return true;
#if defined(OTA_QSPI_RAK3401_RADIO_BUS_HANDOFF)
if (!_shared_radio_bus_acquired) {
acquire_rak3401_radio_bus();
_shared_radio_bus_acquired = true;
}
#endif
#if defined(OTA_QSPI_POWER_PIN)
pinMode(OTA_QSPI_POWER_PIN, OUTPUT);
digitalWrite(OTA_QSPI_POWER_PIN, HIGH);
@@ -447,12 +494,16 @@ void OtaStoreQspiNrf52::releaseFlash() {
nrf_qspi_disable(NRF_QSPI);
nrf_qspi_event_clear(NRF_QSPI, NRF_QSPI_EVENT_READY);
if (_memory_operation_pending) {
#if defined(OTA_QSPI_RAK3401_RADIO_BUS_HANDOFF)
disconnect_qspi_pins();
#else
const nrf_qspi_pins_t disconnected = {
NRF_QSPI_PIN_NOT_CONNECTED, NRF_QSPI_PIN_NOT_CONNECTED,
NRF_QSPI_PIN_NOT_CONNECTED, NRF_QSPI_PIN_NOT_CONNECTED,
NRF_QSPI_PIN_NOT_CONNECTED, NRF_QSPI_PIN_NOT_CONNECTED
};
nrf_qspi_pins_set(NRF_QSPI, &disconnected);
#endif
}
}
_qspi_active = false;
@@ -465,6 +516,12 @@ void OtaStoreQspiNrf52::releaseFlash() {
#elif defined(QSPI_FLASH_EN)
if (!_memory_operation_pending) digitalWrite(QSPI_FLASH_EN, LOW);
#endif
#if defined(OTA_QSPI_RAK3401_RADIO_BUS_HANDOFF)
if (_shared_radio_bus_acquired) {
release_rak3401_radio_bus();
_shared_radio_bus_acquired = false;
}
#endif
}
bool OtaStoreQspiNrf52::dmaReadAligned(uint32_t address, uint32_t length) {
+18 -1
View File
@@ -15,7 +15,21 @@
#endif
#if defined(OTA_QSPI_SHARED_WISBLOCK_SPI) && defined(RAK_3401)
#error "RAK3401's RAK13302 radio already owns the WisBlock SPI bus/chip-select"
#if !defined(OTA_QSPI_RAK3401_RADIO_BUS_HANDOFF)
#error "RAK3401 WisBlock SPI staging requires the explicit RAK13302 bus-handoff contract"
#endif
#if !defined(OTA_QSPI_CS_ARDUINO_PIN)
#error "RAK3401 shared-SPI staging requires an explicit flash chip-select"
#elif OTA_QSPI_CS_ARDUINO_PIN == 26
#error "RAK3401 W25 flash and RAK13302 radio must use different chip-selects"
#endif
#if !defined(OTA_QSPI_SCK_ARDUINO_PIN) || !defined(OTA_QSPI_IO0_ARDUINO_PIN) || \
!defined(OTA_QSPI_IO1_ARDUINO_PIN)
#error "RAK3401 radio-bus handoff requires explicit Arduino SPI pin overrides"
#elif OTA_QSPI_SCK_ARDUINO_PIN != 3 || OTA_QSPI_IO0_ARDUINO_PIN != 30 || \
OTA_QSPI_IO1_ARDUINO_PIN != 29 || OTA_QSPI_CS_ARDUINO_PIN != 31
#error "RAK3401 W25 handoff is bound to SCK P0.03, MOSI P0.30, MISO P0.29, CS P0.31"
#endif
#endif
namespace mesh {
@@ -113,6 +127,9 @@ class OtaStoreQspiNrf52 : public OtaStore {
bool _qspi_active = false;
bool _qspi_awake = false;
bool _qspi_ready = false;
#if defined(OTA_QSPI_RAK3401_RADIO_BUS_HANDOFF)
bool _shared_radio_bus_acquired = false;
#endif
bool _memory_operation_pending = false;
bool _io_ok = true;
bool _meta_dirty = false;
+4 -1
View File
@@ -2,7 +2,7 @@
#include <stdint.h>
// AUTO-GENERATED by tools/mota/gen_targets.py - do not edit by hand.
// 609 OTA-capable build targets. Maps target_id (= sha2-256:4 of the target name, LE uint32)
// 612 OTA-capable build targets. Maps target_id (= sha2-256:4 of the target name, LE uint32)
// to the human-readable env name, so a node/tool can name a target seen over the air WITHOUT
// transmitting the string in the .mota / LoRa protocol. Regenerate when the OTA env set changes.
// Size-constrained receivers can set OTA_TARGET_NAME_TABLE=0. They still match targets by ID;
@@ -444,6 +444,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0xced7e127, "RAK_3112_sensor" },
{ 0x6925aaf0, "RAK_3112_terminal_chat" },
{ 0x2fa509c1, "RAK_3401_repeater_lora_ota_no_external_sensors" },
{ 0xa52ba3c8, "RAK_3401_repeater_rak13302_w25q16_lora_ota" },
{ 0x9f4d58ac, "RAK_4631_companion_radio_ble" },
{ 0x7a55dec3, "RAK_4631_companion_radio_ethernet" },
{ 0x5e69738a, "RAK_4631_companion_radio_full" },
@@ -453,6 +454,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0x41e33a97, "RAK_4631_repeater_bridge_rs232_serial2_lora_ota_no_external_sensors" },
{ 0x29a0da19, "RAK_4631_repeater_lora_ota_no_external_sensors" },
{ 0x29bc38dc, "RAK_4631_repeater_rak15001_slot_c_lora_ota" },
{ 0xc62da371, "RAK_4631_repeater_w25q16_lora_ota" },
{ 0xf1d3c5a8, "RAK_4631_terminal_chat" },
{ 0xc6d55752, "RAK_WisMesh_Tag_companion_radio_ble" },
{ 0x60683191, "RAK_WisMesh_Tag_companion_radio_usb" },
@@ -463,6 +465,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
{ 0x51fa1a49, "RAK_WisMesh_Tag_sensor" },
{ 0xdb73638b, "SenseCap_Solar_repeater" },
{ 0xd904c2d5, "SenseCapIndicator-ESPNow_comp_radio_usb" },
{ 0x3a14aac7, "SenseCapIndicator-LoRa-N16R2_comp_radio_usb_wifi" },
{ 0x620569f4, "SenseCapIndicator-LoRa_comp_radio_usb" },
{ 0x08483f6b, "SenseCapIndicator-LoRa_comp_radio_usb_wifi" },
{ 0x0db48f35, "solarxiao_30S_companion_radio_ble" },
+89 -22
View File
@@ -1,6 +1,23 @@
#include "MomentaryButton.h"
#define MULTI_CLICK_WINDOW_MS 280
#define BUTTON_DEBOUNCE_MS 25
#if defined(NRF52_PLATFORM) && \
defined(MOMENTARY_BUTTON_WAKE_FROM_SLEEP) && \
MOMENTARY_BUTTON_WAKE_FROM_SLEEP
namespace {
// nRF52 companion builds use sd_app_evt_wait() between loop iterations. The
// button state machine remains intentionally polling-based, but it still needs
// a GPIO event to wake that poller. Both edges matter: a falling edge records
// button-down and a rising edge records release. The companion loop stays
// awake while needsPolling() reports a gesture deadline so long/multi-click
// timing can complete without another GPIO edge.
void wakeMomentaryButtonPoller() {}
} // namespace
#endif
MomentaryButton::MomentaryButton(int8_t pin, int long_press_millis, bool reverse, bool pulldownup, bool multiclick) {
_pin = pin;
@@ -11,10 +28,14 @@ MomentaryButton::MomentaryButton(int8_t pin, int long_press_millis, bool reverse
cancel = 0;
_long_millis = long_press_millis;
_threshold = 0;
_press_active = false;
_click_count = 0;
_last_click_time = 0;
_multi_click_window = multiclick ? MULTI_CLICK_WINDOW_MS : 0;
_pending_click = false;
_candidate_level = prev;
_candidate_since = 0;
_debouncing = false;
}
MomentaryButton::MomentaryButton(int8_t pin, int long_press_millis, int analog_threshold) {
@@ -26,15 +47,26 @@ MomentaryButton::MomentaryButton(int8_t pin, int long_press_millis, int analog_t
cancel = 0;
_long_millis = long_press_millis;
_threshold = analog_threshold;
_press_active = false;
_click_count = 0;
_last_click_time = 0;
_multi_click_window = MULTI_CLICK_WINDOW_MS;
_pending_click = false;
_candidate_level = prev;
_candidate_since = 0;
_debouncing = false;
}
void MomentaryButton::begin() {
if (_pin >= 0 && _threshold == 0) {
pinMode(_pin, _pull ? (_reverse ? INPUT_PULLUP : INPUT_PULLDOWN) : INPUT);
#if defined(NRF52_PLATFORM) && \
defined(MOMENTARY_BUTTON_WAKE_FROM_SLEEP) && \
MOMENTARY_BUTTON_WAKE_FROM_SLEEP
// The ISR deliberately owns no button logic; it only makes a sleeping
// event-driven main loop run the normal debounced polling state machine.
attachInterrupt((uint32_t)_pin, wakeMomentaryButtonPoller, CHANGE);
#endif
}
}
@@ -46,6 +78,7 @@ bool MomentaryButton::isPressed() const {
void MomentaryButton::cancelClick() {
cancel = 1;
down_at = 0;
_press_active = false;
_click_count = 0;
_last_click_time = 0;
_pending_click = false;
@@ -66,29 +99,52 @@ int MomentaryButton::check(bool repeat_click) {
if (_pin < 0) return BUTTON_EVENT_NONE;
int event = BUTTON_EVENT_NONE;
int btn = _threshold > 0 ? (analogRead(_pin) < _threshold) : digitalRead(_pin);
const uint32_t now = millis();
const int raw_btn =
_threshold > 0 ? (analogRead(_pin) < _threshold) : digitalRead(_pin);
// Treat prev as the stable electrical level. A raw transition must remain
// unchanged for a short interval before it can alter gesture state. Without
// this, one physical release can be counted two or three times and a short
// click can silently turn into KEY_PREV or a triple-click action.
int btn = prev;
if (raw_btn == prev) {
_debouncing = false;
} else if (!_debouncing || raw_btn != _candidate_level) {
_candidate_level = raw_btn;
_candidate_since = now;
_debouncing = true;
} else if ((uint32_t)(now - _candidate_since) >= BUTTON_DEBOUNCE_MS) {
btn = raw_btn;
_debouncing = false;
}
if (btn != prev) {
if (isPressed(btn)) {
down_at = millis();
down_at = now;
_press_active = true;
} else {
// button UP
if (_long_millis > 0) {
if (down_at > 0 && (unsigned long)(millis() - down_at) < _long_millis) { // only a CLICK if still within the long_press millis
_click_count++;
_last_click_time = millis();
_pending_click = true;
}
} else {
if (!cancel && _press_active && _long_millis > 0) {
if ((uint32_t)(now - down_at) >= (uint32_t)_long_millis) {
// Normally the polling loop reports this while the button is still
// down. Also handle release-only polling so event-driven platforms
// cannot lose a long press if no intermediate poll occurred.
event = BUTTON_EVENT_LONG_PRESS;
_click_count = 0;
_last_click_time = 0;
_pending_click = false;
} else {
_click_count++;
_last_click_time = millis();
_last_click_time = now;
_pending_click = true;
}
} else if (!cancel && _press_active) {
_click_count++;
_last_click_time = now;
_pending_click = true;
}
if (event == BUTTON_EVENT_CLICK && cancel) {
event = BUTTON_EVENT_NONE;
_click_count = 0;
_last_click_time = 0;
_pending_click = false;
}
_press_active = false;
down_at = 0;
}
prev = btn;
@@ -97,27 +153,38 @@ int MomentaryButton::check(bool repeat_click) {
cancel = 0;
}
if (_long_millis > 0 && down_at > 0 && (unsigned long)(millis() - down_at) >= _long_millis) {
if (_long_millis > 0 && _press_active
&& (uint32_t)(now - down_at) >= (uint32_t)_long_millis) {
if (_pending_click) {
// long press during multi-click detection - cancel pending clicks
cancelClick();
} else {
event = BUTTON_EVENT_LONG_PRESS;
_press_active = false;
down_at = 0;
_click_count = 0;
_last_click_time = 0;
_pending_click = false;
}
}
if (down_at > 0 && repeat_click) {
unsigned long diff = (unsigned long)(millis() - down_at);
if (_press_active && repeat_click) {
uint32_t diff = (uint32_t)(now - down_at);
if (diff >= 700) {
event = BUTTON_EVENT_CLICK; // wait 700 millis before repeating the click events
}
}
if (_pending_click && (millis() - _last_click_time) >= _multi_click_window) {
if (down_at > 0) {
if (_pending_click
&& (uint32_t)(now - _last_click_time) >= (uint32_t)_multi_click_window) {
// A press candidate first observed before the deadline may legitimately
// become the next click even if its debounce interval crosses the window.
// A candidate first observed at/after the deadline must not revive and
// merge an already-expired sequence.
const bool press_candidate_in_window = _debouncing
&& isPressed(_candidate_level)
&& (uint32_t)(_candidate_since - _last_click_time)
< (uint32_t)_multi_click_window;
if (press_candidate_in_window || _press_active) {
// still pressed - wait for button release before processing clicks
return event;
}
@@ -142,4 +209,4 @@ int MomentaryButton::check(bool repeat_click) {
}
return event;
}
}
+9 -2
View File
@@ -14,11 +14,15 @@ class MomentaryButton {
bool _reverse, _pull;
int _long_millis;
int _threshold; // analog mode
unsigned long down_at;
uint32_t down_at;
bool _press_active;
uint8_t _click_count;
unsigned long _last_click_time;
uint32_t _last_click_time;
int _multi_click_window;
bool _pending_click;
int8_t _candidate_level;
uint32_t _candidate_since;
bool _debouncing;
bool isPressed(int level) const;
@@ -30,4 +34,7 @@ public:
void cancelClick(); // suppress next BUTTON_EVENT_CLICK (if already in DOWN state)
uint8_t getPin() { return _pin; }
bool isPressed() const;
bool needsPolling() const {
return _debouncing || _press_active || _pending_click;
}
};
+52 -11
View File
@@ -2,6 +2,10 @@
#include "../UsbLogging.h"
#include <TFT_eSPI.h>
#if defined(NRF52_PLATFORM)
#include <nrf_gpio.h>
#endif
//#include <Fonts/GFXFF/FreeSans9pt7b.h>
// Optimised ST7735 display driver, derived from Adafruit_ST7735 library.
@@ -462,12 +466,40 @@ bool ST7735Display::begin() {
if (!_isOn) {
if (_peripher_power) _peripher_power->claim();
delay(100); // TEMP!!
delay(100); // allow the peripheral rail to stabilize
pinMode(PIN_TFT_RST, OUTPUT);
pinMode(PIN_TFT_CS, OUTPUT);
pinMode(PIN_TFT_DC, OUTPUT);
// Preload the inactive latch before changing direction. This prevents an
// active-low backlight from flashing while the controller initializes.
digitalWrite(PIN_TFT_LEDA_CTL, !PIN_TFT_LEDA_CTL_ACTIVE);
pinMode(PIN_TFT_LEDA_CTL, OUTPUT);
// turnOff() releases the TFT bus pins to prevent back-powering. Restore
// them explicitly before touching SPI: on Adafruit nRF52, SPIClass::begin()
// is intentionally a no-op after the first initialization and therefore
// cannot repair pin modes that application power saving changed.
pinMode(PIN_TFT_SDA, OUTPUT);
pinMode(PIN_TFT_SCL, OUTPUT);
#if defined(NRF52_PLATFORM)
// SPIClass::begin() deliberately returns early after its first call. Match
// the Adafruit nRF52 SPI core's high-drive GPIO setup here so a display
// wake repairs the bus even while the SPI object remains initialized.
nrf_gpio_cfg(PIN_TFT_SCL,
NRF_GPIO_PIN_DIR_OUTPUT,
NRF_GPIO_PIN_INPUT_CONNECT,
NRF_GPIO_PIN_NOPULL,
NRF_GPIO_PIN_H0H1,
NRF_GPIO_PIN_NOSENSE);
nrf_gpio_cfg(PIN_TFT_SDA,
NRF_GPIO_PIN_DIR_OUTPUT,
NRF_GPIO_PIN_INPUT_DISCONNECT,
NRF_GPIO_PIN_NOPULL,
NRF_GPIO_PIN_H0H1,
NRF_GPIO_PIN_NOSENSE);
#endif
#ifdef ESP_PLATFORM
_spi->begin(PIN_TFT_SCL, -1 /* _miso */, PIN_TFT_SDA /* _mosi */, -1);
#else
@@ -487,7 +519,19 @@ bool ST7735Display::begin() {
_resetAndInit();
// Re-enter normal display mode explicitly and let the controller settle
// before priming its display RAM. A framebuffer transfer made only before
// DISPON can be lost while the panel is completing wake initialization.
sendCommand(ST77XX_NORON);
delay(10);
sendCommand(ST77XX_DISPON);
delay(100);
// Prime the now-active controller with the retained UI frame before enabling
// the backlight. This makes a button-only wake visible even when the UI has
// no other reason to redraw; a newly allocated sprite is already zeroed.
endFrame();
digitalWrite(PIN_TFT_LEDA_CTL, PIN_TFT_LEDA_CTL_ACTIVE);
_isOn = true;
}
@@ -497,13 +541,15 @@ bool ST7735Display::begin() {
void ST7735Display::_resetAndInit() {
if (!spriteReady()) return;
// Pulse Reset low for 10ms
// Pulse reset low, then give the controller its full reset-release recovery
// time before sending SLPOUT. Shorter delays can work on a cold panel but
// fail intermittently when the shared peripheral rail has only just cycled.
digitalWrite(PIN_TFT_RST, HIGH);
delay(2);
digitalWrite(PIN_TFT_RST, LOW);
delay(10);
digitalWrite(PIN_TFT_RST, HIGH);
delay(2);
delay(120);
// run init commands
displayInit(Rcmd1);
@@ -517,13 +563,6 @@ void ST7735Display::_resetAndInit() {
displayInit(Rcmd3);
setRotation(DISPLAY_ROTATION);
// clear the buffer before display on
sprite->fillScreen(ST77XX_BLACK);
endFrame();
// turn on backlight
digitalWrite(PIN_TFT_LEDA_CTL, PIN_TFT_LEDA_CTL_ACTIVE);
}
void ST7735Display::turnOn() {
@@ -540,7 +579,9 @@ void ST7735Display::turnOff() {
// Now turn off the backlight
digitalWrite(PIN_TFT_LEDA_CTL, !PIN_TFT_LEDA_CTL_ACTIVE);
// Prevent back-powering to save 2.8 mA
// Prevent back-powering to save 2.8 mA. Keep the SPI object initialized:
// begin() restores these GPIO directions explicitly on the next wake, and
// retaining the peripheral avoids an unchecked nrfx uninit/reinit cycle.
pinMode(PIN_TFT_CS, INPUT);
pinMode(PIN_TFT_DC, INPUT);
pinMode(PIN_TFT_SDA, INPUT);