radiochron

sergii-ziborov/radiochron Checked 4 days ago

IoT-focused pure-Rust Wi-Fi diagnostics library with change-only recording and typed verdicts

A pure-Rust Wi-Fi flight-recorder engine: native WLAN collectors, 802.11 beacon analysis, connection-history verdicts, shared incident classification, a bounded flight state machine, portable BLE history/risk detectors, and a change-only recorder. No PowerShell, no netsh text scraping, no embedded C#, no .NET — and no build toolchain beyond a stock rustup. This crate is the engine. It knows nothing about MCP, JSON-RPC, or any transport — that lives in radiochron-mcp, which depends on this one. An IoT service, CLI or metrics exporter wants this crate and nothing else.

Summary extracted from the README.

radiochron

radiochron.com · Know why Wi-Fi failed — even after it recovered.

A pure-Rust Wi-Fi flight-recorder engine: native WLAN collectors, 802.11 beacon analysis, connection-history verdicts, shared incident classification, a bounded flight state machine, portable BLE history/risk detectors, and a change-only recorder. No PowerShell, no netsh text scraping, no embedded C#, no .NET — and no build toolchain beyond a stock rustup.

This crate is the engine. It knows nothing about MCP, JSON-RPC, or any transport — that lives in radiochron-mcp, which depends on this one. An IoT service, CLI or metrics exporter wants this crate and nothing else.

[dependencies]
radiochron = "0.6"

Repository family

The IoT/core dependency stays deliberately independent from its delivery surfaces:

Repository Purpose
radiochron this portable Rust engine
radiochron-mcp separate pure-Rust MCP server built directly on the engine
radiochron-js standalone Node/npm application library over this engine
radiochron-agent unattended Wi-Fi/BLE collector with durable spool and MQTT/OTLP/Prometheus export
radiochron-electron separate Windows/macOS UI consuming radiochron-js
radiochron-site source for radiochron.com

Why no toolchain

Collectors reach the OS through hand-written FFI. Windows DLLs are resolved at run time via LoadLibraryExW restricted to System32; Linux talks directly to nl80211; macOS uses the public CoreWLAN and SystemConfiguration frameworks. The windows crate would drag in windows-link/raw-dylib, which needs mingw's dlltool on the GNU target or the multi-gigabyte Visual C++ build tools plus the Windows SDK on MSVC. Instead, the eight wlanapi.dll and four wevtapi.dll entry points are declared by hand with a handful of #[repr(C)] structs.

The result: three direct dependencies — serde, serde_json, anyhow — for a 13-crate tree including everything transitive, and a build that needs nothing but rustup (the self-sufficient GNU toolchain works with no Visual Studio installed). A bare-metal build does not activate anyhow or any hosted collector.

Selecting capabilities

Features are granular so a hosted sensor that only needs association state and link strength takes status and nothing else:

radiochron = { version = "0.6", default-features = false, features = ["status"] }
Feature Enables Depends on
std Hosted runtime used by OS, clock, filesystem and network integrations —
embedded no_std + alloc firmware adapter, WLAN models, IE parser, findings, chronicle and metrics —
ble no_std + alloc BLE advertisements, iBeacon/Eddystone identity, history and risk evidence —
monitor no_std + alloc radiotap and 802.11 frame analysis for monitor-mode captures ([wlan::monitor]) —
incident Shared incident evidence model and deterministic classifier ([incident]) —
flight Pure bounded flight-recorder state machine ([flight]) —
status Interface enumeration + current-connection attributes ([wlan::wifi_status]) std
scan Nearby BSS list with raw 802.11 IE parsing ([wlan::bss]) status
analyze The findings engine ([wlan::analyze]) scan
sample Connection dynamics sampled over a window ([wlan::sample]) status
history Reading the Windows WLAN AutoConfig event log ([events]) std
record Writing our own change log — the [chronicle] std
connectivity Radio/auth/IP/DNS/TCP/Internet diagnosis ([connectivity]) status

default enables std and every hosted capability. embedded is deliberately opt-in and does not enable an operating-system collector.

Reading history and writing it are separate on purpose: history reads what Windows already recorded; record keeps a chronicle of our own through a pluggable [chronicle::Sink] — which is what "history" will mean on platforms whose OS keeps no such log.

Source architecture

Public modules are thin facades over focused internal components. WLAN keeps models, IE parsing, scan lifecycle and platform collectors separate; Linux keeps Generic Netlink socket I/O separate from wire encoding; connectivity separates orchestration, probes and platform IP discovery; embedded Chronicle separates schema, metrics, change detection and recording. Public paths remain stable through facade re-exports.

