Browse Source

- add no-receive-timeout after which the program will be exited (and will be restarted by systemd)
- minor improvements

FloKra 11 months ago
parent
commit
e41a650aab
3 changed files with 49 additions and 25 deletions
  1. 4 0
      CHANGELOG.txt
  2. 40 25
      cul2mqtt.py
  3. 5 0
      cul2mqtt_example.ini

+ 4 - 0
CHANGELOG.txt

@@ -1,3 +1,7 @@
+2023-05-30:
+ - add no-receive-timeout after which the program will be exited (and will be restarted by systemd)
+ - minor improvements
+
 2023-05-29: 
   - fix #1 - TypeError: cannot unpack non-iterable NoneType object
         add try/except to catch this rarely occuring error

+ 40 - 25
cul2mqtt.py

@@ -18,7 +18,7 @@ import os
 import re
 import configparser
 
-version = 0.3
+version = 0.4
 
 # Change working dir to the same dir as this script
 os.chdir(sys.path[0])
@@ -36,7 +36,7 @@ devdata = {}
 RXcodesToDevFunction_IT = {}
 RXcodesToDevFunction_RAW = {}
 InTopicsToDevIds = {}
-
+lastDataReceiveTime = time.time()
 
 # config vars
 deviceConfigFile = config['main'].get('devices_config_yml')
@@ -580,7 +580,11 @@ def encodeInterTechnoRX(itname, cmd):
         if debug: log_write("    unknown or invalid IT code '" + rx_code + "'")
 
 def cul_received(payload, source_cul):
-    global lastReceivedTime, lastReceivedMaxAge
+    global lastReceivedTime, lastReceivedMaxAge, lastDataReceiveTime
+    
+    lastDataReceiveTime = time.time()
+    if debug:
+        print("lastDataReceiveTime=" + str(lastDataReceiveTime))
     
     if payload[:2] == 'is': # msg is reply from CUL to raw send command
         pass
@@ -853,29 +857,40 @@ if mqtt_user is not None and mqtt_password is not None:
 mqttc.connect(mqtt_server, mqtt_port, 60)
 mqttc.loop_start()
 
-while True:
-    if receive_from_serial_cul:
-        serLine = ser.readline()
-        if len(serLine) > 0:
-            now = int(round(time.time() * 1000))
-            recvCmd = serLine.decode('ascii')
-            recvCmd = recvCmd.rstrip('\r\n')
+try:
+    while True:
+        if receive_from_serial_cul:
+            serLine = ser.readline()
+            if len(serLine) > 0:
+                now = int(round(time.time() * 1000))
+                recvCmd = serLine.decode('ascii')
+                recvCmd = recvCmd.rstrip('\r\n')
+                
+                #if debug:
+                #    print("lastSentCmd: " + lastSentCmd + ", lastSentCmdTime=" + str(lastSentCmdTime))
+                
+                if recvCmd == lastSentCmd and (now - lastSentCmdTime) < filterSelfSentIncomingTimeout:
+                    pass
+                else:
+                    if verbose:
+                        log_write("")
+                        log_write("UART-CUL RX: '" + recvCmd + "'")
+                    cul_received(recvCmd, "UART")
             
-            #if debug:
-            #    print("lastSentCmd: " + lastSentCmd + ", lastSentCmdTime=" + str(lastSentCmdTime))
+        #touch("/tmp/culagent_running")
+        
+        # check if receive timeout is exceeded 
+        # - if so there is possibly something wrong
+        # -> quit program (will be restarted by systemd)
+        if config['main'].get('dataReceiveTimeout') is not None:
+            if (time.time() - lastDataReceiveTime) >= float(config['main'].get('dataReceiveTimeout')):
+                print("WARNING: received no data from CUL for >" + str(config['main'].get('dataReceiveTimeout')) + "s -> something has gone wrong -> quitting program.")
+                quit()
+        #else:
+        #    print("dataReceiveTimeout not configured")
             
-            if recvCmd == lastSentCmd and (now - lastSentCmdTime) < filterSelfSentIncomingTimeout:
-                pass
-            else:
-                if verbose:
-                    log_write("")
-                    log_write("UART-CUL RX: '" + recvCmd + "'")
-                cul_received(recvCmd, "UART")
         
-    sleep(0.05)
-    
-##         #print "test"
-##         #touch("/tmp/culagent_running")
+        sleep(0.05)
 
-#except KeyboardInterrupt:
-#    print("\n")
+except KeyboardInterrupt:
+    print("\n")

+ 5 - 0
cul2mqtt_example.ini

@@ -9,6 +9,11 @@ lastReceivedMaxAge = 500
 
 lastSentMinInterval = 1500
 
+# quit program if nothing has been received for some time
+# so that systemd will restart it.
+# -> don't set too low if there is not much activity on CUL compatible RF in the location!
+dataReceiveTimeout = 180
+
 [cul]
 serialPort = /dev/serial/by-id/usb-1a86_USB2.0-Serial-if00-port0
 serialBaudrate = 38400