Skip to content

Node architecture ​

One module map explains the whole node: sensor in, one decision per second, conditions out, four files that survive a reboot. nodes/core/ is the sensor-agnostic core that does it, compiled unchanged for every node. This page covers the modules, the 1 Hz data path, the two feature spaces, boot and persistence, what it all costs, and how the modular rewrite differs from the MVP.

Module map ​

main.cpp is about 20 lines of identity: it builds the sensor and calls app.begin(sensor, id) plus app.tick() from the loop. Everything else is nodes/core/, compiled unchanged for every node. The full file list is on the repository layout page.

ModuleFileJob
Composition rootnode_runtime.h/.cppthe real setup()/loop(); wires sensor, monitor, library, episodes, messaging, console
Monitortinyrl_monitor.h/.cppTinyRL integration: nn::Sequential + streaming score + evidence
Optimizerstreaming_optimizer.hStreamingOptimizer (Stream-X v3 App. A); v2 ObGD via -DMONITOR_USE_OBGD
Feature spacefeature_space.hfrozen anchored-ratio condition space
Condition librarycondition_library.h/.cpplearned centroids, JSONL on flash
Episodesepisode.h/.cppopen/feed/close lifecycle + summaries
Messaginguns_messaging.h/.cppWiFi/MQTT, 5 topics, State/* + Action/feedback
Persistencepersistence.h/.cppmodel.bin + net.bin + conditions.jsonl + pending.jsonl
Consoleconsole.h/.cppserial console + JSON feedback path
Confignode_config.hcompile-time limits, topic layout, defaults
JSON writerjson_mini.htiny JSON writer for payloads
TRNG shimesp_shim.cgetentropy -> esp_random (TinyRL TRNG on ESP32)

(README.md L269-318.)

One second in the life of a node (the 1 Hz data path) ​

  1. SensorNodeApp::tick() polls the sensor (Modbus registers) and gates on freshness (node_runtime.cpp).
  2. mon_.step() maps the features into the era's observation, predicts the next step, takes one bounded update, updates the score EMA (tinyrl_monitor.cpp). The observation is era-gated: frozen z (legacy), anchored-ratio levels (rel-obs arm), or per-condition centered residuals obs = (rel - c_matched) / u_matched with a nearest-condition frame for unknowns (current cond-obs arm). The settle gate (per-feature motion EMAs floored at CAL units, 8-step dwell) holds decisions and training off mid-transition, and the update runs only on settled steps of matched (labeled) conditions, at the floor rate once the condition's own score band says the net has converged there. A label arriving mid-settled-state rescales the cond-era input frame, so optimizer state is dropped on frame switches (bench 2026-11-21: without it the heal took thousands of steps).
  3. Alarm semantics, era-gated (node_config.h, MODEL_VERSION): the legacy z era keeps the positional Schmitt latch over any named condition, with an unmatched state alarming after 5 settled steps above the fit theta. The cond era replaces the latch with the condition's own calibrated evidence: a matched state alarms only when the leaky evidence accumulator (ACC_ALARM = 5, fed by the score's excess over the condition's own surprise band and by the positional aggregate's excess over its positional band) crosses its trigger; quiet leaks the accumulator and never resets it. Radius-edge stickiness: a state that drifts past the quiet edge stays matched to its last condition while within MATCH_Q; beyond MATCH_Q it is genuinely unknown. An unmatched state gates on the global fit theta and opens an episode the same way: open() names it if the position matches a centroid, else the state publishes unidentified, feeds settled samples, and at ASK_MIN_BATCH = 15 stores a pending batch and asks (episode.cpp, pending store).
  4. While alarmed, ep_.feed() accumulates per-feature means; on clear the episode closes; the centroid refines by EMA 0.9/0.1 on close of NORMAL-kind episodes only (a fault episode's mean folds in the recovery tail and poisons the centroid, 2026-11-19).
  5. UnsMessaging publishes only on state or condition change; autosave rewrites the flash files at most every 5 min (flash-wear budget, AUTOSAVE_MS).

Two feature spaces (do not merge them) ​

SpaceFrozen whenUsed forNever for
z-space (Welford moments)end of theta fitnetwork input in the legacy z era, surprise, thetacondition matching
anchored-ratio decades (rel = log2((x+A)/(mu+A)), A = 6 CAL sigma)end of CALcondition centroids + per-condition match units, episode summaries, and, centered per condition, (rel - c)/u, the cond-era network inputraw z-scores for matching

The split protects labels from network drift: centroids live in a space that stopped moving at the end of CAL, so a label learned today still matches weeks later no matter what the net does. The cond era goes one step further: the network reads the anchored-ratio frame centered on the matched condition's own centroid and scaled by its own units, so every regime's training manifold sits at 0 and surprise is stationary per regime.

Boot and persistence ​

The four files and their contents are listed on the lifecycle page.

What it costs ​

ItemValueWhere
Network4-32-32-4, 1,348 paramsnode_config.h NET_HIDDEN
Optimizer statetraces + leaky max + grads, about 16 KBstreaming_optimizer.h
Compute per stepforward + backward + update at 1 Hz, far under 0.1% CPU at 240 MHzruntime claim, README
Flash budgetfour files, autosave at most every 5 min (about 12 writes per hour)node_config.h AUTOSAVE_MS
Bigger netsPSRAM used transparently, see the stack pageplatformio.ini

Measured footprints per env: about 17-19% static RAM and 31% of the app partition on both node images (bash tests/run_mcu.sh; exact numbers on the tests page).

From the MVP to the modular rewrite ​

Before nodes/core/ there was a single-file MVP, vfd_streamq.cpp (a 24-bin transition-histogram learner). The rewrite replaced it; the comparison explains most of the design:

AreaMVP (vfd_streamq.cpp)This rewrite
Learninghand-rolled 24-bin transition histograms + NLLTinyRL nn::Sequential (sparse Linear -> LayerNorm -> LeakyReLU x2) doing one-step prediction; reward = -surprise; optimized by ObGD (eligibility traces + overshooting bound) from examples/stream_x/src/obgd.h
Normalizationlog-binning onlytwo spaces with distinct jobs: frozen log-range (condition library) + the network's observation, era-gated: z-scores frozen after theta fit (legacy z env), rel levels (rel-obs A/B arm), per-condition centered residuals (rel - c)/u (cond-obs env, MODEL_VERSION 8)
Weightsnone to persistnet.bin: Linear layers serialized verbatim; node resumes monitoring after reboot with zero relearning (plug-and-play)
ScoreNLL EMAprediction-error EMA (stationary ~O(1) under normal, spikes on regime change) - theta = mu + 4 sigma unchanged
Episodes/library/feedback/UNSnonesemantics preserved 1:1 from the first modular cut (same topics, same actions, same console), but generic over the feature profile
State/eventflat i_mean...generic meas:{<feature>:<value>} built from the profile; discovery added via retained State/node_info
Bug fixlibLoad() used strtof without skipping commas -> centroids 2..N loaded as 0 after every rebootfixed (separator guard), verified by round-trip test

Why the net instead of the histogram: the histogram NLL only saw pairs of consecutive bins; the network learns the joint one-step dynamics of all features, and the optimizer's update bound keeps the update size sane during the anomaly burst itself (the moments with the biggest gradients are exactly the moments you don't want rewriting the model). StreamQ/StreamAC remain unused because a condition monitor has no action space - the update loop mirrors stream_q.h so a future control node (setpoints, derating) can drop StreamQ in beside the monitor.

Migration notes from the MVP days (kept for history): an old /model.bin (v3 histogram) is ignored once; press s to relearn. State/event's meas replaced the flat i_mean/... fields at schema v1.1. The centroid-reload bug fix changed conditions.jsonl parsing only - the file format is unchanged, existing labels survive the upgrade.