Every Rust source file is limited to 300 lines. The integration test tests/source_layout.rs enforces the limit so new platform code must extend an existing architectural seam or introduce a focused module rather than rebuild a monolith.

Microcontrollers (no_std + alloc)

RadioChron now builds for bare-metal targets such as thumbv7em-none-eabihf. The final firmware must provide a global allocator; RadioChron uses alloc for SSIDs, BSS lists and structured findings, but it does not use std, threads, files, sockets or an OS collector:

radiochron = { version = "0.6", default-features = false, features = ["embedded"] }

Implement [embedded::Collector] over the callbacks exposed by ESP-IDF, Zephyr, Embassy or the radio vendor's HAL. Append observations into the supplied buffers; [embedded::Snapshot] reuses their capacity between polls. The [embedded::bss_entry] helper turns the common firmware scan fields and raw IE bytes into a complete analyzable entry.

use radiochron::embedded::{Collector, Snapshot};
use radiochron::wlan::{WifiStatus, bss::BssEntry};

fn poll<C: Collector>(wifi: &mut C, snapshot: &mut Snapshot) -> Result<(), C::Error> {
    snapshot.refresh(wifi)?;
    let report = snapshot.analyze();
    // Publish report.findings through the firmware's own transport.
    Ok(())
}

See examples/embedded.rs for a complete adapter. This is intended for ESP32-class and Cortex-M systems with a heap. A fixed-capacity, heapless profile for very small MCUs is not claimed yet.

ESP-IDF adapter

radiochron-esp-idf directly implements the embedded collector for the Rust esp-idf-svc EspWifi and BlockingWifi<EspWifi> types:

use radiochron::embedded::Snapshot;
use radiochron_esp_idf::EspIdfCollector;

let mut collector = EspIdfCollector::new(wifi);
let mut snapshot = Snapshot::new();
snapshot.refresh(&mut collector)?;
let report = snapshot.analyze();

ESP-IDF supplies SSID, BSSID, RSSI, channel, PHY and authentication mode. Its high-level scan API does not supply raw beacon IEs, so the adapter marks those bytes incomplete and never invents RSN/PMF data. The normalized authentication mode is retained separately for security findings.

Firmware chronicle and metrics

[embedded::chronicle::Chronicle] is also no_std. Firmware supplies a monotonic [Clock] and a [Sink] backed by RAM, NVS, flash or its own offline spool. The recorder writes only association, disconnect, roam and signal changes with schema_version, device/boot identity, sequence and deterministic event ID.

Its heartbeat metrics include expected/connected time, connectivity uptime, association attempts, disconnect/roam counts, RSSI min/max/mean, disconnect reason, backend successes/failures and time-to-associate/IP/backend. Sleep can be excluded from the uptime denominator through set_connectivity_expected. See examples/embedded_chronicle.rs.

Bluetooth LE history and risk evidence

Enable ble alone for a portable no_std + alloc BLE engine, or combine it with embedded to write BLE observations and findings through the same versioned Chronicle envelope:

radiochron = { version = "0.6", default-features = false, features = ["ble"] }

[ble::Collector] accepts advertisements from an OS, firmware SDK or external scanner. [ble::Tracker] keeps first/last seen, dwell, recurrence, RSSI range, sensor count and moving-session count. It detects configured persistent unknowns, co-travel across caller-defined movement sessions, disappearance of expected devices, concurrent strong identities in distinct zones, and beacon floods. Allowlisted identities suppress unknown/co-travel findings.

iBeacon and Eddystone UID are decoded into identities that survive address rotation. A protocol adapter may supply another stable identity; otherwise public/static addresses are treated as address identities and private/random addresses as ephemeral. Raw addresses and payloads are deliberately absent from Chronicle events; only an opaque identity key and payload fingerprint are recorded.

These are evidence rules, not danger declarations. RSSI is not distance, persistence alone is not tracking, co-travel requires a moving sensor (or multiple correctly labelled sessions), and clone evidence requires a decoded or caller-supplied strong identity plus trustworthy sensor zones/clocks.

Collect

use radiochron::wlan;

// Every WLAN interface and, for the associated one, SSID / BSSID / PHY / dBm.
for status in wlan::wifi_status()? {
    if let Some(c) = status.connection {
        println!("{:?} {} {} dBm (est)", c.ssid, c.phy_type, c.rssi_dbm_estimate);
    }
}

