ADR-007: Mains Power Awareness Through Power Sources¶
Status¶
Accepted Date: 2026-09-13 | Amended Date: 2026-09-19 | Amended Date: 2026-09-30 | Amended Date: 2026-10-11
Context¶
Some WiZ bulbs sit behind smart relays. openHAB or Home Assistant holds a signal that tells whether the circuit has mains power. "Powered" is not the same state as "on". Today wiz2mqtt cannot tell the two apart: an unpowered bulb looks the same as a faulty bulb. Both show availability = offline.
The hard case is a mixed environment. The same lights are controlled by wiz2mqtt and by classic wall switches. When a wall switch cuts the circuit, every bulb on it goes dark and unreachable at once. wiz2mqtt then reads each absent bulb on every telemetry cycle. An absent bulb holds the asyncio.Lock of pywizlight for the full 13 s timeout. A failed cycle costs 13 s plus the 60 s interval, because the scheduler delays after completion rather than at a fixed rate.
A consumer wants one simple rule. In openHAB the rule "the lamp is lit" must come from one message, not from a join of two topics. The signal is optional: many circuits have no relay, and the feature must still work there.
A lighting group ([[groups]], ADR-003) matches a circuit most of the time, but not always. One bulb of a group can sit on a different circuit. The addressing must handle that exception without a second inventory.
The design was settled in a design interview (decisions Q2, Q4, Q5, Q11, Q14, Q15, Q20, Q21, Q23). This ADR records the addressing, the state model, the traffic rule, the configuration surface and the legacy mapping. ADR-008 records the restore. ADR-009 records the power requests.
Decision¶
Add a [[power_sources]] block to the inventory. A power source declares a circuit and claims member bulbs. wiz2mqtt derives a belief about the power of each source and publishes the belief, not the raw relay signal. The belief goes into the state payload of every member bulb as a powered key. A consumer computes "the lamp is lit" as state AND powered from one message.
Source of the powered value. Three options were weighed: (a) republish the raw relay signal; (b) publish a derived belief where evidence outranks the signal; © no source-level entity, only a per-bulb flag. Option (b) is chosen. The belief has three values, on, off and unknown, and follows three rules in order:
- If a minimum of one member bulb answers, the belief is
on. Evidence outranks the signal. - If no bulb answers and a signal exists, the belief is the signal.
- If no bulb answers and no signal exists, the belief is
unknown.
Rule 1 makes the powered flag useful on a circuit that has no relay signal at all.
Bulb state while unpowered. Three options were weighed: (a) publish OFF; (b) publish the desired state plus a powered key; © publish unknown. Option (b) is chosen. While wiz2mqtt cannot observe the bulb, wiz2mqtt/{bulb}/state publishes the desired state (ADR-008). Option (a), "publish OFF", was proposed first and then withdrawn. The reason: reality is recoverable from intent as state AND powered, but intent is not recoverable from reality. The desired state carries strictly more information.
Addressing. Three options were weighed: (a) a power_source key on every bulb only; (b) a [[power_sources]] block with group or members plus a per-bulb override; © reuse [[groups]] with extra keys. Option (b) is chosen. The membership resolves per bulb, in this order:
- The
power_sourcekey on the bulb wins. - A power source block that names the group of the bulb claims the bulb.
- The bulb is not power-aware. The bulb behaves as it does today.
A block accepts group or members. Exactly one of the two is permitted. A bulb belongs to a maximum of one power source. The validator follows the pattern of _groups_valid (settings.py:107-122).
Availability. availability = offline now has one meaning only: the bulb must answer, and the bulb does not answer. That is a real fault. An unpowered bulb is not offline; it is powered = false.
Traffic. While a power source is known to be off, wiz2mqtt skips the network read for its member bulbs and does not advance the failure counter (_FAILURE_THRESHOLD, entity.py:20).
Legacy mapping. when_unreachable moves from the bulb to the power source. On the power source it tells wiz2mqtt what an unreachable bulb means when there is no better evidence: "fault" (default) or "no_power". extra="forbid" makes a stale bulb-level key a hard ValidationError. The migration maps a legacy bulb-level when_unreachable = "off" to an implicit single-bulb power source with when_unreachable = "no_power" and emits a warning that names the replacement. The repository has no deprecation precedent and no aliases.
Field conventions. A duration is a bare float in seconds, and the unit is stated in description=. A boolean uses the enable_<noun> form. Every new field carries Field(description=...). signal_topic gets a validator that follows the cosalette topic_prefix check: reject + and #, restrict the character set, reject an empty value. docs/configuration.md is hand-maintained and must be edited by hand.
queued_command_ttl = 86400.0 # seconds
[[bulbs]]
name = "living-room"
ip = "192.168.1.102"
power_source = "downstairs-circuit" # optional; beats any group reference
restore_previous_state = true # default false
[[power_sources]]
name = "downstairs-circuit"
group = "downstairs" # or members = [...], exactly one
signal_topic = "openhab/relay/downstairs/state" # optional
when_unreachable = "fault" # "fault" (default) or "no_power"
enable_power_on_request = true # default false
enable_power_off_request = false # default false
power_off_idle_delay = 600.0 # seconds
wiz_bulbs_only = false # must be true before a power-off request
Decision Drivers¶
- A consumer must tell "unpowered" from "faulty". Today both states look the same on the wire
- The business logic in openHAB must stay simple:
state AND poweredfrom one message, with no join across topics - The signal is optional. The feature must work on a circuit that has no relay at all
- A lighting group matches a circuit most of the time, but not always. The exceptions need an escape hatch, not a second inventory
- An absent bulb costs 13 s of a held pywizlight lock per cycle. A known-dark circuit must not be read at all
- Intent is more valuable than reality. A payload that carries the desired state lets a consumer recover reality; the reverse is not true
Considered Options¶
Option 1: Raw signal, OFF while unpowered, per-bulb key only¶
Republish the raw relay signal as the powered value (source option a). Publish state = OFF for a bulb while its circuit is unpowered (state option a). Address the circuit with a power_source key on every bulb, with no block of its own (addressing option a).
- Advantages: The smallest code change: no belief, no block, no resolution order; The
poweredvalue is a pure passthrough, so it is easy to explain;OFFis a value that every consumer already understands - Disadvantages: A circuit with no relay signal has no
poweredvalue at all, so the feature does not work there;OFFerases the intent. When the circuit returns, nothing on the wire says what the bulb should show; A raw signal that is stale or wrong contradicts a bulb that answers, and the consumer has no rule to break the tie; Thepower_sourcekey must be repeated on every bulb of a circuit, and the circuit-level settings (signal topic, requests) have no home
Option 2: Derived belief, desired state plus powered, power_sources block with override (chosen)¶
Publish a derived belief where an answering bulb outranks the signal (source option b). Publish the desired state plus a powered key while the bulb is unpowered (state option b). Declare a [[power_sources]] block with group or members, and let a per-bulb power_source key override the group reference (addressing option b).
- Advantages: Works with no relay signal: one answering bulb sets the belief to
on;state AND poweredgives the lit state from one message, and the desired state is still on the wire for the restore;availability = offlineregains one meaning: a real fault; The block gives the circuit-level settings a home, and the per-bulb key handles the exception where a group and a circuit differ; A known-dark circuit skips the network read, which saves 13 s of a held lock per absent bulb per cycle - Disadvantages:
poweredis a new key outside the Home Assistant JSON light schema, so ADR-001 must adopt it; A belief is derived, so a consumer must trust the rules of wiz2mqtt instead of a raw sensor; The bulb-levelwhen_unreachablemoves to the power source, which is a configuration change
Option 3: Per-bulb flag, unknown while unpowered, groups reuse¶
Publish no source-level entity; only a per-bulb powered flag exists (source option c). Publish state = unknown while the bulb is unpowered (state option c). Reuse [[groups]] with extra keys such as signal_topic instead of a new block (addressing option c).
- Advantages: No new inventory block; the operator edits a block that already exists;
unknownis honest about what wiz2mqtt can observe; No source-level entity to announce, so the discovery surface stays as it is - Disadvantages:
unknownerases the intent in the same wayOFFdoes; A group is a consumer-side fan-out construct (ADR-003). Power keys on a group change its meaning, and a bulb whose circuit differs from its group has no override; No source-level entity means no place to publish the belief or the desired power (ADR-009); The rulestate AND poweredstill needs apoweredvalue, and a per-bulb flag cannot express evidence from a peer bulb on the same circuit
Decision Matrix¶
| Criterion | Raw signal, OFF while unpowered, per-bulb key only | Derived belief, desired state plus powered, power_sources block with override | Per-bulb flag, unknown while unpowered, groups reuse |
|---|---|---|---|
| A consumer can tell unpowered from faulty | 3 | 5 | 3 |
| openHAB rule stays one expression on one message | 4 | 5 | 3 |
| Works with no relay signal | 1 | 5 | 2 |
| Intent survives an outage (reality recoverable from the payload) | 1 | 5 | 1 |
| Handles a circuit that differs from a lighting group | 4 | 5 | 1 |
| Traffic saving on a dark circuit | 4 | 5 | 3 |
| Size of the configuration change | 4 | 3 | 4 |
Scale: 1 (poor) to 5 (excellent)
Consequences¶
Positive¶
- A consumer tells "unpowered" from "faulty" from one retained message:
powered = falseversusavailability = offline - The openHAB rule for "the lamp is lit" is
state AND powered, with no join across topics - The
poweredflag works on a circuit with no relay, because an answering bulb sets the belief toon availability = offlinemeans a real fault only- A known-dark circuit costs no network reads and no failure counts; the 13 s lock hold per absent bulb per cycle disappears
- The per-bulb
power_sourcekey handles the exception where a lighting group and a circuit differ - A legacy
when_unreachable = "off"on a bulb still starts, with a warning that names the replacement
Negative¶
poweredis a new key that ADR-001 must adopt. It sits outside the Home Assistant JSON light schema, like the existinghsbkey- The bulb-level
when_unreachablemoves to the power source, which is a configuration change for every operator who set it - A bulb on a source with no signal and no answering peer stays
unknown; wiz2mqtt cannot say more than it can observe - The belief is derived, so a wrong rule in wiz2mqtt shows as a wrong
poweredvalue on every member bulb at once
2026-09-13
Amendment (2026-09-14) — Additive¶
Membership. Resolve each bulb once: explicit power_source; then a source whose members contains it; then a source whose group contains it; otherwise none. Reject ambiguous implicit claims, including members/group overlap. Explicit references must name a source and override implicit claims.
Signal contract. signal_topic is a retained status input, never a command surface. Accept only UTF-8 on or off (lowercase, whitespace trimmed once); ignore and warn on every other payload without echoing it, leaving belief unchanged. A topic is unique per source. Broker ACLs permit only the configured controller to publish it; wiz2mqtt subscribes and never publishes there.
Source contract. Each source is one retained wiz2mqtt/{source}/state device payload: {\"powered\": \"on\" | \"off\" | \"unknown\", \"power_request\": \"on\" | \"off\" | null, \"members\": [...]}. It exposes the first field as the power binary sensor and the second as the diagnostic desired-power binary sensor. Source names must not collide with bulb or group names.
Amendment (2026-09-19) — Corrective¶
Rationale: Rule 1 counted every answer of a member bulb, also an answer that came before the signal. A member that answered once stays 'answering' until it fails three reads in a row (_FAILURE_THRESHOLD). Thus a relay signal off changed the belief only 13 + 60 + 13 + 60 + 13 = 159 s after the signal. Without a signal the time is 159 s to 219 s, so the signal removed only the first wait. The power requests (ADR-009) and the skip of reads (Traffic) waited the same 159 s (cap-hfro).
Justification for amendment (not supersession): The belief rules are not in a release yet: the last release of wiz2mqtt is 0.2.4 (2026-09-16), and the power sources came after it. The change is confined to the belief computation in
power.py, the failure count and the first read after a signal change inentity.py, and the cache bypass of that read in the adapter. No wire format, configuration key or consumer contract changes. Only the time until the belief changes becomes shorter.
Revised Decision¶
The belief follows three rules in order. Only rule 1 changes:
- If a minimum of one member bulb answered after the last change of the signal, the belief is
on. New evidence outranks the signal. - If no bulb answered after the last change of the signal and a signal exists, the belief is the signal.
- If no bulb answers and no signal exists, the belief is
unknown(fault) oroff(no_power).
A change of the signal makes each older answer of a member stale. A repeat of the same signal is not a change. Thus a signal off sets the belief off at once, and a member that answers after the signal sets the belief on again.
Only a poll clears a stale answer. A bulb with power pushes its state every few seconds, and the adapter answers from that push cache for up to 60 s. A cached push from before the signal is not an answer after it. Thus the first read of a member with a stale answer bypasses both push caches (the adapter's and pywizlight's) and polls the bulb itself.
A failed read is firm while the signal decides. If a read of a member fails while the signal is off and the belief is off, the failure counts as three failures. wiz2mqtt skips the reads of that bulb from the next tick (Traffic). A member that answered after the signal keeps the three-failure debounce, because its belief is on. The no_power tie-break of rule 3 also keeps the debounce: without a signal, one lost read is not firm evidence.
Additional Positive Consequences¶
- A signal
offsets the beliefoffat once. The skip of reads starts after one failed read (about 13 s), and a power request reacts at once - Evidence still outranks the signal: a member that answers after the signal sets the belief
onagain
Additional Negative Consequences¶
- A wrong signal
offon a live circuit showspowered = falseuntil the poll that the signal starts answers, normally in less than 1 s - Each change of the signal costs one poll per member, also on a host that receives pushes
- If one read fails transiently while a wrong signal
offis active, wiz2mqtt skips the reads of that bulb until the belief changes or the bulb boots
Amendment (2026-09-30) — Corrective¶
Rationale: A successful get_state request can begin before a relay-off signal and complete after it. Treating that in-flight result as an answer after the signal restores the on belief for the entire dark period, bypassing queued commands and boot grace.
Justification for amendment (not supersession): The correction is confined to the evidence timestamp in wiz2mqtt's power-belief path. It changes no configuration, MQTT topic, or payload schema, and consumers already rely on the documented post-signal evidence rule, so no migration or superseding ADR is warranted.
Revised Decision¶
For rule 1, a member answer is newer than a signal change only when the poll was issued at or after that change. Stamp each get_state request with a monotonic time immediately before it is issued. A response from a request issued before the source's latest signal change remains stale and cannot set bulb_answered or clear stale_answers. A response from a request issued at or after the change is fresh evidence and can again make the belief on.
Additional Positive Consequences¶
- A read racing a relay-off edge cannot erase the edge's stale marker, so commands while the circuit is dark are queued and boot grace remains available on the next power-on.
Additional Negative Consequences¶
- A response that began just before a genuine relay-on edge is conservatively ignored as power evidence until the next poll or push-triggered observation.
Amendment (2026-10-11) — Corrective¶
Rationale: wiz2mqtt 0.2.14 still reported powered 'on' 4-47 ms after a relay signal 'off', and kept it for the whole dark period (cap-m4u1). Two gaps let an answer from a live bulb count as evidence after the edge. First, pywizlight's updateState returns its cached state when a push arrives while a getPilot is in flight, so the authoritative read after the edge could return a push the bulb sent before the cut. Second, the relay reports 'off' before its contacts have cut the bulb: in the report, wiz2mqtt receives the signal 50-90 ms after openHAB logs the actuator change, and the bulb still answered 70-110 ms after the relay opened. A read issued at once is therefore answered by a bulb that is about to go dark, and rule 1 lets that answer outrank the signal. The worst observed lag, signal delivery plus supply hold-up, is about 160 ms.
Justification for amendment (not supersession): The correction is confined to wiz2mqtt's adapter (the authoritative poll) and the first read after a signal 'off' in entity.py. It adds one optional power-source key whose default only delays a read by half a second; no MQTT topic, payload schema or existing configuration key changes, and rule 1 and the 3-read debounce keep their meaning. Operators need no migration, so a superseding ADR would only restate this one.
Revised Decision¶
Keep rules 1-3, the 2026-09-19 stale marking and the 2026-09-30 issue-time stamp, and close the two gaps that let pre-cut evidence count after a signal 'off'.
- A push that cuts an authoritative read short does not answer it. When pywizlight returns its cached state because a push arrived during the getPilot, the adapter polls again, up to three attempts in all. A bulb that keeps pushing on every attempt is accepted as answering, since each push is itself proof of life.
- The first read after a signal 'off' waits
signal_off_holdoffseconds. A source with asignal_topicdelays a member's first read after the 'off' edge untilsignal_at + signal_off_holdoff, through the shutdown-awarectx.sleep, and stamps the read's issue time after the wait. The default is 0.5 s, about three times the worst lag in the report (~160 ms); 0 disables the delay. The key has no effect without asignal_topicand logs a warning when set there. The belief is already 'off' during the wait, so a command in that window is queued for the return path. - The 3-read debounce stays. A member that answered after the signal still needs three failed reads before the belief turns 'off'. With the hold-off in place an answer after the edge is real evidence that the signal is wrong or the bulb is fed from elsewhere, and a single lost datagram must not undo it.
Additional Positive Consequences¶
- A relay 'off' edge holds: a bulb that is still powered for the first ~100 ms after the edge can no longer flip powered back to 'on' for the whole dark period.
- Operators with a slow relay or long signal path can raise signal_off_holdoff per source without a code change.
Additional Negative Consequences¶
- Every member read after a signal 'off' starts half a second later by default, and that tick runs that much longer.
- A bulb that answers only after a longer hold-up than signal_off_holdoff still outranks the signal; the operator must raise the value for that source.
- A bulb that pushes on every attempt of an authoritative poll is still accepted, so pushes sent right before a cut can count once in that rare case.