|
| 1 | +import asyncio |
| 2 | +from bleak import BleakClient, BleakScanner |
| 3 | +from datetime import datetime |
| 4 | + |
| 5 | +# The GATT characteristic that sends temp/humidity notifications |
| 6 | +DATA_CHAR = "ebe0ccc1-7a0a-4b0c-8a1a-6ff2997da3a6" |
| 7 | + |
| 8 | + |
| 9 | +async def scan(): |
| 10 | + devices = await BleakScanner.discover(timeout=10) |
| 11 | + for d in devices: |
| 12 | + if d.name and "LYWSD03" in d.name: |
| 13 | + print(f"{d.name} -> {d.address}") |
| 14 | + |
| 15 | + |
| 16 | +async def read(address: str): |
| 17 | + async with BleakClient(address) as client: |
| 18 | + data = await client.read_gatt_char(DATA_CHAR) |
| 19 | + temp = int.from_bytes(data[0:2], "little", signed=True) / 100 |
| 20 | + humi = data[2] |
| 21 | + voltage = int.from_bytes(data[3:5], "little") / 1000 |
| 22 | + print(f"Temperature: {temp}°C") |
| 23 | + print(f"Humidity: {humi}%") |
| 24 | + print(f"Voltage: {voltage}V") |
| 25 | + |
| 26 | + |
| 27 | +async def read_loop(address: str, interval: float = 2.0): |
| 28 | + async with BleakClient(address) as client: # connect once |
| 29 | + while True: |
| 30 | + data = await client.read_gatt_char(DATA_CHAR) |
| 31 | + temp = int.from_bytes(data[0:2], "little", signed=True) / 100 |
| 32 | + humi = data[2] |
| 33 | + print(f"{temp}°C / {humi}%") |
| 34 | + print(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) |
| 35 | + await asyncio.sleep(interval) |
| 36 | + |
| 37 | + |
| 38 | +# Scan to find MACs (only needed once): |
| 39 | +# asyncio.run(scan()) |
| 40 | + |
| 41 | +# Read with your known MAC: |
| 42 | +# asyncio.run(read("229C6152-3E39-45DB-3A8B-D48CB72D171F")) |
| 43 | +# asyncio.run(read("99C9B552-C48E-0764-B56E-916ADDD6A0EA")) |
| 44 | +asyncio.run(read_loop("99C9B552-C48E-0764-B56E-916ADDD6A0EA", interval=0)) |
0 commit comments