What's new in microblx (dev)?

January 14, 2026 — updated 2026-11-21

Although quiet on the master branch, a lot is going on on -dev. Here's a summary of what's coming (and will become the long awaited v1.0). Release candidates are being tagged on dev now, the latest being v1.0.0-rc7.

new blocks

lsdb-intf and ubx-dbus

A D-Bus interface block that exposes the full node API (create/remove blocks, connect ports, set/get configs, load USC models, ...) over D-Bus. The companion ubx-dbus CLI provides interactive access from the shell.

The plugin extension lets you register custom D-Bus objects at runtime by loading Lua plugin files, so application-specific interfaces can sit alongside the standard org.ubx.node API.

The block is based on the lsdbus bindings. Essentially, this permits creating coordination interfaces that can cleanly and safely interact with the hard real-time processing without impacting real-time performance.

lfrb

A new lock-free ring buffer iblock based on a minimal internal liblfq implementation which is based on a Vyukov MPMC queue. This replaces the external liblfds dependency which didn't support arm64. Strongly typed, hard-real-time safe. lfrb is now always the default iblock, and the deprecated lfds_cyclic block is removed.

gpio

Linux GPIO block using libgpiod v2. Ports are created dynamically from the gpios config array: each input line becomes an out-port, each output line becomes an in-port (type unsigned int). Supports active-low polarity, pull bias, and emit-on-change mode.

iio

Linux Industrial I/O blocks via libiio for ADCs, DACs, IMUs, and environmental sensors. Two variants:

  • ubx/iio: polled, synchronous sysfs read each step; also supports DAC output
  • ubx/iio_buf: buffered, hardware samples at sampling_frequency; ptrig drains the kernel buffer

Ports are created dynamically from the channels config; type is always double (physical scaled value).

gps

GPS block that reads from gpsd via its shared memory interface. Emits a single gps out-port of type ubx_gps_data with position, velocity, fix quality, and uncertainty fields.

webgraph

A luablock that serves an interactive browser graph of the running node using React Flow + ELK.js. Blocks are shown as nodes (colour-coded by state) with ports, configs, and iblock edges. The page auto-refreshes and re-runs the ELK layered layout. Requires luasocket and json.lua; JS libs are fetched from CDN on first load. Self-trigger it at a low rate alongside your composition, no separate process needed.

ubx-launch gained a matching -webgraph [PORT] flag to attach one automatically:

$ ubx-launch -c threshold.usc -webgraph

webgraph showing the threshold example composition

This replaces the old webif block, which was removed, as it had grown too complex and unmaintainable. How long a request may block step is now bounded, and webgraph is documented as what it is: a development tool, not something to leave in a production composition.

All bridging iblocks are now drawn as edges, labelled name [type], not just lfrb, so vstore and latch connections no longer show up as blocks. The layout is denser, the header has view toggles and the edges carry hover tooltips. A full /api/graph takes some 250 ms on a Cortex-A53 with 67 blocks, so the auto refresh polls the cheap /api/stats instead. ubx-dbus --webgraph [PORT] starts a webgraph block in an already running node, and ClearNode keeps it, like the D-Bus block itself.

math_double / math_float

Applies any single-argument math.h function element-wise to an input array, with optional per-element mul and add (y = f(x) * mul + add). The function is selected via the func config string ("sin", "sqrt", "log", etc.).

netsink

A luablock-based streaming sink for live-plotting and telemetry (primarily PlotJuggler). It drains input ports and emits one message per sample over the network. Two transports (UDP datagrams or a ZeroMQ PUB socket) and two encodings (JSON or MessagePack) are selectable, all via lua_str globals. Ports are created dynamically from the ports declaration:

{ name="sink", type="luablock:netsink" },
-- ...
{ name="sink", config = {
     lua_str = [[
        ports     = { x="double", v="double" }
        transport = "zmq"          -- "udp" (default) or "zmq"
        format    = "msgpack"      -- "json" (default) or "msgpack"
        uri       = "tcp://*:9870"
     ]],
} },

Ports default to scalars; a "[N]" suffix declares an array port (pos="double[3]"), which serializes as a nested array and is expanded by PlotJuggler into pos/0, pos/1, ...

