MQTT physical observations
PHOS optionally subscribes to explicitly configured or approved sensor topics on an external MQTT broker. This is observation-only: no commands, PHOS state publishing, or new MCP tools. Direct ESPHome Native API support is a separate optional provider with its own configured-device and mapping workflow; see the ESPHome Native API guide.
Installation and boundaries
Install phos-robot[mqtt] in the PHOS environment. The selected client is
aiomqtt 2.5, an asyncio wrapper
around paho-mqtt supporting Python 3.8+. PHOS itself requires Python 3.10 or
newer; the documented full Raspberry Pi installation baseline and CI use Python
3.11. The MQTT dependency, network connections, and broker are optional. PHOS
supports MQTT 3.1.1 and 5.
The provider owns an asynchronously cancelled task and reconnects and restores
subscriptions with capped exponential backoff and jitter. The client queue holds
at most 128 messages; aiomqtt can discard messages when full and does not expose
the count here, so complete temporal coverage cannot be assumed.
Discovery implementation status
Discovery is optional. A broker may opt into the candidate collector with
discovery: {enabled: true, prefix:
homeassistant}. It subscribes only to sensor, binary sensor and device
configuration topics within that prefix. Candidate records are bounded to 128
per broker. Administrators can inspect the current candidates on the dedicated
Connectivity → MQTT Discovery page or through GET /api/v1/mqtt/discovery/candidates; these
views require the existing administrator session. On that page,
review candidates in the expandable Discovered Sensors table, then use its
row actions to save changes, approve, reject or revoke. Search and status filters
apply without clearing unsaved edits. Save changes stores a process-local review
proposal and does not authorize a source. Approving unsaved changes asks for
confirmation, saves the proposal and checks the same candidate revision before
authorizing it. The table distinguishes approval, activation and device
availability; broker connectivity and freshness are shown in expanded details. For an incomplete candidate, enter the missing information
and save a valid edit before approval. PHOS does not infer missing sensor metadata. The required 120-second freshness value prefilled for a discovered mapping is a
PHOS policy default, not an interval or freshness value reported by the device;
review it in Advanced Settings. No expected update interval or timestamp is
inferred. Approval saves the exact reviewed mapping and revision
in the broker's canonical discovery_approvals configuration. A changed
announcement invalidates an old review; approval also checks that the submitted
mapping still matches the current edit. Repeated approvals are idempotent.
Approvals can be revoked from the same page, including after restart when a
candidate is temporarily absent. Rejections and edits are process-local.
An administrator may delete an unapproved candidate from the same row after a confirmation. Deletion clears PHOS's local candidate, reviewed edit, and local rejection state; it does not publish to MQTT, delete a retained announcement, or change any manual mapping. An approved candidate must be revoked first, so the existing persistence, observation fencing, and selective subscription reconciliation complete before the row can be deleted. If the broker still retains or republishes the configuration announcement, PHOS can discover the candidate again. To remove it at the source, use an authorized external MQTT administration client to publish an empty retained payload to that exact Discovery configuration topic; PHOS never performs that broker-side operation.
New approvals activate dynamically in the running provider. PHOS validates the
current discovery announcement and exact approved revision, then adds state and
availability subscriptions to its existing broker connection. Missing discovery
information or a disconnected broker leaves a mapping pending and it is retried
after a matching announcement or reconnect. A changed or withdrawn announcement
suspends the mapping; a changed revision requires explicit reapproval. A
detected revision change marks the saved approval invalid, including
across restarts. If that configuration write fails, the source remains suspended
in the running process and reports invalidation_persistence_failed; repair
configuration storage before restarting, because the failure cannot be recorded
durably. In particular, after such a failure a restart followed by the device
republishing the old approved revision may activate that mapping. In the running
process, PHOS keeps it suspended and retries the invalidation only on a later
announcement, at most once per five seconds per source. Display-only name
changes do not change the revision. Shared topics
remain subscribed while any authorized source needs them. Revocation waits for
in-flight message processing and removes subscriptions no longer needed before
reporting runtime deactivation. Broker disconnection is not discovery removal;
after reconnect, PHOS again waits for a current matching announcement. Retained
physical readings are still withheld. External observations remain isolated
from native state and existing public context and MCP responses.
aiomqtt 2.x does not expose MQTT 5 UNSUBACK reason codes. When a topic is no
longer needed, PHOS instead removes its local authorization and rebuilds the
affected provider's connection with a clean MQTT session. MQTT 3.1.1 explicitly
uses clean_session=True; MQTT 5 explicitly uses clean_start=True. PHOS
restores only authorized subscriptions. Shared topics do not cause a reconnect
while another source still needs them. Other sources on that broker experience
a temporary interruption during a rebuild; other providers are independent.
Revocation is not reported as broker-side reconciliation success until the new
clean connection and its subscriptions succeed. An explicit discovery removal
also invalidates the approval and requires reapproval.
The isolated amqtt broker tests exercise authenticated discovery approval,
restart, live ingress, sensitive changes and reapproval, revocation with a clean
session, shared manual topics, explicit removals and broker loss. They inspect
the test broker's subscription records; they do not inspect MQTT 5 UNSUBACK
reason codes. A captured ESPHome temperature announcement is tested through
structured Web approval and live broker ingestion; other ecosystem examples are
synthetic. Physical interoperability and Mosquitto remain separate validations.
The experimental parser accepts retained configuration metadata separately from
measurements and limits payloads to 16 KiB, 32 device components and eight JSON
nesting levels. It accepts only simple {{ value_json.key }} paths of up to four
components; unsupported expressions and unknown operational options are rejected.
The explicitly recognized ESPHome suggested display precision (sug_dsp_prc)
is informational and does not change source authorization or interpretation.
It never evaluates templates. Unrecognized or ambiguous semantic classes are not mapped,
including carbon dioxide where discovery metadata does not establish whether a
reading is directly measured or estimated. This is not a claim of Home Assistant,
ESPHome or Zigbee2MQTT compatibility. See the official Home Assistant MQTT
discovery, ESPHome MQTT
component and Zigbee2MQTT Home Assistant
integration
documentation for their respective formats.
Each live source observation goes through the existing physical provider
validation and Core event bus. Its provider, source, optional device/entity and
zone identities remain distinct. Accepted, authorized MQTT measurements are
exposed as external_observations by phos_get_physical_context and as a
separate source list in physical assessment. They do not overwrite native
environment, air-quality, or motion fields; they do not enter native temporal
history; and they do not change PHOS motion, behavior, eyes, speech, or signals.
The read model is bounded, RAM-only, and protocol-neutral. It stores only the
latest accepted measurement per source, calculates freshness when MCP is read,
and omits a revoked, removed, retired, or no-longer-authorized source. An active
subscription is not proof that a measurement has passed validation. See
MCP physical context.
Provider capabilities describe configured mapping quantities, not proof that
the broker, a device or sensor is currently available.
External-observation lifecycle
Discovery approval persists the reviewed mapping and authorizes a source; it
does not manufacture a reading. A subsequent eligible, non-retained measurement
must reach canonical ingress before it appears in MCP. Source availability and
measurement freshness are independent: an offline source is presented as
unavailable, while an otherwise available source becomes stale after its own
configured stale_after_seconds limit. Reapproval starts a new authorization
lifecycle and cannot reveal a retained value from the previous approval.
The external_observations array can therefore be empty while a broker is
connected: the source may be unapproved, inactive, unavailable, stale, awaiting
a new eligible measurement, or rejected at canonical ingress. Use the MQTT
diagnostics and the debug sequence documented below to find the first missing
stage; do not infer a current condition from a retained broker packet.
Broker and security
Use a locally managed broker such as Mosquitto and follow its configuration reference for listener, authentication, TLS and ACLs. Grant PHOS read-only access to its exact mapped topics. PHOS does not run a broker. TLS uses certificate and hostname verification; a local CA path is optional. With TLS disabled, communication and credentials are unencrypted; use that only on a suitably protected local network.
username_ref and password_ref are non-secret logical names. Store values
separately with SecretsService in the active configuration's .phos-secrets
directory. Never place credentials in YAML, observations, logs or API payloads.
The Web broker editor can write new encrypted MQTT slots without reading them.
Existing logical references can also be provisioned by trusted local administration. On the PHOS machine, this prompts
for both values without placing them in shell history:
python - <<'PY'
from getpass import getpass
from pathlib import Path
from robot.config import RuntimeConfig
from robot.secrets import SecretsService
config = RuntimeConfig.from_file()
store = SecretsService(config.resolve_path(Path('.')) / '.phos-secrets')
for reference in ('mqtt.username', 'mqtt.password'):
store.set_secret(reference, getpass(f'{reference}: '))
PY
Missing secrets or dependencies leave that broker unavailable until corrected; use Apply MQTT / Retry to replace the unavailable instance. Transient network failures use bounded connection retries. Other brokers and native operation continue.
Canonical configuration
Add the following section to the active config/phos.yaml; legacy documents
without it receive a disabled empty section. Configuration is validated and
persisted through RuntimeConfig and ConfigRepository. Apply changes through
the shared live MQTT application path (or Reload configuration after a local
file edit). At most four brokers and 64 sources per broker are
supported; topic wildcards are rejected. Secret references below are names only.
mqtt:
enabled: true
brokers:
- id: mqtt-room
host: broker.local
port: 8883
client_id: phos-room
username_ref: mqtt.username
password_ref: mqtt.password
protocol: "3.1.1"
tls: {enabled: true, ca_file: certs/broker-ca.pem}
keepalive: 60
timeout_seconds: 5
qos: 1
retry_initial_seconds: 1
retry_max_seconds: 60
sources:
- id: temperature
topic: room/temperature
quantity: temperature_c
format: scalar
unit: c
expected_interval_seconds: 30
stale_after_seconds: 120
zone: room
- id: humidity
topic: room/environment
quantity: humidity_percent
format: json
field: environment.humidity
unit: "%rh"
stale_after_seconds: 120
- {id: co2, topic: room/co2, quantity: co2_ppm, format: scalar, unit: ppm, stale_after_seconds: 120}
- {id: estimated-co2, topic: room/eco2, quantity: eco2_ppm, format: scalar, unit: ppm, stale_after_seconds: 120}
- id: presence
topic: room/presence
quantity: presence
format: mapped
unit: null
value_map: {"ON": present, "OFF": absent}
stale_after_seconds: 120
availability_topic: room/status
available_payload: online
unavailable_payload: offline
- id: motion
topic: room/motion
quantity: motion
format: mapped
unit: null
value_map: {"ON": moving, "OFF": stationary}
stale_after_seconds: 120
- {id: light, topic: room/light, quantity: illuminance_lux, format: scalar, unit: lx, stale_after_seconds: 120}
- id: contact
topic: room/contact
quantity: contact
format: json
field: open
unit: null
value_map: {"true": open, "false": closed}
stale_after_seconds: 120
scalar accepts UTF-8 numeric values, mapped maps exact text through
value_map, and json extracts a field using up to four dot-separated object
keys. JSON booleans map via lowercase true/false. The supported scalar and
enumerated quantities are listed in the
observation model; MQTT vector
payloads are not supported. Optional source fields are device_id, entity_id,
zone, timestamp_field, clock_domain, upstream_id_field, and availability
settings. Expected interval is validation/documentation, not a polling schedule.
When an optional timestamp or upstream-ID JSON field is absent, the observation
remains valid with that metadata unknown. If present, each must be a string.
Maximum payload size is 4096 bytes. Malformed UTF-8/JSON, duplicate JSON keys,
missing fields, unsupported units and invalid values are rejected without
interpreting payloads as instructions. No templates or scripts are evaluated.
An ESPHome device can publish a configured sensor using its MQTT component; configure the device separately and map its exact state topic and unit. No Home Assistant instance or discovery message is required.
For example, an ESPHome device with a DHT22 sensor can publish the scalar temperature topic above (this minimal fragment assumes its broker connection has been configured for the local deployment):
mqtt:
broker: broker.local
sensor:
- platform: dht
pin: GPIO4
model: DHT22
temperature:
name: Room temperature
state_topic: room/temperature
Identity, freshness and recovery
MQTT packet IDs and the DUP flag are not physical measurement identities.
Identical live readings remain valid. An explicitly mapped JSON upstream ID is
processed by canonical bounded duplicate/conflict detection. Broker reconnect is
not assumed to be a device restart; generation remains unchanged across transport reconnects, but advances when
the runtime replaces a provider instance. Source timestamps are optional and untrusted by default. A broker
may explicitly set trusted_clock_domains and max_clock_skew_seconds, and a
source may map timestamp_field and clock_domain; the runtime-owned policy
independently checks skew. No capture time is fabricated from receipt time.
Retained state readings are withheld, including after reconnect. A retained offline availability can mark a source unavailable; retained online alone is an unknown hint. A live offline message produces an unavailable observation without a value. Unavailable presence is not absence, and unavailable contact is not closed. Disconnect clears source freshness and emits unavailable status; reconnect starts unknown. Per-source staleness is evaluated from local monotonic receipt time when diagnostics are read; no synthetic stale transition is emitted.
The internal diagnostics() reports connection state, last connection,
reconnection attempts, subscription/source counts, accepted/rejected/retained
counts, safe error category and per-source availability. It never retains raw
payloads or credentials. On connection failure check reachability, topic ACLs,
credential references, CA trust and hostname. On unknown/stale sources check
live data, exact topic, mapping, availability and freshness threshold. Error
details are intentionally not exposed. These are internal diagnostics, not new
dashboard or API interfaces.
Deterministic tests use a fake asynchronous client. An optional test also uses a
real local amqtt broker when its separate test-only dependencies are installed.
Mosquitto interoperability and Raspberry Pi hardware validation remain separate.
Broker administration
Connectivity → MQTT provides one structured form per broker and an Add broker
form (up to four brokers). Required fields are the stable broker identifier,
hostname or IP address, TCP port and MQTT client identifier. IPv6 addresses are
unbracketed, for example 2001:db8::1. New brokers enable discovery because the
canonical schema requires discovery or at least one manual source mapping.
MQTT has a global enable switch; discovery has a per-broker switch. The schema
does not define a per-broker enable switch.
Advanced Settings exposes existing username/password references, protocol 3.1.1/5, TLS verification and optional CA path, keepalive, connection timeout, QoS, initial/maximum reconnect delays, trusted clock domains and maximum skew. Discovery prefix follows the canonical topic validation rules. Manual mappings and discovery approvals are preserved when editing a broker; removing a broker removes its configuration and associated mappings/approvals.
Optional username and password inputs are write-only. Blank inputs retain the selected references. Supplying a replacement creates a fresh encrypted secret slot through SecretsService; plaintext never enters runtime YAML or responses. Clearing a reference detaches that credential. Detached secret slots are retained rather than deleting a credential potentially shared by another configuration. Stale form revisions are rejected in the parent application process. All broker changes, global enable/disable, credentials, TLS, connection and discovery settings apply without a PHOS restart. Apply MQTT / Retry reapplies the current saved settings after a failed runtime application. The standalone editor can still save while the runtime is absent, but accurately reports application as pending. Approving/reapproving/revoking individual sources remains dynamic.
The application service serializes MQTT saves and discovery review transactions, validates the full canonical document, persists it and delegates reconciliation through the registered lifecycle applier to the runtime event loop. Core's existing behavior registry owns every provider: added instances start, removed instances stop, changed instances are replaced, and equivalent instances retain their connections and subscriptions. There is no second provider manager. Connection establishment remains asynchronous; saved/applied configuration is reported separately from connection and sensor freshness. Missing dependencies, authentication, TLS or network failures affect only the relevant broker. A failed cleanup keeps ownership and fences ingress, blocks its replacement and can be retried; other brokers continue. Shutdown serializes with reconciliation and Core cancels/drains the same provider tasks and connections.
Discovery approvals are scoped to the established broker security boundary.
Changes to broker ID, host, port, client ID, username/password references,
protocol, TLS/CA configuration, discovery prefix or clock trust invalidate saved
approvals before replacement. An imported approval on a new broker is also
invalidated. A current announcement alone cannot clear that durable fence:
review and explicitly approve it again in MQTT Discovery. Review responses carry
a provider_token that the Web form round-trips; approval after provider
replacement or restoration of invalidated approvals requires the current token.
A token from a prior instance is rejected even for an identical announcement. Connection timing and
QoS changes preserve existing approvals, but replacements still wait for a
matching current announcement before subscribing to approved state topics.
Manual mappings remain explicit administrator configuration. Retired instances
cannot publish observations or persist discovery invalidations; queued ingress
is checked again after its serialization lock. Replacement generations advance. Invalidation fences that arrive during a save
are carried across cutover and persisted before success is acknowledged. An
announcement still being reconciled at cutover requires fresh review rather
than assuming its authorization. Failed fence persistence leaves the runtime
suspended and reports application failure until Apply MQTT / Retry succeeds.
The page shows Applying configuration, Connecting, Connected, Disconnected, Reconnecting, Configuration failed and Disabled, using runtime-owned diagnostics. A successful configuration application does not mean a successful connection. External edits to credential values or CA file contents under an unchanged reference/path are outside broker field-change detection; connection retries or a subsequent affected-provider replacement resolve the updated external values.
Test Connection uses the saved broker settings, not unsaved edits, through the application service and existing MQTT client adapter. It performs a bounded MQTT handshake with a unique temporary client identifier, no subscriptions and no publishing. This avoids evicting the active PHOS session. Brokers enforcing client-ID-specific ACLs may reject this diagnostic identity even when the configured production identity is allowed. Results distinguish success, refusal, timeout, authentication failure, TLS failure, invalid/missing credentials, missing optional dependency and other connection errors; they never include library exception text or credentials. A successful test says nothing about sensor availability or measurement freshness.
Topic Explorer
Connectivity → MQTT Discovery includes a read-only Topic Explorer. Select a
saved broker, enter a filter such as phos-lab/#, and start the session. MQTT
has no universal topic list: the list contains only topics for which messages
were actually received. Select a topic to inspect its latest UTF-8 payload,
receipt time, retained flag, detected numeric/boolean/JSON/text format, and up
to 32 simple JSON field paths. Binary payloads are identified without display.
No unit or measurement meaning is inferred. A retained message is identified
as such and must not be mistaken for a newly published measurement.
One session can run at a time, for at most 60 seconds. It retains at most 64
unique topics and one sample per topic, accepts payloads and topics up to 1024
and 256 bytes respectively, and processes at most 10 messages per second;
messages rejected by these processing limits are counted and discarded. The
client incoming queue is limited to one message and can discard further messages
without exposing a count; transport libraries may allocate a single packet before
PHOS can reject an oversized payload. JSON field paths are limited to four
levels and 32 fields. An unrestricted filter such as # or +/# requires
explicit confirmation; broker ACLs still apply. The optional MQTT dependency
must be installed. Broker connection and subscription failures appear as safe
categories rather than raw library messages.
The session uses the saved broker security settings and SecretsService on an isolated client with a temporary ID. It never publishes or forwards diagnostic messages to observation ingress or MCP. Samples stay in bounded process memory and are erased when the session stops, expires or disconnects; they are not logged or persisted. Stop closes the diagnostic connection without touching production subscriptions. Runtime shutdown also cancels the diagnostic task.
Troubleshooting external observations
Start with Connectivity → MQTT: verify the optional MQTT dependency, broker address, TLS and authentication settings, and a unique client ID. A duplicate client ID, denied topic ACL, unavailable secret, certificate failure, or broker network failure can prevent connection without affecting native sensors. Then check MQTT Discovery: an announcement may be absent or unsupported, and a candidate must be reviewed and approved before it can subscribe to measurements.
For an approved source that is absent from MCP, distinguish the following:
- The source is active but has not received a new eligible measurement.
- The device is offline, or its availability topic marks it unavailable.
- The only received state is retained; retained measurements are withheld.
- The value was malformed, mismatched its mapping, or failed canonical ingress.
- The source became stale, was revoked, removed, suspended, or replaced.
At DEBUG level, the relevant bounded diagnostics appear in this logical order:
PHOS MQTT observation accepted
PHOS external observation event
PHOS external observation stored
PHOS external observation context stored=… exposed=…
PHOS MCP physical context external_observations=…
Find the first absent stage rather than treating an empty array as proof that
the broker is disconnected. The exact acceptance/event ordering can vary with
the runtime scheduler. Do not log credentials or arbitrary payloads. Use an
authenticated MCP Inspector or another permitted MCP client to read
phos_get_physical_context, then return logging to INFO after diagnosis.