Files
MicrOBU/obu-firmware/main/serial_link.cpp
T
Ashin Walpola ce18a393ea Fragment large V2X_RX messages and decode road-RSU SPATEMs
The firmware dropped every received ITS message over 494 bytes (one link
message), so a road RSU's 888-byte SPATEM and 1198-byte MAPEM never reached
the phone. V2X_RX now goes out in link fragments up to 2300 bytes, best
effort and non-blocking; messages up to 494 bytes are unchanged.

The app's SPATEM decoder then refused those messages because they carry
intersection and movement names and advisory speed lists. It now reads past
both, checked against asn1tools on 718 distinct messages.

Adds the pure fragmenter with host tests and a pcap replay, a Kotlin
cross-check on the firmware's own fragments, tools/rx_size_compare.py,
docs/08-large-message-reception.md and station-link revision 3.
2026-11-23 17:34:56 +01:00

180 lines
7.6 KiB
C++

#include "serial_link.hpp"
#include <driver/usb_serial_jtag.h>
#include <esp_log.h>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <algorithm>
#include <atomic>
#include <cstdarg>
#include <cstdio>
#include <cstring>
namespace microbu::serial {
namespace {
std::uint16_t crc16_ccitt_false_step(std::uint16_t crc, std::uint8_t octet) {
crc ^= static_cast<std::uint16_t>(octet) << 8;
for (int bit = 0; bit < 8; ++bit) crc = (crc & 0x8000) ? static_cast<std::uint16_t>((crc << 1) ^ 0x1021) : static_cast<std::uint16_t>(crc << 1);
return crc;
}
}
std::uint16_t crc16_ccitt_false(const std::uint8_t* data, std::size_t length) {
std::uint16_t crc = 0xFFFF;
for (std::size_t i = 0; i < length; ++i) crc = crc16_ccitt_false_step(crc, data[i]);
return crc;
}
Bytes encode_frame(FrameType type, const Bytes& payload) {
Bytes out;
out.reserve(payload.size() + 7);
out.push_back(0xAA); out.push_back(0x55);
out.push_back(static_cast<std::uint8_t>(type));
out.push_back(payload.size() & 0xFF); out.push_back(payload.size() >> 8);
out.insert(out.end(), payload.begin(), payload.end());
const auto crc = crc16_ccitt_false(out.data() + 2, out.size() - 2);
out.push_back(crc & 0xFF); out.push_back(crc >> 8);
return out;
}
void Decoder::feed(const std::uint8_t* data, std::size_t length, const Handler& handler) {
for (std::size_t i = 0; i < length; ++i) {
const std::uint8_t b = data[i];
switch (state_) {
case State::SYNC0: state_ = (b == 0xAA) ? State::SYNC1 : State::SYNC0; break;
case State::SYNC1: state_ = (b == 0x55) ? State::TYPE : (b == 0xAA ? State::SYNC1 : State::SYNC0); break;
case State::TYPE: type_ = b; state_ = State::LEN_LO; break;
case State::LEN_LO: length_ = b; state_ = State::LEN_HI; break;
case State::LEN_HI:
length_ |= static_cast<std::uint16_t>(b) << 8;
payload_.clear();
if (length_ > maximum_payload) state_ = State::SYNC0; // untrustworthy boundary: resync
else state_ = length_ == 0 ? State::CRC_LO : State::PAYLOAD;
break;
case State::PAYLOAD:
payload_.push_back(b);
if (payload_.size() >= length_) state_ = State::CRC_LO;
break;
case State::CRC_LO: crc_ = b; state_ = State::CRC_HI; break;
case State::CRC_HI: {
crc_ |= static_cast<std::uint16_t>(b) << 8;
// CRC over head then payload without concatenating them: same running value as encode_frame.
const std::uint8_t head[3] = {type_, static_cast<std::uint8_t>(length_ & 0xFF), static_cast<std::uint8_t>(length_ >> 8)};
std::uint16_t crc = 0xFFFF;
for (auto octet : head) crc = crc16_ccitt_false_step(crc, octet);
for (auto octet : payload_) crc = crc16_ccitt_false_step(crc, octet);
if (crc == crc_) { ++frames_; handler(Frame {static_cast<FrameType>(type_), payload_}); }
else ++crc_errors_;
state_ = State::SYNC0;
break;
}
}
}
}
namespace {
SemaphoreHandle_t writer_lock = nullptr;
Counters the_counters;
Decoder::Handler frame_handler;
vprintf_like_t previous_vprintf = nullptr;
// A host that has the port enumerated but does not read lets the TX buffer fill. Waiting 500 ms per
// frame then stalled every logging task, the BLE host included, and delayed the phone's requests by a
// minute (2026-10-05). After a timeout the serial side counts as stalled: frames are dropped at once,
// one short probe per second finds a host that reads again, and any received byte ends the stall.
std::atomic<bool> stalled {false};
std::atomic<std::uint32_t> last_frame_at_ms {0}; // MicrOBU: 32-bit, no libatomic needed on RV32
std::atomic<std::int64_t> next_probe_us {0};
bool write_all(const Bytes& frame, TickType_t timeout) {
std::size_t sent = 0;
while (sent < frame.size()) {
const int count = usb_serial_jtag_write_bytes(frame.data() + sent, frame.size() - sent, timeout);
if (count <= 0) return false; // the host detects an incomplete frame by CRC
sent += count;
}
return true;
}
// ESP_LOG sink: one LOG frame per call, never a raw write into the frame stream.
int log_to_frame(const char* format, va_list args) {
char line[256];
const int length = std::vsnprintf(line, sizeof line, format, args);
if (length <= 0) return 0;
std::size_t n = static_cast<std::size_t>(length) < sizeof line ? length : sizeof line - 1;
while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) --n;
if (n == 0) return length;
// esp_log colour escapes are stripped by the host; keep the line verbatim otherwise.
write(FrameType::LOG, Bytes(line, line + n));
return length;
}
void reader_task(void*) {
Decoder decoder;
std::uint8_t buffer[512];
for (;;) {
const int count = usb_serial_jtag_read_bytes(buffer, sizeof buffer, pdMS_TO_TICKS(20));
if (count > 0) {
stalled = false;
decoder.feed(buffer, static_cast<std::size_t>(count), [](Frame frame) {
last_frame_at_ms = static_cast<std::uint32_t>(esp_timer_get_time() / 1000);
frame_handler(std::move(frame));
});
the_counters.frames = decoder.frames();
the_counters.crc_errors = decoder.crc_errors();
}
}
}
}
void start(const Decoder::Handler& on_frame) {
frame_handler = on_frame;
writer_lock = xSemaphoreCreateMutex();
usb_serial_jtag_driver_config_t config {};
config.rx_buffer_size = 8192;
config.tx_buffer_size = 8192;
ESP_ERROR_CHECK(usb_serial_jtag_driver_install(&config));
previous_vprintf = esp_log_set_vprintf(log_to_frame);
xTaskCreate(reader_task, "link_rx", 6144, nullptr, 12, nullptr);
}
bool write(FrameType type, const Bytes& payload) {
if (payload.size() > maximum_payload || !writer_lock) return false;
// MicrOBU: nothing on the native port (phone on BLE, or unplugged): do not even try, or the first
// write after every pause waits out the timeout on the station task.
if (!usb_serial_jtag_is_connected()) { ++the_counters.write_failures; return false; }
TickType_t timeout = pdMS_TO_TICKS(500);
if (stalled) {
const auto now = esp_timer_get_time();
if (now < next_probe_us) { ++the_counters.write_failures; return false; }
next_probe_us = now + 1000000;
timeout = std::max<TickType_t>(1, pdMS_TO_TICKS(20));
}
const auto frame = encode_frame(type, payload);
if (xSemaphoreTake(writer_lock, stalled ? 0 : pdMS_TO_TICKS(1000)) != pdTRUE) { ++the_counters.write_failures; return false; }
const bool ok = write_all(frame, timeout);
stalled = !ok;
xSemaphoreGive(writer_lock);
if (!ok) ++the_counters.write_failures;
return ok;
}
bool try_write(FrameType type, const Bytes& payload) {
if (payload.size() > maximum_payload || !writer_lock || stalled) return false;
// Like write(): no host on the native port means nothing to queue, or the 8 kB TX buffer fills with
// fragments nobody reads and the next host starts on stale bytes.
if (!usb_serial_jtag_is_connected()) return false;
const auto frame = encode_frame(type, payload);
if (xSemaphoreTake(writer_lock, 0) != pdTRUE) return false;
const bool queued = usb_serial_jtag_write_bytes(frame.data(), frame.size(), 0) == static_cast<int>(frame.size());
xSemaphoreGive(writer_lock);
return queued;
}
Counters counters() { return the_counters; }
std::uint32_t last_frame_ms() { return last_frame_at_ms.load(); }
} // namespace microbu::serial