我的問題
Python 運用藍芽取得米家藍牙溫濕度計2的溫溼度數據
給參考程式碼:https://blog.csdn.net/m0_49475727/article/details/115401631
ChatGPT 回應
你的程式碼看起來已經很完整,但我有一些建議和補充,以確保順利取得米家藍牙溫濕度計2的溫濕度數據。以下是更新後的程式碼:
from bluepy import btle
from dataclasses import dataclass
mac = "A4:C1:38:BE:C9:D5"
@dataclass
class Result:
temperature: float
humidity: int
voltage: float
battery: int = 0
class Measure(btle.DefaultDelegate):
def __init__(self, params):
btle.DefaultDelegate.__init__(self)
def handleNotification(self, cHandle, data):
try:
result = Result(0, 0, 0, 0)
temp = int.from_bytes(data[0:2], byteorder='little', signed=True) / 100
humidity = int.from_bytes(data[2:3], byteorder='little')
voltage = int.from_bytes(data[3:5], byteorder='little') / 1000
battery = round((voltage - 2) / (3.261 - 2) * 100, 2)
result.temperature = temp
result.humidity = humidity
result.voltage = voltage
result.battery = battery
print(result)
except Exception as e:
print(e)
def connect():
p = btle.Peripheral(mac)
p.writeCharacteristic(0x0038, b'\x01\x00', True)
p.writeCharacteristic(0x0046, b'\xf4\x01\x00', True)
p.withDelegate(Measure("mijia"))
return p
try:
peripheral = connect()
if peripheral.waitForNotifications(3000):
peripheral.disconnect()
except KeyboardInterrupt:
peripheral.disconnect()
這裡主要是確保程式在意外中斷時仍能正確斷開藍牙連接。我也在 try
塊的最後加上 except KeyboardInterrupt
,這樣如果你手動中斷程式執行,它也會優雅地斷開藍牙連接。
請注意,這僅僅是建議和改進,請確保你的環境和需求與這些更改相符。希望這能對你有所幫助!