Device drivers
A plugin is a driver. It is the only place vendor vocabulary is allowed: it emits fully normalised canonical state and accepts canonical commands, encoding them to the vendor wire itself. No framework, API or frontend code parses a vendor key or coerces a wire value (constraints). A driver that leaves a conversion to the framework does not work, because the framework has no code that would perform it.
This page is the architecture view of the driver contract. The vocabulary a driver targets is in device-model.md; the step-by-step guide is development/plugin-authoring.md.
Three responsibilities
| Path | Direction | What the driver supplies |
|---|---|---|
| State | vendor payload to canonical state | a parser that emits a canonical device record |
| Command | canonical command to vendor wire | a translator behind the typed command overload |
| Availability | what this instance exposes | a capability availability descriptor |
The state path
The device event sink exposes two state methods:
// Raw path: the fallback for a message the driver cannot type.
Task DeviceStateChangedAsync(string deviceSourceId, string stateJson, CancellationToken ct);
// Driver path: a normalised canonical graph plus the opaque raw payload, retained verbatim.
Task DeviceStateChangedAsync(string deviceSourceId, CanonicalDevice state, string? rawVendorPayload, CancellationToken ct);
The canonical overload is a default-interface method, so every existing sink keeps compiling. Pass the whole original vendor message as the raw payload: it feeds the unmapped-property hatch, telemetry and forensics, and it is never parsed above the source boundary. The host keeps it only when it is a JSON document (at most 24 levels deep, with no NUL or lone-surrogate escape); any other payload, such as a SOAP XML body, is discarded and the canonical state still applies. On the raw overload the state itself must be such a document, or the update is skipped.
A parser returns nothing for a message it cannot type, and the driver falls back to the raw overload. Never drop a message. Raw state lands with no canonical value, so nothing typed reads it.
The sink also carries discovery (DeviceDiscoveredAsync with a typed discovery record), removal
(DeviceRemovedAsync), availability, descriptor changes (DeviceCapabilitiesChangedAsync) and
momentary events (DeviceEventOccurredAsync, with an optional raw payload and observed-at instant).
A removal of a device's last source that a utility meter reads from does not delete the device: the host keeps it,
marks the source offline and raises an alert for the user, and the call returns normally. Reporting the source again
brings the kept device back online.
A WASM driver's state is the canonical record it names
A WASM driver has one state import, device-emit-state, and its document is the canonical record
itself, in the canonical wire form and named by its type:
{"type":"Switch","channels":[{"index":1,"isOn":true}]}
The host reads it with the reader that reads stored typed state and passes it to the sink's canonical
overload. A document with no type, or whose type is not a canonical device type, stays raw state;
one that names a canonical type but is not that type's record, or names Unknown, is refused with
invalid_request. The host does not compare the record's type with the announced device kind. A WASM
driver passes no vendor payload beside the record, so its source keeps no raw payload. A channel is
addressed by its canonical key (switch.channels[1].isOn); a document keyed switch.isOn names a key
no catalogue holds and lands as raw state.
The WIT already says the document is canonical state with the host as its schema authority, so a WASM driver needs nothing beyond that one import. The host does not project raw state through the announced descriptor, because that would be the framework-side projector the driver rule rules out.
The four parts of a driver
- A discovery registry: a concurrent map from whatever id the state event carries to the whole typed discovery record, populated at discovery and pruned on the vendor's device-removed event. The whole record is stored, because it carries the per-capability vendor keys the parser needs.
- A state parser: discovery record plus payload to a canonical record, or nothing. It is key-agnostic: it reads each vendor key off the discovery record and never hardcodes a wire key, so discovery and state cannot drift apart.
- A routing method: a registry hit and a non-null parse go to the typed sink with the raw payload retained; a registry miss or a null parse goes to the raw path.
- A command encoder: canonical command to vendor wire.
Factor any vendor-label matching into one helper shared by discovery and state, so the two paths
cannot disagree. Prefer discriminating substrings for suffixed or parenthesised labels and exact
whole-word matches for single-word labels, and order overlapping substrings longest-first: a
particulate label of PM1 is a prefix of PM10.
Device state lives in the host, never in plugin memory, and a long-lived connection is opened only under a connection-ownership lease (constraints).
The command path
IInputPlugin carries two command methods and an opt-in flag:
// Raw-property writes: the property map, untranslated.
Task SendDeviceCommandAsync(string deviceSourceId, string commandName, string payloadJson, CancellationToken ct);
// Canonical intent, translated to the vendor wire by the driver.
Task SendDeviceCommandAsync(string deviceSourceId, DeviceCommand command, CancellationToken ct);
bool SupportsTypedCommands => false;
The typed overload and the flag are default-interface members: the overload throws
NotSupportedException and the flag is false, so a plugin that does not take canonical commands still
loads. A driver opts in by overriding both. The framework dispatches canonical intent to the typed
overload only when the flag is true; for a plugin that has not opted in, the canonical endpoint answers
422 rather than falling back.
A DeviceCommand carries a device type plus an ordered list of capability assignments. Each
assignment is flat and discriminated by capability kind, with nullable value members for the bool,
token, number, text and colour cases. It carries canonical keys, tokens and units only; a vendor wire
value never appears in it. Every bool to "ON", canonical token to vendor token, unit conversion and
key remapping happens inside the plugin.
The string overload receives raw-property writes: the command name is the single property key, or
composite for several, and the payload is the property map serialised as-is. The framework performs
no coercion and no canonical mapping on it.
Command validation, idempotency and error classes
What the host checks before a command reaches the driver, and how it answers.
Validation
- Against the commanded source. A command is validated against the descriptor of the source being commanded, never the active source's, and against the device type's catalog. A source-targeted command does no failover.
- Channel members are not catalog keys. Only the channel-list key is, so a member is validated against the base capability plus the device's channel set.
- Catalog numeric bounds are authoritative. Non-finite numbers are rejected early, because they slip past every comparison and later throw a raw serializer message. A numeric string from a widget is accepted.
- Text is guarded. Free-form
Text,OpenEnumand everyTokenSettoken are refused when they hold NUL or control characters (jsonb cannot store NUL) and are capped in count and length, since each is persisted verbatim. An emptyTokenSetarray is valid and means "the whole home". - Raw properties are bounded. The raw-property hatch applies no coercion, caps the map and string sizes, rejects NUL recursively, and accepts only keys that are controllable capabilities of the target (the logical device's capability rows, or the source's own list for a source-targeted write) or unmapped properties the target's state declares writable (the active source's, or the targeted source's); an undeclared or read-only key is refused. The caller's device control, time windows and token scope apply, and the write is audited.
- Alias spellings of canonical tokens are rewritten to the canonical token before validation.
Idempotency
With an Idempotency-Key header, the command-log id is a deterministic, UUIDv5-style derivation scoped
by device, principal and (when named) target physical device. Two replicas handling a retry compute
the same primary key and the database collapses the race; a read-before-insert fast path exists, and a
collision surfaces the winner, so nothing is dispatched twice. Without a key every request inserts its
own row. A replay answers what the original did, except that a replayed Failed row re-runs the live
refusal checks, because it may have been a refusal.
Error classes
| Answer | When |
|---|---|
200 |
The plugin accepted the command |
400 |
A refused command (the problem's errorCode names the failed target); no active source (a scene reports the device offline); the plugin is not running |
403 / 404 |
Access denied; an unknown or invisible device |
422 |
The plugin has not opted in to typed commands |
502 |
The plugin reported the command Failed; the problem carries device.command.failed and commandLogId, so a client tells it from a proxy's bare 502 and never reads it as success |
504 |
The adapter deadline passed (a timeout, or an HttpClient cancellation while the caller's token is still live). The command log is marked TimedOut first, as outcome unknown, so it never shows as pending |
500 |
Any other infrastructure fault propagates, so a real server problem is never masked |
A serialization failure or deadlock (SQLSTATE 40001/40P01) raised while recording a dispatched command
is a dispatch failure, not an infrastructure fault: the row is completed Failed with the error text.
The classification goes through DatabaseContention.IsSerializationFailureOrDeadlock
(constraints), so
it is the same whether the provider wraps the fault in InvalidOperationException or raises
DbUpdateConcurrencyException; every other DbUpdateException, cancellation, timeout and
out-of-memory still propagates. When the deadlock hits the write that marks the command Accepted, the
plugin has already sent it, so history can show Failed for a command the device carried out; the
next state report shows the real state, and a client that repeats a non-idempotent command such as a
toggle can run it twice.
For a PTZ command the quiet window is written before the plugin call, so the camera cannot move before the window exists; a failed window write does not stop the move.
The authoring helper
Reeve.PluginAuthoring is a published package of reusable coercions, so a driver stays thin in
practice while the framework stays translation-free. It references only Reeve.Contracts, so it is
legal for a plugin to reference. It is a convenience, not a trust or enforcement boundary: nothing
forces its use, and referencing it grants no capability. A driver may re-implement the few coercions
it needs instead.
| Primitive | Role |
|---|---|
VendorPayload |
Read-only view over a parsed vendor message: pull a value by vendor key and run it through a map or converter. |
ToggleMap |
Vendor on/off to canonical bool. Recognises ON/OFF, true/false, 1/0, yes/no, open/close, JSON booleans and numbers. |
ValueMap / EnumTokenMap |
Vendor token to canonical token. Construction rejects a non-canonical target, so a vendor string cannot escape as a canonical value. |
UnitConverters |
Pure converters into canonical units: mireds to kelvin, vendor brightness to percent, Fahrenheit to Celsius, energy and power scaling, range clamping. |
CanonicalDeviceBuilder |
Fluent construction of the typed records, always a real record and never a dictionary: Light, Outlet, Climate, MediaPlayer and Sensor. |
DeviceCommandReader |
Resolve a command value by canonical key, optionally translating it to the wire in one call. |
WireMap |
The outbound mirror: canonical value to vendor wire value. It validates the canonical input side at construction; vendor strings are the declared outputs. |
CanonicalAvailability |
Builds the availability descriptor against the generated catalog. |
Numeric command translation reuses the inverse converters rather than re-deriving the maths.
What only the driver does
Everything that turns vendor data into canonical data, or back, lives in the driver and nowhere else:
- truthiness and every other value coercion (
"ON",1,"open"totrue); - resolving which vendor key carries which capability, at discovery and at state time;
- mapping
booland canonical tokens to the vendor's command values; - unit conversion in both directions;
- building the per-instance descriptor from what the vendor advertises.
The host stores what the driver emits and validates what a caller sends against the canonical catalog and the descriptor. It holds no projector from vendor payloads to typed devices and no per-vendor branch; adding a vendor requires no change outside the plugin.
Rules the helper enforces, and the ones it cannot
The value rules are in constraints. In addition:
- A canonical value with no declared wire form throws, rather than being guessed or passed through; silent fallbacks hide real gaps. Tokens a device cannot accept are left unmapped.
- Vendor payloads are not in canonical units. Voltage arrives in millivolts, temperature in centi-degrees, energy in the vendor's own scale. The driver converts, the descriptor declares the unit, and no client converts.
- Never derive a declared capability from a field's presence in the response schema. A vendor's
protocol response often carries fields the specific unit does not implement, returning empty or
false rather than an error. A source that cannot observe a capability reports it as unknown, never
as false:
falsefor a privacy shutter asserts the camera lacks the hardware. - An unrecognised token from the wire is dropped, not passed through. The canonical enum is closed, and an invented token pollutes the time series.
- Never fabricate a capability. A device or entity the driver cannot classify yields the unknown discovery record. A default that maps any unrecognised binary class onto a plausible-looking capability is worse than no capability.
- Never force controllability true. It flows from the vendor's own access or configuration signal.
- Occupancy, presence and motion are three slots. A driver does not collapse them.
- An enum is converted whole or not at all. A vendor enum is convertible only when its entire emittable token set maps onto the canonical set. Handle one normalising value and the whole owning type as a unit.
- The payload reader treats a JSON string as absent for a numeric read. A transport that publishes stringly-typed numbers normalises them to JSON numbers before the parser runs.
- A driver never declares the critical flag or per-channel operator names; the host overlays them (device-model.md).
Declaring availability
The descriptor is built against the generated catalog, which supplies the kind, label and canonical unit. The plugin contributes only the per-instance facts: presence, controllability and instance narrowing. The builder fails loudly at declaration time on an unknown key, a kind mismatch, an enum token outside the catalog set or a duplicate key, so a driver cannot declare a non-canonical key or token.
Produce the instance's allowed token set by mapping the device's advertised vendor set through the same vendor-to-canonical maps the state path uses: one tested coercion per enum, shared by both directions.
For a static capability set the framework builds the descriptor itself, once at discovery, through one mapper over the typed discovery record: presence follows from the discovery slot being non-null, and controllability from that discovered feature's own controllable flag. There is no opt-in switch and no attribute; an accurate discovery record is the whole contract. Push an explicit descriptor only when availability changes at runtime, and push the whole descriptor, because the stored snapshot is replaced wholesale.
A capability whose options are vendor-defined per device (a light's effect list, a fan's preset modes)
is declared as an OpenEnum whose suggested options ride the instance's allowed-token list; a set of
such tokens is a TokenSet.
Adding a capability to the canonical model
Adding one is a mechanical four-layer wiring, and a missing layer is a silent hole:
- the member on the canonical record, as an init-only property;
- the matching optional feature slot on the typed discovery record in the SDK;
- the descriptor-builder arm and the canonical-state snapshot arm in the framework's discovery mapper;
- the resolver arm that reads the value back out of canonical state.
Then regenerate both artefacts (code generation).
Canonical model code generation
The typed records in Reeve.Contracts are the single source of truth for the device model. The
backend capability catalog (CanonicalCapabilityCatalog.g.cs) and the frontend mirror
(frontend/src/contracts/generated/canonicalDevices.ts) are generated from them by backend/contracts-codegen
and committed.
- Reflection over the built contracts assembly, not Roslyn, so attribute values and allowed-token sets are type-safe. Output is deterministic: device types in enum order, members in constructor order.
- Init-only properties are capabilities. Widening a primary constructor breaks the ABI of already-built plugins, so a new canonical member is an init-only property, and the generator treats it as a capability.
- Loud failure. The generator fails on an unmappable member (a plain string would ship as opaque text through catalog, storage ordinal and both TypeScript twins), on a resting token the member does not allow, on a missing sibling, on a non-numeric power leaf, and on a command rule on a nested member.
- The TypeScript emitter mirrors the real JSON form: a type-level string-enum converter yields a string enum; otherwise the numeric ordinal is emitted.
- Never hand-edit either generated file. Regenerate with
dotnet run --project backend/contracts-codegen -- generateand commit both.
The contracts-codegen CI job runs dotnet run --project backend/contracts-codegen -- check and fails when the
committed catalog or the frontend mirror drifts from the model.
Unmapped properties
Vendor-specific fields go on the record's unmapped-property list, the one place in the canonical contract that carries a vendor key and a raw value. Writes arrive through the raw-property endpoint:
POST /api/devices/{id}/raw-properties
Content-Type: application/json
{ "properties": { "<vendorKey>": <jsonValue> } }
The framework forwards the keys and values to the plugin's string command overload untranslated; the driver receives exactly what the caller sent. If a property is a real, reusable device capability, add it to the canonical model instead (constraints).
Re-description and channel identity
A plugin may re-read a source's current model through RedescribeDeviceAsync, and opts in by
overriding SupportsRedescribe to true. It is a replica-level call: a replica that does not hold the
source's connection lease returns NotOwner, so the host can ask the owner. A plugin never returns
Unreachable for a peer-owned connection; a plugin without a per-source lease never returns
NotOwner, and a non-clustered host reads NotOwner as Unreachable. Returned descriptors follow
the ordinary discovery validation and application path, and the result runs through the model change
pipeline (device-model.md).
Channel declarations carry a stable opaque SourceId assigned by the plugin and a host-facing channel
number. The number is the canonical channel address; SourceId lets the host match the same physical
channel when declarations reorder or change. SourceChannelReplacement maps a prior source and
channel identity to its replacement during re-description, so references survive without treating
channel numbers as identities. The numbering rules are in
constraints.
Source removal notices
A plugin whose sources stand for something outside Reeve (a node on a Matter fabric) implements the
optional IDeviceSourceRemovalHandler:
OnSourcesRemovedAsync(DeviceSourcesRemovedNotice, ct)is called after an operator's removal commits, with the removed source ids, the ids the instance still has (read after the commit) and the acting user. The host groups removed sources by plugin instance and calls once per instance, off the request, on the replica that served theDELETE, bounded to 30 seconds and logged. The call never fails or delays theDELETEand is never retried.DescribeSourceRemoval(sourceId)is the text the removal dialog shows. Both dialogs fetch it when they open (GET /api/logical-devices/{id}/removal-notices,GET /api/devices/sources/{sourceId}/removal-notices), asking each source once, concurrently, with a 2-second bound each, and show one notice per plugin. It may run concurrently on pool threads, so it reads local state only, never blocks and never throws. It is not part of any device DTO, because the realtime broadcast and merge paths produce the same DTO and every detail read would pay a plugin call per source.- A removal the plugin itself reported through
IDeviceEventSink.DeviceRemovedAsyncis not announced. A replica that crashes between the commit and the call, an unreachable adapter or a timeout leave the plugin untold; the source is already gone in Reeve, and the plugin decides what a retry means. Treat the notice as idempotent. WASM plugins never receive it.
Reporting problems to the operator
A plugin raises an issue through IPluginIssueRegistry with a stable code and a severity,
optionally with a rendered fix hint, a guided repair flow and a subject, and clears it when the
condition resolves. The host surfaces issues as alerts. Health checks and audit records answer "is the
system up" and "who did what"; neither is where an operator looks to find "this bridge needs
re-authorising".
- Raising is idempotent per plugin instance, code and optional subject: a second raise updates the open alert in place.
- Clearing a code that has no open issue is a no-op, so a plugin never needs to check first. An operator's snooze or silence outlives the clear, so a later raise of the same code is suppressed as before.
- Metadata is capped at 32 KB and the fix-hint Markdown is sanitised by the host. Metadata is visible to any administrator and to the database; never put secrets in it.
- A subject on a code the core maps is refused with
ArgumentException.
Reaching another plugin's devices
A plugin always has full access to the devices it owns. Access to any other plugin's devices requires both a permission (read or control) and a device-type scope. An in-memory ownership index maps a source's external id to its owning plugin instance; it is seeded from the database at start and maintained on discover and remove.
An absent or empty device-type list means all types. An operator narrowing a specific requested set down to nothing means deny every other plugin's devices. The two are never conflated, and the empty-narrowing case fails closed.
Host services a driver may need
| Facility | Contract |
|---|---|
| Connection ownership | A plugin holding a long-lived per-device connection takes a connection-ownership lease before connecting, or every replica opens its own socket to the same device. The lease goes through the cluster at every replica count, so a single node's acquire answers null whenever the replica is not serving. A null lease means "not now", never "never": a peer owns the resource, or this replica is not serving (starting, fenced or draining). An exception from TryAcquireAsync is transient as well, because the mutex lets a database error propagate. Retry on a bounded interval, and again after Lost fires or the connection is evicted. Observe the lease's Lost token (or poll IsStillOwnedAsync) and close the connection when it ends; a drain also fires Lost, and the lease stays held until the plugin disposes it. |
| Guarded HTTP client | Egress passes a request-forgery guard (network egress). Per-host certificate pinning by thumbprint is available for LAN devices that serve HTTPS under a private root; a pinned host accepts only the pinned leaf, and an un-pinned host keeps system validation. |
| Object storage | A namespaced blob store scoped per plugin type, so deleting and re-adding an instance keeps its data (data.md). |
| Discovery helpers | A dependency-free SSDP search helper and a UPnP event-notification parser. mDNS is not bundled, because it would push a third-party dependency onto every plugin transitively; a plugin that needs mDNS references a library itself. |
| Integration transport | Strictly opt-in on the host-services surface, like the guarded HTTP client. Every plugin must be able to run without one. |
Locality-aware plugin APIs are added as default-implemented members on an existing facade, never as a new positional record parameter (binary-incompatible with every plugin built against the old constructor) and never as a new sub-facade interface, because each facade binds one permission code and a pure query would then force a manifest change and fresh operator consent.
Packaging
| Package | Gives the author |
|---|---|
Reeve.Contracts |
The canonical device model: the typed records, the capability-kind enum, the token classes, the unit tokens, the metadata attributes, the canonical command, the availability descriptor and the generated capability catalog. |
Reeve.PluginAbstractions |
The plugin SDK: the plugin, registration and factory interfaces, the typed state and command overloads, host services and the discovery records. It references only Reeve.Contracts and carries no third-party dependencies. |
Reeve.PluginAuthoring |
The optional authoring helper. |
All three are published NuGet packages; a plugin compiles against a released version (plugins.md).
Checklist for a new driver
- Every supported vendor message is parsed to a canonical record and pushed through the typed sink with the whole original message as the raw payload; untypeable messages fall back to the raw overload.
SupportsTypedCommandsis true and the typed overload translates canonical intent to the vendor wire. No framework coercion is relied upon.- Every device exposes an accurate availability descriptor: presence, controllability, instance-narrowed tokens, numeric bounds and unit.
- Every number is in its declared canonical unit, and every enum value is a canonical token from a catalog-validated map.
- Vendor-specific fields go to unmapped properties, not faked as canonical capabilities.
- The plugin reports a device's real name or none, never a placeholder it later replaces (naming).
- A session plugin reports every device it knows in its snapshot on connect (device-model.md).
- Vendor wire-translation tests drive the real mapper end to end. Hand-baked payload fixtures that bypass it turn a green suite into cover for a shipped protocol break.
See also
- device-model.md: the vocabulary and its invariants.
- plugins.md: plugin lanes, loading and distribution.
- integrations.md: sidecars, the session plane and protocol-level traps.
- development/plugin-authoring.md: the authoring guide, lifecycle, configuration and discovery matchers.
- development/plugin-testkit.md: testing a driver.