Commit 1fa9fe9b authored by Peter-Bernd Otte's avatar Peter-Bernd Otte

Update python/enocean-concentrator/config.yml,...

Update python/enocean-concentrator/config.yml, python/enocean-concentrator/enocean-concentrator.py files
parent cda85dc3
12345678:
description: Test PTM215
ip: '0x12345678'
topic: room/switch/topmostswitch
type: PTM215
1234567a:
description: Test PTM215
ip: '0x1234567a'
topic: room/switch/bottommostswitch
type: PTM215
\ No newline at end of file
......@@ -3,30 +3,54 @@
import paho.mqtt.client as paho
import json
import time
from datetime import datetime
import re
import logging
import logging, argparse
import sys
import yaml # pip3 install pyyaml
broker="localhost"
clientname = "enocean-eg"
logging.basicConfig(level=logging.WARNING, format='%(asctime)-6s %(levelname)-8s %(message)s')
logger = logging.getLogger("Concentrator")
logging.basicConfig(level=logging.WARNING, format='%(asctime)-15s %(name)-6s %(levelname)-8s %(message)s')
logger = logging.getLogger(clientname)
logger.setLevel(logging.DEBUG)
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("-c", "--config-file", help="provide filepath for YAML configuration file", default="config.yml", type=str)
parser.add_argument("-b", "--mqtt-broker-host", help="MQTT broker hostname", default="locahlhost")
parser.add_argument("mqtt_client_name", help="MQTT client name. Needs to be unique in the MQTT namespace, eg enocean-eg-concentrator.", type=str)
args = parser.parse_args()
logger.setLevel(logging.WARNING-(args.verbosity*10 if args.verbosity <=2 else 20) )
supportedSensors = {"TFBHSB55":"TippFunk Bewegungsmelder", "FBH63":"Bewegungsmelder", "PTM215":"Taster",
"FHF":"Funk Fenstergriff", "FTKE":"Hebel Sensor", "FTK":"Solar Reed Sensor", "FRW":"Funk Rauch-Sensor",
"FSM60B":"Funk Wasser Sensor" }
with open("enoceansenders.json") as f:
data = json.load(f)
#with open("config.json") as f:
# data = json.load(f)
if not os.path.exists(args.config_file):
logger.error("Config file "+args.config_file+" not found.")
sys.exit(2)
with open(args.config_file, 'r') as ymlfile:
data = yaml.full_load(ymlfile) # see https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation
data = {k.lower(): v for k, v in data.items()} #make all dict keys lowercase
for k,v in data.items():
if v['type'] not in supportedSensors:
logger.error("In senders file, type: "+v['type']+" is not supported.")
sys.exit(1)
receiverlast = {} # save this message as the last from this enocean receiver
def on_connect(client, userdata, flags, rc):
if rc==0:
print("MQTT connected OK. Return code", rc)
client.subscribe("homie/+/enocean-messages")
print("MQTT: Subscribed to all topics")
else:
print("Bad connection. Return code=",rc)
def on_disconnect(client, userdata, rc):
if rc != 0:
print ("Unexpected MQTT disconnection. Will auto-reconnect")
receiverlast = [] # save this message as the last from this enocean receiver
senderlast = {} #last Message from enocean device
def on_message(client, userdata, message):
global receiverlast
......@@ -39,11 +63,26 @@ def on_message(client, userdata, message):
splittopic = re.split("/", message.topic)
logger.info("EnOcean Sender: "+splittopic[1])
receiverlast[splittopic[1]] = j # save this message as the last from this enocean receiver
#update the list of received messages during the last few 100ms
t = datetime.now()
t = time.mktime(t.timetuple()) + t.microsecond / 1E6
receiverlast = [x for x in receiverlast if t-x['time'] < 0.2] # delete all messages older than a certain period
receiverlast.append({**j, 'receiver':splittopic[1]}) # save this message as the last from this enocean receiver
#check, whether the same paket has already been received
for x in receiverlast:
if splittopic[1]!=x['receiver'] and x['type']==j['type'] and x['data']==j["data"]:
logger.debug("The paket has already been received by "+x['receiver'])
return
#received packet the first time received, process it
if j['type'] == 1:
if j["data"][0] in (0xf6, 0xd5, 0xa5): #Senders ROrg: 1BS vom PTM215, 1BS vom FTK, 4BS
s = "".join('{:02x}'.format(x) for x in j['data'][-5:-1]) #Enocean Device ID
if s not in data:
logger.warning("IP 0x"+s+" not in senders file. Cant process this event.")
return
logger.debug(data[s])
retain = True if (data[s]['type'] in ("TFBHSB55", "FBH63", "FSM60B", "FHF", "FTKE", "FTK", "FRW")) else False
dataToSend = {'time':j['time'], 'rssi':j["optData"][-2], 'type':data[s]['type']} #signal strength
......@@ -77,7 +116,7 @@ def on_message(client, userdata, message):
dataToSend['v'] = 0 if j['data'][1]==0xf0 else 1 if j['data'][1]==0xd0 else 2 #LUT explanation see next dict
LUT = {0xf0:"closed", 0xc0: "open", 0xe0: "open", 0xd0: "tilted"}
if j['data'][1] in LUT: dataToSend['descr'] = LUT[j['data'][1]]
elif data[s]['type'] == "FTKE":
elif data[s]['type'] == "FTKE": #handle bar
dataToSend['v'] = 0 if j['data'][1] == 0xf0 else 1 #returns 0 if closed(=0xf0) otherwiese 1 (tilted=0xe0)
elif data[s]['type'] == "FTK": #magnet sensor
dataToSend['v'] = 0 if j['data'][1]==9 else 1 #returns 0 if closed(=0x9) otherwise 1 (tilted=0x8)
......@@ -94,12 +133,12 @@ def on_message(client, userdata, message):
senderlast[s] = j #to use the value next time, eg. when the push button is released
client=paho.Client(clientname+"-concentrator")
client=paho.Client(args.mqtt_client_name)
client.on_message=on_message
logger.info("Conncting to broker "+broker)
client.connect(broker)
client.subscribe("homie/"+clientname+"/messages")
client.on_connect = on_connect
client.on_disconnect = on_disconnect
logger.info("Conncting to broker "+args.mqtt_broker_host)
client.connect(args.mqtt_broker_host)
client.loop_start()
logger.info("MQTT loop started.")
......@@ -108,4 +147,4 @@ while True:
client.disconnect()
client.loop_stop()
logger.info("Program stopped.")
logger.info("Program stopped.")
\ No newline at end of file
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