Created
March 8, 2023 21:14
-
-
Save HimaJyun/e8847bce7e1f0cf1cb38c7567117a2b5 to your computer and use it in GitHub Desktop.
Switchbot Plug Mini / Python / Bluetooth (BLE) / sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import bleak | |
import bleak.backends.scanner | |
import argparse | |
debug = True | |
prev_seq = None | |
async def cb(_, adv: bleak.backends.scanner.AdvertisementData): | |
global prev_seq | |
manufacturer_data = adv.manufacturer_data | |
# 0x0969=Woan Technology (Shenzhen) Co., Ltd. == SwitchBot | |
# https://btprodspecificationrefs.blob.core.windows.net/assigned-numbers/Assigned%20Number%20Types/Assigned%20Numbers.pdf | |
if 0x0969 not in manufacturer_data: | |
return | |
# https://github.com/OpenWonderLabs/SwitchBotAPI-BLE/blob/latest/devicetypes/plugmini.md#plug-mini-broadcast-message | |
data = manufacturer_data[0x0969] | |
if prev_seq == data[6]: | |
return | |
prev_seq = data[6] | |
if debug: | |
print(f"RSSI:\t{adv.rssi}") | |
print("MAC:\t{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*data[0:6])) | |
print(f"SEQ:\t{int(data[6])}") | |
print(f"State:\t{data[7] == 0x80}") | |
bits = data[8] | |
print(f"Delay:\t{bool((bits & 0b001))}") | |
print(f"Timer:\t{bool((bits & 0b010))}") | |
print(f"Sync:\t{bool((bits & 0b100))}") | |
print(f"WiFi:\t{data[9]}") | |
print(f"Over:\t{bool((data[10] & 0b1000_000) >> 7)}") | |
print(f"Power:\t{(((data[10] << 8) | data[11]) & 0b01111111_11111111) / 10} W") | |
async def scan(timeout): | |
async with bleak.BleakScanner(timeout=timeout, detection_callback=cb) as _: | |
await asyncio.sleep(timeout) | |
def main(): | |
p = argparse.ArgumentParser() | |
p.add_argument("--timeout", "-t", type=int, default=5) | |
a = p.parse_args() | |
loop = asyncio.new_event_loop() | |
loop.run_until_complete(scan(a.timeout)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment