66 lines
1.8 KiB
Python
Executable File
66 lines
1.8 KiB
Python
Executable File
import json
|
|
#import fileinput
|
|
import serial
|
|
|
|
import paho.mqtt.client as paho
|
|
|
|
#input = '{"model":"Oregon-THGR810","id":226,"channel":10,"battery_ok":0,"temperature_C":19.7,"humidity":24,"protocol":"Oregon Scientific Weather Sensor"}'
|
|
SKIP_KEYS = [ "type", "model", "subtype", "channel", "id", "mic", "mod", "freq", "sequence_num", "message_type", "exception", "raw_msg", "protocol", "duration", "sync", "flags", "status" ]
|
|
TOPIC_KEYS = [ "type", "model", "subtype", "channel", "id" ]
|
|
|
|
#default="devices[/type][/model][/subtype][/channel][/id]"
|
|
prefix = "home/rtl_433"
|
|
|
|
broker = "localhost"
|
|
port = 1883
|
|
|
|
serialdev = "/dev/ttyACM0"
|
|
serialspeed = 115200
|
|
|
|
|
|
def generate_topic(jsonin):
|
|
topic = prefix+'/devices'
|
|
for t in TOPIC_KEYS:
|
|
if t in jsonin:
|
|
topic += '/' + str(jsonin[t])
|
|
return topic
|
|
|
|
def publish(jsonin, prefix_device):
|
|
for t in jsonin:
|
|
if t not in SKIP_KEYS:
|
|
topic = prefix_device + '/' + t
|
|
value = jsonin[t]
|
|
#print("{} {}".format(topic, value))
|
|
mqtt.publish(topic, value)
|
|
|
|
def on_connect(client, userdata, flags, reason_code, properties):
|
|
print(f"Connected to MQTT")
|
|
client.subscribe(prefix+"/cmd")
|
|
|
|
def on_message(client, userdata, msg):
|
|
print(msg.topic+" "+str(msg.payload))
|
|
if(str(msg.topic) == prefix+"/cmd"):
|
|
ser.write(msg.payload)
|
|
|
|
mqtt=paho.Client(paho.CallbackAPIVersion.VERSION2)
|
|
mqtt.on_connect = on_connect
|
|
mqtt.on_message = on_message
|
|
mqtt.connect(broker,port)
|
|
mqtt.loop_start()
|
|
|
|
ser = serial.Serial(serialdev, serialspeed)
|
|
|
|
#for input in fileinput.input():
|
|
while True:
|
|
input = ser.readline()
|
|
try:
|
|
data = json.loads(input)
|
|
except json.decoder.JSONDecodeError:
|
|
print("Error JSON, received {}".format(input))
|
|
continue
|
|
#print(data)
|
|
mqtt.publish(prefix+'/events', input.rstrip())
|
|
prefix_device = generate_topic(data)
|
|
publish(data, prefix_device)
|
|
|