// Nearby APs. Wait for the driver's real completion notification, then retain
// per-interface errors alongside useful entries from other radios.
let refresh = wlan::bss::scan_and_wait(std::time::Duration::from_secs(12))?;
let collection = wlan::bss::bss_list_detailed()?;
# Ok::<(), anyhow::Error>(())

Analyze — findings, not records

analyze returns conclusions, not raw evidence: co-channel contention, crowded-channel association, weak signal, roam and band-steering candidates, insecure security, hidden SSIDs and scan-quality problems. Every [Finding] carries a caveat stating why it might be wrong — RSSI, for instance, is reconstructed by most Windows drivers from a 0..100 quality scale, so a reported −71 dBm may be anywhere in −69..−73.

use radiochron::wlan::{self, analyze};

let entries = wlan::bss::bss_list()?;
let status = wlan::wifi_status()?;
let connection = status.iter().find_map(|s| s.connection.as_ref());

let analysis = analyze::analyze(&entries, connection);
for finding in &analysis.findings {
    // finding.severity, finding.title, finding.caveat, ...
}
# Ok::<(), anyhow::Error>(())

sample::sample_connection_on(interface_guid, duration_s, interval_ms) answers a different question — not "what is the state" but "is it stable": RSSI min/max/mean and swing, rx-rate range, distinct BSSIDs and roam count over a window. Collector errors are separate from genuine disconnected samples.

Monitor mode — what a scan cannot see

A scan list says who is in range. It cannot say how much the air is costing, because the frames that carry that answer never appear in one. Enable monitor for a portable no_std + alloc analyzer over raw captures:

radiochron = { version = "0.6", default-features = false, features = ["monitor"] }

[wlan::monitor::parse_capture] decodes the radiotap header and the 802.11 MAC header; [wlan::monitor::Census] aggregates frames into two measurements that the beacon census can only gesture at:

  • Retry rate. The proportion of frames carrying the Retry bit is observed contention, not a neighbour count used as a proxy for it.
  • Deauthentication and disassociation reason codes. This is what makes "why did the link drop" answerable where no operating-system event log exists — 4-way handshake timeout, inactivity, 802.1X failure, AP out of resources.

Probe requests additionally name the networks clients are looking for, which identifies a hidden SSID without joining it. Frames the driver flagged with a failed checksum are counted separately and never fold into the retry rate: a bad FCS means the Retry bit itself may be corrupt.

Retention is bounded and configurable

Nothing a census keeps is kept forever. Eviction records name a BSSID and probed networks name what people nearby are looking for, so a collector left running would otherwise accumulate a log of its surroundings — a memory leak and a privacy problem in the same object.

[wlan::monitor::CensusPolicy] sets both an age and a ceiling; the default keeps fifteen minutes and a few hundred records. Counters survive expiry, so evictions_total still reports how often links dropped after the identifying detail is gone, and records_expired says the retained lists are a window rather than a complete account.

use radiochron::wlan::monitor::{Census, CensusPolicy};

// A fleet exporter that must ship aggregates and hold no identifying detail.
let mut census = Census::with_policy(CensusPolicy::counters_only());

// Or an explicit window.
let mut census = Census::with_policy(CensusPolicy {
    retain_ms: 60 * 60 * 1000,
    max_evictions: 512,
    max_probed_networks: 64,
});
# let _ = &mut census;

Expiry needs a clock the crate does not own: pass a monotonic reading to observe_at, exactly as [ble::Tracker] takes one. observe without a clock still honours the count ceilings but cannot expire by age, which is correct for a single bounded window and wrong for a daemon.

The feature is deliberately outside default, and radiochron-mcp does not enable it: capture needs elevated privilege and disturbs the live link, so no tool should receive it by accident.

Parsing captures nothing and is pure over bytes. parse_capture reads a radiotap-prefixed buffer; parse_frame takes a bare 802.11 frame plus a [wlan::monitor::RadioMetadata] the caller built from its own SDK, which is how a firmware callback with no radiotap header reaches the same decoders.

Capture backend Mechanism Cost
Linux nl80211 creates a separate monitor interface, frames read from AF_PACKET CAP_NET_ADMIN; the station keeps its association
macOS BIOCSDLT selects the radiotap link type on a BPF device, which is what enables monitor mode root; the station interface itself switches, so Wi-Fi drops for the duration
ESP32 firmware registers a promiscuous callback; radiochron-esp-idf supplies mode control and the translation the radio parks on one channel
Windows none wlanapi exposes no monitor mode and the driver discards management frames before userspace

