mirror of
https://github.com/alexhopeoconnor/firmware.git
synced 2026-10-16 16:41:33 +10:00
SenseCAP Indicator: RP2040 peripherals for the main firmware (#6220)
* indicator: RP2040 peripherals for the main firmware The SenseCAP Indicator RP2040 co-processor serves as a generic peripheral bridge over a serial protobuf link (interdevice.proto): - FakeI2C implements TwoWire and tunnels write and read transactions, so the standard sensor drivers and the I2C scan work unmodified on the bridged second bus (WIRE1) - FakeUART forwards GPS NMEA to the regular GPS driver - SD card access with chunked file transfers, paged directory listings and card statistics; device-ui loads map tiles and map styles from the card behind the RP2040 - link at 2M baud with 4KB chunks, message structs kept off task stacks Log messages carrying their own bracket tag render it like a thread name. Replaces the earlier IndicatorSensor/COBS approach. * indicator: address review Correlate responses with request ids, serialize the shared TX buffer, reject oversized frames, fix RX buffer overflow and NMEA truncation, full-length file paths. * indicator: assign the GPS FakeUART at runtime Static initialization order across translation units is undefined, so createGps() assigns and null-checks the bridged serial instead. Bound the NMEA length defensively. * indicator: bump device-ui pin to 27e6c0c * indicator: ping/pong link probe, non-blocking runOnce, FakeI2C locking The RP2040 sends nothing unsolicited without a GPS module attached, so wait_ready now probes with the new ping message instead of listening passively. runOnce skips its pump while a requester holds link_lock, keeping the main loop from blocking for a full request timeout. FakeI2C serializes transactions between the UI task and the main loop with an owner-tracked lock held from beginTransmission to transaction end. * indicator: link resync, config-honoring GPS, bridged-bus routing, stats validity Frame resync scans to the next magic instead of flushing the RX buffer, and the pump handles all buffered frames per pass. The RX drain reads in bulk and the protobuf encoder gets the correct buffer bound. GPS honors the gps_mode setting on the Indicator instead of always running. RTC, I2C keyboard and motion sensor drivers resolve WIRE1 through ScanI2CTwoWire::fetchI2CBus so bridged buses reach the right transport. FakeUART implements flush/availableForWrite/const-write from the Stream contract and fences its cross-core ring buffer. SdCardInfo.stats_valid is passed through to device-ui, and the remote FS backend gains the remove operation used for cleanup of failed tile saves. * indicator: retry lost link round trips, I2CResult UNSPECIFIED Remote FS operations retry once on a transport timeout. Correlation ids drop late responses of the first attempt; a retried append whose first attempt landed is recognized by the offset conflict carrying the resulting file size. Definitive failures are not retried, missing-tile probes stay a single round trip. Regenerated bindings add the I2CResult.Status UNSPECIFIED zero value so an empty result cannot decode as success. * indicator: nack responses, rename bridge classes to I2CProxy/UARTProxy A request the co-processor cannot decode or handle is nacked, so the requester fails fast instead of burning its timeout. All requests stage the shared tx_message under link_lock. FakeI2C and FakeUART are renamed to I2CProxy and UARTProxy after the pattern they implement, with their instances following suit. Drops dead code (unused NO_NEWS_PAUSE, unreachable not-running branches, doubled include guards) and the GPS pin log line that is meaningless on the tunneled port. * indicator: refuse a co-processor that speaks another protocol version The ping/pong handshake now carries InterdeviceVersion. A pong reporting a version other than ours means the RP2040 runs firmware that does not match this build, so the bridge stays shut down for the session and the mismatch is logged with both versions. Requests fail fast instead of being misinterpreted by the other side. * indicator: regen protos, interdevice protocol version 2 * indicator: per-task I2C contexts, gated handshake, retryable link failures The bridged I2C bus is shared between the main loop and the UI task, and TwoWire has no transaction bracket a lock can span: drivers drain the read buffer with available()/read() long after requestFrom() returned. Each calling task therefore gets its own staging and read buffers instead of a lock that could be left held (or that could not protect the read buffer anyway). The transaction is staged inside the link, under its lock. No request is sent before the co-processor has completed the version handshake, and runOnce keeps probing until it does, so a co-processor that boots slowly or reboots on its watchdog no longer leaves the bridge dead for the session. Requests in flight are counted, not flagged: two threads can be in a request and the first one out must not clear the other's state. File operations are retried on a lost frame and on a co-processor busy with card maintenance, but not on a refusal (nack) or a definitive failure, and they release the SPI lock while they wait so a slow link does not starve the radio. * indicator: fail safe on a peer mismatch, wait out card maintenance FileStatus moved to a fresh tag: reusing the tag of the removed success flag made every failure status decode as success on a peer that predates it. A card being mounted (busy) is retried rather than reported as an empty slot, and a co-processor busy with card maintenance is waited out: mounting takes seconds and the free space scan of a large card walks its whole FAT, which is not a reason to report a missing tile. The bridged I2C bus releases the SPI lock as well, so the keyboard scan on the UI task cannot starve the radio either. Slot claims in the I2C proxy are atomic, NMEA is not sent to a peer we refuse to talk to, and the handshake is completed by the unsolicited ping the co-processor sends when it has booted, which also reports a reboot. * indicator: regen protos, FileStatus back on the original tags * indicator: regen protos, ping/pong carry the InterdeviceVersion enum * indicator: point the protobufs submodule at the merged interdevice protos * indicator: pin device-ui to the branch with the remote SD support * indicator: honor the txOnly flag of flush, report dropped GPS writes flush() through a Stream pointer discarded the receive buffer: the flag is txOnly, and HardwareSerial::flush() keeps what has been received. write() reported bytes as written even when the link refused to send them. The link probe uses Throttle for its rate limit. * indicator: decide the log tag on the formatted message, hex request ids The thread tag was suppressed based on the printf template, which disagrees with the rendered message it is compared against: a format starting with a conversion could produce two tags, and one without a trailing bracket-space lost the tag entirely. vprintf now receives the thread name and picks. Also shifts only the bytes actually buffered after a frame, throttles with Throttle and logs request ids as hex. * indicator: SD mount, eject and format commands over the link * indicator: bound how long a busy card state blocks the UI task * indicator: a busy co-processor must not block the UI task for ever The busy retry re-armed its own budget on every busy answer, so a co-processor that stayed busy kept the caller in the loop with no way out. Transport retries and the wait for a busy card are now separate budgets that only count down. * indicator: start each request from an aligned receive buffer A byte run lost mid-response (a UART overflow during a 4KB tile chunk, when the display starves the RX interrupt) misaligns the assembly buffer. The buffer was never reset, so the poison outlived the request and cascaded into the following chunks of the same tile: one glitch dropped a whole multi-chunk tile, while single-chunk tiles resynced in the idle gap and survived. Each request now flushes the buffer first, bounding a glitch to the one chunk it hit. Adds resync/decode/timeout counters, logged rarely, to see the rate. * indicator: enlarge the LVGL heap for low-zoom map tiles The heap was 3MB and the image cache reserves 1.5MB of it, so a low-zoom map tile could not find a large enough contiguous block to decode and rendered white. 5MB of the 8MB PSRAM fixes it with room to spare. * indicator: advance the device-ui and protobufs pins to the merged commits Point the protobufs submodule at the merged SD command protos (protobufs #986) so it matches the checked in interdevice sources, and bump the device-ui archive to the current indicator branch tip that carries the SD button and format UI. * Update device-ui library dependency URL * remove cutom sdkconfig * remove duplicated synchronisation (after PR11278 is in place) * set commit reference to updated RemoteSDService class * Add board_level configuration for release * fix cppcheck errors --------- Co-authored-by: Manuel <71137295+mverch67@users.noreply.github.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Co-authored-by: CodeRabbit <noreply@coderabbit.ai> Co-authored-by: mverch67 <manuel.verch@gmx.de>
This commit is contained in:
co-authored by
Manuel
coderabbitai[bot]
CodeRabbit
mverch67
parent
25996e9330
commit
4b4e82bd72
@@ -0,0 +1,516 @@
|
||||
#ifdef SENSECAP_INDICATOR
|
||||
|
||||
#include "IndicatorSerial.h"
|
||||
#include "concurrency/LockGuard.h"
|
||||
#include "mesh/comms/UARTProxy.h"
|
||||
#include <HardwareSerial.h>
|
||||
#include <Throttle.h>
|
||||
#include <pb_decode.h>
|
||||
#include <pb_encode.h>
|
||||
|
||||
SensecapIndicator *sensecapIndicator;
|
||||
|
||||
SensecapIndicator::SensecapIndicator(HardwareSerial &serial) : OSThread("SensecapIndicator")
|
||||
{
|
||||
_serial = &serial;
|
||||
// Twice the largest frame: the pump runs from the cooperative main
|
||||
// loop, which can stall for tens of ms while data keeps arriving
|
||||
_serial->setRxBufferSize(2 * PB_BUFSIZE);
|
||||
_serial->setPins(SENSOR_RP2040_RXD, SENSOR_RP2040_TXD);
|
||||
_serial->begin(SENSOR_BAUD_RATE);
|
||||
LOG_DEBUG("Start indicator communication thread");
|
||||
}
|
||||
|
||||
int32_t SensecapIndicator::runOnce()
|
||||
{
|
||||
// A requester is pumping the link itself and holds link_lock for up
|
||||
// to its full request timeout; blocking on the lock here would stall
|
||||
// every other thread of the cooperative main loop with it
|
||||
if (requests_in_flight > 0)
|
||||
return (10);
|
||||
concurrency::LockGuard guard(&link_lock);
|
||||
pump();
|
||||
// Keep probing until the co-processor has answered the handshake: it
|
||||
// may boot slower than we do, or reboot on its watchdog. Without this
|
||||
// the bridge would stay dead for the rest of the session.
|
||||
if (!handshake_done)
|
||||
probe_link();
|
||||
// Diagnostics for the map-tile transfers: a resync or a decode failure
|
||||
// means a response was corrupted on the wire, a timeout means it never
|
||||
// arrived. Printed at most once every two seconds, and only when
|
||||
// something went wrong.
|
||||
if ((link_resyncs || link_decode_fail || link_timeouts) && !Throttle::isWithinTimespanMs(last_link_report, 2000)) {
|
||||
last_link_report = millis();
|
||||
LOG_WARN("link: resync=%u decode_fail=%u timeout=%u", (unsigned)link_resyncs, (unsigned)link_decode_fail,
|
||||
(unsigned)link_timeouts);
|
||||
link_resyncs = link_decode_fail = link_timeouts = 0;
|
||||
}
|
||||
return (10);
|
||||
}
|
||||
|
||||
// Send a ping, rate limited. The co-processor answers with a pong carrying
|
||||
// the protocol version it speaks. Caller holds link_lock.
|
||||
void SensecapIndicator::probe_link()
|
||||
{
|
||||
// last_probe 0 means we have not probed at all yet, which must not throttle
|
||||
if (last_probe != 0 && Throttle::isWithinTimespanMs(last_probe, 250))
|
||||
return;
|
||||
meshtastic_InterdeviceMessage &msg = tx_message;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.which_data = meshtastic_InterdeviceMessage_ping_tag;
|
||||
msg.data.ping = meshtastic_InterdeviceVersion_INTERDEVICE_VERSION_CURRENT;
|
||||
stamp_request(msg);
|
||||
send_uplink_unlocked(msg);
|
||||
last_probe = millis();
|
||||
}
|
||||
|
||||
// Read whatever is available on the link and process complete packets
|
||||
void SensecapIndicator::pump()
|
||||
{
|
||||
size_t space_left = PB_BUFSIZE - pb_rx_size;
|
||||
pb_rx_size += serial_check((char *)pb_rx_buf + pb_rx_size, space_left);
|
||||
check_packet();
|
||||
}
|
||||
|
||||
// Pump the link until `flag` goes true, a nack arrives, or the timeout
|
||||
// expires
|
||||
bool SensecapIndicator::wait_response(const bool &flag, uint32_t timeout_ms)
|
||||
{
|
||||
uint32_t start = millis();
|
||||
while (!flag) {
|
||||
pump();
|
||||
if (request_nacked)
|
||||
return false; // the other side could not handle the request
|
||||
if (!Throttle::isWithinTimespanMs(start, timeout_ms)) {
|
||||
link_timeouts++;
|
||||
return false;
|
||||
}
|
||||
delay(1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// assign the next correlation id to a request, skipping the unsolicited 0
|
||||
uint32_t SensecapIndicator::stamp_request(meshtastic_InterdeviceMessage &request)
|
||||
{
|
||||
if (++next_request_id == 0)
|
||||
next_request_id = 1;
|
||||
request.id = next_request_id;
|
||||
expected_id = next_request_id;
|
||||
request_nacked = false;
|
||||
// Start the response for this request from an aligned buffer. A byte run
|
||||
// lost mid-response (a UART overflow during a 4KB chunk) leaves the
|
||||
// assembly misaligned, and without this that poison would outlive the
|
||||
// request and cascade into the following chunks of the same tile. The
|
||||
// link is single-outstanding and stale responses are dropped by id, so
|
||||
// nothing worth keeping is ever pending here (at most a partial NMEA
|
||||
// sentence, which self-heals).
|
||||
pb_rx_size = 0;
|
||||
return next_request_id;
|
||||
}
|
||||
|
||||
// callers hold link_lock: the co-processor has completed the handshake and
|
||||
// speaks our protocol version. Fails fast instead of timing out per request.
|
||||
bool SensecapIndicator::link_ready()
|
||||
{
|
||||
return handshake_done && link_compatible;
|
||||
}
|
||||
|
||||
// The co-processor reported the protocol version it speaks, in a pong or in
|
||||
// the unsolicited ping it sends when it has booted. Anything else than ours
|
||||
// means its firmware does not match this build, and every request would be
|
||||
// misinterpreted. Caller holds link_lock.
|
||||
void SensecapIndicator::note_handshake(uint32_t peer_version)
|
||||
{
|
||||
bool compatible = peer_version == meshtastic_InterdeviceVersion_INTERDEVICE_VERSION_CURRENT;
|
||||
bool changed = !handshake_done || compatible != link_compatible;
|
||||
if (changed) {
|
||||
if (compatible)
|
||||
LOG_INFO("RP2040 link up, interdevice protocol v%u", (unsigned)peer_version);
|
||||
else
|
||||
LOG_ERROR("RP2040 speaks interdevice protocol v%u, this firmware speaks v%u. Flash the matching "
|
||||
"indicator_rp2040 firmware; sensors, GPS and SD card stay disabled",
|
||||
(unsigned)peer_version, (unsigned)meshtastic_InterdeviceVersion_INTERDEVICE_VERSION_CURRENT);
|
||||
}
|
||||
link_compatible = compatible;
|
||||
handshake_done = true;
|
||||
}
|
||||
|
||||
bool SensecapIndicator::i2c_transact(uint8_t address, const uint8_t *wbuf, size_t wlen, size_t rlen, meshtastic_I2CResult *result,
|
||||
uint32_t timeout_ms)
|
||||
{
|
||||
InFlight busy(requests_in_flight);
|
||||
concurrency::LockGuard guard(&link_lock);
|
||||
if (!link_ready())
|
||||
return false;
|
||||
|
||||
meshtastic_InterdeviceMessage &msg = tx_message;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.which_data = meshtastic_InterdeviceMessage_i2c_transaction_tag;
|
||||
msg.data.i2c_transaction.address = address;
|
||||
msg.data.i2c_transaction.read_len = rlen;
|
||||
if (wlen > sizeof(msg.data.i2c_transaction.write_data.bytes))
|
||||
return false;
|
||||
msg.data.i2c_transaction.write_data.size = wlen;
|
||||
if (wlen)
|
||||
memcpy(msg.data.i2c_transaction.write_data.bytes, wbuf, wlen);
|
||||
|
||||
stamp_request(msg);
|
||||
i2c_result_ready = false;
|
||||
if (!send_uplink_unlocked(msg))
|
||||
return false;
|
||||
|
||||
if (!wait_response(i2c_result_ready, timeout_ms))
|
||||
return false;
|
||||
*result = i2c_result;
|
||||
i2c_result_ready = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SensecapIndicator::file_request(meshtastic_InterdeviceMessage &request, meshtastic_FileTransfer *out, uint32_t timeout_ms)
|
||||
{
|
||||
stamp_request(request);
|
||||
file_response_ready = false;
|
||||
pending_file = out;
|
||||
if (!send_uplink_unlocked(request) || !wait_response(file_response_ready, timeout_ms)) {
|
||||
pending_file = NULL;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SensecapIndicator::file_read(const char *path, uint32_t offset, uint32_t length, meshtastic_FileTransfer *out,
|
||||
uint32_t timeout_ms)
|
||||
{
|
||||
InFlight busy(requests_in_flight);
|
||||
concurrency::LockGuard guard(&link_lock);
|
||||
if (!link_ready())
|
||||
return false;
|
||||
|
||||
meshtastic_InterdeviceMessage &msg = tx_message;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.which_data = meshtastic_InterdeviceMessage_file_transfer_tag;
|
||||
msg.data.file_transfer.operation = meshtastic_FileOperation_GET;
|
||||
strncpy(msg.data.file_transfer.filepath, path, sizeof(msg.data.file_transfer.filepath) - 1);
|
||||
msg.data.file_transfer.offset = offset;
|
||||
msg.data.file_transfer.length = length;
|
||||
return file_request(msg, out, timeout_ms);
|
||||
}
|
||||
|
||||
bool SensecapIndicator::file_write(const char *path, uint32_t offset, const uint8_t *data, size_t len, bool create,
|
||||
meshtastic_FileTransfer *out, uint32_t timeout_ms)
|
||||
{
|
||||
InFlight busy(requests_in_flight);
|
||||
concurrency::LockGuard guard(&link_lock);
|
||||
if (!link_ready())
|
||||
return false;
|
||||
|
||||
meshtastic_InterdeviceMessage &msg = tx_message;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.which_data = meshtastic_InterdeviceMessage_file_transfer_tag;
|
||||
msg.data.file_transfer.operation = create ? meshtastic_FileOperation_POST : meshtastic_FileOperation_PUT;
|
||||
strncpy(msg.data.file_transfer.filepath, path, sizeof(msg.data.file_transfer.filepath) - 1);
|
||||
msg.data.file_transfer.offset = offset;
|
||||
if (len > sizeof(msg.data.file_transfer.filedata.bytes))
|
||||
return false;
|
||||
msg.data.file_transfer.filedata.size = len;
|
||||
memcpy(msg.data.file_transfer.filedata.bytes, data, len);
|
||||
return file_request(msg, out, timeout_ms);
|
||||
}
|
||||
|
||||
bool SensecapIndicator::file_remove(const char *path, meshtastic_FileTransfer *out, uint32_t timeout_ms)
|
||||
{
|
||||
InFlight busy(requests_in_flight);
|
||||
concurrency::LockGuard guard(&link_lock);
|
||||
if (!link_ready())
|
||||
return false;
|
||||
|
||||
meshtastic_InterdeviceMessage &msg = tx_message;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.which_data = meshtastic_InterdeviceMessage_file_transfer_tag;
|
||||
msg.data.file_transfer.operation = meshtastic_FileOperation_DELETE;
|
||||
strncpy(msg.data.file_transfer.filepath, path, sizeof(msg.data.file_transfer.filepath) - 1);
|
||||
return file_request(msg, out, timeout_ms);
|
||||
}
|
||||
|
||||
bool SensecapIndicator::list_directory(const char *path, uint32_t offset, meshtastic_DirectoryListing *out, uint32_t timeout_ms)
|
||||
{
|
||||
InFlight busy(requests_in_flight);
|
||||
concurrency::LockGuard guard(&link_lock);
|
||||
if (!link_ready())
|
||||
return false;
|
||||
|
||||
meshtastic_InterdeviceMessage &msg = tx_message;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.which_data = meshtastic_InterdeviceMessage_directory_listing_tag;
|
||||
strncpy(msg.data.directory_listing.directory, path, sizeof(msg.data.directory_listing.directory) - 1);
|
||||
msg.data.directory_listing.offset = offset;
|
||||
|
||||
stamp_request(msg);
|
||||
dir_response_ready = false;
|
||||
pending_dir = out;
|
||||
if (!send_uplink_unlocked(msg) || !wait_response(dir_response_ready, timeout_ms)) {
|
||||
pending_dir = NULL;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SensecapIndicator::sd_info(meshtastic_SdCardInfo *out, uint32_t timeout_ms)
|
||||
{
|
||||
InFlight busy(requests_in_flight);
|
||||
concurrency::LockGuard guard(&link_lock);
|
||||
if (!link_ready())
|
||||
return false;
|
||||
|
||||
meshtastic_InterdeviceMessage &msg = tx_message;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.which_data = meshtastic_InterdeviceMessage_get_sd_info_tag;
|
||||
msg.data.get_sd_info = true;
|
||||
|
||||
stamp_request(msg);
|
||||
sd_info_ready = false;
|
||||
pending_sd_info = out;
|
||||
if (!send_uplink_unlocked(msg) || !wait_response(sd_info_ready, timeout_ms)) {
|
||||
pending_sd_info = NULL;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SensecapIndicator::sd_command(meshtastic_SdCommand command, meshtastic_SdCardInfo *out, uint32_t timeout_ms)
|
||||
{
|
||||
InFlight busy(requests_in_flight);
|
||||
concurrency::LockGuard guard(&link_lock);
|
||||
if (!link_ready())
|
||||
return false;
|
||||
|
||||
meshtastic_InterdeviceMessage &msg = tx_message;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.which_data = meshtastic_InterdeviceMessage_sd_command_tag;
|
||||
msg.data.sd_command = command;
|
||||
|
||||
stamp_request(msg);
|
||||
sd_info_ready = false;
|
||||
pending_sd_info = out;
|
||||
if (!send_uplink_unlocked(msg) || !wait_response(sd_info_ready, timeout_ms)) {
|
||||
pending_sd_info = NULL;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SensecapIndicator::wait_ready(uint32_t timeout_ms)
|
||||
{
|
||||
InFlight busy(requests_in_flight);
|
||||
concurrency::LockGuard guard(&link_lock);
|
||||
uint32_t start = millis();
|
||||
while (!handshake_done) {
|
||||
// The co-processor never sends anything unsolicited unless a GPS
|
||||
// module is attached, so waiting passively would leave the bridge
|
||||
// down forever on GPS-less units. Ping until it answers; the pong
|
||||
// touches no peripherals on the other side and carries the
|
||||
// protocol version it speaks. If it does not answer in time,
|
||||
// runOnce keeps probing (a slow boot must not disable the bridge
|
||||
// for the session), but no request is sent until it does.
|
||||
probe_link();
|
||||
pump();
|
||||
if (handshake_done)
|
||||
break;
|
||||
if (!Throttle::isWithinTimespanMs(start, timeout_ms))
|
||||
return false;
|
||||
delay(1);
|
||||
}
|
||||
return link_compatible;
|
||||
}
|
||||
|
||||
bool SensecapIndicator::send_uplink(const meshtastic_InterdeviceMessage &message)
|
||||
{
|
||||
InFlight busy(requests_in_flight);
|
||||
concurrency::LockGuard guard(&link_lock);
|
||||
if (!link_ready())
|
||||
return false; // nothing is sent to a peer we do not speak the same protocol with
|
||||
return send_uplink_unlocked(message);
|
||||
}
|
||||
|
||||
// callers must hold link_lock: pb_tx_buf is shared
|
||||
bool SensecapIndicator::send_uplink_unlocked(const meshtastic_InterdeviceMessage &message)
|
||||
{
|
||||
pb_tx_buf[0] = MT_MAGIC_0;
|
||||
pb_tx_buf[1] = MT_MAGIC_1;
|
||||
|
||||
pb_ostream_t stream = pb_ostream_from_buffer(pb_tx_buf + MT_HEADER_SIZE, PB_BUFSIZE - MT_HEADER_SIZE);
|
||||
if (!pb_encode(&stream, meshtastic_InterdeviceMessage_fields, &message)) {
|
||||
LOG_DEBUG("pb_encode failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Store the payload length in the header
|
||||
pb_tx_buf[2] = stream.bytes_written / 256;
|
||||
pb_tx_buf[3] = stream.bytes_written % 256;
|
||||
|
||||
bool rv = send((const char *)pb_tx_buf, MT_HEADER_SIZE + stream.bytes_written);
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
size_t SensecapIndicator::serial_check(char *buf, size_t space_left)
|
||||
{
|
||||
int avail = _serial->available();
|
||||
if (avail <= 0)
|
||||
return 0;
|
||||
if ((size_t)avail > space_left)
|
||||
avail = space_left;
|
||||
// bulk copy out of the driver's RX buffer; only reads what is available
|
||||
return _serial->read((uint8_t *)buf, avail);
|
||||
}
|
||||
|
||||
// Distance to the next byte that could start a frame. Skips the corrupt
|
||||
// prefix while keeping anything that may be a frame queued behind it (a
|
||||
// trailing lone MT_MAGIC_0 counts, its successor has not arrived yet).
|
||||
static size_t scan_magic(const pb_byte_t *buf, size_t len)
|
||||
{
|
||||
for (size_t i = 1; i < len; i++) {
|
||||
if (buf[i] == MT_MAGIC_0 && (i + 1 == len || buf[i + 1] == MT_MAGIC_1))
|
||||
return i;
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
void SensecapIndicator::check_packet()
|
||||
{
|
||||
// process everything buffered; one pump can deliver several frames
|
||||
while (pb_rx_size >= MT_HEADER_SIZE) {
|
||||
size_t payload_len = (size_t)(pb_rx_buf[2] << 8 | pb_rx_buf[3]);
|
||||
if (pb_rx_buf[0] != MT_MAGIC_0 || pb_rx_buf[1] != MT_MAGIC_1 || payload_len + MT_HEADER_SIZE > PB_BUFSIZE) {
|
||||
// Corrupt or false header: resync on the next magic instead of
|
||||
// flushing, one bad byte must not cost the frames behind it
|
||||
size_t skip = scan_magic(pb_rx_buf, pb_rx_size);
|
||||
link_resyncs++;
|
||||
LOG_DEBUG("Bad frame header, dropping %u bytes", (unsigned)skip);
|
||||
memmove(pb_rx_buf, pb_rx_buf + skip, pb_rx_size - skip);
|
||||
pb_rx_size -= skip;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (payload_len + MT_HEADER_SIZE > pb_rx_size)
|
||||
return; // frame not complete yet
|
||||
|
||||
handle_packet(payload_len);
|
||||
}
|
||||
}
|
||||
|
||||
bool SensecapIndicator::handle_packet(size_t payload_len)
|
||||
{
|
||||
meshtastic_InterdeviceMessage &message = rx_message;
|
||||
memset(&message, 0, sizeof(message));
|
||||
|
||||
// Decode the protobuf and shift forward any remaining bytes in the buffer
|
||||
// (which, if present, belong to the packet that we're going to process on the
|
||||
// next loop)
|
||||
pb_istream_t stream = pb_istream_from_buffer(pb_rx_buf + MT_HEADER_SIZE, payload_len);
|
||||
bool status = pb_decode(&stream, meshtastic_InterdeviceMessage_fields, &message);
|
||||
size_t remaining = pb_rx_size - MT_HEADER_SIZE - payload_len;
|
||||
memmove(pb_rx_buf, pb_rx_buf + MT_HEADER_SIZE + payload_len, remaining);
|
||||
pb_rx_size = remaining;
|
||||
|
||||
if (!status) {
|
||||
link_decode_fail++;
|
||||
LOG_DEBUG("Decoding failed");
|
||||
return false;
|
||||
}
|
||||
packets_received++;
|
||||
switch (message.which_data) {
|
||||
case meshtastic_InterdeviceMessage_nmea_tag:
|
||||
// send String to NMEA processing
|
||||
uartProxy->stuff_buffer(message.data.nmea, strnlen(message.data.nmea, sizeof(message.data.nmea) - 1));
|
||||
return true;
|
||||
case meshtastic_InterdeviceMessage_i2c_result_tag:
|
||||
// response for the transaction i2c_transact() is waiting on
|
||||
if (message.id == expected_id) {
|
||||
i2c_result = message.data.i2c_result;
|
||||
i2c_result_ready = true;
|
||||
} else {
|
||||
LOG_DEBUG("Drop stale i2c response id=0x%08x", message.id);
|
||||
}
|
||||
return true;
|
||||
case meshtastic_InterdeviceMessage_file_transfer_tag:
|
||||
if (pending_file && message.id == expected_id) {
|
||||
*pending_file = message.data.file_transfer;
|
||||
pending_file = NULL;
|
||||
file_response_ready = true;
|
||||
} else {
|
||||
LOG_DEBUG("Drop stale file response id=0x%08x", message.id);
|
||||
}
|
||||
return true;
|
||||
case meshtastic_InterdeviceMessage_directory_listing_tag:
|
||||
if (pending_dir && message.id == expected_id) {
|
||||
*pending_dir = message.data.directory_listing;
|
||||
pending_dir = NULL;
|
||||
dir_response_ready = true;
|
||||
} else {
|
||||
LOG_DEBUG("Drop stale listing response id=0x%08x", message.id);
|
||||
}
|
||||
return true;
|
||||
case meshtastic_InterdeviceMessage_ping_tag: {
|
||||
// The co-processor pings us unsolicited (id 0) when it has booted,
|
||||
// which is also how a reboot after its watchdog is noticed. It
|
||||
// reports the version it speaks, so this completes the handshake
|
||||
// just like a pong does.
|
||||
if (message.id == 0) {
|
||||
if (handshake_done)
|
||||
LOG_WARN("RP2040 rebooted");
|
||||
note_handshake(message.data.ping);
|
||||
}
|
||||
// answer regardless of state. tx_message is safe to reuse: a request
|
||||
// in flight was already encoded into pb_tx_buf when it was sent
|
||||
meshtastic_InterdeviceMessage &pong = tx_message;
|
||||
memset(&pong, 0, sizeof(pong));
|
||||
pong.id = message.id;
|
||||
pong.which_data = meshtastic_InterdeviceMessage_pong_tag;
|
||||
pong.data.pong = meshtastic_InterdeviceVersion_INTERDEVICE_VERSION_CURRENT;
|
||||
send_uplink_unlocked(pong);
|
||||
return true;
|
||||
}
|
||||
case meshtastic_InterdeviceMessage_pong_tag:
|
||||
// the answer to our probe, carrying the version it speaks
|
||||
note_handshake(message.data.pong);
|
||||
return true;
|
||||
case meshtastic_InterdeviceMessage_nack_tag:
|
||||
// A nack for the request in flight is definitive: resending it would
|
||||
// only be refused again. An id of 0 means the co-processor could not
|
||||
// even decode the frame, which may just as well have been an
|
||||
// unrelated NMEA uplink, so that one only ends the wait (the caller
|
||||
// may retry it as the transport failure it is).
|
||||
if (message.id == expected_id) {
|
||||
LOG_WARN("Request 0x%08x nacked by the co-processor", expected_id);
|
||||
request_nacked = true;
|
||||
} else if (message.id == 0) {
|
||||
LOG_WARN("Co-processor could not decode a frame");
|
||||
}
|
||||
return true;
|
||||
case meshtastic_InterdeviceMessage_sd_info_tag:
|
||||
if (pending_sd_info && message.id == expected_id) {
|
||||
*pending_sd_info = message.data.sd_info;
|
||||
pending_sd_info = NULL;
|
||||
sd_info_ready = true;
|
||||
} else {
|
||||
LOG_DEBUG("Drop stale sd info response id=0x%08x", message.id);
|
||||
}
|
||||
return true;
|
||||
default:
|
||||
// the other messages really only flow downstream
|
||||
LOG_DEBUG("Got a message of unexpected type");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool SensecapIndicator::send(const char *buf, size_t len)
|
||||
{
|
||||
size_t wrote = _serial->write(buf, len);
|
||||
if (wrote == len)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
#endif // SENSECAP_INDICATOR
|
||||
@@ -0,0 +1,144 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef SENSECAP_INDICATOR
|
||||
|
||||
#include "concurrency/Lock.h"
|
||||
#include "concurrency/OSThread.h"
|
||||
#include "configuration.h"
|
||||
|
||||
#include "mesh/generated/meshtastic/interdevice.pb.h"
|
||||
#include <atomic>
|
||||
|
||||
// Magic number at the start of all MT packets
|
||||
#define MT_MAGIC_0 0x94
|
||||
#define MT_MAGIC_1 0xc3
|
||||
|
||||
// The header is the magic number plus a 16-bit payload-length field
|
||||
#define MT_HEADER_SIZE 4
|
||||
|
||||
#define PB_BUFSIZE (meshtastic_InterdeviceMessage_size + MT_HEADER_SIZE)
|
||||
|
||||
class SensecapIndicator : public concurrency::OSThread
|
||||
{
|
||||
public:
|
||||
explicit SensecapIndicator(HardwareSerial &serial);
|
||||
int32_t runOnce() override;
|
||||
// Standalone send (e.g. NMEA from UARTProxy), takes link_lock to
|
||||
// serialize the shared TX buffer against the request methods
|
||||
bool send_uplink(const meshtastic_InterdeviceMessage &message);
|
||||
|
||||
// Run one tunneled I2C transaction: an optional write of wlen bytes
|
||||
// followed by an optional read of rlen bytes with repeated start. The
|
||||
// request is staged under the link lock, so callers need no locking.
|
||||
bool i2c_transact(uint8_t address, const uint8_t *wbuf, size_t wlen, size_t rlen, meshtastic_I2CResult *result,
|
||||
uint32_t timeout_ms = 100);
|
||||
|
||||
// Synchronous file operations against the SD card attached to the RP2040.
|
||||
// The response (chunk data, file size, status) is written to *out.
|
||||
// Returns false when the link is down or the request timed out; a
|
||||
// request the co-processor answered is true, with out->status carrying
|
||||
// the outcome (FILE_BUSY is worth retrying, the other failures are not).
|
||||
bool file_read(const char *path, uint32_t offset, uint32_t length, meshtastic_FileTransfer *out, uint32_t timeout_ms = 1000);
|
||||
// Sequential chunked write: create=true starts a new file (offset must be 0),
|
||||
// create=false appends (offset must equal the current file size)
|
||||
bool file_write(const char *path, uint32_t offset, const uint8_t *data, size_t len, bool create, meshtastic_FileTransfer *out,
|
||||
uint32_t timeout_ms = 1000);
|
||||
bool file_remove(const char *path, meshtastic_FileTransfer *out, uint32_t timeout_ms = 1000);
|
||||
// List directory entries starting at entry number `offset` (paged,
|
||||
// subdirectories get a trailing slash)
|
||||
// the first page of a large directory has to walk it to the end to count
|
||||
// the entries, so this one gets a longer budget
|
||||
bool list_directory(const char *path, uint32_t offset, meshtastic_DirectoryListing *out, uint32_t timeout_ms = 5000);
|
||||
// SD card statistics, answered from state the co-processor cached at
|
||||
// mount time, so this never waits on the card. used/free are only
|
||||
// meaningful once stats_valid is set: the FAT scan behind them runs in
|
||||
// the background. `busy` means a card is being mounted right now.
|
||||
bool sd_info(meshtastic_SdCardInfo *out, uint32_t timeout_ms = 500);
|
||||
// Mount the card, or release it so it can be pulled safely. Answered with
|
||||
// the card state as it is right now (a mount is still busy at that point).
|
||||
bool sd_command(meshtastic_SdCommand command, meshtastic_SdCardInfo *out, uint32_t timeout_ms = 500);
|
||||
|
||||
// True when the last request was refused by the co-processor rather than
|
||||
// lost: retrying it would only be refused again
|
||||
bool last_request_nacked() const { return request_nacked; }
|
||||
|
||||
// True once the co-processor has answered and speaks our protocol
|
||||
// version. Actively probes it (it never speaks unsolicited unless a GPS
|
||||
// module is attached) and pumps the link until a pong arrives or the
|
||||
// timeout expires. Used to defer bridge traffic until the co-processor
|
||||
// has booted. A version mismatch fails permanently: no request is sent
|
||||
// to a co-processor running incompatible firmware.
|
||||
bool wait_ready(uint32_t timeout_ms);
|
||||
|
||||
private:
|
||||
// The UI task requests map tiles while the main loop pumps the link;
|
||||
// every send/pump sequence must hold this lock
|
||||
concurrency::Lock link_lock;
|
||||
pb_byte_t pb_tx_buf[PB_BUFSIZE] = {};
|
||||
pb_byte_t pb_rx_buf[PB_BUFSIZE] = {};
|
||||
size_t pb_rx_size = 0; // Number of bytes currently in the buffer
|
||||
HardwareSerial *_serial = nullptr;
|
||||
uint32_t packets_received = 0;
|
||||
// The handshake gates the bridge: no request is sent before the
|
||||
// co-processor has answered a ping with the protocol version we speak.
|
||||
// A mismatch is permanent, a missing answer is retried by runOnce (the
|
||||
// co-processor may boot slower than we do, or reboot on its watchdog).
|
||||
bool link_compatible = false;
|
||||
bool handshake_done = false;
|
||||
uint32_t last_probe = 0;
|
||||
// link health diagnostics for the map-tile transfers, reported rarely
|
||||
uint32_t link_resyncs = 0;
|
||||
uint32_t link_decode_fail = 0;
|
||||
uint32_t link_timeouts = 0;
|
||||
uint32_t last_link_report = 0;
|
||||
meshtastic_I2CResult i2c_result = meshtastic_I2CResult_init_zero;
|
||||
bool i2c_result_ready = false;
|
||||
// Statically allocated message structs: with 4KB file chunks an
|
||||
// InterdeviceMessage is ~4.6KB, too large for task stacks. Both are
|
||||
// only touched while link_lock is held, so requests staged by one
|
||||
// thread cannot be overwritten by another.
|
||||
meshtastic_InterdeviceMessage rx_message = meshtastic_InterdeviceMessage_init_zero;
|
||||
meshtastic_InterdeviceMessage tx_message = meshtastic_InterdeviceMessage_init_zero;
|
||||
// Response destinations for the file operation in flight
|
||||
meshtastic_FileTransfer *pending_file = NULL;
|
||||
meshtastic_DirectoryListing *pending_dir = NULL;
|
||||
meshtastic_SdCardInfo *pending_sd_info = NULL;
|
||||
bool file_response_ready = false;
|
||||
bool dir_response_ready = false;
|
||||
bool sd_info_ready = false;
|
||||
// responses echo the id of the request they answer, so a reply that
|
||||
// arrives after its request timed out cannot satisfy a later request
|
||||
uint32_t next_request_id = 0;
|
||||
uint32_t expected_id = 0;
|
||||
// a nack response fails the request in flight without its timeout
|
||||
bool request_nacked = false;
|
||||
// Number of requesters inside a request/response round trip, each
|
||||
// holding link_lock for up to its timeout. runOnce skips its pump while
|
||||
// this is nonzero so the cooperative main loop is not blocked on the
|
||||
// lock for that long. A counter, not a flag: the UI task and the main
|
||||
// loop can both be in a request, and the first one out must not clear
|
||||
// the state of the other.
|
||||
std::atomic<int> requests_in_flight{0};
|
||||
struct InFlight {
|
||||
std::atomic<int> &count;
|
||||
explicit InFlight(std::atomic<int> &c) : count(c) { count++; }
|
||||
~InFlight() { count--; }
|
||||
};
|
||||
bool link_ready();
|
||||
void probe_link(); // caller holds link_lock
|
||||
void note_handshake(uint32_t peer_version); // caller holds link_lock
|
||||
uint32_t stamp_request(meshtastic_InterdeviceMessage &request);
|
||||
bool send_uplink_unlocked(const meshtastic_InterdeviceMessage &message);
|
||||
// callers hold link_lock (the request was staged in the shared tx_message)
|
||||
bool file_request(meshtastic_InterdeviceMessage &request, meshtastic_FileTransfer *out, uint32_t timeout_ms);
|
||||
bool wait_response(const bool &flag, uint32_t timeout_ms);
|
||||
void pump();
|
||||
size_t serial_check(char *buf, size_t space_left);
|
||||
void check_packet();
|
||||
bool handle_packet(size_t payload_len);
|
||||
bool send(const char *buf, size_t len);
|
||||
};
|
||||
|
||||
extern SensecapIndicator *sensecapIndicator;
|
||||
|
||||
#endif // SENSECAP_INDICATOR
|
||||
@@ -0,0 +1,141 @@
|
||||
#ifdef SENSECAP_INDICATOR
|
||||
|
||||
#include "I2CProxy.h"
|
||||
#include "../IndicatorSerial.h"
|
||||
|
||||
I2CProxy *i2cProxy = new I2CProxy();
|
||||
|
||||
// Transaction state of the calling task. Slots are claimed on first use and
|
||||
// never released: the set of tasks touching the bridged bus is fixed (main
|
||||
// loop, UI task).
|
||||
I2CProxy::Context &I2CProxy::ctx()
|
||||
{
|
||||
TaskHandle_t self = xTaskGetCurrentTaskHandle();
|
||||
for (size_t i = 0; i < MAX_TASKS; i++) {
|
||||
if (_ctx[i].task == self)
|
||||
return _ctx[i];
|
||||
}
|
||||
// claiming a slot must be atomic: two tasks that pick the same one would
|
||||
// interleave their transactions in one buffer set
|
||||
Context *claimed = nullptr;
|
||||
portENTER_CRITICAL(&_claim_mux);
|
||||
for (size_t i = 0; i < MAX_TASKS && !claimed; i++) {
|
||||
if (_ctx[i].task == nullptr) {
|
||||
_ctx[i].task = self;
|
||||
claimed = &_ctx[i];
|
||||
}
|
||||
}
|
||||
portEXIT_CRITICAL(&_claim_mux);
|
||||
if (claimed)
|
||||
return *claimed;
|
||||
LOG_WARN("I2CProxy: more tasks than contexts, sharing the last one");
|
||||
return _ctx[MAX_TASKS - 1];
|
||||
}
|
||||
|
||||
void I2CProxy::beginTransmission(uint8_t address)
|
||||
{
|
||||
Context &c = ctx();
|
||||
c.txAddress = address;
|
||||
c.txLen = 0;
|
||||
c.txPending = true;
|
||||
}
|
||||
|
||||
size_t I2CProxy::write(uint8_t data)
|
||||
{
|
||||
Context &c = ctx();
|
||||
if (!c.txPending || c.txLen >= MAX_WRITE)
|
||||
return 0;
|
||||
c.txBuf[c.txLen++] = data;
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t I2CProxy::write(const uint8_t *data, size_t len)
|
||||
{
|
||||
size_t n = 0;
|
||||
while (n < len && write(data[n]))
|
||||
n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
uint8_t I2CProxy::endTransmission(bool stopBit)
|
||||
{
|
||||
Context &c = ctx();
|
||||
if (!stopBit) {
|
||||
// Keep the buffered write pending, it is combined with the following
|
||||
// requestFrom() into a single write+read transaction
|
||||
return 0;
|
||||
}
|
||||
uint8_t rv = transact(c, c.txAddress, 0);
|
||||
c.txLen = 0;
|
||||
c.txPending = false;
|
||||
return rv;
|
||||
}
|
||||
|
||||
size_t I2CProxy::requestFrom(uint8_t address, size_t len, bool stopBit)
|
||||
{
|
||||
(void)stopBit;
|
||||
Context &c = ctx();
|
||||
if (len > MAX_READ)
|
||||
len = MAX_READ;
|
||||
|
||||
// a write pending for this address is executed together with the read as
|
||||
// one transaction with repeated start
|
||||
if (!c.txPending || c.txAddress != address)
|
||||
c.txLen = 0;
|
||||
|
||||
uint8_t rv = transact(c, address, len);
|
||||
c.txLen = 0;
|
||||
c.txPending = false;
|
||||
return rv == 0 ? c.rxLen : 0;
|
||||
}
|
||||
|
||||
int I2CProxy::available()
|
||||
{
|
||||
const Context &c = ctx();
|
||||
return (int)(c.rxLen - c.rxPos);
|
||||
}
|
||||
|
||||
int I2CProxy::read()
|
||||
{
|
||||
Context &c = ctx();
|
||||
return c.rxPos < c.rxLen ? c.rxBuf[c.rxPos++] : -1;
|
||||
}
|
||||
|
||||
int I2CProxy::peek()
|
||||
{
|
||||
const Context &c = ctx();
|
||||
return c.rxPos < c.rxLen ? c.rxBuf[c.rxPos] : -1;
|
||||
}
|
||||
|
||||
// Run one tunneled transaction, returns TwoWire endTransmission error codes:
|
||||
// 0 success, 1 data too long, 2 NACK on address, 3 NACK on data, 4 other, 5 timeout
|
||||
uint8_t I2CProxy::transact(Context &c, uint8_t address, size_t rlen)
|
||||
{
|
||||
c.rxLen = 0;
|
||||
c.rxPos = 0;
|
||||
|
||||
if (!sensecapIndicator)
|
||||
return 4;
|
||||
if (c.txLen > MAX_WRITE)
|
||||
return 1;
|
||||
|
||||
meshtastic_I2CResult result = meshtastic_I2CResult_init_zero;
|
||||
if (!sensecapIndicator->i2c_transact(address, c.txBuf, c.txLen, rlen, &result))
|
||||
return 5;
|
||||
|
||||
switch (result.status) {
|
||||
case meshtastic_I2CResult_Status_OK:
|
||||
c.rxLen = result.read_data.size > MAX_READ ? MAX_READ : result.read_data.size;
|
||||
memcpy(c.rxBuf, result.read_data.bytes, c.rxLen);
|
||||
return 0;
|
||||
case meshtastic_I2CResult_Status_NACK_ADDRESS:
|
||||
return 2;
|
||||
case meshtastic_I2CResult_Status_NACK_DATA:
|
||||
return 3;
|
||||
default:
|
||||
// includes UNSPECIFIED: an empty result must not read as success
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
|
||||
#endif // SENSECAP_INDICATOR
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef SENSECAP_INDICATOR
|
||||
|
||||
#include "../generated/meshtastic/interdevice.pb.h"
|
||||
#include <Wire.h>
|
||||
|
||||
/**
|
||||
* TwoWire implementation that tunnels bus traffic to the RP2040 over the
|
||||
* interdevice serial link, making the sensors attached to the secondary MCU
|
||||
* usable by the regular sensor drivers of the main firmware.
|
||||
*
|
||||
* beginTransmission()/write() buffer an outgoing write. The buffered write is
|
||||
* executed as a single serial round trip on endTransmission(true). A write
|
||||
* followed by endTransmission(false) and requestFrom() is combined into one
|
||||
* write+read transaction with repeated start, matching driver access
|
||||
* patterns.
|
||||
*
|
||||
* Constructed on bus number 0: TwoWire::begin() is final and cannot be
|
||||
* intercepted, but it returns without touching hardware when the bus is
|
||||
* already initialized, which is always true for bus 0 (local touch panel).
|
||||
*
|
||||
* Thread safety: the bus is shared between the main loop (sensor drivers)
|
||||
* and the UI task (keyboard scanner), and TwoWire has no transaction
|
||||
* bracket a lock could safely span - drivers drain the read buffer with
|
||||
* available()/read() long after requestFrom() returned. Each calling task
|
||||
* therefore gets its own staging and read buffers; the tunneled round trip
|
||||
* itself is serialized by the link. Tasks beyond MAX_TASKS share the last
|
||||
* context, which is only correct if they do not run concurrently.
|
||||
*/
|
||||
class I2CProxy : public TwoWire
|
||||
{
|
||||
public:
|
||||
I2CProxy() : TwoWire(0), _ctx{} {}
|
||||
|
||||
bool end() override { return true; }
|
||||
bool setClock(uint32_t) override { return true; }
|
||||
|
||||
void beginTransmission(uint8_t address) override;
|
||||
uint8_t endTransmission(bool stopBit) override;
|
||||
uint8_t endTransmission() override { return endTransmission(true); }
|
||||
|
||||
size_t requestFrom(uint8_t address, size_t len, bool stopBit) override;
|
||||
size_t requestFrom(uint8_t address, size_t len) override { return requestFrom(address, len, true); }
|
||||
|
||||
void onReceive(const std::function<void(int)> &) override {}
|
||||
void onRequest(const std::function<void()> &) override {}
|
||||
|
||||
size_t write(uint8_t data) override;
|
||||
size_t write(const uint8_t *data, size_t len) override;
|
||||
int available() override;
|
||||
int read() override;
|
||||
int peek() override;
|
||||
void flush() override {}
|
||||
|
||||
private:
|
||||
// Derived from the generated protobuf limits (interdevice.options)
|
||||
static const size_t MAX_WRITE = sizeof(meshtastic_I2CTransaction{}.write_data.bytes);
|
||||
static const size_t MAX_READ = sizeof(meshtastic_I2CResult{}.read_data.bytes);
|
||||
|
||||
// main loop, UI task, and one spare
|
||||
static const size_t MAX_TASKS = 3;
|
||||
|
||||
struct Context {
|
||||
TaskHandle_t task = nullptr;
|
||||
uint8_t txAddress = 0;
|
||||
uint8_t txBuf[MAX_WRITE];
|
||||
size_t txLen = 0;
|
||||
bool txPending = false;
|
||||
uint8_t rxBuf[MAX_READ];
|
||||
size_t rxLen = 0;
|
||||
size_t rxPos = 0;
|
||||
};
|
||||
Context _ctx[MAX_TASKS];
|
||||
portMUX_TYPE _claim_mux = portMUX_INITIALIZER_UNLOCKED;
|
||||
|
||||
// per-task transaction state, claimed on first use
|
||||
Context &ctx();
|
||||
uint8_t transact(Context &c, uint8_t address, size_t rlen);
|
||||
};
|
||||
|
||||
extern I2CProxy *i2cProxy;
|
||||
|
||||
#endif // SENSECAP_INDICATOR
|
||||
@@ -0,0 +1,114 @@
|
||||
#include "UARTProxy.h"
|
||||
|
||||
#ifdef SENSECAP_INDICATOR
|
||||
|
||||
UARTProxy *uartProxy = new UARTProxy();
|
||||
|
||||
UARTProxy::UARTProxy() {}
|
||||
|
||||
void UARTProxy::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert, unsigned long timeout_ms,
|
||||
uint8_t rxfifo_full_thrhd)
|
||||
{
|
||||
baudrate = baud;
|
||||
buf_clear();
|
||||
LOG_DEBUG("UARTProxy::begin(%lu)", baud);
|
||||
}
|
||||
|
||||
void UARTProxy::end()
|
||||
{
|
||||
buf_clear();
|
||||
}
|
||||
|
||||
int UARTProxy::available()
|
||||
{
|
||||
return buf_avail();
|
||||
}
|
||||
|
||||
int UARTProxy::peek()
|
||||
{
|
||||
if (buf_tail == buf_head)
|
||||
return -1;
|
||||
__sync_synchronize(); // pair with the producer barrier in buf_push
|
||||
return buf[buf_tail];
|
||||
}
|
||||
|
||||
int UARTProxy::read()
|
||||
{
|
||||
if (buf_tail == buf_head)
|
||||
return -1;
|
||||
__sync_synchronize(); // pair with the producer barrier in buf_push
|
||||
uint8_t ret = buf[buf_tail];
|
||||
// the slot must be read before the producer is told it is free again
|
||||
__sync_synchronize();
|
||||
buf_tail = (buf_tail + 1) % BUF_SIZE;
|
||||
return ret;
|
||||
}
|
||||
|
||||
void UARTProxy::flush(bool txOnly)
|
||||
{
|
||||
// writes are packed into one uplink message each, so there is never
|
||||
// anything in flight to wait for. Dropping the unread receive buffer is
|
||||
// what flush(false) is for (GPS::clearBuffer uses it).
|
||||
if (!txOnly)
|
||||
buf_clear();
|
||||
}
|
||||
|
||||
uint32_t UARTProxy::baudRate()
|
||||
{
|
||||
return baudrate;
|
||||
}
|
||||
|
||||
void UARTProxy::updateBaudRate(unsigned long speed)
|
||||
{
|
||||
baudrate = speed;
|
||||
}
|
||||
|
||||
size_t UARTProxy::setRxBufferSize(size_t size)
|
||||
{
|
||||
return size;
|
||||
}
|
||||
|
||||
size_t UARTProxy::write(const char *buffer)
|
||||
{
|
||||
return write((char *)buffer, strlen(buffer));
|
||||
}
|
||||
|
||||
size_t UARTProxy::write(uint8_t *buffer, size_t size)
|
||||
{
|
||||
return write((char *)buffer, size);
|
||||
}
|
||||
|
||||
size_t UARTProxy::write(char *buffer, size_t size)
|
||||
{
|
||||
if (!sensecapIndicator)
|
||||
return 0; // the link is constructed after this global
|
||||
// static: ~4.6KB struct, too large for task stacks; only written from
|
||||
// the cooperative main loop (GPS thread)
|
||||
static meshtastic_InterdeviceMessage message;
|
||||
memset(&message, 0, sizeof(message));
|
||||
if (size >= sizeof(message.data.nmea)) {
|
||||
size = sizeof(message.data.nmea) - 1; // truncate, keep room for the terminator
|
||||
}
|
||||
memcpy(message.data.nmea, buffer, size);
|
||||
message.which_data = meshtastic_InterdeviceMessage_nmea_tag;
|
||||
LOG_DEBUG("UARTProxy::write %u bytes", (unsigned)size);
|
||||
// the link refuses to send before the handshake, and to a co-processor
|
||||
// running incompatible firmware: report the bytes as not written rather
|
||||
// than pretending a GPS command was delivered
|
||||
if (!sensecapIndicator->send_uplink(message))
|
||||
return 0;
|
||||
return size;
|
||||
}
|
||||
|
||||
size_t UARTProxy::stuff_buffer(const char *buffer, size_t size)
|
||||
{
|
||||
// push buffer byte-wise, stop when full
|
||||
for (size_t i = 0; i < size; i++) {
|
||||
if (!buf_push(buffer[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
#endif // SENSECAP_INDICATOR
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef SENSECAP_INDICATOR
|
||||
|
||||
#include "../IndicatorSerial.h"
|
||||
#include <Stream.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
/**
|
||||
* Stream that proxies the GPS serial port of the RP2040 over the interdevice
|
||||
* link: reads come from a ring buffer the link fills, writes go out as one
|
||||
* uplink message each.
|
||||
*/
|
||||
class UARTProxy : public Stream
|
||||
{
|
||||
public:
|
||||
UARTProxy();
|
||||
|
||||
void begin(unsigned long baud, uint32_t config = 0x800001c, int8_t rxPin = -1, int8_t txPin = -1, bool invert = false,
|
||||
unsigned long timeout_ms = 20000UL, uint8_t rxfifo_full_thrhd = 112);
|
||||
void end();
|
||||
int available();
|
||||
int peek();
|
||||
int read();
|
||||
// HardwareSerial semantics: the flag is txOnly, not "wait". Only a
|
||||
// flush(false) discards what has been received but not read yet.
|
||||
void flush(bool txOnly);
|
||||
// HardwareSerial::flush() is uartFlushTxOnly(txOnly = true): it waits
|
||||
// for the transmitter and keeps the receive buffer
|
||||
void flush() override { flush(true); }
|
||||
// writes are buffered into one uplink message, so this is its capacity
|
||||
// (Print's default of 0 would make drivers back off forever)
|
||||
int availableForWrite() override { return (int)sizeof(meshtastic_InterdeviceMessage{}.data.nmea) - 1; }
|
||||
uint32_t baudRate();
|
||||
void updateBaudRate(unsigned long speed);
|
||||
size_t setRxBufferSize(size_t size);
|
||||
size_t write(const char *buffer);
|
||||
size_t write(char *buffer, size_t size);
|
||||
size_t write(uint8_t *buffer, size_t size);
|
||||
size_t write(const uint8_t *buffer, size_t size) override { return write((char *)buffer, size); }
|
||||
|
||||
size_t stuff_buffer(const char *buffer, size_t size);
|
||||
size_t write(uint8_t c) override { return write(&c, 1); }
|
||||
|
||||
private:
|
||||
unsigned long baudrate = 115200;
|
||||
|
||||
// Self-contained single-producer/single-consumer byte ring buffer.
|
||||
// (An external RingBuf.h is ambiguous in this build: SdFat ships a
|
||||
// conflicting header via device-ui.)
|
||||
static const size_t BUF_SIZE = 2048;
|
||||
uint8_t buf[BUF_SIZE] = {};
|
||||
volatile size_t buf_head = 0; // write index (producer)
|
||||
volatile size_t buf_tail = 0; // read index (consumer)
|
||||
|
||||
bool buf_push(uint8_t c)
|
||||
{
|
||||
size_t next = (buf_head + 1) % BUF_SIZE;
|
||||
if (next == buf_tail)
|
||||
return false; // full
|
||||
buf[buf_head] = c;
|
||||
// producer and consumer run on different cores: the byte must be
|
||||
// visible before the index says it is there
|
||||
__sync_synchronize();
|
||||
buf_head = next;
|
||||
return true;
|
||||
}
|
||||
void buf_clear() { buf_tail = buf_head; }
|
||||
size_t buf_avail() { return (buf_head + BUF_SIZE - buf_tail) % BUF_SIZE; }
|
||||
};
|
||||
|
||||
extern UARTProxy *uartProxy;
|
||||
|
||||
#endif // SENSECAP_INDICATOR
|
||||
Reference in New Issue
Block a user