1740 lines
56 KiB
Markdown
1740 lines
56 KiB
Markdown
# LoRa Transport Layer Design Document
|
||
|
||
**Project:** zig-p2p
|
||
**Version:** 1.0
|
||
**Created:** February 2026
|
||
**Status:** Draft
|
||
|
||
---
|
||
|
||
## Executive Summary
|
||
|
||
This document describes the design for adding LoRa (Long Range) radio as a transport layer to zig-p2p, enabling **off-grid P2P mesh networks** that operate without internet infrastructure.
|
||
|
||
### Key Capabilities
|
||
|
||
| Capability | Description |
|
||
|------------|-------------|
|
||
| **Range** | 2-15km urban, 40km+ rural/maritime |
|
||
| **Power** | Years on battery (sleep modes) |
|
||
| **Infrastructure** | None required - pure radio mesh |
|
||
| **Mesh Routing** | Multi-hop message forwarding |
|
||
| **Encryption** | AES-128-CCM (lightweight for constraints) |
|
||
|
||
### Use Cases
|
||
|
||
- Disaster recovery communication
|
||
- Remote area sensor networks
|
||
- Maritime/wilderness mesh
|
||
- Agricultural IoT
|
||
- Event/festival temporary networks
|
||
- Underground/mine communication
|
||
|
||
---
|
||
|
||
## Table of Contents
|
||
|
||
1. [Overview](#1-overview)
|
||
2. [LoRa Fundamentals](#2-lora-fundamentals)
|
||
3. [Architecture](#3-architecture)
|
||
4. [Transport Implementation](#4-transport-implementation)
|
||
5. [Mesh Routing Protocol](#5-mesh-routing-protocol)
|
||
6. [Cryptography](#6-cryptography)
|
||
7. [Message Fragmentation](#7-message-fragmentation)
|
||
8. [Duty Cycle Management](#8-duty-cycle-management)
|
||
9. [Hardware Support](#9-hardware-support)
|
||
10. [Gateway Mode](#10-gateway-mode)
|
||
11. [Implementation Plan](#11-implementation-plan)
|
||
12. [Appendices](#appendices)
|
||
|
||
---
|
||
|
||
## 1. Overview
|
||
|
||
### 1.1 Why LoRa?
|
||
|
||
LoRa (Long Range) is a spread-spectrum modulation technique that enables long-range, low-power wireless communication. Unlike WiFi or cellular, LoRa:
|
||
|
||
- Works without any infrastructure
|
||
- Achieves multi-kilometer range on milliwatts
|
||
- Operates on license-free ISM bands
|
||
- Penetrates buildings and obstacles well
|
||
- Enables battery life measured in years
|
||
|
||
### 1.2 Transport Comparison
|
||
|
||
| Aspect | UDP | WebRTC | **LoRa** |
|
||
|--------|-----|--------|----------|
|
||
| Range | Global (internet) | Global (internet) | **2-40km (radio)** |
|
||
| Infrastructure | Requires internet | Requires internet | **None** |
|
||
| Bandwidth | 1 Gbps+ | 100 Mbps+ | **0.3-37 kbps** |
|
||
| Packet Size | 64 KB | 16 KB | **255 bytes** |
|
||
| Power | High | High | **Ultra-low** |
|
||
| Latency | 1-100ms | 10-100ms | **100ms-seconds** |
|
||
| Duplex | Full | Full | **Half** |
|
||
| Duty Cycle | None | None | **1-10% (regulated)** |
|
||
|
||
### 1.3 Design Goals
|
||
|
||
1. **Seamless Integration**: LoRa as another transport option alongside UDP/WebRTC
|
||
2. **Automatic Routing**: Multi-hop mesh without manual configuration
|
||
3. **Constrained Crypto**: Secure but lightweight for 255-byte packets
|
||
4. **Duty Cycle Compliant**: Respect regional radio regulations
|
||
5. **Power Efficient**: Support deep sleep modes for battery operation
|
||
6. **Gateway Support**: Bridge LoRa mesh to internet
|
||
|
||
---
|
||
|
||
## 2. LoRa Fundamentals
|
||
|
||
### 2.1 Physical Layer
|
||
|
||
LoRa uses Chirp Spread Spectrum (CSS) modulation:
|
||
|
||
```
|
||
Frequency
|
||
▲
|
||
│ ╱╲ ╱╲ ╱╲
|
||
│ ╱ ╲ ╱ ╲ ╱ ╲ ← Up-chirps (data bits)
|
||
│ ╱ ╲╱ ╲╱ ╲
|
||
│ ╱ ╲
|
||
└──────────────────────► Time
|
||
```
|
||
|
||
**Key Parameters:**
|
||
|
||
| Parameter | Options | Trade-off |
|
||
|-----------|---------|-----------|
|
||
| **Spreading Factor (SF)** | 7-12 | Higher = longer range, slower |
|
||
| **Bandwidth (BW)** | 7.8kHz - 500kHz | Higher = faster, shorter range |
|
||
| **Coding Rate (CR)** | 4/5 - 4/8 | Higher = more error correction |
|
||
| **TX Power** | 2-20 dBm | Higher = longer range, more power |
|
||
|
||
### 2.2 Data Rates
|
||
|
||
| SF | BW | Bit Rate | Range (approx) | Airtime (255 bytes) |
|
||
|----|-----|----------|----------------|---------------------|
|
||
| 7 | 500kHz | 37.5 kbps | 2 km | 55 ms |
|
||
| 7 | 125kHz | 5.5 kbps | 5 km | 200 ms |
|
||
| 10 | 125kHz | 980 bps | 10 km | 1.3 s |
|
||
| 12 | 125kHz | 250 bps | 15+ km | 4.5 s |
|
||
|
||
### 2.3 Frequency Bands
|
||
|
||
| Region | Frequency | Max Power | Duty Cycle |
|
||
|--------|-----------|-----------|------------|
|
||
| **Europe (EU868)** | 868 MHz | 25 mW (14 dBm) | 1% |
|
||
| **North America (US915)** | 915 MHz | 1 W (30 dBm) | None* |
|
||
| **Asia (AS923)** | 923 MHz | 100 mW (20 dBm) | Varies |
|
||
| **Australia (AU915)** | 915 MHz | 1 W (30 dBm) | None* |
|
||
| **India (IN865)** | 865 MHz | 30 mW (15 dBm) | None |
|
||
|
||
*Frequency hopping required for continuous TX in US/AU.
|
||
|
||
### 2.4 Packet Structure
|
||
|
||
```
|
||
┌────────────────────────────────────────────────────────────┐
|
||
│ LoRa PHY Packet │
|
||
├──────────┬──────────┬────────────────────────┬────────────┤
|
||
│ Preamble │ Header │ Payload │ CRC │
|
||
│ 8 symbols│ 4.25 sym │ 0-255 bytes │ 2 bytes │
|
||
└──────────┴──────────┴────────────────────────┴────────────┘
|
||
|
||
Header (Explicit Mode):
|
||
- Payload length (8 bits)
|
||
- Coding rate (3 bits)
|
||
- CRC present (1 bit)
|
||
```
|
||
|
||
---
|
||
|
||
## 3. Architecture
|
||
|
||
### 3.1 Multi-Transport Stack
|
||
|
||
```
|
||
┌─────────────────────────────────────────────────────────────────────────┐
|
||
│ zig-p2p Application │
|
||
│ (A2A Agents, File Transfer, DHT) │
|
||
└─────────────────────────────────────────────────────────────────────────┘
|
||
│
|
||
▼
|
||
┌─────────────────────────────────────────────────────────────────────────┐
|
||
│ Transport Abstraction │
|
||
│ │
|
||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
||
│ │ UDP │ │ WebRTC │ │ LoRa │ │
|
||
│ │ Transport │ │ Transport │ │ Transport │ │
|
||
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
|
||
│ │ │ │ │
|
||
└──────────┼─────────────────┼─────────────────┼──────────────────────────┘
|
||
│ │ │
|
||
▼ ▼ ▼
|
||
┌────────────┐ ┌────────────┐ ┌────────────┐
|
||
│ POSIX │ │ Browser │ │ SX1276/ │
|
||
│ Sockets │ │ WebRTC │ │ SX1262 │
|
||
└────────────┘ └────────────┘ └────────────┘
|
||
│ │ │
|
||
▼ ▼ ▼
|
||
Internet Internet Radio (ISM)
|
||
```
|
||
|
||
### 3.2 LoRa Transport Components
|
||
|
||
```
|
||
┌─────────────────────────────────────────────────────────────────────────┐
|
||
│ LoRa Transport │
|
||
│ │
|
||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐│
|
||
│ │ Radio │ │ Mesh │ │ Fragment │ │ Crypto ││
|
||
│ │ Driver │ │ Router │ │ Manager │ │ Layer ││
|
||
│ │ │ │ │ │ │ │ ││
|
||
│ │ • TX/RX │ │ • Routing │ │ • Split │ │ • AES-CCM ││
|
||
│ │ • CAD │ │ • Forwarding │ │ • Reassemble │ │ • Key mgmt ││
|
||
│ │ • RSSI/SNR │ │ • Neighbor │ │ • Dedup │ │ • Nonce ││
|
||
│ └──────────────┘ └──────────────┘ └──────────────┘ └─────────────┘│
|
||
│ │
|
||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||
│ │ Duty Cycle │ │ Power │ │ Channel │ │
|
||
│ │ Manager │ │ Manager │ │ Manager │ │
|
||
│ │ │ │ │ │ │ │
|
||
│ │ • Airtime │ │ • Sleep │ │ • Hop freq │ │
|
||
│ │ • Throttle │ │ • Wake │ │ • LBT │ │
|
||
│ │ • Queue │ │ • Schedule │ │ • Selection │ │
|
||
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||
│ │
|
||
└─────────────────────────────────────────────────────────────────────────┘
|
||
```
|
||
|
||
### 3.3 Node Types
|
||
|
||
| Type | Description | Hardware |
|
||
|------|-------------|----------|
|
||
| **Endpoint** | Sends/receives messages, may sleep | ESP32 + LoRa |
|
||
| **Router** | Always-on, forwards messages | ESP32 + LoRa (powered) |
|
||
| **Gateway** | Bridges LoRa ↔ Internet | RPi + LoRa + Ethernet |
|
||
| **Tracker** | GPS-enabled mobile node | T-Beam |
|
||
|
||
---
|
||
|
||
## 4. Transport Implementation
|
||
|
||
### 4.1 Transport Interface
|
||
|
||
```zig
|
||
const std = @import("std");
|
||
const Transport = @import("../core/transport.zig").Transport;
|
||
|
||
pub const LoRaTransport = struct {
|
||
allocator: std.mem.Allocator,
|
||
|
||
// Hardware
|
||
radio: *RadioDriver,
|
||
|
||
// Configuration
|
||
config: LoRaConfig,
|
||
region: RegionConfig,
|
||
|
||
// State
|
||
node_id: NodeId,
|
||
state: TransportState,
|
||
|
||
// Subsystems
|
||
router: MeshRouter,
|
||
fragmenter: FragmentManager,
|
||
crypto: LoRaCrypto,
|
||
duty_cycle: DutyCycleManager,
|
||
power: PowerManager,
|
||
|
||
// Callbacks
|
||
on_receive: ?*const fn (from: NodeId, data: []const u8) void,
|
||
|
||
const NodeId = [4]u8; // 32-bit node addresses
|
||
|
||
const TransportState = enum {
|
||
idle,
|
||
transmitting,
|
||
receiving,
|
||
sleeping,
|
||
};
|
||
|
||
pub fn init(allocator: std.mem.Allocator, config: LoRaConfig) !*LoRaTransport {
|
||
const self = try allocator.create(LoRaTransport);
|
||
|
||
self.* = .{
|
||
.allocator = allocator,
|
||
.radio = try RadioDriver.init(config.spi_device),
|
||
.config = config,
|
||
.region = RegionConfig.forRegion(config.region),
|
||
.node_id = generateNodeId(),
|
||
.state = .idle,
|
||
.router = try MeshRouter.init(allocator),
|
||
.fragmenter = try FragmentManager.init(allocator),
|
||
.crypto = try LoRaCrypto.init(config.network_key),
|
||
.duty_cycle = DutyCycleManager.init(config.region),
|
||
.power = PowerManager.init(config.power_mode),
|
||
.on_receive = null,
|
||
};
|
||
|
||
// Configure radio
|
||
try self.radio.configure(.{
|
||
.frequency = self.region.default_frequency,
|
||
.spreading_factor = config.spreading_factor,
|
||
.bandwidth = config.bandwidth,
|
||
.coding_rate = config.coding_rate,
|
||
.tx_power = config.tx_power,
|
||
.sync_word = MESH_SYNC_WORD,
|
||
});
|
||
|
||
return self;
|
||
}
|
||
|
||
pub fn deinit(self: *LoRaTransport) void {
|
||
self.radio.deinit();
|
||
self.router.deinit();
|
||
self.fragmenter.deinit();
|
||
self.allocator.destroy(self);
|
||
}
|
||
|
||
// Transport interface implementation
|
||
pub fn transport(self: *LoRaTransport) Transport {
|
||
return .{
|
||
.ptr = self,
|
||
.vtable = &vtable,
|
||
};
|
||
}
|
||
|
||
const vtable = Transport.VTable{
|
||
.send = send,
|
||
.receive = receive,
|
||
.close = close,
|
||
.canSend = canSend,
|
||
.canReceive = canReceive,
|
||
.getRemoteId = getRemoteId,
|
||
.getState = getState,
|
||
};
|
||
|
||
fn send(ptr: *anyopaque, data: []const u8) Transport.Error!usize {
|
||
const self: *LoRaTransport = @ptrCast(@alignCast(ptr));
|
||
|
||
// Check duty cycle
|
||
if (!self.duty_cycle.canTransmit(data.len)) {
|
||
return error.WouldBlock; // Queue and retry later
|
||
}
|
||
|
||
// Encrypt
|
||
const encrypted = try self.crypto.encrypt(data);
|
||
|
||
// Fragment if necessary
|
||
if (encrypted.len > MAX_PAYLOAD_SIZE) {
|
||
try self.sendFragmented(encrypted);
|
||
} else {
|
||
try self.sendSingle(encrypted);
|
||
}
|
||
|
||
return data.len;
|
||
}
|
||
|
||
fn sendSingle(self: *LoRaTransport, data: []const u8) !void {
|
||
var packet = LoRaPacket{
|
||
.header = .{
|
||
.version = PROTOCOL_VERSION,
|
||
.type = .data,
|
||
.source = self.node_id,
|
||
.dest = self.current_dest,
|
||
.ttl = self.config.default_ttl,
|
||
.sequence = self.next_sequence(),
|
||
},
|
||
.payload = data,
|
||
};
|
||
|
||
// Serialize and transmit
|
||
const raw = packet.serialize();
|
||
|
||
// CSMA/CA - listen before talk
|
||
try self.channelAccessWait();
|
||
|
||
try self.radio.transmit(raw);
|
||
self.duty_cycle.recordTransmission(raw.len);
|
||
}
|
||
|
||
fn receive(ptr: *anyopaque, buffer: []u8) Transport.Error!usize {
|
||
const self: *LoRaTransport = @ptrCast(@alignCast(ptr));
|
||
|
||
// Check for received packet
|
||
if (try self.radio.receive(buffer)) |packet| {
|
||
// Process through mesh router
|
||
const result = try self.router.handlePacket(packet);
|
||
|
||
switch (result) {
|
||
.for_us => |data| {
|
||
// Decrypt
|
||
const decrypted = try self.crypto.decrypt(data);
|
||
|
||
// Check if fragment
|
||
if (try self.fragmenter.process(decrypted)) |complete| {
|
||
@memcpy(buffer[0..complete.len], complete);
|
||
return complete.len;
|
||
}
|
||
return error.WouldBlock; // Fragment incomplete
|
||
},
|
||
.forward => |fwd_packet| {
|
||
// Rebroadcast for mesh
|
||
try self.forwardPacket(fwd_packet);
|
||
return error.WouldBlock;
|
||
},
|
||
.drop => return error.WouldBlock,
|
||
}
|
||
}
|
||
|
||
return error.WouldBlock;
|
||
}
|
||
|
||
fn canSend(ptr: *anyopaque) bool {
|
||
const self: *LoRaTransport = @ptrCast(@alignCast(ptr));
|
||
return self.state == .idle and self.duty_cycle.canTransmit(MAX_PACKET_SIZE);
|
||
}
|
||
|
||
fn canReceive(ptr: *anyopaque) bool {
|
||
const self: *LoRaTransport = @ptrCast(@alignCast(ptr));
|
||
return self.radio.hasData();
|
||
}
|
||
|
||
fn channelAccessWait(self: *LoRaTransport) !void {
|
||
// CSMA/CA: Listen Before Talk with random backoff
|
||
var attempts: u32 = 0;
|
||
const max_attempts = 10;
|
||
|
||
while (attempts < max_attempts) {
|
||
// Check if channel is clear (CAD - Channel Activity Detection)
|
||
if (!try self.radio.isChannelBusy()) {
|
||
return; // Channel clear, proceed
|
||
}
|
||
|
||
// Random backoff
|
||
const backoff_ms = self.randomBackoff(attempts);
|
||
std.time.sleep(backoff_ms * std.time.ns_per_ms);
|
||
attempts += 1;
|
||
}
|
||
|
||
return error.ChannelBusy;
|
||
}
|
||
|
||
fn randomBackoff(self: *LoRaTransport, attempt: u32) u32 {
|
||
_ = self;
|
||
var rng = std.rand.DefaultPrng.init(@intCast(std.time.milliTimestamp()));
|
||
const max_backoff = @min(1000, 50 * std.math.pow(u32, 2, attempt));
|
||
return rng.random().intRangeAtMost(u32, 10, max_backoff);
|
||
}
|
||
};
|
||
```
|
||
|
||
### 4.2 Configuration
|
||
|
||
```zig
|
||
pub const LoRaConfig = struct {
|
||
// Hardware
|
||
spi_device: []const u8 = "/dev/spidev0.0",
|
||
reset_pin: u8 = 22,
|
||
dio0_pin: u8 = 25,
|
||
|
||
// Radio parameters
|
||
region: Region = .us915,
|
||
spreading_factor: u8 = 7, // 7-12
|
||
bandwidth: Bandwidth = .bw_125khz,
|
||
coding_rate: CodingRate = .cr_4_5,
|
||
tx_power: u8 = 17, // dBm
|
||
|
||
// Mesh parameters
|
||
default_ttl: u8 = 3, // Max hops
|
||
enable_routing: bool = true,
|
||
|
||
// Security
|
||
network_key: [16]u8, // Pre-shared AES key
|
||
|
||
// Power management
|
||
power_mode: PowerMode = .always_on,
|
||
sleep_interval_ms: u32 = 0,
|
||
|
||
// Duty cycle
|
||
respect_duty_cycle: bool = true,
|
||
|
||
pub const Region = enum {
|
||
eu868,
|
||
us915,
|
||
as923,
|
||
au915,
|
||
in865,
|
||
};
|
||
|
||
pub const Bandwidth = enum {
|
||
bw_7_8khz,
|
||
bw_10_4khz,
|
||
bw_15_6khz,
|
||
bw_20_8khz,
|
||
bw_31_25khz,
|
||
bw_41_7khz,
|
||
bw_62_5khz,
|
||
bw_125khz,
|
||
bw_250khz,
|
||
bw_500khz,
|
||
};
|
||
|
||
pub const CodingRate = enum {
|
||
cr_4_5,
|
||
cr_4_6,
|
||
cr_4_7,
|
||
cr_4_8,
|
||
};
|
||
|
||
pub const PowerMode = enum {
|
||
always_on, // Router mode
|
||
duty_cycled, // Periodic wake
|
||
on_demand, // Wake on activity
|
||
};
|
||
};
|
||
|
||
pub const RegionConfig = struct {
|
||
frequencies: []const u32,
|
||
default_frequency: u32,
|
||
max_tx_power: u8,
|
||
duty_cycle_percent: u8,
|
||
dwell_time_ms: ?u32,
|
||
|
||
pub fn forRegion(region: LoRaConfig.Region) RegionConfig {
|
||
return switch (region) {
|
||
.eu868 => .{
|
||
.frequencies = &[_]u32{ 868_100_000, 868_300_000, 868_500_000 },
|
||
.default_frequency = 868_100_000,
|
||
.max_tx_power = 14,
|
||
.duty_cycle_percent = 1,
|
||
.dwell_time_ms = null,
|
||
},
|
||
.us915 => .{
|
||
.frequencies = &[_]u32{
|
||
902_300_000, 902_500_000, 902_700_000, 902_900_000,
|
||
903_100_000, 903_300_000, 903_500_000, 903_700_000,
|
||
// ... 64 uplink + 8 downlink channels
|
||
},
|
||
.default_frequency = 903_900_000,
|
||
.max_tx_power = 30,
|
||
.duty_cycle_percent = 100, // No limit with freq hopping
|
||
.dwell_time_ms = 400, // Max dwell time per channel
|
||
},
|
||
.as923 => .{
|
||
.frequencies = &[_]u32{ 923_200_000, 923_400_000 },
|
||
.default_frequency = 923_200_000,
|
||
.max_tx_power = 16,
|
||
.duty_cycle_percent = 1,
|
||
.dwell_time_ms = 400,
|
||
},
|
||
// ... other regions
|
||
};
|
||
}
|
||
};
|
||
```
|
||
|
||
---
|
||
|
||
## 5. Mesh Routing Protocol
|
||
|
||
### 5.1 Routing Strategy: Flooding with TTL
|
||
|
||
Simple, robust flooding-based routing similar to Meshtastic:
|
||
|
||
```
|
||
Node A sends message to Node D:
|
||
|
||
[A]──────[B]──────[C]──────[D]
|
||
\ /
|
||
\────[E]────/
|
||
|
||
1. A broadcasts (TTL=3)
|
||
2. B and E receive, decrement TTL, rebroadcast (TTL=2)
|
||
3. C receives from B and E (dedup), rebroadcast (TTL=1)
|
||
4. D receives from C, message delivered
|
||
```
|
||
|
||
### 5.2 Mesh Router Implementation
|
||
|
||
```zig
|
||
pub const MeshRouter = struct {
|
||
allocator: std.mem.Allocator,
|
||
node_id: NodeId,
|
||
|
||
// Deduplication
|
||
seen_messages: std.AutoHashMap(MessageId, SeenEntry),
|
||
|
||
// Neighbor tracking
|
||
neighbors: std.AutoHashMap(NodeId, NeighborInfo),
|
||
|
||
// Pending acknowledgments
|
||
pending_acks: std.AutoHashMap(MessageId, PendingAck),
|
||
|
||
const MessageId = packed struct {
|
||
source: NodeId,
|
||
sequence: u16,
|
||
};
|
||
|
||
const SeenEntry = struct {
|
||
timestamp: i64,
|
||
hop_count: u8,
|
||
rssi: i8,
|
||
};
|
||
|
||
const NeighborInfo = struct {
|
||
last_seen: i64,
|
||
rssi: i8, // Received signal strength
|
||
snr: i8, // Signal-to-noise ratio
|
||
hop_count: u8, // Hops to reach this neighbor
|
||
packet_loss: f32, // Estimated packet loss rate
|
||
};
|
||
|
||
pub fn init(allocator: std.mem.Allocator) !MeshRouter {
|
||
return .{
|
||
.allocator = allocator,
|
||
.node_id = undefined, // Set by transport
|
||
.seen_messages = std.AutoHashMap(MessageId, SeenEntry).init(allocator),
|
||
.neighbors = std.AutoHashMap(NodeId, NeighborInfo).init(allocator),
|
||
.pending_acks = std.AutoHashMap(MessageId, PendingAck).init(allocator),
|
||
};
|
||
}
|
||
|
||
pub const HandleResult = union(enum) {
|
||
for_us: []const u8, // Deliver to application
|
||
forward: ForwardPacket, // Rebroadcast
|
||
drop: DropReason, // Discard
|
||
};
|
||
|
||
pub const DropReason = enum {
|
||
duplicate,
|
||
ttl_expired,
|
||
not_for_us,
|
||
invalid,
|
||
};
|
||
|
||
pub fn handlePacket(self: *MeshRouter, raw: []const u8, rssi: i8, snr: i8) !HandleResult {
|
||
const packet = try LoRaPacket.parse(raw);
|
||
const header = packet.header;
|
||
|
||
// Update neighbor info
|
||
try self.updateNeighbor(header.source, rssi, snr, header.ttl);
|
||
|
||
// Check for duplicate
|
||
const msg_id = MessageId{
|
||
.source = header.source,
|
||
.sequence = header.sequence,
|
||
};
|
||
|
||
if (self.seen_messages.contains(msg_id)) {
|
||
return .{ .drop = .duplicate };
|
||
}
|
||
|
||
// Record as seen
|
||
try self.seen_messages.put(msg_id, .{
|
||
.timestamp = std.time.milliTimestamp(),
|
||
.hop_count = MAX_TTL - header.ttl,
|
||
.rssi = rssi,
|
||
});
|
||
|
||
// Is this for us?
|
||
if (std.mem.eql(u8, &header.dest, &self.node_id) or
|
||
std.mem.eql(u8, &header.dest, &BROADCAST_ADDR))
|
||
{
|
||
// Handle acknowledgment if required
|
||
if (header.flags.ack_requested) {
|
||
try self.sendAck(header.source, header.sequence);
|
||
}
|
||
|
||
return .{ .for_us = packet.payload };
|
||
}
|
||
|
||
// Not for us - forward if TTL > 0
|
||
if (header.ttl > 0) {
|
||
return .{ .forward = .{
|
||
.packet = raw,
|
||
.new_ttl = header.ttl - 1,
|
||
.delay_ms = self.calculateForwardDelay(rssi),
|
||
}};
|
||
}
|
||
|
||
return .{ .drop = .ttl_expired };
|
||
}
|
||
|
||
fn calculateForwardDelay(self: *MeshRouter, rssi: i8) u32 {
|
||
// Nodes with better signal wait longer (let weaker nodes forward first)
|
||
// This helps messages reach farther nodes
|
||
_ = self;
|
||
const base_delay: u32 = 100;
|
||
const rssi_factor = @as(u32, @intCast(@max(0, rssi + 120))); // RSSI is negative
|
||
return base_delay + rssi_factor * 5;
|
||
}
|
||
|
||
fn updateNeighbor(self: *MeshRouter, node: NodeId, rssi: i8, snr: i8, ttl: u8) !void {
|
||
const result = try self.neighbors.getOrPut(node);
|
||
const now = std.time.milliTimestamp();
|
||
|
||
if (result.found_existing) {
|
||
// Exponential moving average for RSSI
|
||
const alpha: f32 = 0.3;
|
||
result.value_ptr.rssi = @intFromFloat(
|
||
alpha * @as(f32, @floatFromInt(rssi)) +
|
||
(1 - alpha) * @as(f32, @floatFromInt(result.value_ptr.rssi))
|
||
);
|
||
result.value_ptr.snr = snr;
|
||
result.value_ptr.last_seen = now;
|
||
} else {
|
||
result.value_ptr.* = .{
|
||
.last_seen = now,
|
||
.rssi = rssi,
|
||
.snr = snr,
|
||
.hop_count = MAX_TTL - ttl,
|
||
.packet_loss = 0,
|
||
};
|
||
}
|
||
}
|
||
|
||
fn sendAck(self: *MeshRouter, dest: NodeId, sequence: u16) !void {
|
||
const ack = LoRaPacket{
|
||
.header = .{
|
||
.version = PROTOCOL_VERSION,
|
||
.type = .ack,
|
||
.source = self.node_id,
|
||
.dest = dest,
|
||
.ttl = 1, // ACKs don't need to travel far
|
||
.sequence = sequence,
|
||
},
|
||
.payload = &.{},
|
||
};
|
||
|
||
// Queue for transmission
|
||
try self.tx_queue.push(ack);
|
||
}
|
||
|
||
pub fn cleanupStale(self: *MeshRouter) void {
|
||
const now = std.time.milliTimestamp();
|
||
const message_ttl_ms = 60 * 1000; // 1 minute
|
||
const neighbor_ttl_ms = 5 * 60 * 1000; // 5 minutes
|
||
|
||
// Clean old seen messages
|
||
var msg_it = self.seen_messages.iterator();
|
||
while (msg_it.next()) |entry| {
|
||
if (now - entry.value_ptr.timestamp > message_ttl_ms) {
|
||
_ = self.seen_messages.remove(entry.key_ptr.*);
|
||
}
|
||
}
|
||
|
||
// Clean stale neighbors
|
||
var neighbor_it = self.neighbors.iterator();
|
||
while (neighbor_it.next()) |entry| {
|
||
if (now - entry.value_ptr.last_seen > neighbor_ttl_ms) {
|
||
_ = self.neighbors.remove(entry.key_ptr.*);
|
||
}
|
||
}
|
||
}
|
||
};
|
||
```
|
||
|
||
### 5.3 Packet Header
|
||
|
||
```zig
|
||
pub const LoRaPacketHeader = packed struct {
|
||
version: u4, // Protocol version
|
||
type: PacketType, // 4 bits
|
||
source: NodeId, // 32 bits - sender
|
||
dest: NodeId, // 32 bits - destination (or broadcast)
|
||
ttl: u8, // Time to live (hop count)
|
||
sequence: u16, // Sequence number for dedup
|
||
flags: Flags, // 8 bits
|
||
|
||
// Total: 13 bytes
|
||
|
||
const PacketType = enum(u4) {
|
||
data = 0,
|
||
ack = 1,
|
||
discovery = 2,
|
||
routing = 3,
|
||
fragment = 4,
|
||
heartbeat = 5,
|
||
};
|
||
|
||
const Flags = packed struct {
|
||
ack_requested: bool,
|
||
is_fragment: bool,
|
||
is_encrypted: bool,
|
||
priority: u2, // 0=low, 3=high
|
||
reserved: u3,
|
||
};
|
||
};
|
||
|
||
pub const LoRaPacket = struct {
|
||
header: LoRaPacketHeader,
|
||
payload: []const u8,
|
||
|
||
pub fn serialize(self: *const LoRaPacket) [255]u8 {
|
||
var buffer: [255]u8 = undefined;
|
||
const header_bytes = std.mem.asBytes(&self.header);
|
||
@memcpy(buffer[0..header_bytes.len], header_bytes);
|
||
@memcpy(buffer[header_bytes.len..][0..self.payload.len], self.payload);
|
||
return buffer;
|
||
}
|
||
|
||
pub fn parse(data: []const u8) !LoRaPacket {
|
||
if (data.len < @sizeOf(LoRaPacketHeader)) {
|
||
return error.PacketTooShort;
|
||
}
|
||
|
||
return .{
|
||
.header = @as(*const LoRaPacketHeader, @ptrCast(data.ptr)).*,
|
||
.payload = data[@sizeOf(LoRaPacketHeader)..],
|
||
};
|
||
}
|
||
|
||
pub fn maxPayloadSize() usize {
|
||
return 255 - @sizeOf(LoRaPacketHeader); // 242 bytes
|
||
}
|
||
};
|
||
```
|
||
|
||
---
|
||
|
||
## 6. Cryptography
|
||
|
||
### 6.1 Constraints
|
||
|
||
Full Noise Protocol handshake is too large for LoRa:
|
||
|
||
| Protocol | Message Size | Suitable? |
|
||
|----------|--------------|-----------|
|
||
| Noise XX | 128+ bytes | ❌ Too large |
|
||
| Noise NK | 48 bytes | ⚠️ Tight |
|
||
| ECDH + AES | 32 bytes | ⚠️ Possible |
|
||
| **PSK + AES-CCM** | **16 bytes overhead** | ✅ Best fit |
|
||
|
||
### 6.2 Lightweight Crypto Implementation
|
||
|
||
```zig
|
||
pub const LoRaCrypto = struct {
|
||
network_key: [16]u8, // Pre-shared network key
|
||
session_keys: std.AutoHashMap(NodeId, SessionKey),
|
||
nonce_counter: u32,
|
||
|
||
const SessionKey = struct {
|
||
key: [16]u8,
|
||
created_at: i64,
|
||
message_count: u32,
|
||
};
|
||
|
||
pub fn init(network_key: [16]u8) !LoRaCrypto {
|
||
return .{
|
||
.network_key = network_key,
|
||
.session_keys = std.AutoHashMap(NodeId, SessionKey).init(allocator),
|
||
.nonce_counter = 0,
|
||
};
|
||
}
|
||
|
||
/// Encrypt payload using AES-128-CCM
|
||
/// Overhead: 16 bytes (auth tag) + 4 bytes (nonce prefix)
|
||
pub fn encrypt(self: *LoRaCrypto, plaintext: []const u8, dest: NodeId) !EncryptedPayload {
|
||
// Get or derive session key
|
||
const session_key = try self.getSessionKey(dest);
|
||
|
||
// Build nonce: 4 bytes counter + 4 bytes node_id + 5 bytes padding
|
||
var nonce: [13]u8 = undefined;
|
||
@memcpy(nonce[0..4], std.mem.asBytes(&self.nonce_counter));
|
||
@memcpy(nonce[4..8], &self.node_id);
|
||
@memset(nonce[8..13], 0);
|
||
|
||
self.nonce_counter += 1;
|
||
|
||
// Encrypt with AES-128-CCM (16-byte tag)
|
||
var ciphertext: [MAX_PAYLOAD]u8 = undefined;
|
||
var tag: [16]u8 = undefined;
|
||
|
||
std.crypto.aead.aes_ccm.AesCcm(16).encrypt(
|
||
ciphertext[0..plaintext.len],
|
||
&tag,
|
||
plaintext,
|
||
&.{}, // No additional data
|
||
nonce,
|
||
session_key.key,
|
||
);
|
||
|
||
return .{
|
||
.nonce_prefix = nonce[0..4].*,
|
||
.ciphertext = ciphertext[0..plaintext.len],
|
||
.tag = tag,
|
||
};
|
||
}
|
||
|
||
pub fn decrypt(self: *LoRaCrypto, encrypted: EncryptedPayload, source: NodeId) ![]const u8 {
|
||
const session_key = try self.getSessionKey(source);
|
||
|
||
// Reconstruct nonce
|
||
var nonce: [13]u8 = undefined;
|
||
@memcpy(nonce[0..4], &encrypted.nonce_prefix);
|
||
@memcpy(nonce[4..8], &source);
|
||
@memset(nonce[8..13], 0);
|
||
|
||
// Decrypt and verify
|
||
var plaintext: [MAX_PAYLOAD]u8 = undefined;
|
||
|
||
try std.crypto.aead.aes_ccm.AesCcm(16).decrypt(
|
||
plaintext[0..encrypted.ciphertext.len],
|
||
encrypted.ciphertext,
|
||
encrypted.tag,
|
||
&.{},
|
||
nonce,
|
||
session_key.key,
|
||
);
|
||
|
||
return plaintext[0..encrypted.ciphertext.len];
|
||
}
|
||
|
||
fn getSessionKey(self: *LoRaCrypto, peer: NodeId) !SessionKey {
|
||
if (self.session_keys.get(peer)) |key| {
|
||
return key;
|
||
}
|
||
|
||
// Derive session key from network key and peer IDs
|
||
const key = deriveKey(self.network_key, self.node_id, peer);
|
||
try self.session_keys.put(peer, .{
|
||
.key = key,
|
||
.created_at = std.time.milliTimestamp(),
|
||
.message_count = 0,
|
||
});
|
||
|
||
return self.session_keys.get(peer).?;
|
||
}
|
||
|
||
fn deriveKey(network_key: [16]u8, local: NodeId, remote: NodeId) [16]u8 {
|
||
// HKDF-style key derivation
|
||
var input: [24]u8 = undefined;
|
||
@memcpy(input[0..16], &network_key);
|
||
@memcpy(input[16..20], &local);
|
||
@memcpy(input[20..24], &remote);
|
||
|
||
return std.crypto.hash.Blake2b128.hash(&input, .{});
|
||
}
|
||
};
|
||
|
||
const EncryptedPayload = struct {
|
||
nonce_prefix: [4]u8, // First 4 bytes of nonce
|
||
ciphertext: []const u8,
|
||
tag: [16]u8, // AES-CCM auth tag
|
||
|
||
pub fn totalSize(plaintext_len: usize) usize {
|
||
return 4 + plaintext_len + 16; // 20 bytes overhead
|
||
}
|
||
};
|
||
```
|
||
|
||
### 6.3 Key Distribution Options
|
||
|
||
| Method | Security | Complexity |
|
||
|--------|----------|------------|
|
||
| **Pre-shared key (PSK)** | Network-wide | Simple - configure once |
|
||
| **Per-peer PSK** | Pairwise | Medium - O(n) keys |
|
||
| **Out-of-band exchange** | Full | Complex - needs internet/QR |
|
||
| **DHT key discovery** | Full | Needs gateway to internet |
|
||
|
||
**Recommended:** Start with network-wide PSK, upgrade to per-peer keys via gateway when available.
|
||
|
||
---
|
||
|
||
## 7. Message Fragmentation
|
||
|
||
### 7.1 Why Fragmentation?
|
||
|
||
With 255-byte packets and ~20 bytes crypto overhead + 13 bytes header:
|
||
|
||
```
|
||
Available per packet: 255 bytes
|
||
LoRa header: -13 bytes
|
||
Crypto overhead: -20 bytes
|
||
Fragment header: -4 bytes
|
||
─────────────────────────────────
|
||
Max payload: 218 bytes per fragment
|
||
```
|
||
|
||
For messages > 218 bytes, fragmentation is required.
|
||
|
||
### 7.2 Fragment Manager
|
||
|
||
```zig
|
||
pub const FragmentManager = struct {
|
||
allocator: std.mem.Allocator,
|
||
pending: std.AutoHashMap(FragmentKey, FragmentState),
|
||
next_message_id: u16,
|
||
|
||
const MAX_FRAGMENTS = 32;
|
||
const MAX_MESSAGE_SIZE = MAX_FRAGMENTS * MAX_FRAGMENT_PAYLOAD; // ~7KB
|
||
const FRAGMENT_TIMEOUT_MS = 30_000;
|
||
|
||
const FragmentKey = struct {
|
||
source: NodeId,
|
||
message_id: u16,
|
||
};
|
||
|
||
const FragmentState = struct {
|
||
total_fragments: u8,
|
||
received_mask: u32,
|
||
data: [MAX_MESSAGE_SIZE]u8,
|
||
fragment_sizes: [MAX_FRAGMENTS]u8,
|
||
started_at: i64,
|
||
};
|
||
|
||
const FragmentHeader = packed struct {
|
||
message_id: u16,
|
||
fragment_num: u8,
|
||
total_fragments: u8,
|
||
// Total: 4 bytes
|
||
};
|
||
|
||
pub fn fragment(self: *FragmentManager, data: []const u8) ![]LoRaPacket {
|
||
const num_fragments = (data.len + MAX_FRAGMENT_PAYLOAD - 1) / MAX_FRAGMENT_PAYLOAD;
|
||
|
||
if (num_fragments > MAX_FRAGMENTS) {
|
||
return error.MessageTooLarge;
|
||
}
|
||
|
||
var packets = try self.allocator.alloc(LoRaPacket, num_fragments);
|
||
const message_id = self.next_message_id;
|
||
self.next_message_id +%= 1;
|
||
|
||
for (0..num_fragments) |i| {
|
||
const start = i * MAX_FRAGMENT_PAYLOAD;
|
||
const end = @min(start + MAX_FRAGMENT_PAYLOAD, data.len);
|
||
const fragment_data = data[start..end];
|
||
|
||
var payload: [MAX_FRAGMENT_PAYLOAD + 4]u8 = undefined;
|
||
const header = FragmentHeader{
|
||
.message_id = message_id,
|
||
.fragment_num = @intCast(i),
|
||
.total_fragments = @intCast(num_fragments),
|
||
};
|
||
|
||
@memcpy(payload[0..4], std.mem.asBytes(&header));
|
||
@memcpy(payload[4..][0..fragment_data.len], fragment_data);
|
||
|
||
packets[i] = LoRaPacket{
|
||
.header = .{
|
||
.type = .fragment,
|
||
.flags = .{ .is_fragment = true },
|
||
// ... other fields set by caller
|
||
},
|
||
.payload = payload[0 .. 4 + fragment_data.len],
|
||
};
|
||
}
|
||
|
||
return packets;
|
||
}
|
||
|
||
pub fn reassemble(self: *FragmentManager, source: NodeId, data: []const u8) !?[]const u8 {
|
||
const header = @as(*const FragmentHeader, @ptrCast(data.ptr)).*;
|
||
const fragment_data = data[4..];
|
||
|
||
const key = FragmentKey{
|
||
.source = source,
|
||
.message_id = header.message_id,
|
||
};
|
||
|
||
// Get or create state
|
||
const result = try self.pending.getOrPut(key);
|
||
if (!result.found_existing) {
|
||
result.value_ptr.* = .{
|
||
.total_fragments = header.total_fragments,
|
||
.received_mask = 0,
|
||
.data = undefined,
|
||
.fragment_sizes = [_]u8{0} ** MAX_FRAGMENTS,
|
||
.started_at = std.time.milliTimestamp(),
|
||
};
|
||
}
|
||
|
||
const state = result.value_ptr;
|
||
|
||
// Check timeout
|
||
if (std.time.milliTimestamp() - state.started_at > FRAGMENT_TIMEOUT_MS) {
|
||
_ = self.pending.remove(key);
|
||
return null; // Timeout, discard
|
||
}
|
||
|
||
// Store fragment
|
||
const offset = @as(usize, header.fragment_num) * MAX_FRAGMENT_PAYLOAD;
|
||
@memcpy(state.data[offset..][0..fragment_data.len], fragment_data);
|
||
state.fragment_sizes[header.fragment_num] = @intCast(fragment_data.len);
|
||
state.received_mask |= @as(u32, 1) << @intCast(header.fragment_num);
|
||
|
||
// Check if complete
|
||
const expected_mask = (@as(u32, 1) << @intCast(header.total_fragments)) - 1;
|
||
if (state.received_mask == expected_mask) {
|
||
// Calculate total size
|
||
var total_size: usize = 0;
|
||
for (0..header.total_fragments) |i| {
|
||
total_size += state.fragment_sizes[i];
|
||
}
|
||
|
||
const complete = try self.allocator.dupe(u8, state.data[0..total_size]);
|
||
_ = self.pending.remove(key);
|
||
return complete;
|
||
}
|
||
|
||
return null; // Not complete yet
|
||
}
|
||
|
||
pub fn cleanupStale(self: *FragmentManager) void {
|
||
const now = std.time.milliTimestamp();
|
||
var it = self.pending.iterator();
|
||
while (it.next()) |entry| {
|
||
if (now - entry.value_ptr.started_at > FRAGMENT_TIMEOUT_MS) {
|
||
_ = self.pending.remove(entry.key_ptr.*);
|
||
}
|
||
}
|
||
}
|
||
};
|
||
```
|
||
|
||
---
|
||
|
||
## 8. Duty Cycle Management
|
||
|
||
### 8.1 Regulatory Requirements
|
||
|
||
LoRa operates on ISM bands with duty cycle limits:
|
||
|
||
| Region | Band | Duty Cycle | Max TX per hour |
|
||
|--------|------|------------|-----------------|
|
||
| EU868 | 868 MHz | 1% | 36 seconds |
|
||
| EU868 | 869.4-869.65 MHz | 10% | 360 seconds |
|
||
| US915 | 915 MHz | None* | Unlimited |
|
||
| AS923 | 923 MHz | 1% (LBT) | 36 seconds |
|
||
|
||
*US requires frequency hopping or <400ms dwell time.
|
||
|
||
### 8.2 Duty Cycle Manager
|
||
|
||
```zig
|
||
pub const DutyCycleManager = struct {
|
||
region: RegionConfig,
|
||
transmission_log: std.ArrayList(TransmissionRecord),
|
||
current_airtime_ms: u64,
|
||
window_start: i64,
|
||
|
||
const WINDOW_MS = 3600 * 1000; // 1 hour rolling window
|
||
|
||
const TransmissionRecord = struct {
|
||
timestamp: i64,
|
||
airtime_ms: u32,
|
||
frequency: u32,
|
||
};
|
||
|
||
pub fn init(region: LoRaConfig.Region) DutyCycleManager {
|
||
return .{
|
||
.region = RegionConfig.forRegion(region),
|
||
.transmission_log = std.ArrayList(TransmissionRecord).init(allocator),
|
||
.current_airtime_ms = 0,
|
||
.window_start = std.time.milliTimestamp(),
|
||
};
|
||
}
|
||
|
||
pub fn canTransmit(self: *DutyCycleManager, packet_size: usize) bool {
|
||
self.pruneOldRecords();
|
||
|
||
const airtime = self.calculateAirtime(packet_size);
|
||
const max_airtime = WINDOW_MS * self.region.duty_cycle_percent / 100;
|
||
|
||
return self.current_airtime_ms + airtime <= max_airtime;
|
||
}
|
||
|
||
pub fn recordTransmission(self: *DutyCycleManager, packet_size: usize, frequency: u32) !void {
|
||
const airtime = self.calculateAirtime(packet_size);
|
||
|
||
try self.transmission_log.append(.{
|
||
.timestamp = std.time.milliTimestamp(),
|
||
.airtime_ms = airtime,
|
||
.frequency = frequency,
|
||
});
|
||
|
||
self.current_airtime_ms += airtime;
|
||
}
|
||
|
||
pub fn timeUntilCanTransmit(self: *DutyCycleManager, packet_size: usize) u64 {
|
||
if (self.canTransmit(packet_size)) {
|
||
return 0;
|
||
}
|
||
|
||
const airtime = self.calculateAirtime(packet_size);
|
||
const max_airtime = WINDOW_MS * self.region.duty_cycle_percent / 100;
|
||
const needed = self.current_airtime_ms + airtime - max_airtime;
|
||
|
||
// Find when enough old records will expire
|
||
var accumulated: u64 = 0;
|
||
const now = std.time.milliTimestamp();
|
||
|
||
for (self.transmission_log.items) |record| {
|
||
accumulated += record.airtime_ms;
|
||
if (accumulated >= needed) {
|
||
return @intCast(record.timestamp + WINDOW_MS - now);
|
||
}
|
||
}
|
||
|
||
return WINDOW_MS; // Worst case
|
||
}
|
||
|
||
fn calculateAirtime(self: *DutyCycleManager, packet_size: usize) u32 {
|
||
// LoRa airtime calculation
|
||
// Based on SX1276 datasheet formulas
|
||
_ = self;
|
||
|
||
const sf: u32 = 7; // Spreading factor
|
||
const bw: u32 = 125_000; // Bandwidth Hz
|
||
const cr: u32 = 5; // Coding rate denominator (4/5)
|
||
const preamble: u32 = 8;
|
||
const header_enabled = true;
|
||
const crc_enabled = true;
|
||
|
||
// Symbol time
|
||
const t_sym = (@as(u64, 1) << sf) * 1000 / bw; // ms
|
||
|
||
// Preamble time
|
||
const t_preamble = (preamble + 4.25) * t_sym / 1000;
|
||
|
||
// Payload symbols
|
||
const pl = packet_size;
|
||
const h: u32 = if (header_enabled) 0 else 1;
|
||
const de: u32 = if (sf >= 11) 1 else 0;
|
||
const crc: u32 = if (crc_enabled) 16 else 0;
|
||
|
||
const payload_symbols = 8 + @max(
|
||
@as(i32, @intCast(
|
||
std.math.divCeil(u32,
|
||
8 * pl - 4 * sf + 28 + crc - 20 * h,
|
||
4 * (sf - 2 * de)
|
||
).? * cr
|
||
)),
|
||
0
|
||
);
|
||
|
||
const t_payload = @as(u32, @intCast(payload_symbols)) * t_sym / 1000;
|
||
|
||
return @intCast(t_preamble + t_payload);
|
||
}
|
||
|
||
fn pruneOldRecords(self: *DutyCycleManager) void {
|
||
const cutoff = std.time.milliTimestamp() - WINDOW_MS;
|
||
|
||
// Remove records older than window
|
||
var i: usize = 0;
|
||
while (i < self.transmission_log.items.len) {
|
||
if (self.transmission_log.items[i].timestamp < cutoff) {
|
||
self.current_airtime_ms -= self.transmission_log.items[i].airtime_ms;
|
||
_ = self.transmission_log.orderedRemove(i);
|
||
} else {
|
||
i += 1;
|
||
}
|
||
}
|
||
}
|
||
};
|
||
```
|
||
|
||
---
|
||
|
||
## 9. Hardware Support
|
||
|
||
### 9.1 Supported Chips
|
||
|
||
| Chip | Frequency | Features | Support |
|
||
|------|-----------|----------|---------|
|
||
| **SX1276** | 137-1020 MHz | Classic, widespread | ✅ Primary |
|
||
| **SX1278** | 137-525 MHz | Lower frequency bands | ✅ Supported |
|
||
| **SX1262** | 150-960 MHz | Lower power, better | ✅ Supported |
|
||
| **SX1268** | 410-810 MHz | Lower band variant | ✅ Supported |
|
||
| **LLCC68** | 150-960 MHz | SX126x compatible | ✅ Supported |
|
||
|
||
### 9.2 Supported Boards
|
||
|
||
| Board | MCU | LoRa Chip | Price | Notes |
|
||
|-------|-----|-----------|-------|-------|
|
||
| **Heltec LoRa32 V3** | ESP32-S3 | SX1262 | ~$18 | OLED, USB-C |
|
||
| **TTGO T-Beam** | ESP32 | SX1276/62 | ~$28 | GPS, 18650 |
|
||
| **LilyGo T3-S3** | ESP32-S3 | SX1262 | ~$22 | Compact |
|
||
| **RAK4631** | nRF52840 | SX1262 | ~$30 | Ultra-low power |
|
||
| **RPi + RFM95** | BCM2835 | SX1276 | ~$45 | Full Linux |
|
||
| **Adafruit Feather** | SAMD21 | RFM95 | ~$35 | Arduino compat |
|
||
|
||
### 9.3 Radio Driver Interface
|
||
|
||
```zig
|
||
pub const RadioDriver = struct {
|
||
chip: ChipType,
|
||
spi: *SPI,
|
||
pins: Pins,
|
||
config: RadioConfig,
|
||
|
||
const ChipType = enum {
|
||
sx1276,
|
||
sx1262,
|
||
};
|
||
|
||
const Pins = struct {
|
||
reset: u8,
|
||
dio0: u8, // RX done / TX done interrupt
|
||
dio1: u8, // Optional
|
||
busy: ?u8, // SX126x only
|
||
};
|
||
|
||
pub fn init(spi_device: []const u8, pins: Pins) !*RadioDriver {
|
||
const self = try allocator.create(RadioDriver);
|
||
|
||
self.spi = try SPI.open(spi_device);
|
||
self.pins = pins;
|
||
|
||
// Reset chip
|
||
try self.reset();
|
||
|
||
// Detect chip type
|
||
const version = try self.readRegister(REG_VERSION);
|
||
self.chip = switch (version) {
|
||
0x12 => .sx1276,
|
||
0x21, 0x22 => .sx1262,
|
||
else => return error.UnknownChip,
|
||
};
|
||
|
||
return self;
|
||
}
|
||
|
||
pub fn configure(self: *RadioDriver, config: RadioConfig) !void {
|
||
self.config = config;
|
||
|
||
switch (self.chip) {
|
||
.sx1276 => try self.configureSX1276(config),
|
||
.sx1262 => try self.configureSX1262(config),
|
||
}
|
||
}
|
||
|
||
pub fn transmit(self: *RadioDriver, data: []const u8) !void {
|
||
switch (self.chip) {
|
||
.sx1276 => {
|
||
// Set to standby
|
||
try self.writeRegister(REG_OP_MODE, MODE_STDBY);
|
||
|
||
// Write to FIFO
|
||
try self.writeRegister(REG_FIFO_ADDR_PTR, 0);
|
||
for (data) |byte| {
|
||
try self.writeRegister(REG_FIFO, byte);
|
||
}
|
||
try self.writeRegister(REG_PAYLOAD_LENGTH, @intCast(data.len));
|
||
|
||
// Start TX
|
||
try self.writeRegister(REG_OP_MODE, MODE_TX);
|
||
|
||
// Wait for TX done (DIO0 interrupt or poll)
|
||
try self.waitForTxDone();
|
||
},
|
||
.sx1262 => {
|
||
// SX126x uses command interface
|
||
try self.sendCommand(CMD_SET_STANDBY, &.{0x00});
|
||
try self.sendCommand(CMD_WRITE_BUFFER, &.{0x00} ++ data);
|
||
try self.sendCommand(CMD_SET_TX, &.{ 0x00, 0x00, 0x00 });
|
||
try self.waitForTxDone();
|
||
},
|
||
}
|
||
}
|
||
|
||
pub fn receive(self: *RadioDriver, buffer: []u8) !?usize {
|
||
switch (self.chip) {
|
||
.sx1276 => {
|
||
// Check for RX done flag
|
||
const irq_flags = try self.readRegister(REG_IRQ_FLAGS);
|
||
if (irq_flags & IRQ_RX_DONE == 0) {
|
||
return null; // No packet
|
||
}
|
||
|
||
// Check CRC
|
||
if (irq_flags & IRQ_CRC_ERROR != 0) {
|
||
try self.writeRegister(REG_IRQ_FLAGS, 0xFF); // Clear
|
||
return null;
|
||
}
|
||
|
||
// Read packet
|
||
const len = try self.readRegister(REG_RX_NB_BYTES);
|
||
const addr = try self.readRegister(REG_FIFO_RX_CURRENT_ADDR);
|
||
try self.writeRegister(REG_FIFO_ADDR_PTR, addr);
|
||
|
||
for (0..len) |i| {
|
||
buffer[i] = try self.readRegister(REG_FIFO);
|
||
}
|
||
|
||
// Clear IRQ
|
||
try self.writeRegister(REG_IRQ_FLAGS, 0xFF);
|
||
|
||
return len;
|
||
},
|
||
.sx1262 => {
|
||
// Similar for SX126x
|
||
// ...
|
||
},
|
||
}
|
||
}
|
||
|
||
pub fn getRSSI(self: *RadioDriver) !i8 {
|
||
switch (self.chip) {
|
||
.sx1276 => {
|
||
const raw = try self.readRegister(REG_PKT_RSSI_VALUE);
|
||
return @as(i8, @intCast(raw)) - 157; // dBm
|
||
},
|
||
.sx1262 => {
|
||
var status: [3]u8 = undefined;
|
||
try self.sendCommand(CMD_GET_RSSI_INST, &.{}, &status);
|
||
return -@as(i8, @intCast(status[1] / 2));
|
||
},
|
||
}
|
||
}
|
||
|
||
pub fn getSNR(self: *RadioDriver) !i8 {
|
||
switch (self.chip) {
|
||
.sx1276 => {
|
||
const raw = try self.readRegister(REG_PKT_SNR_VALUE);
|
||
return @as(i8, @bitCast(raw)) / 4; // dB
|
||
},
|
||
.sx1262 => {
|
||
// SX126x returns SNR with RSSI
|
||
// ...
|
||
},
|
||
}
|
||
}
|
||
|
||
pub fn isChannelBusy(self: *RadioDriver) !bool {
|
||
// Channel Activity Detection (CAD)
|
||
switch (self.chip) {
|
||
.sx1276 => {
|
||
try self.writeRegister(REG_OP_MODE, MODE_CAD);
|
||
|
||
// Wait for CAD done
|
||
while (true) {
|
||
const flags = try self.readRegister(REG_IRQ_FLAGS);
|
||
if (flags & IRQ_CAD_DONE != 0) {
|
||
try self.writeRegister(REG_IRQ_FLAGS, 0xFF);
|
||
return (flags & IRQ_CAD_DETECTED) != 0;
|
||
}
|
||
}
|
||
},
|
||
.sx1262 => {
|
||
try self.sendCommand(CMD_SET_CAD, &.{});
|
||
// ...
|
||
},
|
||
}
|
||
}
|
||
|
||
pub fn sleep(self: *RadioDriver) !void {
|
||
switch (self.chip) {
|
||
.sx1276 => try self.writeRegister(REG_OP_MODE, MODE_SLEEP),
|
||
.sx1262 => try self.sendCommand(CMD_SET_SLEEP, &.{0x00}),
|
||
}
|
||
}
|
||
};
|
||
```
|
||
|
||
---
|
||
|
||
## 10. Gateway Mode
|
||
|
||
### 10.1 LoRa ↔ Internet Bridge
|
||
|
||
```
|
||
Internet
|
||
│
|
||
┌─────────────┴─────────────┐
|
||
│ │
|
||
▼ ▼
|
||
┌──────────┐ ┌──────────┐
|
||
│ Cloud │ │ Mobile │
|
||
│ Server │ │ App │
|
||
└────┬─────┘ └────┬─────┘
|
||
│ │
|
||
│ UDP/WebRTC │
|
||
└────────────┬─────────────┘
|
||
│
|
||
┌──────┴──────┐
|
||
│ Gateway │
|
||
│ (RPi+LoRa) │
|
||
└──────┬──────┘
|
||
│ LoRa
|
||
┌───────────┼───────────┐
|
||
▼ ▼ ▼
|
||
┌──────────┐ ┌──────────┐ ┌──────────┐
|
||
│ Sensor │ │ Sensor │ │ Mobile │
|
||
│ Node A │ │ Node B │ │ Node │
|
||
└──────────┘ └──────────┘ └──────────┘
|
||
```
|
||
|
||
### 10.2 Gateway Implementation
|
||
|
||
```zig
|
||
pub const LoRaGateway = struct {
|
||
allocator: std.mem.Allocator,
|
||
|
||
// Transports
|
||
lora: *LoRaTransport,
|
||
udp: *UDPTransport,
|
||
|
||
// Routing
|
||
lora_nodes: std.AutoHashMap(NodeId, NodeInfo),
|
||
internet_peers: std.AutoHashMap(PeerId, PeerInfo),
|
||
|
||
// Translation table
|
||
lora_to_peer: std.AutoHashMap(NodeId, PeerId),
|
||
peer_to_lora: std.AutoHashMap(PeerId, NodeId),
|
||
|
||
pub fn init(allocator: std.mem.Allocator, lora_config: LoRaConfig, udp_port: u16) !*LoRaGateway {
|
||
const self = try allocator.create(LoRaGateway);
|
||
|
||
self.* = .{
|
||
.allocator = allocator,
|
||
.lora = try LoRaTransport.init(allocator, lora_config),
|
||
.udp = try UDPTransport.init(allocator, udp_port),
|
||
.lora_nodes = std.AutoHashMap(NodeId, NodeInfo).init(allocator),
|
||
.internet_peers = std.AutoHashMap(PeerId, PeerInfo).init(allocator),
|
||
.lora_to_peer = std.AutoHashMap(NodeId, PeerId).init(allocator),
|
||
.peer_to_lora = std.AutoHashMap(PeerId, NodeId).init(allocator),
|
||
};
|
||
|
||
return self;
|
||
}
|
||
|
||
pub fn run(self: *LoRaGateway) !void {
|
||
while (true) {
|
||
// Check LoRa for messages
|
||
var lora_buffer: [256]u8 = undefined;
|
||
if (try self.lora.receive(&lora_buffer)) |len| {
|
||
try self.handleLoRaMessage(lora_buffer[0..len]);
|
||
}
|
||
|
||
// Check UDP for messages
|
||
var udp_buffer: [65536]u8 = undefined;
|
||
if (try self.udp.receive(&udp_buffer)) |msg| {
|
||
try self.handleInternetMessage(msg);
|
||
}
|
||
|
||
// Small sleep to prevent busy loop
|
||
std.time.sleep(1 * std.time.ns_per_ms);
|
||
}
|
||
}
|
||
|
||
fn handleLoRaMessage(self: *LoRaGateway, data: []const u8) !void {
|
||
const packet = try LoRaPacket.parse(data);
|
||
|
||
// Is this destined for an internet peer?
|
||
if (self.lora_to_peer.get(packet.header.dest)) |peer_id| {
|
||
// Forward to internet
|
||
try self.forwardToInternet(peer_id, packet.payload);
|
||
} else if (std.mem.eql(u8, &packet.header.dest, &GATEWAY_ADDR)) {
|
||
// Message for gateway itself
|
||
try self.handleGatewayMessage(packet);
|
||
}
|
||
// Else: local LoRa mesh message, let LoRaTransport handle routing
|
||
}
|
||
|
||
fn handleInternetMessage(self: *LoRaGateway, msg: UDPMessage) !void {
|
||
// Is this destined for a LoRa node?
|
||
if (self.peer_to_lora.get(msg.peer_id)) |node_id| {
|
||
// Forward to LoRa mesh
|
||
try self.forwardToLoRa(node_id, msg.data);
|
||
}
|
||
}
|
||
|
||
fn forwardToInternet(self: *LoRaGateway, peer_id: PeerId, data: []const u8) !void {
|
||
// Encapsulate LoRa message in UDP packet
|
||
const wrapped = try self.wrapForInternet(data);
|
||
try self.udp.send(peer_id, wrapped);
|
||
}
|
||
|
||
fn forwardToLoRa(self: *LoRaGateway, node_id: NodeId, data: []const u8) !void {
|
||
// May need to fragment for LoRa
|
||
if (data.len > MAX_LORA_PAYLOAD) {
|
||
// Fragment and send
|
||
const fragments = try self.lora.fragmenter.fragment(data);
|
||
for (fragments) |frag| {
|
||
try self.lora.sendPacket(node_id, frag);
|
||
// Respect duty cycle between fragments
|
||
std.time.sleep(100 * std.time.ns_per_ms);
|
||
}
|
||
} else {
|
||
try self.lora.sendPacket(node_id, data);
|
||
}
|
||
}
|
||
|
||
fn handleGatewayMessage(self: *LoRaGateway, packet: LoRaPacket) !void {
|
||
// Handle registration, keep-alive, etc.
|
||
const msg_type = packet.payload[0];
|
||
|
||
switch (msg_type) {
|
||
MSG_REGISTER => {
|
||
// LoRa node wants internet access
|
||
const node_id = packet.header.source;
|
||
const peer_id = try self.allocatePeerId(node_id);
|
||
try self.lora_to_peer.put(node_id, peer_id);
|
||
try self.peer_to_lora.put(peer_id, node_id);
|
||
|
||
// Send confirmation
|
||
try self.lora.sendPacket(node_id, &.{ MSG_REGISTER_ACK } ++ &peer_id);
|
||
},
|
||
MSG_KEEPALIVE => {
|
||
// Update last seen
|
||
if (self.lora_nodes.getPtr(packet.header.source)) |info| {
|
||
info.last_seen = std.time.milliTimestamp();
|
||
}
|
||
},
|
||
else => {},
|
||
}
|
||
}
|
||
};
|
||
```
|
||
|
||
---
|
||
|
||
## 11. Implementation Plan
|
||
|
||
### 11.1 Phases
|
||
|
||
| Phase | Duration | Deliverables |
|
||
|-------|----------|--------------|
|
||
| **Phase 1: Core** | 2 weeks | Radio driver, basic TX/RX |
|
||
| **Phase 2: Mesh** | 2 weeks | Routing, fragmentation, dedup |
|
||
| **Phase 3: Crypto** | 1 week | AES-CCM encryption |
|
||
| **Phase 4: Duty Cycle** | 1 week | Airtime tracking, compliance |
|
||
| **Phase 5: Gateway** | 2 weeks | LoRa ↔ UDP bridge |
|
||
| **Phase 6: Testing** | 2 weeks | Multi-node testing, range tests |
|
||
|
||
**Total: 10 weeks**
|
||
|
||
### 11.2 Phase 1: Core Radio Driver
|
||
|
||
**Tasks:**
|
||
- [ ] SPI interface for ESP32/RPi
|
||
- [ ] SX1276 register read/write
|
||
- [ ] SX1262 command interface
|
||
- [ ] Basic TX/RX functions
|
||
- [ ] RSSI/SNR reading
|
||
- [ ] CAD (Channel Activity Detection)
|
||
|
||
**Test:** Two nodes ping-pong
|
||
|
||
### 11.3 Phase 2: Mesh Networking
|
||
|
||
**Tasks:**
|
||
- [ ] Packet header format
|
||
- [ ] Flooding router with TTL
|
||
- [ ] Message deduplication
|
||
- [ ] Neighbor discovery
|
||
- [ ] Fragmentation/reassembly
|
||
- [ ] CSMA/CA
|
||
|
||
**Test:** 3+ node mesh, message delivery
|
||
|
||
### 11.4 Phase 3: Cryptography
|
||
|
||
**Tasks:**
|
||
- [ ] AES-128-CCM implementation
|
||
- [ ] Nonce management
|
||
- [ ] Key derivation
|
||
- [ ] PSK configuration
|
||
|
||
**Test:** Encrypted message exchange
|
||
|
||
### 11.5 Phase 4: Duty Cycle
|
||
|
||
**Tasks:**
|
||
- [ ] Airtime calculation
|
||
- [ ] Rolling window tracking
|
||
- [ ] Transmission throttling
|
||
- [ ] Queue management
|
||
- [ ] Region configuration
|
||
|
||
**Test:** EU868 1% duty cycle compliance
|
||
|
||
### 11.6 Phase 5: Gateway
|
||
|
||
**Tasks:**
|
||
- [ ] LoRa ↔ UDP translation
|
||
- [ ] Node registration
|
||
- [ ] Address mapping
|
||
- [ ] Keep-alive mechanism
|
||
- [ ] Reconnection handling
|
||
|
||
**Test:** LoRa node → gateway → internet → cloud
|
||
|
||
### 11.7 Hardware Requirements for Testing
|
||
|
||
| Quantity | Item | Purpose |
|
||
|----------|------|---------|
|
||
| 3+ | Heltec LoRa32 V3 | Mesh nodes |
|
||
| 1 | Raspberry Pi + RFM95 | Gateway |
|
||
| 1 | T-Beam | Mobile/GPS testing |
|
||
| - | USB power banks | Field testing |
|
||
|
||
---
|
||
|
||
## Appendices
|
||
|
||
### A. Protocol Constants
|
||
|
||
```zig
|
||
// Protocol version
|
||
pub const PROTOCOL_VERSION: u4 = 1;
|
||
|
||
// Addresses
|
||
pub const BROADCAST_ADDR: NodeId = .{ 0xFF, 0xFF, 0xFF, 0xFF };
|
||
pub const GATEWAY_ADDR: NodeId = .{ 0x00, 0x00, 0x00, 0x01 };
|
||
|
||
// Limits
|
||
pub const MAX_TTL: u8 = 7;
|
||
pub const MAX_PACKET_SIZE: usize = 255;
|
||
pub const MAX_PAYLOAD_SIZE: usize = 222; // After headers + crypto
|
||
pub const MAX_FRAGMENT_PAYLOAD: usize = 218;
|
||
pub const MAX_FRAGMENTS: u8 = 32;
|
||
pub const MAX_MESSAGE_SIZE: usize = MAX_FRAGMENTS * MAX_FRAGMENT_PAYLOAD;
|
||
|
||
// Timeouts
|
||
pub const FRAGMENT_TIMEOUT_MS: u32 = 30_000;
|
||
pub const NEIGHBOR_TIMEOUT_MS: u32 = 300_000;
|
||
pub const MESSAGE_DEDUP_MS: u32 = 60_000;
|
||
|
||
// Sync word (different from LoRaWAN to avoid interference)
|
||
pub const MESH_SYNC_WORD: u8 = 0x12;
|
||
|
||
// Message types
|
||
pub const MSG_REGISTER: u8 = 0x01;
|
||
pub const MSG_REGISTER_ACK: u8 = 0x02;
|
||
pub const MSG_KEEPALIVE: u8 = 0x03;
|
||
pub const MSG_DATA: u8 = 0x04;
|
||
```
|
||
|
||
### B. Comparison with Existing Projects
|
||
|
||
| Feature | zig-p2p + LoRa | Meshtastic | Reticulum |
|
||
|---------|----------------|------------|-----------|
|
||
| **Multi-transport** | UDP + WebRTC + LoRa | LoRa only | Multi (LoRa, IP, etc.) |
|
||
| **File transfer** | Yes (via gateway) | Limited | Yes |
|
||
| **Browser support** | Yes (WebRTC) | No | No |
|
||
| **Agent/LLM support** | Yes (A2A) | No | No |
|
||
| **ESP32 standalone** | Yes | Yes | No (needs host) |
|
||
| **Implementation** | Zig | C++ (Arduino) | Python |
|
||
| **Protocol docs** | This document | Open | Open |
|
||
|
||
### C. References
|
||
|
||
- [Meshtastic Protocol](https://meshtastic.org/docs/overview)
|
||
- [Reticulum Network Stack](https://reticulum.network/)
|
||
- [LoRa Alliance Specifications](https://lora-alliance.org/resource_hub/)
|
||
- [SX1276 Datasheet](https://www.semtech.com/products/wireless-rf/lora-connect/sx1276)
|
||
- [SX1262 Datasheet](https://www.semtech.com/products/wireless-rf/lora-connect/sx1262)
|
||
- [EU Radio Regulations (ETSI EN 300 220)](https://www.etsi.org/deliver/etsi_en/300200_300299/30022002/03.02.01_60/en_30022002v030201p.pdf)
|
||
- [FCC Part 15 (US)](https://www.ecfr.gov/current/title-47/chapter-I/subchapter-A/part-15)
|
||
|
||
---
|
||
|
||
*Document version: 1.0*
|
||
*Created: February 2026*
|