Commit 95b8e0a3 authored by Peter-Bernd Otte's avatar Peter-Bernd Otte

First version of redirector

parent db116557
#!/usr/bin/python
import json
import time
from datetime import datetime
import paho.mqtt.client as paho
import os
import numbers
import parse
from urllib.request import urlopen
import traceback
broker="localhost"
mlast = {}
def on_connect(client, userdata, flags, rc):
if rc==0:
print("MQTT connected OK. Return code", rc)
client.subscribe("homie/fsr-og/zigbee/paulineFenster")
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")
def on_message(client, userdata, message):
try:
global mlast
t = datetime.now()
t = time.mktime(t.timetuple()) + t.microsecond / 1E6
m = message.payload.decode("utf-8")
# print("received:",str(m), message.topic)
# the lambda in loads is for converting the object name into a int, if appropiate
j = json.loads(m, object_hook=lambda d: {int(k) if k.lstrip('-').isdigit() else k: v for k, v in d.items()})
print ("Topic:",message.topic,"JSON",j)
if type(j) is not dict: #anpassen, falls es keine Zeitinfo hat
j={'v':j,'time':t}
if ('time' not in j) or (t-j['time'] > 10): # corrects the time of too much in the future
j['time'] = t
mlast[message.topic] = j
#homie/fsr-og/zigbee/reed1 {"battery":100,"voltage":3005,"contact":true,"linkquality":31}
#{"type": "FTK", "rssi": 92, "v": 1, "time": 1576484631.811821}
mydict={}
mydict['type'] = "AqaraReed"
mydict['rssi'] = j['linkquality']
mydict['v'] = 0 if j['contact'] == True else 1
mydict['voltage'] = j['voltage']
mydict['time'] = time.time()
print(mydict)
client.publish("homie/zigbee/paulineFenster", json.dumps(mydict, sort_keys=True), retain=True, qos=1)
except:
traceback.print_exc()
quit(0)
client= paho.Client("reactor")
client.on_message=on_message
client.on_connect = on_connect
client.on_disconnect = on_disconnect
print("connecting to broker ",broker)
client.connect(broker)
client.loop_start() #start loop to process received messages in separate thread
print ("MQTT Loop started.")
while True:
time.sleep(.5)
# client.loop_forever()
client.disconnect()
client.loop_stop()
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