Both transports go straight through the LuaJIT FFI, no luasocket or lzmq dependency. For RT decoupling, run the sink on its own thread at a lower rate (thread=1, period=100) with deep connection buffers (buffer_len=N); each step drains the full buffer so no samples are lost on the RT side.

$ ubx-launch -c netsink.usc

netsink streaming sin/cos/tan to PlotJuggler over UDP

ZeroMQ messages start with a topic frame, the layout PlotJuggler's ZMQ subscriber expects. A raw format sends the port bytes as they are, tagged with the type hash, for consumers that know the types. Struct ports work too.

(Previously called udpsink; renamed now that it does more than UDP; the migration is a one-word type change.)

signal processing: stats, movavg, ewma, mux/demux

A set of small, generic building blocks for composing signal chains. All are runtime-typed: element type and vector length are chosen via the type and data_len configs instead of at compile time, so one block serves all numeric types.

  • ubx/stats: running min, max, mean, std and cnt of the input signal, computed online with Welford's algorithm and emitted as a struct ubx_stat. Vectors are accumulated per element; the output rate can be throttled with stats_output_rate, and skip_first discards N startup samples, so a single transient outlier doesn't ruin min/max and dominate mean and stddev for the rest of the run.
  • ubx/movavg: fixed-window moving average, with a mode config selecting the window aggregate (mean, median, min or max). The median is RT-safe (insertion sort into a preallocated scratch buffer).
  • ubx/ewma: exponentially weighted moving average (y += alpha * (x - y)), the cheap, state-free-ish alternative to a window filter.
  • ubx/mux, ubx/demux: composition glue: mux concatenates nin input ports into one vector, demux partitions a vector onto nout output ports. The optional in_len/out_len configs assign per-port sub-vector lengths, which makes demux double as a slicing block, connect only the outputs you need.

vstore and latch

Two new connection iblocks for cases where lfrb's lock-free queue is paid for but not used. Neither is a default, pick them per connection, once the respective precondition has been checked.

ubx/vstore is a single-slot value store for a connection whose writer and reader are stepped by the same trigger in the same thread. That pair needs neither a queue nor synchronisation: the write always completes before the read begins. Per connection and step lfrb performs four atomic read-modify-writes, which are not uniformly cheap (on an ARMv8.0 target without LSE each becomes an outline-atomics helper call), and spreads freeq/usedq/slot/elem over several cache lines, where vstore is one allocation with the payload next to its flag. It keeps lfrb's read contract exactly (0 when there is no unread value) and counts violations of its own precondition on an overwrites port.

ubx/latch is a single-writer, multi-reader latest-value store: a read does not consume, so any number of readers share one latch and the value stays available until the writer replaces it. Concurrency is a seqlock: the writer is wait-free, and a reader catching a write in progress retries and then reports no-data rather than spinning. Unlike vstore it is safe across threads. Use it for published state sampled by an unrelated cycle, or for signals only written on change. Single scalars are passed with one atomic, so the reader never retries; arrays keep the seqlock:

{ src="ptrig.overrun_cnt", tgt="overruns.in", type="ubx/latch" },

The catch is the same for both: the return value means a value exists, not a new value arrived. Anything that must act only on fresh input stays on lfrb.

pack and unpack

ubx/pack publishes a set of ports as one frame into a lock-free broadcast buffer in shared memory; ubx/unpack writes the frames to its out-ports. Pack and unpack blocks are paired by a packid, in the same node, across subsystems, or in another process, and any number of readers can follow one pack block. Each frame records which ports had new data, so a port without new data stays without new data downstream. Both blocks are hard real-time (no allocation or syscall in step). The new ubx-pack tool lists, reads and replays segments, and webgraph draws a pack/unpack pair as one fat edge.

fdtrig

A second active trigger: ubx/fdtrig blocks in poll(2) on one file descriptor and steps the active chain once per wakeup, so a composition can be driven by the outside world instead of a clock. Three sources: a gpio line (chardev v2 uAPI, no libgpiod), a periodic timerfd, or a pollable path (FIFO, character device). It shares the thread configs of ptrig (sched_policy, sched_priority, affinity, cpuset, ...) and reports what happened on out-ports: event_cnt, coalesced_cnt for events merged into one step, and for gpio lost_cnt from the kernel's 16-event line buffer plus latency_ns, the time from the kernel event timestamp to the start of the step.

