Skip to content

feat(curtain): add validated opt-in diagnostics and charging states - #576

Draft
hCoureau wants to merge 3 commits into
sblibs:mainfrom
hCoureau:feat/curtain-diagnostics
Draft

hCoureau wants to merge 3 commits into
sblibs:mainfrom
hCoureau:feat/curtain-diagnostics

Conversation

@hCoureau

@hCoureau hCoureau commented Oct 3, 2026 •

Copy link
Copy Markdown

Curtain charging codes 4–6 currently decode incorrectly or raise an indexing error, and short diagnostic replies can partially update cached data. Decode all seven documented states, retain unknown raw codes, and validate successful response status and length before replacing each page snapshot.

Add explicit refresh_diagnostics() and opt-in set_diagnostics_interval(900) polling for Curtain 3. Diagnostics become due independently of advertisement freshness, run during stationary updates, expose per-page observation timestamps, and preserve cached values after failed reads. Basic updates reach subscribers first; optional Bluetooth failures do not fail successful movement commands. The chain query provides the topology needed to decode paired diagnostic pages without treating zero battery or settings as absence.

Validation:

  • Diagnostics branch: Poetry pytest with coverage — 1,472 passed, 92% total coverage.
  • Full dependent stack: pytest passed on Python 3.11–3.14; regression coverage includes normal/silent movement, stop, both position orientations, older curtains, and shared cover decoding.
  • Repository pre-commit checks pass; package builds successfully.

This is a draft pending physical-device validation. Responses are protocol fixtures; paired hardware, USB charging, and solar-specific behavior have not been validated on hardware. Motor snapshots and cached setting accessors are prepared on dependent branches and will be submitted separately after this PR merges. Touch-to-Open writes remain gated on app captures; no guessed setter bytes are included.

Protocol reference: https://github.com/OpenWonderLabs/SwitchBotAPI-BLE/blob/latest/devicetypes/curtain3.md

@codecov

codecov Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.59155% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
switchbot/devices/base_cover.py 93.54% 2 Missing ⚠️
Files with missing lines Coverage Δ
switchbot/__init__.py 100.00% <ø> (ø)
switchbot/const/__init__.py 100.00% <100.00%> (ø)
switchbot/const/curtain.py 100.00% <100.00%> (ø)
switchbot/devices/curtain.py 98.77% <100.00%> (+0.08%) ⬆️
switchbot/devices/base_cover.py 97.50% <93.54%> (-2.50%) ⬇️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bluetoothbot

bluetoothbot commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

PR Review — feat(curtain): add validated opt-in diagnostics and charging states

Solid, well-tested opt-in diagnostics. One concern blocks merge: the new status-byte check now runs on every curtain's basic update, and it was only checked against Curtain 3 fixtures.

What's good:

  • Fixes the IndexError on charging code 6 and keeps unknown raw codes instead of crashing.
  • Builds each page in a local snapshot and replaces the cache only after validation, so truncated replies no longer cause partial updates.
  • Keeps diagnostics strictly opt-in, defers them while the curtain is moving, and swallows optional transport failures so a successful open() never fails.
  • Thorough tests: every truncated length, rejected status codes, cadence, callback ordering, and the older-curtain gating.

What needs attention:

  • get_basic_info() now rejects any reply whose byte 0 isn't 0x01, for all curtain models. Older Curtain/Curtain 2 hardware wasn't checked, so update() could silently stop refreshing them. The same check now applies to the inherited blind tilt / roller shade adv page.
  • Curtain _get_chain_length ignores the advertised deviceChain, so standalone extended-page calls drop device1 until a basic or chain read has happened.
  • Diagnostic update() sends the basic-info command twice.
  • Charging-code mapping depends on the order the enum members are declared.
  • The stateOfCharge strings for codes 4 and 5 change meaning; this should be stated as a behavior change for downstream consumers.

🟡 Important

1. Basic-info status check now applies to every curtain, but was only checked against Curtain 3 fixtures
switchbot/devices/curtain.py:120-121

get_basic_info() now returns None unless data[0] == 1. This path is not limited to Curtain 3. It runs on every update() for every SwitchbotCurtain, including original Curtain / Curtain 2 hardware.

The previous fixtures used 0x00 as byte 0, and the code accepted any status except a bare \x07/\x00. All existing basic-info tests were rewritten from 0 to 1 to fit the new rule. They were not checked against captures from older devices. The PR description says hardware validation is still pending.

