Commit 8c4431ef authored by Peter-Bernd Otte's avatar Peter-Bernd Otte

Changed brightness from 0..1

Added logger, argparse
parent 2efa344a
......@@ -8,15 +8,26 @@ from FSRData import *
import paho.mqtt.client as paho
import json
import re
import logging
import argparse
debug = False
broker="dom"
MQTTClientName = "fsr-ww"
format = "%(asctime)-9s %(name)-6s %(levelname)-8s %(message)s"
logging.basicConfig(format=format, datefmt="%H:%M:%S")
logger = logging.getLogger(MQTTClientName)
parser = argparse.ArgumentParser(description='Workload distributor for trivial parallelism.')
parser.add_argument("-v", "--verbosity", help="increase output verbosity", default=0, action="count")
parser.add_argument("SerialDeviceName", help="Serial port used, eg /dev/ttyUSB0")
args = parser.parse_args()
logger.setLevel(logging.WARNING-(args.verbosity*10 if args.verbosity <=2 else 20) )
broker="dom"
RelaisOffset = 0x01000000 #Eltako Relais should be programmed to react on addresses like 0x01000000 + RelaisID
Const_USBPort = str(sys.argv[1])
print ('Use the following Serial-Device:',Const_USBPort)
ser = serial.Serial(Const_USBPort, 57600, timeout=0)
logger.info('Use the following Serial-Device: '+str(args.SerialDeviceName) )
ser = serial.Serial(args.SerialDeviceName, 57600, timeout=0)
WatchDogCounter = 20*60*10 # ca. 10 mins
AskRelaisID = 0
......@@ -30,10 +41,10 @@ def AskRelais(relaidid, count=1):
for i in range(count):
queue.append(r)
def SwitchFSR14(relaisid,brightness):
def SwitchFSR14(relaisid,brightness): #brightness from 0 to 100
global queue
global relaisStatus
relaisStatus[relaisid]["setv"] = brightness
relaisStatus[relaisid]["setv"] = brightness/100
b = 9 if brightness>0 else 8 #9 switches the output on, 8=off
r = FSRData(id=RelaisOffset+relaisid, data=0x01000000+b)
queue.insert(0,r)
......@@ -41,7 +52,7 @@ def SwitchFSR14(relaisid,brightness):
def SwitchFUD14(relaisid, brightness): #brightness 0..100
global queue
global relaisStatus
relaisStatus[relaisid]["setv"] = brightness
relaisStatus[relaisid]["setv"] = brightness/100
b = (brightness<<16)+9 if brightness in range(101) else 8
dimspeed = 1 #dim speed: 1 fastest, 255=slowest, 0=set at device
r = FSRData(id=RelaisOffset+relaisid, data=0x02000000+ b+ (dimspeed<<8) ) #data byte 1 = dim speed
......@@ -53,46 +64,57 @@ def on_message(client, userdata, message):
m = message.payload.decode("utf-8")
j = json.loads(m)
if debug: print ("Topic:",message.topic,"JSON",j)
logger.info("Topic: "+message.topic+" JSON:"+str(j))
msplit = re.split("/", message.topic)
if len(msplit) == 4 and msplit[3].lower() == "set" and msplit[2].isdigit() and int(msplit[2]) in range(128):
relaisID = int(msplit[2])
b = int(j) #brightness
if debug: print("RelaisID",relaisID,"b",b)
b = float(j) #brightness from 0..1
if (b<0 or b>1): b=0
logger.debug("RelaisID: "+str(relaisID)+" b: "+str(b) )
if relaisID in relaisStatus:
if relaisStatus[relaisID]["type"] == "FUD14":
if debug: print("Switch FUD", relaisID)
SwitchFUD14(relaisID, b)
logger.debug("Switch FUD ID "+str(relaisID))
SwitchFUD14(relaisID, round(b*100))
AskRelais(relaisID, count=2) #necessary to check more often because of dim speed
elif relaisStatus[relaisID]["type"] == "FSR14":
if debug: print("Switching FSR14 ID",msplit[2])
SwitchFSR14(relaisID, b)
logger.debug("Switching FSR14 ID "+str(relaisID))
SwitchFSR14(relaisID, round(b*100))
else:
print("Relais Type not supported.")
logger.error("Relais Type not supported.")
AskRelais(relaisID)
else:
print("Relais Type not yet known for ID",relaisID)
logger.error("Relais Type not yet known for ID "+str(relaisID))
def on_connect(client, userdata, flags, rc):
if rc==0:
logger.info("MQTT connected OK. Return code "+str(rc) )
client.subscribe("homie/"+MQTTClientName+"/+/set")
logger.debug("MQTT: Subscribed to all topics")
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(MQTTClientName)
client.on_message=on_message
print("connecting to broker ",broker)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
logger.info("connecting to broker: "+broker)
client.connect(broker)
client.subscribe("homie/"+MQTTClientName+"/+/set")
client.loop_start() #start loop to process received messages in separate thread
print ("MQTT Loop started.")
logger.debug("MQTT Loop started.")
def processFSRType(time, tr, requestedHseq, requestedType, typeName, brightness): #tr needs to be of FSRClass type
global client
def processFSRType(time, tr, requestedHseq, requestedType, typeName, brightness): #tr needs to be of FSRClass type, brightness from 0..100
global relaisStatus
global MQTTClientName
global debug
brightness = brightness/100
if tr.hseq==requestedHseq and tr.type == requestedType:
tempSetv = relaisStatus[tr.id]["setv"] if tr.id in relaisStatus else brightness #save the old setv value
if (tr.id in relaisStatus and relaisStatus[tr.id]["v"] != brightness) or (tr.id not in relaisStatus):
relaisStatus[tr.id] = {"type":typeName, "v": brightness, "time":time, "setv": tempSetv}
if debug: print("Set Relais", tr.id, "relaisStatus", relaisStatus[tr.id])
logger.info("Set Relais "+str(tr.id)+" relaisStatus "+str(relaisStatus[tr.id]) )
client.publish("homie/"+MQTTClientName+"/"+str(tr.id), json.dumps(relaisStatus[tr.id], sort_keys=True), qos=1, retain=True)
charSet = bytearray()
......@@ -102,24 +124,25 @@ while (WatchDogCounter > 0):
AskRelais(AskRelaisID)
ts = queue.pop(0)
if debug: print("Send",":".join("{:02x}".format(x) for x in ts.getByteArray() ))
tempStr = ":".join("{:02x}".format(x) for x in ts.getByteArray() )
logger.debug("Send "+tempStr)
ser.write(ts.getByteArray())
time.sleep(.05)
while ser.inWaiting() > 0:
charSet += ser.read()
while len(charSet)>1 and charSet[0] != 0xa5 and charSet[1] != 0x5a:
print("Deleted the following byte, because they do not start with 0xa5 0x5a: (int)",charSet.pop(0))
logger.warning("Deleted the following byte, because it does not start with 0xa5 0x5a: (int) "+str(charSet.pop(0)))
if len(charSet) >= 14:
WatchDogCounter = 20*60*10 # ca. 10 mins
tr = FSRData(charSet[:14])
if debug: print("Incoming:", len(charSet), "Data 0x{:08x}".format(tr.data), charSet)
logger.debug("Incoming: "+str(len(charSet))+" Data 0x{:08x}".format(tr.data)+" "+str(charSet) )
if tr.correctCRC():
t = datetime.now()
t = time.mktime(t.timetuple()) + t.microsecond / 1E6
processFSRType(t, tr, 139, 5, "FSR14", 100 if (tr.data>>24)==0x70 else 0 )
processFSRType(t, tr, 139, 7, "FUD14", (tr.data>>16)&0xff )
client.publish("homie/"+MQTTClientName+"/messages", json.dumps({"data":list(tr.getByteArray()), "time":t}, sort_keys=True), qos=1)
# client.publish("homie/"+MQTTClientName+"/messages", json.dumps({"data":list(tr.getByteArray()), "time":t}, sort_keys=True), qos=1)
charSet = charSet[14:]
# time.sleep(1)
......
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