Fix device discovery when Bluetooth adapter is in passive scanning mode #397
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.
Fixes #284
Summary
This PR adds support for discovering Switchbot devices when the Bluetooth adapter is performing passive scans by fetching device information from the Switchbot cloud API and caching MAC address to model mappings.
Problem
When a Bluetooth adapter is configured for passive scanning (not sending scan requests), it only receives passive advertisements from devices. These passive advertisements from Switchbot devices contain only manufacturer data without service data, making it impossible to identify the device model from the advertisement alone. This causes discovery to fail when the adapter is in passive scanning mode.
Solution
Added a new
fetch_cloud_devices()
function that:Once the cache is populated, the advertisement parser can identify passive devices by their MAC address and correctly decode their advertisements.
Usage
How It Works
Before this PR: When adapter is in passive scan mode, advertisements couldn't be decoded
After this PR: Same passive scan advertisements are now decoded
Implementation Details
New Components
switchbot/utils.py
: Addedformat_mac_upper()
to normalize MAC addressesswitchbot/devices/device.py
:get_devices()
to returndict[str, SwitchbotModel]
with formatted MACsfetch_cloud_devices()
as the public API_extract_region()
helper to reduce code duplicationswitchbot/adv_parser.py
:_MODEL_TO_MAC_CACHE
for storing MAC to model mappingspopulate_model_to_mac_cache()
helper functionAPI Model Mappings
Added mappings for all known Switchbot device types:
Unknown models are logged with their full payload to help identify new devices.
Testing
Added comprehensive test coverage:
tests/test_device.py
: Tests forget_devices()
andfetch_cloud_devices()
tests/test_utils.py
: Tests forformat_mac_upper()
tests/test_adv_parser.py
: Tests showing cache enables passive device discoveryBenefits
Breaking Changes
None. This is purely additive - existing code continues to work as before.
Example Use Case
For Home Assistant or other integrations:
Notes