Impact: suppose an older curtain firmware sends a status byte other than 0x01 for a valid basic-info reply. update() would then silently stop refreshing position, battery and motion state for that device. This is a live regression on the main polling path of the Home Assistant integration, and nothing gets logged.

The same rule now also applies to get_extended_info_adv(), which SwitchbotBlindTilt and SwitchbotRollerShade inherit (base_cover.py:80). The Curtain 3 spec doesn't document those devices.

Fix: either:

  • limit the strict data[0] == 1 check to the new Curtain 3 diagnostic paths and keep the old length-only acceptance in get_basic_info() for other models, or
  • attach a capture from an older curtain (and from a blind tilt / roller shade for the adv page) showing the status byte is 0x01.
_data = await self._get_basic_info()
if not self._valid_diagnostic_response(_data, 8):
    return None

🟢 Suggestions

2. Standalone extended-page calls no longer report the second motor
switchbot/devices/curtain.py:189-198

Before this PR, get_extended_info_summary() / get_extended_info_adv() filled in device1 whenever the payload's second-slot byte was non-zero. Now device1 appears only if _get_chain_length() == 2. On a curtain, that value comes only from _basic_info / _chain_info.

The advertisement already carries deviceChain (adv_parsers/curtain.py:33), and the base-class _get_chain_length falls back to it. The curtain override ignores it.

Impact: a library consumer who calls curtain.get_extended_info_summary() before any update() / get_basic_info() gets only device0, even when the curtain is paired. This is a quiet behavior change in a public method.

Fix: when both cached pages are empty, fall back to super()._get_chain_length() (the advertised deviceChain), or document that these methods now need a prior basic/chain read.

3. Diagnostic update reads basic info twice in a row
switchbot/devices/curtain.py:262-264

update() first calls super().update(), which does a basic-settings read. Then refresh_diagnostics() calls get_basic_info() again. Your own test expects 5 commands per diagnostic update (await_count == 5): basic ×2, then chain, summary and advanced.

On BLE, every extra round-trip adds latency and is another chance to fail, especially through proxies.

Fix: split out a private _refresh_extended_pages() that reads only chain, summary and advanced. update() calls that helper, and refresh_diagnostics() calls basic plus the helper.

info = await self.get_basic_info()
if info is not None:
    self._update_parsed_data(info)
chain = await self.get_extended_chain_info()
4. Wire codes depend on the order the enum members are declared
switchbot/const/curtain.py:18

dict(enumerate(CurtainChargingState)) maps protocol codes 0–6 to whichever member is in that position. If someone reorders the members or inserts a new one (for example a future code 7 placed next to a related state), every decoded charging state shifts without any error. The tests wouldn't catch it either, because test_charging_codes also uses list(CurtainChargingState)[code].

Fix: write out the mapping ({0: NOT_CHARGING, 1: CHARGING_BY_ADAPTER, ...}). Also move the legacy_state dict in base_cover.py:88 to a module-level constant instead of rebuilding it on every loop iteration.

CURTAIN_CHARGING_STATES = dict(enumerate(CurtainChargingState))
5. `stateOfCharge` meaning changes for codes 4 and 5 for existing consumers
switchbot/devices/base_cover.py:84-100

