Commit a48c5746 authored by Peter-Bernd Otte's avatar Peter-Bernd Otte

Added logger and argparse and changed timeout

parent 1b2a0926
#!/usr/bin/python3
import serial
import sys
import time
from datetime import datetime
import paho.mqtt.client as paho
import json
import time
from datetime import datetime
import serial
import logging
import argparse
import sys
from crcTable import *
broker="localhost"
clientName = "enocean-eg"
logging.basicConfig(level=logging.WARNING,
format='%(asctime)-6s %(levelname)-8s %(message)s')
logger = logging.getLogger("enocean receiver")
parser = argparse.ArgumentParser(
description='MQTT EnOcean Receiver from serial devices.')
parser.add_argument("-v", "--verbosity",
help="increase output verbosity", default=0, action="count")
parser.add_argument("-b", "--mqtt-broker-host",
help="MQTT broker hostname. default=localhost", default="localhost")
parser.add_argument("-t", "--watchdog-timeout",
help="timeout in seconds for the watchdog. default=1h", default=100*60*60, type=int)
parser.add_argument("mqtt_client_name",
help="MQTT client name. Needs to be unique in the MQTT namespace, eg enocean-eg.", type=str)
parser.add_argument("serial_device_name",
help="Serial port used, eg /dev/ttyUSB0", type=str)
args = parser.parse_args()
logger.setLevel(logging.WARNING-(args.verbosity *
10 if args.verbosity <= 2 else 20))
Const_USBPort = str(sys.argv[1])
print ('Use the following Serial-Device:',Const_USBPort)
logger.info("MQTT client name: "+args.mqtt_client_name)
logger.info("Watchdog timeout (seconds): "+str(args.watchdog_timeout))
logger.info('Use the following Serial-Device: '+str(args.serial_device_name))
client= paho.Client(clientName)
print("connecting to broker ",broker)
client.connect(broker)
client.loop_start() #start loop to process received messages in separate thread
print ("MQTT Loop started.")
def on_connect(client, userdata, flags, rc):
if rc == 0:
logger.info("MQTT connected OK. Return code"+str(rc))
else:
logger.error("Bad connection. Return code="+str(rc))
def on_disconnect(client, userdata, rc):
if rc != 0:
logger.warning("Unexpected MQTT disconnection. Will auto-reconnect")
client = paho.Client(args.mqtt_client_name)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.enable_logger(logger) # info: https://www.eclipse.org/paho/clients/python/docs/#callbacks
logger.info("Conncting to broker "+args.mqtt_broker_host)
client.connect(args.mqtt_broker_host)
client.loop_start()
logger.info("MQTT loop started.")
def ESPCRC(fDaten):
global CRCWerteTabelle
u8CRC = 0
for x in fDaten:
u8CRC = CRCWerteTabelle[u8CRC ^ x]
return u8CRC
global CRCWerteTabelle
u8CRC = 0
for x in fDaten:
u8CRC = CRCWerteTabelle[u8CRC ^ x]
return u8CRC
ser = serial.Serial(Const_USBPort, 57600, timeout=0)
WatchDogCounter = 100*60*60 # ca. 60 mins
ser = serial.Serial(args.serial_device_name, 57600, timeout=0)
WatchDogCounter = args.watchdog_timeout
charSet = bytearray()
while (WatchDogCounter > 0):
while ser.inWaiting() > 0:
charSet += ser.read()
while len(charSet)>0 and charSet[0] != 0x55:
print("Deleted the following bytes, because they do not start with 0x55: (int)",charSet.pop(0))
if len(charSet) >= 8: #At least Sync-byte, Header (4byte), CRC8H, Data (min 1byte) and CRCD is available
pHeader, pCRCHeader = charSet[1:5], charSet[5]
if pCRCHeader == ESPCRC(pHeader): #CRC Header correct
pDataLength, pOptionalLength, pPaketType = pHeader[0]*256+pHeader[1], pHeader[2], pHeader[3]
if len(charSet) >= pDataLength+pOptionalLength+7: #Sync-byte, Header(4), CRC8H, CRCData | Paket fully received
pFullData = charSet[6:6+pDataLength+pOptionalLength]
pFullDataCRC = charSet[6+pDataLength+pOptionalLength]
if ESPCRC(pFullData) == pFullDataCRC: #Data CRC ok
WatchDogCounter = 100*60*10 #ca 10 minutes
t = datetime.now()
t = time.mktime(t.timetuple()) + t.microsecond / 1E6
pData, pOptData = charSet[6:6+pDataLength], charSet[6+pDataLength:6+pDataLength+pOptionalLength]
print("pPaketType", pPaketType, "Data",pData,"OptData",pOptData)
# list() converts bytearray into array of int
t = datetime.now()
t = time.mktime(t.timetuple()) + t.microsecond / 1E6
client.publish("homie/"+clientName+"/enocean-messages", json.dumps({"type":pPaketType, "data":list(pData), "optData":list(pOptData), "time":t}), qos=1)
else:
print("Data CRC NOT ok")
#Delete the processed data and propare for next paket to receive
charSet = charSet[pDataLength+pOptionalLength+7:]
time.sleep(.01)
WatchDogCounter -= 1
while ser.inWaiting() > 0:
charSet += ser.read()
while len(charSet) > 0 and charSet[0] != 0x55:
print("Deleted the following bytes, because they do not start with 0x55: (int)", charSet.pop(0))
if len(charSet) >= 8: # At least Sync-byte, Header (4byte), CRC8H, Data (min 1byte) and CRCD is available
pHeader, pCRCHeader = charSet[1:5], charSet[5]
if pCRCHeader == ESPCRC(pHeader): # CRC Header correct
pDataLength, pOptionalLength, pPaketType = pHeader[0] * \
256+pHeader[1], pHeader[2], pHeader[3]
# Sync-byte, Header(4), CRC8H, CRCData | Paket fully received
if len(charSet) >= pDataLength+pOptionalLength+7:
pFullData = charSet[6:6+pDataLength+pOptionalLength]
pFullDataCRC = charSet[6+pDataLength+pOptionalLength]
if ESPCRC(pFullData) == pFullDataCRC: # Data CRC ok
WatchDogCounter = args.watchdog_timeout
t = datetime.now()
t = time.mktime(t.timetuple()) + t.microsecond / 1E6
pData, pOptData = charSet[6:6+pDataLength], charSet[6 +
pDataLength:6+pDataLength+pOptionalLength]
print("pPaketType", pPaketType, "Data",
pData, "OptData", pOptData)
# list() converts bytearray into array of int
t = datetime.now()
t = time.mktime(t.timetuple()) + t.microsecond / 1E6
client.publish("homie/"+args.mqtt_client_name)+"/enocean-messages", json.dumps(
{"type": pPaketType, "data": list(pData), "optData": list(pOptData), "time": t}), qos = 1)
else:
print("Data CRC NOT ok")
# Delete the processed data and propare for next paket to receive
charSet=charSet[pDataLength+pOptionalLength+7:]
time.sleep(.01)
WatchDogCounter -= 1
ser.close()
client.disconnect()
client.loop_stop()
logger.info("Program stopped.")
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment