This file explains how flua works under the hood. The user guide is USAGE.md; this is the machinery. Diagrams are ASCII so they render everywhere (GitHub, VS Code, terminal).
Deeper dives, kept out of this file on purpose:
flua runs real Fibaro QuickApps offline. One Python process hosts a lupa runtime (Lua 5.x) and an asyncio event loop:
QuickApp classes, fibaro, api, net,
mqtt, timers. Each QA runs in its own Lua environment (isolated globals). +---------------------------- flua process ----------------------------+
| |
QA files ----> | CLI (argparse, --%% parsing, mode peek) |
| | |
| v |
| LuaEngine -------------------------------------------------- |
| | lupa LuaRuntime | virtual clock | api (sim/HC3) | |
| | inbound deque | TimerManager | qa_* worker pools | |
| | outbound queue | env chain | Hc3Remote (online)| |
| | pump task (THE single Lua entry point) | |
| +-----------------------------------------------------------+ |
| ^ post(msg) | enqueue_outbound(msg) |
| | v |
| Lua QAs (per-QA envs) worker threads |
| quickapp/fibaro/net/mqtt urllib / sockets / RFC6455 / MQTT 3.1.1
| |
+-----------------------------------------------------------------------+
The one rule everything else follows: the pump is the only code that enters the Lua VM, and it never does so while Lua is on the stack.
_PY.* bridges,
which append plain messages to the inbound deque and return immediately.
No Python handler ever calls Lua directly._FLUA.dispatch.The two deliberate exceptions, both documented:
_PY.log) — writing to stdout touches no
Lua state, so it is safe at any call depth, including inside
debugger-stepped code where the pump is frozen. Lua code Python engine Lua runtime
--------- -------------- ------------
_PY.post({type=...}) inbound deque
-----------------------> |
v pump loop:
| tick(clock)
| timers.fire_due()
| drain inbound -> handler
| (api, timers, worker spawn)
| outbound.get() -> batch
|----------------------> _FLUA.dispatch(batch)
| handlers[msg.type](msg)
| (timer fires, callbacks,
| QA bootstrap, ...)
Every message is a dict with a mandatory string type. Functions never
cross the bridge — callbacks are registered Lua-side by integer id. The
full type list lives in src/flua/messages.py; adding one means a handler
in engine.py (inbound) and/or lua/init.lua (outbound).
src/flua/
cli.py argument parsing, --%% config assembly, mode peek (--%%offline),
--run-for / --watch / --check / export / unpack
engine.py LuaEngine: lupa VM, queues, pump, QA lifecycle, worker pools,
the HC3 poller, the auth-lockout guard
api/ the REST surface: one dispatcher, two backends
__init__.py Api.dispatch: regex route table -> handlers -> hybrid forward
(variables on HC3-namespace ids and on PROXY devices route
via the FluaHelper bridge — the controller owns the state)
state.py SimState: devices/rooms/scenes/globals, change & event feeds
routes/*.py pure handlers: (state, request) -> (data, status)
hc3.py Hc3Remote: blocking urllib client, basic auth, raw-body import
http.py urllib-based blocking HTTP (worker threads)
websocket.py minimal RFC 6455 client (stdlib sockets + ssl)
mqtt.py minimal MQTT 3.1.1 client (stdlib sockets + ssl)
sync_socket.py blocking LuaSocket-compatible TCP/UDP (the debugger's sockets)
devices/ the HC3 device catalog (176 real captures) + skeleton builder
config.py --%% annotation parsing, EOH, the offline peek, env helpers
environment.py the os.getenv chain: process env > local .env > ~/.env
timers.py TimerManager on the virtual clock (per-QA attribution)
clock.py VirtualClock: realtime / accelerated / instant, start time
messages.py message type constants + builders
bindings.py the _PY table (post, log, api, api_hc3, net/mqtt entry points)
lua/init.lua the Lua runtime: sanitizer, log, timers, dispatch, QA bootstrap
lua/quickapp.lua the QuickApp/QuickAppBase/QuickAppChild classes
lua/fibaro.lua the fibaro API (HC3-compatible)
lua/net.lua HTTPClient, TCPSocket, UDPSocket, WebSocketClient(+Tls)
lua/mqtt.lua mqtt.Client, mqtt.QoS, the documented event API
lua/init.lua)_PY.post payload passes through a UTF-8 sanitizer:
invalid bytes are hex-escaped, so binary strings (like utf8.charpattern)
cross lupa's strict decode without killing the process. Log lines go
through the same sanitizer before _PY.log._FLUA (qaId/config/arg)
whose metatable falls through to the shared engine table; runtime libs
are loaded into the QA's env before its code. require and dofile are
rebound per QA so loaded files run in the QA's env (_FLUA.loadFile is
the chunk-returning form); raw load/loadfile still compile against
the shared _G.startQaInEnv is the shared QA boot: merge .flua.lua,
evaluate --%%var expressions (load("return "..expr, nil, "t", {config, os})),
load extra files, pcall the chunk, construct the QuickApp instance.handlers.* deliver timers, actions, net/mqtt results,
refreshStates events, QA restarts, and -e preambles.api/)One dispatcher, three outcomes:
api.get(path) -> Api.dispatch
|-- /quickApp/* engine-backed QA file management (local only)
|-- route table pure handlers over SimState -> (data, status)
| |-- resource reads (online) -> the HC3 answers; handlers merge
| | the emu's local resources (emulated QAs, scene QAs) in
| |-- matched 404 + online + entity id < 5000 -> forward to the HC3
| '-- matched 404 + flua id (>= 5000) -> local 404, never forward
'-- no route + online -> forward to the HC3
fibaro.getValue(self.id, ...) work in both modes./devices, /plugins and /scenes lists. Writes stay
in the sim — they never mutate the controller./home, /settings/info and
/settings/location are the controller's real structs merged into the
sim's view — fetched lazily once per run (req.remote_cached, cached on
first access) — with the virtual-clock fields (sun times, date/time,
timestamp) computed on top.--%%offline:true on a QA pins its api.* calls to the sim (the
calling QA's id travels with each request).api.hc3.* forces the remote backend (bypasses hybrid routing;
fibaro.callhc3 uses it). Offline it stands in for the sim.DeviceCreatedEvent / DeviceRemovedEvent
/ DevicePropertyUpdatedEvent / DeviceActionRanEvent with the real
HC3's envelope; updateProperty emits only when the value actually
changes. Configuration edits go to the changes feed instead./flua/embeddedUI — a flua-only route (no HC3 counterpart, always
local): the UI viewer's channel for the device type's default view. The
tables live in devices/uielements.py and resolve watched device
properties (e.g. value) into live label texts/control values per poll.
The elements are deliberately never part of the device structure — the
HC3 UI client renders them itself, so they must not leak into
/devices or the .fqa export./flua/devices — the viewer's device list: the emulated devices
only, with no online union (a controller can carry hundreds of QAs that
the viewer should not render).The full threading model — who may block what, what counts as pending work, and the races that bit us — lives in concurrency.md. This section is the tour version.
All blocking network I/O runs in worker threads; the pump never blocks:
Lua post {httpRequest|tcp*|udp*|ws*|mqtt*}
-> handler spawns an asyncio task
-> asyncio.to_thread(blocking op) on a dedicated pool
-> result -> enqueue_outbound (thread-safe hop: call_soon_threadsafe)
-> pump -> dispatch -> per-QA net/mqtt handlers -> callbacks
In-flight work counts as pending work — the process stays alive until timers, queues, and open connections are all done. The debugger's sockets are the one main-thread exception (see §2).
A QA's api.* calls with a remote backend (online/proxy mode) use the
same worker-thread pattern via the apiCall/apiResult messages: the Lua
side yields a request table, the pump spawns a worker thread running the
hybrid dispatch (serialized against other dispatches by Api's lock — the
sim side is shared state), and the response resumes the QA's coroutine
with (data, status). The QA stays suspended meanwhile — its own messages
defer through the same sleeping/workQueues machinery as
fibaro.sleep — while the pump and every other QA keep running. Offline,
the synchronous _PY.api bridge remains the fast path.
The mirror image is net.*Server (flua extension, server.py): mock
servers hosted on the loop for QA-side testing. The socket is bound
synchronously when the QA calls listen (port 0 resolves at once), and
serving is asyncio-native. Each incoming request posts a serverRequest
message into the pump; the QA handler runs there, and its return value
comes back through the synchronous net_server_reply bridge call (the pump
runs on the loop thread), resolving the connection's future. Servers die
with their QA (exit/restart) and on engine stop.
Timers run on VirtualClock (virtual seconds, epoch-aligned). Modes:
realtime, --speed N accelerated, --instant (timers fire now, time jumps
to each deadline). os.time()/os.date() read the virtual clock (whole
seconds); os.clock() stays the real runtime clock; _FLUA.millitime()
is virtual milliseconds. --start "2027/12/31 23:59:50" sets the origin,
so date logic can be tested at New Year, leap days, DST changes — and the
debugger pause freezes the clock (the freeze is noted around the blocking
receive).
raw file header -> parse_annotations() (--%% directives, EOH header)
--%%include:... -> expand_includes(): the included files' directives
become defaults (QA header wins, files append, nested
includes resolve relative to the including file)
--%%mode:... -> mode decision: --api flag > main QA's mode > online
per-QA config <- CLI flags + globals + locals + .flua.lua base
--%%var:name=expr -> evaluated in Lua with {config, os} in scope
os.getenv(name) -> EnvChain: process env > local .env > ~/.env
The .fqa export/import round-trip reuses the pipeline: unpacked files
carry generated --%% headers, so imports load like any other QA.
--api remote)Hc3Remote (stdlib urllib) speaks basic auth and the raw-body import
transport (POST /quickApp/ with the fqa JSON string — the swagger's
multipart description is misleading; the real transport was verified against a
live HC3). The endpoints' structural reference (paths, parameters, response
codes, schema fields) is docs/specs/hc3-api.json, distilled from the
official swagger, which itself is Fibaro's property and not distributed.
Two safety rules:
/refreshStates and mirrors the real events
into the local buffer, so api.get('/refreshStates?last=N') serves a
merged feed and Lua RefreshStateSubscribers receive them through the
pump.Mode selection: explicit --api > the main QA's --%%offline:true (peeked
before the engine starts) > online if HC3 credentials exist in the env
chain > offline.
QA devices are built from the distilled type schema
(src/flua/devices/type_schemas.json, generated by
scripts/extract_device_schemas.py): typed properties at their declared
defaults, the type's interfaces expanded, and action metadata. The
capture (devices.json — 176 real HC3 device captures, scrubbed of
identity/secrets) is the demoted LAST-RESORT fallback for types the
schema does not know, and the hierarchy resolves unknown types to their
nearest known ancestor. The compat suite (§12) exists to catch exactly
this class of drift.
HC3_TEST=1) —
tests/test_hc3_live.py (lifecycle: read-only + import→call→events→delete,
lockout-safe) and tests/test_hc3_compat.py (shape oracle: the same
request through the sim and the real HC3 must agree on structure).HOME so a developer's real
~/.env can never flip plain tests into online mode. (Online is opt-in
anyway: --%%mode:online or --api remote.)_PY.log), never queue.updateProperty emits an event only when the value changes.HC3_TEST=1.Each of these (plus the identity/routing/event/exit contracts around them) is expanded with its pinning test in invariants.md.