米家藍牙溫濕度計2是小米推出的產品。
開箱文:https://mnya.tw/cc/word/2147.html
Python 呼叫藍牙取得設備數據的完整程式碼如下,僅可在 Windows 環境下運行,Mac 位址請放在與 MiTHM2_win.py 同層目錄下的 mac.ini。
MiTHM2_win.py
from dataclasses import dataclass
import time
from bleak import BleakClient
import asyncio
import configparser
# 讀取 Mac 位址
config = configparser.ConfigParser()
config.read('mac.ini')
Mac = config.get('Bluetooth', 'Mac')
@dataclass
class Result:
temperature: float
humidity: int
voltage: float
battery: int = 0
async def main(address):
client = BleakClient(address, timeout=30.0)
try:
await client.connect()
print("藍牙連線成功!")
while True:
buff = await client.read_gatt_char("ebe0ccc1-7a0a-4b0c-8a1a-6ff2997da3a6")
try:
result = Result(0, 0, 0, 0)
temp = int.from_bytes(
buff[0:2], byteorder='little', signed=True) / 100
humidity = int.from_bytes(buff[2:3], byteorder='little')
voltage = int.from_bytes(buff[3:5], byteorder='little') / 1000
battery = round((voltage - 2) / (3 - 2) * 100, 2)
result.temperature = temp
result.humidity = humidity
result.voltage = voltage
result.battery = battery
print(result)
except Exception as e:
print(e)
time.sleep(1)
finally:
await client.disconnect()
# 執行主函數,開始藍牙連線和數據讀取
asyncio.run(main(Mac))
mac.ini.example
[Bluetooth]
Mac = A4:C1:38:AA:BB:CC
如果需要請事先用指令安裝需要的套件:
pip install bleak configparser