From 06453f90e1ad4db5538acf65c6adc9b7437a2a5d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= <oddstr13@openshell.no>
Date: Tue, 2 Nov 2021 23:48:06 +0100
Subject: [PATCH] Reconnect if the BLE connection dies

---
 solar_ble.py | 43 ++++++++++++++++++-------------------------
 1 file changed, 18 insertions(+), 25 deletions(-)

diff --git a/solar_ble.py b/solar_ble.py
index 6b98fab..bfded7c 100755
--- a/solar_ble.py
+++ b/solar_ble.py
@@ -230,40 +230,33 @@ def write(fh, data):
 dlgt = Delegate()
 
 prev = time.time() - INTERVAL
-with btle.Peripheral(MAC).withDelegate(dlgt) as dev:
 
-    # for svc in dev.services:
-    #    print(svc, svc.uuid)
 
-    #    print(dir(dev))
+while True:
+    try:
+        with btle.Peripheral(MAC).withDelegate(dlgt) as dev:
 
-    #    wd = dev.getServiceByUUID(write_service)
+            wd = dev.getCharacteristics(uuid=write_device)[0]
 
-    #    print(wd)
+            while True:
+                dev.waitForNotifications(1)
 
-    wd = dev.getCharacteristics(uuid=write_device)[0]
-    # print(cs)
-    # print(dir(cs))
-    # print(wd.write(b'\xf0\x03\x00\x0c\x00\x08\x91\xd1'))
+                now = time.time()
+                diff = now - prev
+                if diff >= INTERVAL:
+                    prev += INTERVAL
 
-    #    rd = dev.getCharacteristics(uuid=read_device)[0]
-    #    print(rd.read())
+                    write(wd, CMD_GET_PANEL_STATUS)
+                    dev.waitForNotifications(1)
 
-    while True:
-        dev.waitForNotifications(1)
-
-        now = time.time()
-        diff = now - prev
-        if diff >= INTERVAL:
-            prev += INTERVAL
-
-            write(wd, CMD_GET_PANEL_STATUS)
-            dev.waitForNotifications(1)
-
-            write(wd, CMD_GET_BATTERY_STATE)
-            dev.waitForNotifications(1)
+                    write(wd, CMD_GET_BATTERY_STATE)
+                    dev.waitForNotifications(1)
 
             # if STATUS.get('load_enabled'):
             #    write(wd, CMD_DISABLE_LOAD)
             # else:
             #    write(wd, CMD_ENABLE_LOAD)
+
+    except btle.BTLEDisconnectError:
+        print(datetime.datetime.utcnow().isoformat(" "), "ERROR: Disconnected")
+        time.sleep(1)