{ name="gpiotrig", type="ubx/fdtrig" },
...
{ name="gpiotrig", config = {
     source="gpio", gpio_chip="gpiochip0", gpio_line=17, gpio_edge="rising",
     timeout_ns=10000000, timeout_step=1,
     sched_policy="SCHED_FIFO", sched_priority=80, affinity={ 3 },
     chain0={ { b="#ctrl" } } } },

timeout_ns is a watchdog, not a fallback period: it restarts on every wakeup, so with timeout_step=1 the chain is also stepped timeout_ns after the last event. On POLLERR, POLLHUP, EOF or a read error the block logs and stops itself, and can be started again; for path that reopens the file.

other changes

hot connect and disconnect

Ports can now be connected and disconnected while the blocks using them run. ubx.disconnect no longer requires stopping anything, so rewiring a chain at run-time is two calls:

$ ubx-ilaunch -c /usr/local/share/ubx/examples/usc/threshold.usc
> ubx.disconnect(nd, "sin", "y", "thres", "in")   -- thres gets no more data
> ubx.connect(nd, "sin", "y", "thres", "in")      -- reconnect via a new ubx/lfrb

The same over D-Bus with ubx-dbus -d sin:y:thres:in and ubx-dbus -x sin:y:thres:in.

Importantly, reconfiguring does not slow down or disturb the running composition. The mechanism is liburcu-bp: port read and write run in RCU read-side sections, and a connect publishes a new copy of the port's connection array, then frees the old one once no thread can still be using it. Everything expensive, i.e. the mutex, the allocation and the wait for that grace period, happens in the non-RT control thread. The RT threads neither block nor allocate, and they never wait for a reconfiguration: a slow or blocking iblock delays the writer, never the reader (which is why ubx/mqueue with blocking=1 is now rejected). Measured on a BeaglePlay under PREEMPT_RT with an isolated RT core, 10 connects and disconnects per second have no measurable effect on step time or wakeup latency.

The new cmake option ENABLE_URCU is on by default, which makes liburcu-bp >= 0.11 a build dependency (apt install liburcu-dev, liburcu from oe-core in Yocto). -DENABLE_URCU=OFF builds without it, and ubx-launch --version reports which it is.

There is more to say about this than fits here: the measurements, the C API and the rules that go with it will follow in a separate post. One of those rules is an incompatible change worth knowing about even if you never rewire anything: configs of active blocks are now read-only instead of silently racing.

blockdiagram: model parameters

.usc models can now declare parameters that are set on the command line, instead of being copy-edited per deployment or target:

local PERIOD  = bd.param("PERIOD",  1000, "trigger period [us]")
local GRIPPER = bd.param("GRIPPER", 0,    "1 = gripper attached")
$ ubx-launch -c arm.usc --params                   # list parameters
$ ubx-launch -c arm.usc -D PERIOD=500 -D GRIPPER=1

The value is converted to the type of the default, and a -D for a parameter no loaded model declares is an error, as is a non-numeric value for a numeric default. Names are global across all loaded models, so a submodel included twice reads the same value. Passing a conversion function (e.g. tonumber) as the default makes the parameter required, and an optional fourth argument validates the value -- a plain function or a callable table such as a tableshape type:

local PERIOD = bd.param("PERIOD", 1000, "trigger period [us], > 0",
                        function(v) return v > 0, "must be > 0" end)

ubx-dbus --load-usc understands -D and --params too. The flip side is an incompatible D-Bus signature change: LoadUSCLua went from (s) to (s usc, a{ss} params), so pass an empty dict when there are no parameters. Details in the usc reference.

blockdiagram: direct luablock loading

.usc compositions can now instantiate Lua blocks directly using the luablock:NAME type prefix, with no need to manually import the luablock module, create an instance, and configure lua_file separately:

blocks = {
    { name="ctrl", type="luablock:mycontroller" },
},

The name is resolved against the standard microblx block prefixes.

luablock: self-triggering

luablock now supports built-in self-triggering via the thread and period configs. For non-RT management or interfacing tasks this eliminates the need for a dedicated ptrig:

config = { thread=1, period=100 }  -- self-trigger at 100 ms

preinit / preexit life-cycle hooks

