Examples
Sensors and telemetry
Patchbays for readings that arrive often and mostly say nothing new: room sensors, vehicle telemetry, JSON gateways and service latency samples.
Office temperature#
Intermediate Three rules over temp.<floor>.<room>: a stable mirror for dashboards, a sustained-heat alert with an all-clear, and a tally of heat events.
;; Round to 1dp, ignore wobbles under 0.3°C, republish for dashboards
(on "temp.*.*"
(-> payload-float
(round 1)
(deadband 0.3)
(publish! (subject-append "stable"))))
;; Sustained heat alert + all-clear in one rule: fire "alert" once when
;; the 60-sample moving average reaches 28°C, "ok" once when it falls back
;; to 26°C. A single 28°C threshold chatters: an average that hovers around
;; 28 crosses it back and forth and floods subscribers with alert/ok pairs.
;; (hysteresis LO HI X) is true from X >= HI until X <= LO and holds its
;; answer in between, so the average has to drop 2°C before the all-clear.
;; One predicate, one ring buffer, one prev slot.
(on "temp.*.*"
(transition (hysteresis 26.0 28.0 (moving-avg 60 payload-float))
(publish! (subject-append "alert") "hot")
(publish! (subject-append "ok") "cool")))
;; Daily heat-event tally: increment a per-sensor counter once on each
;; false->true crossing of the same band, ignoring all the in-between
;; samples. Subscribe to `temp.<floor>.<room>.count` for the running
;; total. (rising-edge fires once per transition, so this is a counter
;; of *crossings*, not samples.) Its moving-avg is its own call site, so
;; it keeps its own ring and does not share state with the rule above.
(on "temp.*.*"
(count! (rising-edge (hysteresis 26.0 28.0 (moving-avg 60 payload-float)))))What to notice:
deadbandinstead ofsquelch.squelchpasses any change;deadband 0.3passes only when the value has moved 0.3 from the last one it let through, so a reading wobbling between 21.0 and 21.1 stays quiet.transitioncovers both edges. One rule, one predicate: the first branch runs once when the condition becomes true, the second once when it becomes false. Nothing is published in between.hysteresisstops chatter. A single 28°C threshold flips back and forth when the average hovers around it.(hysteresis 26.0 28.0 X)turns on at 28 and off only at 26.- Call-site state. The second and third rules both contain
(moving-avg 60 payload-float). Each is its own call site with its own ring, so they do not interfere.
in temp.2.kitchen 21.04
out temp.2.kitchen.stable 21
in temp.2.kitchen 21.11
in temp.2.kitchen 21.42
out temp.2.kitchen.stable 21.4Run examples/office-temp.sh to drive enough samples to trip the alert and the all-clear.
Rental car telemetry#
Intermediate The worked example from the introductory blog post: catching over-revs at Peter's Porsche Rentals.
Peter rents out a dozen Porsche 911s and wants to record sustained high engine speeds while each car is on hire.
A script on a Raspberry Pi polls a Bluetooth OBD2 dongle for RPM, coolant temperature and other readings, publishing each to car.<vin>.<pid>. monoblok runs on the Pi and forwards processed subjects over a 5G connection to the reporting system.
What Peter wants:
- A per-car stream of RPM, coolant temperature and speed for the fleet dashboard.
- An alert when the moving average of engine speed exceeds 7500rpm.
- The latest cached readings for each car when the dashboard connects.
RPM updates many times a second and wobbles constantly at a steady throttle. Coolant barely moves once the engine is warm. Publishing all of this unconditioned over a metered 5G connection is wasteful.
;; RPM: quantize to 50rpm buckets, drop duplicates, republish
(on "car.*.rpm"
(-> payload-float
(quantize 50)
(squelch)
(publish! (subject-append "stable"))))
;; Coolant temp: 1°C deadband is plenty
(on "car.*.coolant"
(-> payload-float
(round 0)
(deadband 1.0)
(publish! (subject-append "stable"))))
;; Over-rev alert: sustained above 7500rpm across a 20-sample window.
;; Hold off for 5s between alerts so one long stretch of redline doesn't
;; spam the downstream log once per incoming sample.
(on "car.*.rpm"
(when (> (moving-avg 20 payload-float) 7500.0)
(-> payload
(hold-off 5000)
(publish! (subject-append "alert")))))in car.wp0ab.rpm 3012
out car.wp0ab.rpm.stable 3000
in car.wp0ab.rpm 3020
in car.wp0ab.rpm 3049
out car.wp0ab.rpm.stable 3050
in car.wp0ab.rpm 3110
out car.wp0ab.rpm.stable 3100
in car.wp0ab.coolant 89.6
out car.wp0ab.coolant.stable 90
in car.wp0ab.coolant 90.2
in car.wp0ab.coolant 91.4
out car.wp0ab.coolant.stable 91quantize 50 snaps RPM to 50rpm buckets, so the uplink only carries RPM when it moves into a new bucket, and coolant when it shifts by a degree. The coolant rule uses a deadband to suppress changes smaller than one degree.
The over-rev rule tests a 20-sample moving average against 7500rpm, reducing sensitivity to brief spikes. hold-off 5000 then lets one alert through every five seconds, so a long stretch of redline does not publish once per incoming sample. State is per subject, so each car has its own ring buffer and its own hold-off timer.
To get a single alert and a single all-clear instead of a repeating alert, swap the last rule for a transition, as the office temperature example does:
(on "car.*.rpm"
(transition (> (moving-avg 20 payload-float) 7500.0)
(publish! (subject-append "alert") payload)
(publish! (subject-append "ok") payload)))Peter's backend subscribes to car.*.*.stable and car.*.*.alert and gets a tidy, low-volume feed it can log, graph or react to without doing its own conditioning. Add (lvc ["car.>"]) and a dashboard subscribing to $LVC.car.*.*.stable receives the last known value for every PID on every car without waiting for the next change. Add an export form listing car.*.*.stable and car.*.*.alert and only those subjects cross the 5G link to the office NATS cluster.
Local subscribers can react to the same alert, for example by triggering a dashcam over the local network. An office notification service can subscribe through the export. Neither needs changes to the patchbay rules.
The same rules in YAML#
# YAML sugar for rental-car.edn. It lowers directly to patchbay AST forms.
on:
- sub: "car.*.rpm"
pipeline:
- $payload-float
- [quantize, 50]
- [squelch]
- [publish!, [subject-append, "stable"]]
- sub: "car.*.coolant"
pipeline:
- $payload-float
- [round, 0]
- [deadband, 1.0]
- [publish!, [subject-append, "stable"]]
- sub: "car.*.rpm"
when: [">", [moving-avg, 20, $payload-float], 7500.0]
pipeline:
- $payload
- [hold-off, 5000]
- [publish!, [subject-append, "alert"]]pipeline is the -> pipeline with the start value first, and when beside it is the rule-level guard. Bound values carry a $, and operators that are YAML indicators (">") are quoted. See YAML sugar files.
JSON frames from a gateway#
Intermediate Most off-the-shelf sensors and gateways emit JSON frames, not bare scalars. The pattern is to break the frame out at the head, then treat every field as a normal scalar stream.
; JSON-emitting sensor: one off-the-shelf gateway publishes a flat
; frame like {"temp":12.5,"hum":80,"batt":3.7} on devices.<id>, and
; we want the rest of the patchbay to keep working in scalars.
; Step 1: break the frame out at the head. json-demux is a
; demultiplexer: one wire in, one sub-subject out per named field.
; The publish is implicit (the form has no return value), so this
; sits at the tail of the rule.
; devices.kitchen {"temp":12.5,"hum":80} -> devices.kitchen.temp 12.5
; devices.kitchen.hum 80
; Missing, null, array, and non-selected nested fields are skipped silently.
(on "devices.*" :reentrant true
(json-demux! "temp" "hum" "batt" payload))
; Step 2: from here on, treat each fanned-out subject as a normal
; scalar stream. Round, deadband, publish to a "stable" mirror.
(on "devices.*.temp"
(-> payload-float
(round 1)
(deadband 0.2)
(publish! (subject-append "stable"))))
(on "devices.*.hum"
(-> payload-float
(round 0)
(squelch)
(publish! (subject-append "stable"))))
; Inline lookup: sometimes you only want one field from a frame and
; don't need the demux. Pull it straight off the JSON and into a
; threaded pipeline. json-get returns nil on missing/malformed/non-primitive,
; and publish! is a no-op on nil, so the rule self-skips bad frames.
(on "devices.*"
(-> payload
(json-get "batt")
(publish! (subject-append "battery"))))in devices.kitchen {"temp":12.52,"hum":80.2,"batt":3.7}
out devices.kitchen.temp 12.52
out devices.kitchen.temp.stable 12.5
out devices.kitchen.hum 80.2
out devices.kitchen.hum.stable 80
out devices.kitchen.batt 3.7
out devices.kitchen.battery 3.7
in devices.kitchen {"temp":12.58,"hum":80.4,"batt":3.7}
out devices.kitchen.temp 12.58
out devices.kitchen.hum 80.4
out devices.kitchen.batt 3.7
out devices.kitchen.battery 3.7
in devices.kitchen {"temp":13.1,"hum":81,"batt":3.6}
out devices.kitchen.temp 13.1
out devices.kitchen.temp.stable 13.1
out devices.kitchen.hum 81
out devices.kitchen.hum.stable 81
out devices.kitchen.batt 3.6
out devices.kitchen.battery 3.6The first rule is marked :reentrant true, so the subjects it emits (devices.kitchen.temp and friends) are matched against the rules below it. Without that option they would reach subscribers but not the cleanup rules. The second frame shows the gates working: temperature moved 0.06 and humidity rounds to the same 80, so neither .stable subject repeats.
json-get is the inline alternative when you want one field and no fan-out. Both forms accept dotted paths up to four levels deep, such as "sensor.thermal.temp".
Joins and request-reply#
Intermediate State is per subject, so a rule handling temp.inside cannot see temp.outside directly. (last SUBJECT) reads another subject's value from the last-value cache, which makes a join; reply! answers NATS requests from the same cache.
;; Join two subjects with (last SUBJECT), and answer requests with reply!.
;;
;; (last SUBJECT) returns the latest payload on a literal subject, read from
;; the last-value cache, so the subject must match an (lvc ...) filter. It is
;; nil until that subject has published.
(lvc ["temp.>"])
;; A join. When temp.inside arrives, subtract the last temp.outside from it.
;; A threaded step that gets nil stops the thread, so nothing is published
;; until both subjects have a value. (Arithmetic on a bare nil is a type
;; error; the thread is the nil-safe shape.) Thread-last puts the cached
;; value last: (- payload-float outside) is inside minus outside.
(on "temp.inside"
(-> (last "temp.outside")
(- payload-float)
(publish! "temp.difference" :dp 1)))
;; Request-reply. `nats req ask.outside ""` is answered with the cached
;; outside temperature. reply! publishes to the request's reply subject
;; (reply-to); it does nothing when the message had no reply subject or the
;; value is nil, so asking before the first reading gets no answer.
(on "ask.outside"
(reply! (last "temp.outside")))
;; The derived temp.difference is cached too (a rule's own publish updates
;; the LVC), so it can be asked for the same way.
(on "ask.difference"
(reply! (last "temp.difference")))in temp.inside 21.5
in temp.outside 18
in temp.inside 21.5
out temp.difference 3.5
in temp.inside 22
out temp.difference 4.0The first inside reading publishes nothing, because temp.outside has no value yet and a thread stops on nil. After that, each inside reading publishes the difference. Request-reply needs a real client, since reply-to is always nil under --soundcheck:
monoblok examples/ask.edn
nats pub temp.outside 18
nats req ask.outside ""Latency statistics#
Intermediate Five rules read one stream of per-request latency samples and each publishes a different statistic, so dashboards subscribe to whichever shape they care about without every consumer re-implementing the maths.
;; Live latency distribution from a stream of per-request samples.
;; Each rule reads the same 50-sample window and emits a different
;; statistic on a sub-subject, so dashboards can subscribe to whichever
;; shape they care about without each consumer re-implementing the math.
;;
;; Tick windows (50 samples) here for a deterministic demo; swap any
;; `50` for `:ms 30000` to get a 30-second sliding window instead.
(on "rpc.latency"
(-> payload-float
(median 50)
(publish! "rpc.latency.p50")))
(on "rpc.latency"
(-> payload-float
(percentile 50 0.95)
(publish! "rpc.latency.p95")))
(on "rpc.latency"
(-> payload-float
(percentile 50 0.99)
(publish! "rpc.latency.p99")))
;; Spread of the same window. Pairs nicely with p99: stddev climbing
;; while p99 stays flat means the body is widening even if the tail is
;; the same shape.
(on "rpc.latency"
(-> payload-float
(stddev 50)
(publish! "rpc.latency.stddev")))
;; Cheap trend line beside the windowed stats. (ewma ALPHA X) keeps one
;; number of state instead of a 50-slot ring: each sample moves the
;; average 10% of the way toward it. Unlike the windowed stats it never
;; forgets abruptly, the burst just decays out over the next few dozen
;; samples. Raise ALPHA to follow the signal faster.
(on "rpc.latency"
(-> payload-float
(ewma 0.1)
(publish! "rpc.latency.ewma" :dp 2)))Each rule has its own 50-sample window (call-site state again). Swap any 50 for :ms 30000 to get a 30-second sliding window. ewma is the cheap trend line: one number of state instead of a ring. See Rate, percentiles, distribution shape.
Clock forms and a funnel#
Advanced Most forms run only while handling a message. The clock forms keep a deadline, so they can publish after time passes even if the feed goes quiet. This file shows each of them, a top-level every heartbeat, and the funnel pattern for rolling several subjects into one piece of state.
;; Clock-native patchbay forms in one file.
;;
;; Try publishing numeric values to `clocked.sensor.temp` quickly, then stop.
;; The rules below produce:
;; - `clocked.sensor.temp.stale` true after 5s of silence, false on recovery
;; - `clocked.sensor.temp.debounced` after 250ms of quiet
;; - `clocked.sensor.temp.sampled` every 1s with the latest value
;; - `clocked.sensor.temp.avg5s` every 5s while the window has samples
;; - `clocked.sensor.temp.rate5s` every 5s while the window has samples
;; - `clocked.heartbeat` every 2s, whether or not anything is publishing
;; - `clocked.all.count` a running total across every `clocked.sensor.*`
;; - `clocked.all.avg5s` every 5s, the average across every sensor
(lvc ["clocked.>"])
(on "clocked.sensor.*"
(dropout :ms 5000
:lost (publish! (subject-append "stale") "true")
:found (publish! (subject-append "stale") "false")))
(on "clocked.sensor.*"
(debounce! :ms 250
(subject-append "debounced")
payload))
(on "clocked.sensor.*"
(sample! :ms 1000
(subject-append "sampled")
payload))
(on "clocked.sensor.*"
(aggregate! :ms 5000
(subject-append "avg5s")
:avg
payload-float))
(on "clocked.sensor.*"
(aggregate! :ms 5000
(subject-append "rate5s")
:rate
payload-float))
;; Heartbeat: a top-level `every` rule runs on a timer, not on a publish.
;; The first tick only schedules; it fires every 2s after that. Inside the
;; body `subject` and `payload` are empty strings, so publish to an
;; explicit subject.
(every :ms 2000
(publish! "clocked.heartbeat" "alive"))
;; Funnel: state is per subject, so `count!` and `aggregate!` directly on
;; `clocked.sensor.*` would keep one slot per sensor. To roll every sensor
;; up together, a re-entrant rule republishes each reading on one subject,
;; and the stateful rules below sit on that subject. The funnel subject
;; must not match the filter it came from.
(on "clocked.sensor.*" :reentrant true
(publish! "clocked.all" payload))
(on "clocked.all"
(count!))
(on "clocked.all"
(aggregate! :ms 5000
"clocked.all.avg5s"
:avg
payload-float))| rule | form | behaviour |
|---|---|---|
| stale detection | dropout | the first reading arms quietly; 5s of silence publishes stale true once; the next reading publishes stale false once |
| settle | debounce! | publishes the latest value after 250ms of quiet (a trailing edge) |
| fixed cadence | sample! | publishes the latest value every second after the first match |
| dashboard numbers | aggregate! | publishes the 5-second average and rate on the clock, with or without new messages |
| heartbeat | every | runs on a timer, with no message in scope |
| fleet roll-up | funnel | a re-entrant rule republishes every sensor onto clocked.all, where count! and aggregate! keep one shared slot |
Run it and publish quickly to clocked.sensor.temp, then stop and watch the delayed subjects arrive:
examples/clocked.shUnder --soundcheck, clock state lingers for 10 seconds after end of input so delayed forms can fire; --soundcheck-linger-ms changes that.
MIT licensed · © 2026 Alex Reid
Lexvica offers solutions built with monoblok.