Răsfoiți Sursa

fix unhandled exceptions on mqtt disconnect

subDesTagesMitExtraKaese 1 an în urmă
părinte
comite
b31cd92caf
2 a modificat fișierele cu 15 adăugiri și 11 ștergeri
  1. 9 3
      bleclient.py
  2. 6 8
      main.py

+ 9 - 3
bleclient.py

@@ -14,7 +14,7 @@ class BleClient:
 
     def __init__(self, mac_address: str):
         self.client = BleakClient(mac_address)
-        self.on_details_received = lambda v: print(v)  # Callback function to handle received details
+        self.details_queue = asyncio.Queue()  # Queue to store the received details
 
     async def __aenter__(self):
         await self.client.connect()  # Connect to the BLE device
@@ -55,7 +55,7 @@ class BleClient:
             return
         if len(self.buffer) == 91:
             response = BleClient.parse_details_response(self.buffer)  # Parse the details response from the buffer
-            await self.on_details_received(response)  # Call the callback function with the parsed response
+            self.details_queue.put_nowait(response)  # Add the parsed response to the queue
             self.buffer = bytearray()
         if len(self.buffer) >= 91:
             print(f"received too many bytes ({len(self.buffer)})")
@@ -78,7 +78,13 @@ class BleClient:
         return "".join(map(chr, device_name))
 
     async def request_details(self):
-        await self.write(0xFE043030002bbf1a)  # Send a request for details to the BLE device
+        self.details_queue = asyncio.Queue()  # Clear the queue
+        i = 0
+        while self.details_queue.empty() and i < 10:
+            i += 1
+            await self.write(0xFE043030002bbf1a)  # Send a request for details to the BLE device
+            await asyncio.sleep(0.1)  # Wait for the response to be received
+        return await self.details_queue.get()  # Return the first item in the queue
 
     @staticmethod
     def solar_panel_charge_state(v: int):

+ 6 - 8
main.py

@@ -75,18 +75,16 @@ async def main(address, host, port, username, password):
             try:
                 async with aiomqtt.Client(hostname=host, port=port, username=username, password=password) as client:
                     print(f"Connecting to MQTT broker at {host}:{port}")
-                    async def details_handler(details: dict[str, any]):
-                        if details:
-                            print(f"Battery: {details['battery_percentage']}% ({details['battery_voltage']}V)")
-                            await mqtt_publish(details, client)
-                        else:
-                            print("No values recieved")
                     while True:
                         try:
                             async with BleClient(address) as mppt:
-                                mppt.on_details_received = details_handler
                                 while True:
-                                    await mppt.request_details()
+                                    details = await mppt.request_details()
+                                    if details:
+                                        print(f"Battery: {details['battery_percentage']}% ({details['battery_voltage']}V)")
+                                        await mqtt_publish(details, client)
+                                    else:
+                                        print("No values recieved")
                                     await asyncio.sleep(20.0)
 
                         except BleakDeviceNotFoundError: