Přeskočit obsah

Pattern 12: Status Polling

When to Use

Polling fills the gap when events alone cannot guarantee fresh state.

Scenario Use polling?
Device only supports polling (no events) Yes
Device has events but may miss some on reconnect Yes - fill gaps
Need initial state on adapter start Yes - first poll fills unknowns
Device has reliable real-time events No - events are sufficient

IStatusPoller

Write the poll as its own class that implements IStatusPoller<TThing>. The source generator finds the class, adds the StatusPoll function to TThing and registers the poller with the scheduler. No DI registration and no YAML declaration are needed for the polling logic.

Declare StatusPoll in adapter-registration.yaml only when the Thing needs polling configuration, such as a non-default interval.

internal sealed class PanelStatusPoller(Protocol protocol) : IStatusPoller<Panel>
{
    public async Task PollStatus(Panel panel, CancellationToken ct)
    {
        var partitionStates = await protocol.QueryPartitionStatus(ct);
        foreach (var (num, armState) in partitionStates)
        {
            var partition = panel.InStartupOrder<PartitionDevice>().FirstOrDefault(p => p.Address == num);
            if (partition is null) continue;

            var batch = partition.StatusBatch();
            batch.Set(armState switch
            {
                ArmingStatus.Armed     => PartitionState.Armed,
                ArmingStatus.ArmedHome => PartitionState.ArmedHome,
                _                      => PartitionState.Disarmed,
            });
            await batch.Commit(ct);
        }

        var zoneStates = await protocol.QueryZoneStatus(ct);
        foreach (var (num, flags) in zoneStates)
        {
            var zone = panel.InStartupOrder<ZoneDevice>().FirstOrDefault(z => z.Address == num);
            if (zone is null) continue;

            var batch = zone.StatusBatch();
            if (flags.HasFlag(ZoneFlags.Alarm))  batch.Set(IntrusionDetectorState.Alarm);
            if (flags.HasFlag(ZoneFlags.Tamper)) batch.Set(TamperState.Tampered);
            if (flags.HasFlag(ZoneFlags.Fault))  batch.Set(IntrusionDetectorState.Fault);
            await batch.Commit(ct);
        }
    }
}

Rules:

Rule Why
Services come through the poller's constructor (Protocol, logger, settings) the scheduler creates the poller through DI from the Thing's service provider, so Protocol is the one of the polled panel
The Thing comes as the PollStatus parameter; never store it in a field the poller lives as long as the connection; a stored Thing would outlive its removal from the tree
Find child Things from the Thing parameter (panel.InStartupOrder<T>()) on each poll a descendant query injected into the constructor would hold the panel for the whole connection
One poller per Thing type a second poll for the same type (another IStatusPoller, a static PollStatus, a hand-written IPollableStatus) fails the build with PQ0005
Keep exactly one public constructor the framework cannot choose between several (PQ0003)

Lifetime. The scheduler creates one poller per polled Thing on its first poll after connect and drops it when the Thing disconnects. Three panels in one adapter have three pollers. A poller may keep state between polls of its Thing in fields. State that must survive a reconnect belongs outside the poller, because a reconnect creates a new poller.

Deprecated: static PollStatus and IPollableStatus

A public static Task PollStatus(TThing thing, ...services..., CancellationToken ct) method and a hand-written IPollableStatus on the Thing still work. Both report PQ0004. Move them to IStatusPoller<TThing>: the constructor takes the services, PollStatus takes the Thing and the token.


Cover All Relevant States

The poll must read every status-bearing function the protocol exposes for each polled element in its domain, not just one state (RULE-051). A partition carries armed/disarmed (often a single bit), alarm, and trouble; a zone carries alarm, tamper, bypass, fault; a door carries its own set (open/closed, locked, forced, held); modules carry comm, tamper, power. The authoritative checklist per Thing type: the functions declared in adapter-registration.yaml intersected with the protocol's status queries — each must appear in a batch.Set(...). Skipping a whole element type (e.g. polling zones and outputs but not partitions) leaves its states permanently unknown.


StatusBatch API

StatusBatch collects state updates and publishes them as a single diff.

// create a batch on the Thing
var batch = thing.StatusBatch();

// set state via the state enum - its type selects the function
batch.Set(PartitionState.Armed);
batch.Set(IntrusionDetectorState.Alarm);
batch.Set(OutputState.Active);

// commit: diff against current state, one NATS publish if anything changed
await batch.Commit(ct);

Set(state) selects the target function from the state enum's type at compile time - PartitionState updates the Partition function, OutputState the Output function. There is no function argument and no scope argument.

Commit calls FunctionStatusAggregator.ApplyPollSnapshot which:

  • Scopes to exactly the functions you called Set(...) on
  • Diffs those against last-observed values
  • Publishes one NATS message when anything changed
  • No-ops when nothing changed

Functions you did not Set are left untouched — sibling functions are never cleared.


State Enum Naming

State enums live in Pq.Adapters.Framework and follow the pattern {Function}State:

Function State enum Example values
Partition PartitionState Armed, ArmedHome, Disarmed
IntrusionDetector IntrusionDetectorState Alarm, Fault, Normal
Output OutputState Active, Inactive
ContactSensor ContactState Open, Closed
Tamper TamperState Tampered, Normal

Framework-Managed Functions

These stay framework-owned. A poll batch only touches the functions you Set(...), so it never disturbs them:

  • ConnectionFunction / ConnectionBaseFunction
  • ConnectionQualityFunction
  • LifecycleFunction
  • EnrollmentFunction
  • AccessSynchronizationFunction
  • TimeSynchronizationFunction
  • StatusPollFunction

Scheduling

StatusPollScheduler is a framework singleton:

  • 1-second PeriodicTimer tick
  • Resolves Things from DeviceTreeRegistry at execution time - no direct references held
  • Keeps one poller per registered Thing; the poller receives the Thing on every call
  • Polls every Thing on its own: a device that answers slowly or times out delays only its own next poll, never the other panels. At most one poll per Thing runs at a time
  • Only polls Things in connected state (via IConnectionAware lifecycle)
  • Default interval: 30 seconds, configurable per device type in YAML
device_types:
  - type_id: Panel
    functions:
      StatusPoll:
        poll_interval_seconds: 10

Key Files

File Purpose
Pq.Adapters.Framework/functions.yaml StatusPoll function definition
Pq.Adapters.Framework/Capabilities/StatusPoll/ IStatusPoller, StatusPollerBinding, StatusPollScheduler, deprecated IPollableStatus
Pq.Adapters.Framework/Functions/StatusPoll/StatusPollFunction.cs Framework function (IConnectionAware)
Pq.Adapters.Framework/Models/StatusBatch.cs Batch status composition
Pq.Adapters.Framework/Models/Functions/FunctionBase.cs MapToStatusString, FunctionId
Pq.Adapters.Framework/Models/FunctionStatusAggregator.cs ApplyPollSnapshot diff logic
SourceGenerator/.../StatusPollDetector.cs Detects IStatusPoller classes and deprecated static PollStatus methods, registers poller bindings
SourceGenerator/.../StatusPollDispatcherGenerator.cs Validates poller constructors; generates IPollableStatus for deprecated static PollStatus methods

See Also