Windows loses nothing important by this: it is the one platform whose operating system already records why a link dropped, and the history feature reads that log directly — with history reaching back rather than only covering the capture window.

History — why it dropped earlier

The history feature reads the WLAN AutoConfig event log directly through wevtapi and returns a [events::detect::Verdict]: reconnect loops, an AP repeatedly failing key exchange, a suspected credential mismatch.

use radiochron::events;

let recent = events::recent(200, Some(3600))?; // last hour, up to 200 events
let verdict = events::detect::detect(&recent);
# Ok::<(), anyhow::Error>(())

It reads EvtRenderEventXml — the raw, locale-invariant event XML with structured EventData — not the fully-rendered localized Message string. Every rule keys on numeric event codes, never on prose, so it behaves identically on a German or Japanese Windows.

Record — the chronicle

The record feature keeps a chronicle of change through a pluggable [chronicle::Sink]. The shipped sink is append-only JSONL with built-in rotation (zero new dependencies, greppable, and safer across power loss than a database mid-transaction):

use radiochron::chronicle::{JsonlSink, Recorder, RecorderOptions, RotationPolicy};

let sink = JsonlSink::open("chronicle.jsonl", RotationPolicy::default())?;
let mut recorder = Recorder::new(sink, RecorderOptions::default());
recorder.run_for(std::time::Duration::from_secs(3600))?; // or own the loop via .step()
# Ok::<(), anyhow::Error>(())

The chronicle records change, not polls: a stable link produces one Associated entry per interface and then silence, however long you record. Collector errors never impersonate disconnects; event-log tailing uses EventRecordID and records an explicit HistoryGap when a bounded poll loses records. Its types, sink ([chronicle::Sink], [chronicle::JsonlSink], [chronicle::VecSink]) and [chronicle::ChangeDetector] are OS-free. [chronicle::Collector] makes the recorder portable too: the bundled collector uses WLAN API on Windows and nl80211 on Linux, while a modem or firmware agent can inject its own collector. Every entry carries a multi-device-safe envelope (schema_version, device_id, boot_id, sequence, clock quality and deterministic event_id). Heavy storage backends stay out of the tree: a SQLite sink is ~30 lines of impl Sink in your crate, which keeps this library building on stock rustup (rusqlite's bundled C compile does not).

Diagnose beyond association

Association does not prove network access. [connectivity::diagnose] reports the chain separately: radio, AP authentication/association, IP assignment, gateway, DNS, application TCP, captive-portal interception, TLS certificate validation, repeated-connect loss/jitter and an explicit Internet endpoint. There are no built-in public probes; an isolated deployment points every check at its own gateway, broker and health endpoint. Windows reads the native DhcpEnabled flag, macOS reads the active SystemConfiguration service and lease, and Linux corroborates active systemd-networkd/NetworkManager leases. Unknown remains a first-class result when Linux has neither lease provenance nor an explicit active static profile; absence of a lease is never guessed to mean static configuration. TLS stays transport-pluggable so core gains no TLS dependency; downstream applications can supply a system-TLS verifier.

Platform support

Windows Linux macOS
interface + association yes yes (nl80211) yes (CoreWLAN)
BSS list with raw IEs yes yes (nl80211) yes (CoreWLAN)
connection history yes no equivalent no equivalent

Windows, Linux and macOS collectors use native OS APIs without shelling out. History remains Windows-specific because Linux has no equivalent WLAN AutoConfig event log; the portable chronicle is the durable history on IoT devices.

  • MSRV: Rust 1.78
  • Edition: 2021

Safety and privacy

SSIDs, BSSIDs, MAC addresses and event logs are sensitive. This library is local-first, has no telemetry, and transmits nothing off the machine. Only run scans against networks you own or are authorized to test. It is not a packet sniffer, a geolocation system, or offensive radio tooling. BLE identity keys are deterministic fingerprints, not cryptographic anonymization guarantees.

crates.io release

The crate release is isolated from the npm, MCP, Electron, agent, and website repositories. A matching v<crate-version> tag runs formatting, clippy, tests, and cargo publish --dry-run before publishing with the protected crates-io GitHub environment and its CARGO_REGISTRY_TOKEN secret. The workflow fails closed if the tag, manifest version, or credential is missing.

License

Licensed under either of Apache-2.0 or MIT, at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.