#!/usr/bin/python3 -u # import serial from time import sleep import os import sys import paho.mqtt.client as mqtt import json # --- CONFIGURATION --- # timeout in s to end script when nothing is received (will be restarted by systemd then) # must be higher than getStatusInterval quitOnNoReceiveTimeout = 75 # status file - on ramdrive (/tmp on RasPi by default) # is "touched" every time a serial message comes in so that working communication can be monitored easily statusFile = '/tmp/ioext_running' # serial port config serialPort = '/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0' serialBaud = 57600 serialTimeout = 1 # should be 1 as above interval/timeout relies on it # MQTT config mqtt_server = "mqtt.lan" mqtt_port = 1883 mqtt_user = "user" mqtt_password = "password" mqtt_base_topic = "T5/HomeSvrIOExt" mqtt_topic_tuerkontakt = "T5/Wohnungstuer/Tuerkontakt" mqtt_topic_pir1 = "T5/VZ/PIR1" mqtt_topic_pir2 = "T5/VZ/PIR2" mqtt_topic_out_temp = "T5/Abstr/Sensors/temp" mqtt_topic_out_hum = "T5/Abstr/Sensors/hum" # --- END CONFIGURATION --- # --- GLOBAL VARS --- noReceiveCount = 0 # increase everytime the serial readline times out (1s timeout) #getStatusCount = 0 # used as heartbeat, get status every 30s verbose = False debug = False quiet = True lastState_tk = None lastState_pir1 = None lastState_pir2 = None # --- END GLOBAL VARS --- if len(sys.argv) >= 2: if sys.argv[1] == "-q": verbose = False debug = False quiet = True #print("VERBOSE=ON") elif sys.argv[1] == "-v": verbose = True debug = False quiet = False #print("VERBOSE=ON") elif sys.argv[1] == "-d": verbose = True quiet = False debug = True #print("DEBUG=ON") def on_connect(client, userdata, flags, rc): if not quiet: print("MQTT connected with result code " + str(rc)) #client.subscribe(mqtt_topic_cmd) #def on_message(client, userdata, msg): # if msg.topic == mqtt_topic_cmd: # payload = msg.payload.decode('ascii') # if payload == "status" or payload == "get conf" or payload == "clear" or payload == "open door" or payload.startswith("set prof ") or payload.startswith("set conf "): # if verbose: # print("serCmd: " + payload) # serCmd = payload + '\n' # ser.write(serCmd.encode('ascii')) # elif verbose: # print("unknown command:", payload) def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) mqttc = mqtt.Client() mqttc.on_connect = on_connect #mqttc.on_disconnect = on_disconnect #mqttc.on_message = on_message mqttc.username_pw_set(mqtt_user, mqtt_password) mqttc.connect(mqtt_server, mqtt_port, 60) mqttc.loop_start() ser = serial.Serial(port=serialPort, baudrate = serialBaud, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=serialTimeout) try: while True: ##ser.flushInput() ## attention truncates incoming strings if there is little time between them #read buffer until cr/lf serLine = ser.readline().strip() # catch exception on invalid char coming in: UnicodeDecodeError: 'ascii' codec can't decode byte 0xf4 in position 6: ordinal not in range(128) try: serLine = serLine.decode('ascii') except: serLine = "" # if there came something in... if(serLine): noReceiveCount = 0 touch(statusFile) #serLine = serLine.strip('\'') #serLine = serLine.strip('\r') #serLine = serLine.strip('\n') if verbose: print ('RX: ' + repr(serLine)) #Echo the serial buffer bytes up to the CRLF back to screen mqttc.publish(mqtt_base_topic + "/RX", str(serLine), qos=0, retain=False) # Tuerkontakt if serLine.startswith('P2='): newState = None if serLine == "P2=L": newState = "OFF" elif serLine == "P2=H": newState = "ON" if newState is not None and lastState_tk != newState: lastState_tk = newState mqttc.publish(mqtt_topic_tuerkontakt, newState, qos=0, retain=False) # PIR #1 if serLine.startswith('P3='): newState = None if serLine == "P3=L": newState = "OFF" elif serLine == "P3=H": newState = "ON" if newState is not None and lastState_pir1 != newState: lastState_pir1 = newState mqttc.publish(mqtt_topic_pir1, newState, qos=0, retain=False) # PIR #2 if serLine.startswith('P4='): newState = None if serLine == "P4=L": newState = "OFF" elif serLine == "P4=H": newState = "ON" if newState is not None and lastState_pir2 != newState: lastState_pir2 = newState mqttc.publish(mqtt_topic_pir2, newState, qos=0, retain=False) # DHT TH sensor # {"T":26.60,"H":36} if serLine.startswith('{"T":'): th = json.loads(serLine) t = round(float(th["T"]), 1) h = int(th["H"]) if t >= -20 and t <= 50: mqttc.publish(mqtt_topic_out_temp, str(t), qos=0, retain=False) if h >= 0 and h <= 100: mqttc.publish(mqtt_topic_out_hum, str(h), qos=0, retain=False) ## publish MQTT messages #if serLine.startswith('EVENT_'): # mqttc.publish(mqtt_topic_event, serLine, qos=0, retain=False) # #os.system(os.path.dirname(os.path.realpath(__file__))+'/event_top5_klingel.py') # #elif serLine.startswith('OK'): # mqttc.publish(mqtt_topic_cmdresponse, serLine, qos=0, retain=False) # #elif serLine.startswith('{"'): # mqttc.publish(mqtt_topic_cmdresponse, serLine, qos=0, retain=False) # #os.system(os.path.dirname(os.path.realpath(__file__))+'/event_top5_klingel.py') # nothing came in this time... else: noReceiveCount += 1 if debug: print("noReceiveCount=" + str(noReceiveCount)) # quit script if nothing has been received for some time - will be restarted by systemd if noReceiveCount >= quitOnNoReceiveTimeout: quit() ## get status every [getStatusInterval] seconds #getStatusCount += 1 #if getStatusCount >= getStatusInterval: # getStatusCount = 0 # serCmd = 'status\n' # ser.write(serCmd.encode('ascii')) #if debug: # print("getStatusCount=" + str(getStatusCount)) except KeyboardInterrupt: print('\n')