Blocks gained two optional life-cycle hooks, preinit and preexit, running before the regular init/cleanup. They add a second structural-mutation point for the rare case where a block must build its own interface from its configuration, e.g. create ports whose number or type depends on a config, or a config whose value drives the creation of other configs. This is what lets netsink above turn its ports declaration into real ports before the connections are wired up.

Most blocks never need this, init remains the place for ordinary setup. Reach for preinit only when interface creation has to depend on configuration. It's available to C blocks and to luablock (just define Lua preinit/preexit functions); the rationale is written up in docs/dev/004.

ptrig: SCHED_DEADLINE support

ptrig now supports Linux EDF scheduling via sched_policy = "SCHED_DEADLINE". Timing parameters are passed via the sched_deadline config (runtime_ns, deadline_ns, period_ns); deadline_ns and period_ns default to the period config when 0. After each chain trigger sched_yield signals budget exhaustion to the kernel. Budget overruns are caught via SIGXCPU and counted on the deadline_throt_cnt out-port. The sched_deadline in-port allows runtime parameter updates without reconfiguration.

ptrig: timing

ptrig got a round of timing features, mostly to answer how late does a trigger actually fire? overrun_cnt only counts whole periods lost, and tstats measure how long the chain ran, not when it started.

  • Latency measurement: latency_stats = 1 writes the per-cycle lateness to a new latency_ns out-port and logs min/max/avg at stop. Connect it to a ubx/stats block for the stddev. It is opt-in, as it costs one extra clock read per cycle.
  • Latency break: latency_break_ns stops ftrace with a marker on the first sample above the limit, so the kernel trace ends at the spike that caused it (see tracing below). Compiled out with TRACING=OFF.
  • Hybrid sleep mode: sleep_mode = 2 sleeps until busy_slack_ns before the deadline and busy-waits the rest, absorbing the OS wakeup latency at busy-wait accuracy. busy_slack_ns must exceed the platform's worst-case wakeup latency, else the mode silently degrades to sleep_mode=0.
  • timerslack_ns sets the trigger thread's timer slack. Linux defaults non-realtime threads to 50 us, which shows up one-to-one as lateness under SCHED_OTHER.
  • cpuset makes the trigger thread join a cgroup v1 cpuset itself; affinity is then applied within it.
  • period in-port adjusts the trigger period at runtime.
  • sync_req / sync_ack ports step the chain once per new sync_req value, to run a chain on a second core in lockstep with a counter. Unconnected, nothing changes.

Also fixed: after a missed deadline ptrig now waits for the realigned deadline instead of firing immediately at an arbitrary phase, so an overrun drops the affected tick(s) and leaves the phase of all later triggers unchanged. Several off-by-one overrun and latency accounting errors found on real hardware are gone, and ubx_nanosleep resumes after a signal instead of returning EINTR, which used to end the ptrig and luablock threads. Stopping a trigger used to take at least 50 ms, because the stop polled for the thread to park; the thread now signals a condvar, so stop returns as soon as the running step is done.

cheaper clock reads: ubx_gettime_ns

ubx_gettime returns a sec/nsec pair, which on the CNTVCT time source costs three 64 bit divisions. The new ubx_gettime_ns returns nanoseconds directly, a single multiply where the counter frequency divides 1e9 evenly. On an AM62x at a 500 us period with sleep_mode=2, mean trigger lateness dropped from 1553 to 1506 ns. Note that both hardware time sources still default to off: the out-of-the-box build pays 65 ns per timestamp against 15 ns for CNTVCT.

const: runtime in port

ubx/cconst and ubx/iconst gained an in port. Writing to it updates the held value at runtime, without a reconfigure cycle. Example use-case: update dynamic configuration safely via the lsdb-intf block.

runtime-typed saturation, ramp and rand

The compile-time typed block variants are being replaced by single, runtime-typed blocks that take the element type and vector length from the type_name and data_len configs:

  • ubx/saturation replaces the ubx/saturation_* blocks (API change); lower_limits/upper_limits are double arrays of length 1 (broadcast) or data_len.
  • ubx/ramp and ubx/rand replace the ubx/ramp_* and ubx/rand_* blocks, which are removed (API change). ramp accumulates in the native type and gives start and slope the configured type, so 64 bit integer ramps stay exact beyond the 2^53 double mantissa, and rand keeps its PRNG state per instance (erand48/jrand48), making multiple instances independent and thread-safe.

