feat(discovery): add callback support for device discovery #437
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR adds a
callbackparameter to theGetSwitchbotDevicesclass. This allows consumers of the library to process device advertisements in real-time as they are discovered.Motivation / Real-world Use Case
I maintain an OSS project called switchbot-actions, which relies on
pySwitchbotfor device scanning. This tool triggers actions (webhooks, MQTT, shell commands) based on sensor updates. A common use case is turning on a light via webhook immediately when a motion sensor detects movement.Currently,
GetSwitchbotDevices.discover()waits for the fullscan_timeout(default 5s) to complete before returning results. This introduces an average latency of half the scan duration, causing a noticeable delay in automation.By adding a callback, applications can process the advertisement packet the moment it is received, enabling near real-time responsiveness without shortening the scan duration.
Changes
GetSwitchbotDevices.__init__to accept acallback.detection_callbackto invoke the user-provided callback._background_tasks) for async callbacks to ensure references are kept alive during execution.Technical Details
inspect.iscoroutinefunctionto determine if the callback should be scheduled as an asyncio task.Backward Compatibility
callbackparameter is optional. Existing implementations usingdiscover()will function exactly as before without any changes.Example Usage
Tests
tests/test_discovery_callback.pycovering: