Skip to content

Physical provider interface and lifecycle

Status: native, optional MQTT, and optional ESPHome Native API providers implemented. This extends the audited architecture, rather than replacing existing sensor providers or runtime lifecycle ownership.

Implemented native-provider foundation

src/robot/physical.py defines the provider-independent PhysicalProvider protocol: stable provider_id, asynchronous start(sink) and stop(), and a read-only snapshot() returning PhysicalProviderStatus. Start returns without waiting for a device. The snapshot separates connection/link availability, generation, supported observation capabilities, source descriptors and a safe error code with a retryability flag. PhysicalSource.available may be unknown: source freshness remains authoritative in the existing sensor services rather than being inferred from the provider's connection.

PhysicalObservation is an immutable, detached internal envelope containing provider/source IDs, session generation, kind, bounded scalar/vector fields, monotonic receipt time and UTC receipt timestamp. Kinds cover measurements, motion, orientation and availability metadata. Units/quantities retain the existing native mapping; sensor-specific validation still occurs in the native decoder/controller boundary. This is not the complete future spatial/provenance schema and is not serialized into existing public responses.

register_physical_provider(core, provider) adds one PhysicalProviderBehavior to the existing Core behavior registry using physical-provider:<provider_id>. That registry enforces uniqueness. Static registration remains a startup-only operation; runtime MQTT reconciliation uses its narrow activate/retire operations to attach and remove individual provider behaviors after startup; there is no second provider/sensor manager. Multiple differently identified instances run concurrently. Lifecycle failures become bounded safe status codes, with cleanup after partial activation. Startup and shutdown use an internal five-second cooperative guard; provider implementations must bound their I/O, cancel and await owned tasks, and report background failures via their snapshot. Core still owns task cancellation and reverse-order behavior shutdown.

The supplied sink validates and normalizes observation semantics before publishing physical.observation on the existing Core event bus. It returns an internal acceptance/rejection code and assessed clock trust; see the observation model for validation, bounded conflict evidence and source-time rules. Providers must use the supplied sink; in-process Python code and other Core publishers are trusted and are not an OS security boundary. Producers must await it serially: there is one observation in flight per producer, no unbounded queue and no per-observation task. Slow asynchronous consumers backpressure that provider while other provider tasks continue. No observations are dropped/coalesced, so this slice introduces no gap markers. Subscribers must remain non-blocking; this is cooperative logical isolation, not protection from blocking Python handlers or faulty native libraries.

flowchart LR
  wire[Existing phos-hw JSON Lines] --> controller[ControllerService]
  controller -->|Validated awaited telemetry| adapter[NativeSerialPhysicalProvider]
  adapter --> envelope[PhysicalObservation]
  envelope --> bus[Existing Core EventBus]
  bus --> runtime[Runtime-owned native source binding]
  runtime --> sensors[Existing sensor services]
  sensors --> semantics[Existing semantics history and application views]

src/robot/hardware/native_provider.py::NativeSerialPhysicalProvider adapts the existing ControllerService; it adds no transport, polling loop or sensor cache. Capabilities in its snapshot mean adapter-supported observation quantities, not proof that firmware advertised or produced every quantity. Firmware capability negotiation and active LED capability remain owned by the original controller. Logical source IDs are <provider_id>/<channel>; they do not prove distinct physical sensor identity or location.

runtime.py::build_runtime registers the default native-controller instance. The runtime subscribes/unsubscribes with its existing lifecycle and routes only that explicit provider and current generation into the existing canonical sensor services. Other registered providers can deliver observations to independent Core consumers but cannot silently overwrite legacy readings. Source-aware configuration/history and public distributed-source exposure remain separate milestones. The existing hardware_controller configuration remains the sole native connection configuration; no new runtime settings or dependencies exist.

Native compatibility includes JSONL framing, heartbeat, capability retries, telemetry, reconnect delay, hot reconfiguration, touch handling, semantic LED output and existing REST/MCP payloads. Legacy direct ControllerService users retain their callback interfaces. The adapter selects awaited ingress instead of invoking those telemetry callbacks twice. Rendering starts after provider activation so lifecycle scheduling cannot leave the first frame on startup state.

Native cancellation now drains reader/readiness tasks and waits for an in-flight open before closing its transport; delayed reads retain their original transport reference. Transport factory and observer failures cannot bypass normal retry/ cleanup. ENS160 normal status after reconnect reestablishes its freshness boundary even if the retained previous validity was also normal; fresh gas reports are still required before values become usable.

Hardware-free verification:

python -m pytest -q tests/test_physical_providers.py tests/test_controller_protocol.py tests/test_runtime.py tests/test_main.py

Tests cover registration, duplicate IDs, multiple fake/native instances, partial startup, failures, awaited backpressure, cancellation during delivery, reader readiness and serial open, reconnect generations, availability recovery, legacy controller status shape and task cleanup. Physical serial/display validation remains separate. Non-cooperative OS calls cannot be force-killed inside Python; a stuck driver may exceed cancellation deadlines and requires deployment-supervisor handling. The optional MQTT adapter and ESPHome Native API integration extend this same lifecycle and ingress. They add no source registry, world store or provider-specific agent-facing operation.

Remaining design requirements

The following sections retain the approved broader design. Proposed network states, per-provider queues, backoff policies and source bindings apply when those providers are implemented; they are not claims about this native slice.

Existing seams to reuse

src/robot/sensors.py already defines environmental, air-quality and IMU provider protocols and services. Local blocking drivers run in service-owned workers. src/robot/hardware/serial_controller.py::ControllerService owns a reconnectable asynchronous session, adapts blocking serial I/O, and pushes accepted observations to those same services. Air-quality and IMU services already reject retired controller generations. Extend these semantics; do not rename public interfaces.