The config that carries the type was called type by these blocks and type_name by the iblocks and cconst. It is type_name everywhere now; blockdiagram still accepts type with a warning, so existing models keep working.

threshold gained an optional hysteresis config (Schmitt trigger): the state switches to 1 only above threshold + hysteresis/2 and back to 0 only below threshold - hysteresis/2, which suppresses event chatter on noisy signals.

tracing: SDT probes and ftrace markers

libubx gained a lightweight, compile-time selectable tracing layer with tracepoints at the framework choke points: step_begin/ step_end around each c-block step and chain_begin/chain_end around each trigger chain run. ptrig additionally emits overrun and dl_overrun events. The backend is picked at build time:

$ cmake -DTRACING=SDT ..     # USDT probes (perf, bpftrace, systemtap)
$ cmake -DTRACING=MARKER ..  # ftrace trace_marker
$ cmake -DTRACING=OFF ..     # default, macros expand to nothing

SDT compiles each probe to a single nop until a consumer attaches, so it can stay enabled in production builds. MARKER writes the events into the kernel ftrace buffer, where they interleave with sched and irq events on a common timeline, which is what answers why a cycle overran. This complements the min/max/avg tstats with per-cycle timelines.

ubx_tracefs_open gives code access to tracefs with any backend, which is what latency_break_ns uses. CI now builds with TRACING=SDT.

rtlog: rebuilt on a lock-free broadcast buffer

The real-time logger was reimplemented on top of the new liblfb, a header-only lock-free broadcast buffer (one producer, any number of independent consumers) that generalises what rtlog used to hand-roll. The shm writer spinlock is gone. Writers first used a process-shared, robust priority-inheritance mutex, and now use the new lfbm multi-producer mode: a writer claims a slot with fetch_add plus CAS and moves on to the next one if it is occupied, so logging threads never sleep on each other, and a writer dying mid-write can't block anyone. Reader-side memory ordering on weakly ordered architectures is fixed too.

struct ubx_log_msg changed accordingly (ABI change): ts is now an int64_t nanosecond timestamp and level an int32_t, giving an identical, fixed-width layout on 32 and 64 bit targets, and the struct is exactly three cache lines, so log frames never straddle one. UBX_LOG_MSG_MAXLEN shrank from 127 to 107 and became a CMake cache variable. Mixed-version processes must not share a log shm.

ubx-launch: proper option parsing

ubx-launch was ported to optparse: all options gained GNU style long forms (the legacy single-dash long options still work but warn), and -l is now short for --loglevel. New -e/--empty launches an empty node (with stdtypes imported), useful together with --dbus to load the actual model later via ubx-dbus --load-usc. --dma-latency holds a /dev/cpu_dma_latency request for the node's lifetime to keep CPUs out of deep idle states, and --validate now reports the validation result in its exit status. Only one running node per name is allowed now, as the name appears in shm and D-Bus names.

ubx-log: syslog forwarding and daemon mode

ubx-log gained two new options: -s tees log messages to syslog (selectable facility via -f LOCAL0..7), and -d daemonizes via libdaemon with a PID file under /run to prevent duplicate instances. Daemon support is now an explicit build option (UBX_LOG_DAEMON). -F disables following, so ubx-log -F dumps the current buffer and exits.

improved enum, struct and union support

Anonymous structs and unions are now handled correctly by cdata.tolua. Named structs and unions gained a custom converter registration mechanism, and enums are properly reflected, with new test coverage throughout.

register (struct) types from Lua

New ubx.type_add(nd, name, cdecl [, doc]) registers a struct type at runtime: no build-time ubx-typegen step or separate C type module needed. It does the ffi.cdef + ffi.sizeof + persistent copy + ubx_type_register in one call, and ubx.type_rm(nd, name) unregisters and frees one it created:

ubx.type_add(nd, "struct point", "struct point { double x; double y; };")
local d = ubx.data_alloc(nd, "struct point")   -- usable like any other type

The registered type is a real, fully-formed ubx_type_t: allocatable, marshallable to/from Lua tables, and visible to tooling. It is node-local (the hash is name-based), meant for self-contained nodes, not for data crossing a process boundary. This lets a luablock expose a genuine typed config instead of smuggling structured configuration through lua_str. See docs/dev/005. ubx-modinfo show prints the struct definition of such types too.

