目前使用python+bleak撰寫藍芽ble讀取,但發現在裝置斷線時,會造成程序卡在讀取,並不會偵測到裝置離線而跳出。
以下是參考的bleak sample code,裝置確認連線後進行client.start_notify,倘若裝置在這當中斷線,程式便會卡死在這。
import asyncio
from bleak import BleakClient, discover
import sys
BLE_DEVICE_NAME = 'test' #
NORDIC_TX = "6e400000-b5a3-f393-e0a9-e50e24dcca9e"
class TXCallback:
def __init__(self, name):
self.name = name
def callback(self, sender, data):
print(f'收到 "{self.name}" 傳來:{data.decode()}')
async def select_device():
ble_list = []
devices = await discover()
print("搜尋裝置…")
for d in devices:
print(f"{d.name} @ {d.address}")
if d.name.find(BLE_DEVICE_NAME) != -1:
ble_list.append({'name': d.name, 'address': d.address})
print('發現目標:', d.name)
return ble_list
async def run():
ble_list = await select_device()
if len(ble_list) == 0:
print('找不到裝置')
loop.stop()
return
print("準備連線~")
for d in ble_list:
client = BleakClient(d['address'])
try:
await client.connect()
cb = TXCallback(d['name'])
await client.start_notify(
NORDIC_TX, cb.callback
)
except Exception as e:
print(e)
if __name__ == "__main__":
try:
loop = asyncio.get_event_loop()
asyncio.ensure_future(run())
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
print("關閉程式")
請問有無較好的處理方式?
更新:經測試,發現都卡在start_notify子程序當中,後來更換成 bluepy後已有解決,裝置斷線也能回傳disconnect。