Encrypted, authenticated MQTT-style pub/sub over LoRa (AES-128-GCM, replay protection, QoS 0/1/2)
Find a file
vratk0529-arch-desktop b7cbc6566e Don't take our own TX done for a received packet; listen again sooner
The receive interrupt stays attached while sending, and TX done raises the
same DIO1 line on SX126x/SX128x. The next poll() then read our own packet back
out of the FIFO, counted it as malformed, and took the radio out of receive
to do it -- right when the other side's ACK was on its way. sendPacket() now
clears the receive flag after transmitting: nothing can have been received
meanwhile, the radio was sending and the packet overwrote the FIFO.

receive() also goes back to receiving right after reading the FIFO, before
decrypting the packet and running the subscriber's callback, instead of
after. On the gateway that callback forwards to MQTT, and the radio sat in
standby through it, so a packet sent right behind another (a retry, the next
publish) was missed and only got through on the next retry 250 ms later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 13:38:02 +01:00
src Don't take our own TX done for a received packet; listen again sooner 2026-11-22 13:38:02 +01:00
library.json first commit 2026-08-06 18:32:08 +02:00
LICENSE Add MIT license and README 2026-11-11 00:19:24 +01:00
README.md Add MIT license and README 2026-11-11 00:19:24 +01:00

lora_secure

Encrypted, authenticated MQTT-style publish/subscribe over LoRa, for Arduino. It works with any radio RadioLib supports, and is meant for small private links, such as a few sensors or a wearable talking to a gateway.

  • Topics with wildcards: subscriptions use MQTT-style filters with + (one level) and # (all remaining levels).
  • QoS 0, 1 and 2: fire-and-forget, at-least-once, and exactly-once, with ACKs, retries and duplicate detection.
  • AES-128-GCM: every packet is encrypted and authenticated, and the header is authenticated too.
  • Replay protection: each packet carries a per-sender counter that never repeats, plus a timestamp that must be close to the receiver's clock.
  • Non-blocking publish: publishAsync() returns at once, and poll() handles retries and timeouts.
  • Several links per device: each LoRaSecure instance drives one radio, so a gateway can serve, for example, 433 MHz and 2.4 GHz side by side (up to 4 links).

It's used by the SmartWatch firmware for the watch's link to a home-automation gateway.

Installation

With PlatformIO, add it to lib_deps:

lib_deps =
    https://forgejo.vratk0529.com/vratk0529/LoraSecureLib.git

Or clone it into your project's lib/ folder. It depends on RadioLib and on rweather/Crypto (for AES.h and GCM.h). library.json declares both, so PlatformIO fetches them automatically.

Usage

#include <RadioLib.h>
#include <lora_secure.h>

// The radio is configured by you. The library only takes it over once it's started.
SX1280 radio = new Module(CS_PIN, DIO1_PIN, RST_PIN, BUSY_PIN);

// 16 bytes, unique to this link, and identical on every device of the link.
static const uint8_t KEY[16] = { /* ... */ };

LoRaSecure link(radio, "home", LORA_DEV_NODE_A, KEY);

void onLight(LoRaSecure &l, const String &topic, const String &payload, uint8_t qos) {
  Serial.printf("%s = %s\n", topic.c_str(), payload.c_str());
}

void setup() {
  Serial.begin(115200);
  radio.begin(2400.0);              // frequency, bandwidth, SF, power... your choice
  link.begin(myClock);              // myClock() returns UTC seconds; nullptr uses time()
  link.subscribe("home/+/light", onLight);
}

void loop() {
  link.poll();                      // call often: receives, dispatches, retries
  // ...
  link.publishAsync("home/watch/battery", "87", 1, [](bool acked, void *) {
    Serial.println(acked ? "delivered" : "no ACK");
  });
}

Device IDs (LORA_DEV_GATEWAY, LORA_DEV_NODE_A, ...) must be unique on a link and lower than LORA_MAX_DEVICES (8 by default).

Rules you must follow

  • Every link needs its own key. The GCM nonce is derived from the sender ID and its counter. Two links keep separate counters, so sharing a key between them would reuse nonces, which breaks GCM completely.
  • The TX counter must never go backwards. By default it's stored in NVS on ESP32 and in the core's emulated EEPROM on STM32. Boards with better storage, such as FRAM or an external EEPROM, should provide their own with setCounterStorage(load, store) before calling begin(). On platforms without built-in storage (or with LORA_SECURE_NO_BUILTIN_STORAGE defined), begin() refuses to start without it.
  • Clocks must roughly agree. Packets more than setMaxClockDrift() seconds away from the receiver's clock are dropped (120 s by default). Nothing is sent or accepted until the clock is set.

API summary

Call What it does
begin(timeSource) / end() Loads the counter, attaches the RX interrupt and starts listening
subscribe(filter, handler) / unsubscribeAll() Registers a topic filter (up to LORA_MAX_SUBSCRIPTIONS, 16 by default)
publish(topic, payload, qos) Sends a message. For QoS 1 and 2 it blocks until the ACK arrives or ackTimeout() passes
publishAsync(topic, payload, qos, onDone, ctx) Sends without blocking; onDone(acked, ctx) runs from poll(). One unacknowledged publish at a time (publishBusy())
poll() Call from loop(): handles received packets and drives retries
suspend() / resume() Puts the radio to sleep, or back into continuous receive
setAckTimeout(ms), setMaxClockDrift(s) Tuning; defaults are 2500 ms and 120 s
stats(), rssi(), lastRxTime(), lastTxTime() Diagnostics: counts of received, sent, auth-failed, replayed and malformed packets

Compile-time options: LORA_MAX_DEVICES, LORA_MAX_SUBSCRIPTIONS, LORA_MAX_LINKS, LORA_TX_RETRY_MS, LORA_SECURE_DEBUG (logging to Serial, on by default), and LORA_SECURE_NO_BUILTIN_STORAGE.

Protocol

Each packet is [header 12 B][ciphertext ≤ 180 B][tag 8 B]:

Header field Size Notes
version 1 B currently 1
source ID 1 B sender's device ID
flags 1 B bits 0-1: QoS, bit 2: ACK
counter 4 B, big-endian per-sender, never repeats
timestamp 4 B, big-endian sender's UTC seconds
message ID 1 B used for ACKs and QoS 2 duplicate detection

The plaintext is topic;payload, at most 180 bytes in total; an ACK has an empty body. The header travels in the clear but is authenticated as GCM associated data. The 12-byte nonce is built from the source ID, counter, timestamp and flags. The tag is truncated to 64 bits.

On every boot the counter jumps ahead by 32 and is saved, and while running it's saved again at least every 32 packets. A reset without a save therefore never reuses a counter value; at worst it skips some.

Known limitations

  • Replays right after a receiver restarts: a receiver remembers each sender's last counter only in RAM. After it reboots, it accepts recorded packets again, as long as their timestamps are still within the clock-drift window and they arrive in counter order. So packets captured in the last couple of minutes can be replayed once, right after the receiver restarts. Keep the window small if that matters to you.
  • Small duplicate memory: QoS 2 duplicate detection remembers the last 8 (sender, message ID) pairs.
  • Message IDs wrap after 256.

License

MIT, see LICENSE.