# device-daemon-core
Reusable async daemon and MQTT infrastructure for the device projects. The crate provides:
- a daemon runner for connect, poll, and publish, graceful shutdown, optional
command handling, and bounded exponential reconnect backoff;
- `ConsoleOutput` and `MqttOutput` with JSON or flattened individual values;
- common MQTT YAML settings, environment overrides, retained availability,
retained state envelopes, and optional retained-command filtering.
- an explicit Modbus RTU minimum inter-frame delay calculation.
Device-specific protocol clients, state shapes, command parsing, output defaults,
and connection recovery decisions remain with each application. No device
project depends on this crate yet.
## Runner contract
Implement `Device<Command>` for an adapter around the device client. Its
`connect` and `poll` errors are treated as hardware failures and cause a
reconnect. `handle_command` parses the MQTT message for that device and returns
`CommandEffect` to continue polling, poll immediately, reconnect, or shut down.
Malformed or rejected commands should be logged/acknowledged by that adapter
without returning a transport failure.
`Output<Snapshot>` handles telemetry and device availability. The runner treats
output errors as transient: it logs them and continues device polling. The
application is responsible for selecting the existing output defaults and
setting a project-specific command filter, if any.
See [`examples/mock_device.rs`](examples/mock_device.rs) for a complete
console-based adapter. An MQTT application uses `MqttConfig::load`,
`MqttOutput::new`, and passes `output.take_control_receiver()` to `run`.
For console operation, construct `ConsoleOutput::new(OutputFormat::Json)` or
`ConsoleOutput::new(OutputFormat::Individual)`. The MQTT configuration includes
`allow_control`, which defaults to `false`; control subscriptions and retained
command delivery remain disabled unless it is explicitly enabled.
## Common MQTT configuration
```yaml
host: localhost
port: 1883
tls: false
# username: mqtt-user
# password: mqtt-password
topic: device-name
client_id: device-name-daemon
qos: 0
keep_alive: 30s
allow_control: false
```
Shared environment overrides are `MQTT_HOST`, `MQTT_PORT`, `MQTT_TLS`,
`MQTT_USERNAME`, `MQTT_PASSWORD`, `MQTT_TOPIC`, `MQTT_CLIENT_ID`, `MQTT_QOS`,
`MQTT_KEEP_ALIVE`, and `MQTT_ALLOW_CONTROL`. `MQTT_KEEP_ALIVE` accepts
human-readable durations; `MQTT_KEEP_ALIVE_SECS` remains supported as a
seconds-only compatibility override. The YAML key `keep_alive_secs` is also
accepted as a legacy alias.
The retained state topic is `<topic>/state`, with the device name, Unix
millisecond timestamp, and device-specific `values`. Availability is published
on `<topic>/availability` and `<topic>/device/availability`; the broker Last
Will marks the daemon offline if its connection is lost. MQTT reconnect
attempts use bounded exponential backoff with equal jitter: the actual delay
is randomly selected from the upper half of the current 1-to-30-second ceiling.
`minimum_modbus_rtu_delay(baud_rate)` computes the minimum silence between RTU
frames, including the fixed 1.75 ms minimum above 19,200 baud. It is
intentionally not a generic serial-delay function; other protocols have
different timing rules.
## Optional serial scanning
Enable the orchestration API with the `serial-scan` feature. A device adapter
provides a `ScanProfile` containing only parameter combinations supported by
that model, plus its preferred defaults, allowed addresses, timeouts, and
inter-probe delay. The scanner tries the default serial settings first, then
the other listed combinations. For each combination it tries the optional
default address, an explicitly configured optional broadcast address, then
the listed addresses, removing duplicates.
The adapter implements `SerialProbe`: it configures the serial port and probes
the device using a protocol-specific, read-only request. Expected no-response
or protocol-mismatch outcomes are returned as `Ok(None)`; unexpected failures
remain errors instead of being silently treated as a missing device. A
broadcast address is never assumed or generated by the core.
Scanning is possible when a device is alone on the bus if the adapter can
identify it reliably using the selected settings and request. Being alone
avoids collisions with other responders, but does not make unsupported baud
rates valid or guarantee that every protocol responds to broadcast. The
adapter must list supported combinations and know which addresses can safely
be queried. This module orders and bounds those probes; it does not open a
serial port or implement any device protocol.
```toml
[dependencies]
device-daemon-core = { version = "0.1", features = ["serial-scan"] }
```