From ff2db22589672d4b8b4ee3591fdd5ad9cd42a726 Mon Sep 17 00:00:00 2001
From: arnaud <arnaud.watlet@umons.ac.be>
Date: Fri, 30 Sep 2022 16:43:39 +0200
Subject: [PATCH] fixing connection to broker on reboot

---
 mqtt_interface.py | 12 +++++++++++-
 mqtt_logger.py    |  5 ++++-
 ohmpi.py          |  7 +++++--
 run.sh            |  7 ++++---
 4 files changed, 24 insertions(+), 7 deletions(-)

diff --git a/mqtt_interface.py b/mqtt_interface.py
index 916a964c..e9005264 100644
--- a/mqtt_interface.py
+++ b/mqtt_interface.py
@@ -20,8 +20,18 @@ def on_message(client, userdata, message):
 
 
 mqtt_client = mqtt.Client(f'ohmpi_{OHMPI_CONFIG["id"]}_listener', clean_session=False)  # create new instance
+print('now this')
 print('connecting to broker')
-mqtt_client.connect(MQTT_CONTROL_CONFIG['hostname'])
+trials = 0
+trials_max = 10
+while trials < trials_max:
+    try:
+        mqtt_client.connect(MQTT_CONTROL_CONFIG['hostname'])
+        trials = trials_max
+    except:
+        print('new trial')
+        time.sleep(2)
+        trials+=1
 print('Subscribing to topic', MQTT_CONTROL_CONFIG['ctrl_topic'])
 mqtt_client.subscribe(MQTT_CONTROL_CONFIG['ctrl_topic'], MQTT_CONTROL_CONFIG['qos'])
 mqtt_client.on_message = on_message
diff --git a/mqtt_logger.py b/mqtt_logger.py
index 10cbbc9d..73106af1 100644
--- a/mqtt_logger.py
+++ b/mqtt_logger.py
@@ -51,8 +51,11 @@ class MQTTHandler(logging.Handler):
         cleanly.
         """
         msg = self.format(record)
-        publish.single(self.topic, msg, self.qos, self.retain,
+        try:
+            publish.single(self.topic, msg, self.qos, self.retain,
                        hostname=self.hostname, port=self.port,
                        client_id=self.client_id, keepalive=self.keepalive,
                        will=self.will, auth=self.auth, tls=self.tls,
                        protocol=self.protocol, transport=self.transport)
+        except Exception as e:
+            print(e)
diff --git a/ohmpi.py b/ohmpi.py
index d5e812b4..ff8ebb59 100644
--- a/ohmpi.py
+++ b/ohmpi.py
@@ -709,8 +709,11 @@ class OhmPi(object):
                     self.exec_logger.debug(reply)
                     reply = bytes(reply, 'utf-8')
                     socket.send(reply)
-            except zmq.Again:
-                time.sleep(.1)
+            except zmq.ZMQError as e:
+                if e.errno == zmq.EAGAIN:
+                    pass # no message was ready (yet!)
+                else:
+                    traceback.print_exc()
 
     def measure(self, cmd_id=None):
         """Run the sequence in a separate thread. Can be stopped by 'OhmPi.stop()'.
diff --git a/run.sh b/run.sh
index 277fafc2..14ddf4c1 100755
--- a/run.sh
+++ b/run.sh
@@ -1,4 +1,5 @@
 #!bin/bash
-
-source ./ohmpy/bin/activate
-python ohmpi.py
+cd /home/pi/OhmPi
+source "/home/pi/OhmPi/ohmpy/bin/activate"
+python --version
+python /home/pi/OhmPi/ohmpi.py
-- 
GitLab