|
|
@@ -46,32 +46,43 @@ def notification_handler(characteristic: BleakGATTCharacteristic, data: bytearra
|
|
|
|
|
|
async def ble_task():
|
|
|
global outdoorConnected
|
|
|
+ client = None
|
|
|
|
|
|
- while True:
|
|
|
- device = await BleakScanner.find_device_by_name(outdoorName)
|
|
|
-
|
|
|
- if device is None:
|
|
|
- outdoorConnected = 0
|
|
|
-
|
|
|
- print("no device found, wait then scan again")
|
|
|
- await asyncio.sleep(10)
|
|
|
- continue
|
|
|
-
|
|
|
- try:
|
|
|
- async with BleakClient(device) as client:
|
|
|
- outdoorConnected = 1
|
|
|
- print(f"connected to {outdoorName}")
|
|
|
-
|
|
|
- await client.start_notify(TEMP_UUID, notification_handler)
|
|
|
- await client.start_notify(PRESSURE_UUID, notification_handler)
|
|
|
- await client.start_notify(HUMIDITY_UUID, notification_handler)
|
|
|
- await client.start_notify(ALTITUDE_UUID, notification_handler)
|
|
|
-
|
|
|
- while (client.is_connected):
|
|
|
- await asyncio.sleep(1)
|
|
|
- except Exception:
|
|
|
- outdoorConnected = 0
|
|
|
- print("exception while connecting or getting data")
|
|
|
+ try:
|
|
|
+ while True:
|
|
|
+ device = await BleakScanner.find_device_by_name(outdoorName)
|
|
|
+
|
|
|
+ if device is None:
|
|
|
+ outdoorConnected = 0
|
|
|
+ print("No device found, wait then scan again")
|
|
|
+ await asyncio.sleep(10)
|
|
|
+ continue
|
|
|
+
|
|
|
+ try:
|
|
|
+ async with BleakClient(device) as client:
|
|
|
+ outdoorConnected = 1
|
|
|
+ print(f"Connected to {outdoorName}")
|
|
|
+
|
|
|
+ await client.start_notify(TEMP_UUID, notification_handler)
|
|
|
+ await client.start_notify(PRESSURE_UUID, notification_handler)
|
|
|
+ await client.start_notify(HUMIDITY_UUID, notification_handler)
|
|
|
+ await client.start_notify(ALTITUDE_UUID, notification_handler)
|
|
|
+
|
|
|
+ while client.is_connected:
|
|
|
+ await asyncio.sleep(1)
|
|
|
+
|
|
|
+ except Exception as e:
|
|
|
+ print(f"Connection lost or error: {e}")
|
|
|
+ finally:
|
|
|
+ outdoorConnected = 0
|
|
|
+ print("Cleaning up connection state...")
|
|
|
+
|
|
|
+ except asyncio.CancelledError:
|
|
|
+ print("BLE task is being cancelled...")
|
|
|
+ if client and client.is_connected:
|
|
|
+ await client.disconnect()
|
|
|
+ outdoorConnected = 0
|
|
|
+ raise
|
|
|
|
|
|
async def sensor_task():
|
|
|
global indoorValues
|