src/robot/core/behaviors.py, core/tasks.py, runtime.py::PhosRuntime, and lifecycle.py already own application task startup, shutdown and configuration application. A provider lifecycle seam is subordinate to that ownership. It is not a parallel sensor manager, process supervisor, state repository, or event bus.

Proposed responsibilities and conceptual operations

Operation Contract
Construct Receive validated typed settings, secret resolver and narrow observation/status sinks. Perform no I/O or SDK import when disabled.
Start Runtime-owned asynchronous activation with a deadline; report connection/capability state without waiting forever for a peer. Repeated activation cannot create duplicate workers/subscriptions.
Describe Return bounded supported observation descriptors and provider health. Discovery is untrusted metadata until mapped/validated.
Deliver Push validated observation candidates to the ingress sink; never mutate domain snapshots, history, behavior, renderer or MCP directly.
Stop Retire generation, unsubscribe, cancel/await work, close transport, and release references within a bounded deadline. Safe after partial startup or repeated calls.

Names are conceptual and may be adapted to existing start/stop/close interfaces. There is no generic execute, arbitrary request forwarding, polling API for MCP, or required actuator interface. Keep native LED execution in its existing semantic output path.

State machine and session ownership

stateDiagram-v2
  [*] --> Disabled
  Disabled --> Starting: enabled valid configuration
  Starting --> Connecting: local initialization succeeds
  Starting --> Unavailable: missing SDK or secret
  Connecting --> Active: authenticated and mappings verified
  Connecting --> Backoff: timeout or peer failure
  Active --> Backoff: connection lost
  Active --> Degraded: partial source failure or overload
  Degraded --> Active: fresh validated recovery
  Degraded --> Backoff: session lost
  Backoff --> Connecting: bounded retry with jitter
  Unavailable --> Starting: explicit restart or validated reconfiguration
  Starting --> Stopping: stop requested
  Connecting --> Stopping: stop requested
  Active --> Stopping: stop requested
  Degraded --> Stopping: stop requested
  Backoff --> Stopping: stop requested
  Unavailable --> Stopping: stop requested
  Stopping --> Disabled: all owned resources released

These are proposed provider states, not replacements for the current ControllerConnection enum or public status strings. Translate them internally; preserve existing controller status responses. Provider connection state and each source's freshness/validity are orthogonal: an active broker can contain stale sources, and loss of one source need not disconnect all others.

One runtime-owned task supervises each enabled provider instance. Every connection attempt/session has a monotonically advancing generation scoped to that instance. Activate a generation only after binding validation. Retire it before reconnect, disable, or replacement; delayed callbacks from retired generations are rejected even if their source IDs match. Capability advertisements apply only to the active generation. Bindings may retain diagnostic metadata without granting live capability or freshness.

Ingress, scheduling and isolation

Network callbacks must do bounded decoding/enqueue work and return. A bounded per-provider queue feeds validation and existing domain services on the owning runtime loop. Reuse thread-safe handoff patterns already used in runtime.py; do not run blocking SDK I/O or expensive parsing on the render loop.

Queue limits, packet sizes, source counts, callback deadlines, and retry ceilings must be explicit before enabling a provider on Pi 3. Coalesce superseded continuous measurements per source/metric only where safe. Preserve discrete edges or explicitly record evidence loss. Overflow must produce a bounded gap marker/counter and invalidate continuity; do not silently claim complete history. Do not add an unbounded task per packet or a persistent backlog.

The current Core EventBus propagates handler exceptions, while SemanticEventPublisher catches observer exceptions but invokes callbacks synchronously. Neither guarantees subscriber latency isolation. Keep provider network waits out of both. Use the existing semantic publisher for qualified transitions; do not use it as a raw telemetry queue or add another bus.

Retry transient network failures with capped exponential backoff and jitter. Authentication/configuration failures remain unavailable with a bounded reason until operator correction; never spin rapidly. Separate source-level validation rejections from transport failures. A faulty optional provider cannot stop native UI, Voice or other providers. This is logical isolation in one process, not a claim of protection against native SDK crashes.

Shutdown and configuration changes

  1. Stop admitting work and retire the active generation.
  2. Detach upstream subscriptions and cancel reconnect timers/readers.
  3. Discard queued expired work; mark affected sources unavailable without inventing physical transitions.
  4. Await owned async tasks and close sockets/SDK resources within deadlines.
  5. Unregister application observers only through their existing owners; do not clear history shared with unrelated providers.

Blocking workers may not be force-killed safely. Bound underlying I/O and joins; report incomplete cleanup and prevent late writes into the next session. Process replacement remains deployment-supervisor work through the shared lifecycle service. No provider or Web handler self-spawns PHOS or runs arbitrary OS commands. Initial network configuration changes may require restart; hot replacement is a later explicit transaction with rollback tests.

Security and acceptance

Resolve secrets at the trusted provider boundary through SecretsService. Provider status contains safe codes and counts, never stored values or raw authentication exceptions. A provider capability cannot grant an agent permission. Use endpoint allow-lists and trusted administrative configuration; sensor data cannot select endpoints, import code, alter mappings, or request expressive acts.

Extend tests/test_controller_protocol.py generation/reconnect tests and tests/test_runtime.py ownership tests with fake network providers. Verify partial start, repeated stop, cancellation during connect/backoff, observer exceptions, slow consumers, queue overflow, identical periodic readings, generation retirement, and resource-count return to baseline. An outage must change only the affected source/provider availability; no new source can become fresh from cached capability metadata alone.