docs: Sphinx out, markdown in

The Sphinx/readthedocs manual is gone, and with it the BUILD_DOCS cmake option. Documentation now lives next to the code as markdown: a rewritten README.md (with a new logo and a navigation row), the usc reference and the block reference, which is also where block development is described now. The old RTD site redirects there.

Casualties of the cleanup: the tutorial and its examples/platform are removed, and the FAQ is reduced to the one question that actually keeps coming up -- how to run with real-time priorities, which the docs now answer with ambient capabilities rather than setcap. ubx-genblock is gone too: generating autotools boilerplate wasn't worth maintaining, so there is now an out-of-tree block example to copy instead, which builds with CMake against the ubx0 pkg-config module and is built and run in CI.

lsdb-intf and ubx-dbus: disconnect, hardening, event loop

The D-Bus interface gained Disconnect (ubx-dbus -d), mirroring ubx.disconnect. Connecting from a second Lua state (ubx-dbus -x) used to fail with failed to create block i_00000001, because iblock names came from a per-state counter; existing names are now skipped.

A hardening pass, mostly found by poking a running node: PropertiesChanged is emitted for all changes, ClearNode stops all triggers before removing anything, port clones and their iblocks are cleaned up with their block, operations on lsdb-intf itself are rejected, and SwitchState/Trigger failures are reported instead of swallowed.

A threaded luablock now gets a Lua global stop_fd, an eventfd written on stop, so a step blocking in an event loop can return. lsdb-intf uses it to run the bus without timeout until stopped: an idle node no longer wakes up three times per second, and a D-Bus call is no longer delayed by up to 100 ms. lsdb-intf now requires thread=1 and lsdbus 7f60472 or newer.

Lua API: fail instead of crash

A batch of robustness fixes in the Lua bindings, all of the "this should have been an error, not a segfault or a silent wrong result" kind:

  • port read/write in the wrong direction raises an error instead of crashing the node
  • data_set rejects strings for non-char types, and connect rejects a non-iblock where an iblock is expected
  • block_unload disconnects the block's iblocks from all ports and removes it from trigger chains
  • log messages are no longer passed as format strings (a % in a message was enough to break logging), and connect no longer modifies the caller's ibconfig table
  • rtlog marks truncated messages with a trailing ~

ubx.lua is now fully documented with ldoc; the API reference is built by the CMake doc target. Tests were reorganised into suites with a single runner, CI moved to Debian trixie, and the lock-free code is stress-tested under ThreadSanitizer.

hot path layout and atomics

ubx_block_t and ubx_port_t now put the fields used on every step, read and write first, and both are allocated cache line aligned, so a step or port access touches a single line. This is an ABI change: rebuild all modules.

Further work in the same direction: ubx/lfrb rounds its internal queue capacity up to a power of 2 for cheaper indexing (the capacity users see is unchanged), liblfq inlines its atomics on aarch64 and skips the exchange when the mailbox is empty, vstore aligns its store and caches the type size, and libubx binds calls to its own functions at link time (-Bsymbolic-functions), so interposing them, e.g. via LD_PRELOAD, no longer affects calls from within libubx.

build: switched to CMake

The build system was migrated from make to CMake, reducing boilerplate and improving IDE and cross-compilation support. --version now reports the compile-time options a binary was built with (time source, tracing backend, log message length, ...), and a tidy target runs clang-tidy with the CERT checks.

various bug fixes

Several minor fixes across ubx.lua, blockdiagram, node cleanup, module reloading, and timing utilities. Notably, blockdiagram re-resolves block references after merging a system, so an overlay can now add connections into the base model instead of having them rejected as unknown blocks. Also worth naming: registering a type wrote to the module's static type, so two nodes sharing a module in one process corrupted each other's type hash (each node now keeps its own copy), and ubx-log mis-coloured invalid log levels. On the Lua side, block_create only applied the configs that exist after cloning, so a config added by a preinit hook was rejected as unknown, and the model loader indexed any value looking for a umf object, which failed on 64 bit cdata such as 1ULL. Two more: removing a node closed the rtlog log segment for all other nodes of the process, whose next log call segfaulted, and ubx.port_read_timed ended its timeout at the next full second, so it waited anywhere between 0 and 1 s and returned without reading at all for a fractional timeout.