Code 4 changes from solar_not_charging to fully_charged, and code 5 from charging_error to solar_not_charging. This follows the linked spec (I couldn't check the spec from here) and fixes the crash on code 6. Still, anyone keying on these strings will see different values for the same device state.

A fix:/feat: commit won't flag this in the semantic-release changelog. Call it out in the commit body or PR so downstream consumers (for example the HA integration) know about the change.


Checklist

  • No hardcoded secrets
  • Input validation at boundaries (BLE response length/status)
  • Backward compatibility of public APIs / existing device models — warning #1, suggestion #2, suggestion #5
  • Error handling does not swallow errors silently
  • No repeated I/O — suggestion #3
  • Maintainable protocol mapping — suggestion #4
  • New branches covered by tests

To rebase and address feedback, mention me: @bluetoothbot rebase critical (fixes 🔴 only), @bluetoothbot rebase important (fixes 🔴 + 🟡), or @bluetoothbot rebase --fix for all. (A bare @bluetoothbot rebase only rebases onto the base branch.)


Silent Failure Analysis

🟠 **6. HIGH** — silent null return
switchbot/devices/curtain.py:117-121

Risk: get_basic_info runs on every update() for every Curtain model, not only Curtain 3. It now returns None without logging when the status byte isn't 1 or the reply is shorter than 8 bytes, so the base update() silently skips the state refresh and _last_full_update. Before, a short reply raised IndexError, a status-0 payload was accepted, and the only rejections were b"\x00"/b"\x07", which logged an error.

_data = await self._get_basic_info()
if not self._valid_diagnostic_response(_data, 8):
    return None

Fix: Log a warning or error with the status byte and length when a basic-info reply is rejected, and confirm on hardware that older Curtain firmware really returns status 1 before making the stricter check mandatory for all models.

🟡 **7. MEDIUM** — removed error logging / silent null return
switchbot/devices/base_cover.py:80-81

Risk: The previous _LOGGER.error("Unsuccessful...") calls were removed. Rejected, empty and truncated replies for the advanced page (and the summary and chain pages in curtain.py) now return None with no trace, which leaves ext_info_* stale and gives operators nothing to diagnose.

if not self._valid_diagnostic_response(_data, 7):
    return None

Fix: Log the status byte and payload length at warning or debug level inside _valid_diagnostic_response, or at each call site, before returning None.

🟡 **8. MEDIUM** — fallback value hides inconsistency
switchbot/devices/curtain.py:189-198

Risk: If the basic and chain pages disagree on chain length, or neither has been read yet (for example, a direct call to get_extended_info_summary), _get_chain_length() returns None. The summary and advanced parsers then quietly keep only device0, drop device1, and still record a fresh success timestamp. The old code used the payload's own data[2]/data[4] check instead.

if (basic_length is not None and chain_length is not None
        and basic_length != chain_length):
    return None
...
for slot in range(2 if self._get_chain_length() == 2 else 1):

Fix: Log the mismatch, and either skip updating the page and its timestamp when the chain length is unknown or inconsistent, or fall back to the payload's own second-device bytes as before.

🟡 **9. MEDIUM** — ignored failure result
switchbot/devices/curtain.py:275-288

Risk: update() discards the False result from refresh_diagnostics() without any log, and transport failures are logged only at debug level. If a user has enabled diagnostics and every refresh fails, the cached diagnostics go stale with nothing visible above debug.

try:
    await self.refresh_diagnostics()
except (*BLEAK_RETRY_EXCEPTIONS, CharacteristicMissingError, SwitchbotOperationError):
    _LOGGER.debug("%s: Optional diagnostic refresh failed", ...)

Fix: Log at debug or info when refresh_diagnostics() returns False, and consider escalating to a warning after repeated consecutive failures.

🟡 **10. MEDIUM** — ambiguous failure signal
switchbot/devices/curtain.py:256-258

Risk: For unsupported models, refresh_diagnostics() returns the same False it uses for rejected or malformed replies, so a caller can't tell that diagnostics will never work on this model from a temporary read failure.

if self.data.get("modelFriendlyName") != "Curtain 3":
    return False

Fix: Raise a dedicated exception (for example NotImplementedError or SwitchbotOperationError) for unsupported models, or expose a separate capability check, so a False return only means a failed read.


Automated review by Kōan (Claude) HEAD=c91ab94 1 min 27s

@bluetoothbot bluetoothbot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

Important issues found.

  • Basic-info status check now applies to every curtain, but was only checked against Curtain 3 fixtures

@bluetoothbot

Copy link
Copy Markdown
Collaborator

Note

No code changes since the last review (c91ab94) — skipping. Push new commits or re-request a review to run again.

2 similar comments
@bluetoothbot

Copy link
Copy Markdown
Collaborator

Note

No code changes since the last review (c91ab94) — skipping. Push new commits or re-request a review to run again.

@bluetoothbot

Copy link
Copy Markdown
Collaborator

Note

No code changes since the last review (c91ab94) — skipping. Push new commits or re-request a review to run again.

hCoureau and others added 3 commits November 21, 2026 21:34
Only Curtain 3 replies have been validated against the spec, so the
0x01 success-status check now applies to Curtain 3 only. Older curtains,
blind tilt and roller shade keep the original acceptance and
second-slot detection, and their fixtures use a 0x00 status byte again.

Also:
- fall back to the advertised deviceChain before any basic or chain read
- read basic info once per diagnostic update instead of twice
- map charging wire codes explicitly instead of by enum order, and make
  the legacy stateOfCharge mapping a module-level constant

Behaviour change for consumers: stateOfCharge for charge code 4 is now fully_charged
(was solar_not_charging) and code 5 is now solar_not_charging (was
charging_error), matching the Curtain 3 spec. Code 6 is charging_error
and no longer raises IndexError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@hCoureau
hCoureau force-pushed the feat/curtain-diagnostics branch from c91ab94 to 267c9c3 Compare November 21, 2026 21:37

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants