Skip to content

Instantly share code, notes, and snippets.

@zerog2k

zerog2k/temp_sensor_parse.py Secret

Created Jul 10, 2020
Embed
What would you like to do?
#!/usr/bin/env python3
import json
import os
import sys
import paho.mqtt.client as mqtt
import time as t
from influxdb import InfluxDBClient
influx_client = InfluxDBClient('localhost', 8086)
influx_client.create_database("iot")
influx_client.switch_database("iot")
influx_json_template = {
"measurement": "temp_sensor",
"tags": {},
"fields": {}
}
# see https://github.com/Portisch/RF-Bridge-EFM8BB1/issues/96
# data is grouped in 9 nibbles
# [0][type] - [id0][id1] - [flags][temp0] - [temp1][temp2] - [humi0][humi1]
#payload like: '{"RfRaw":{"Data":"AAA6061050E80F330055"}}'
TOPIC = "tele/+/RESULT"
SERVER = "localhost"
PORT = 1883
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(TOPIC)
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
line = msg.payload
print(line)
jsondata = json.loads(line.decode('utf-8'))
rfraw = jsondata.get("RfRaw")
if not rfraw:
return
data = rfraw.get("Data")
if data[:8] == 'AAA60610' and data[18:] == '55':
# decode it
slice = data[7:17]
frame = bytes.fromhex(slice)
typ = frame[0] & 0xF
id = frame[1]
flags = (frame[2] & 0xF0) >> 4
tempraw = (frame[2] & 0x0F) << 8 | frame[3]
temp = tempraw / 10.0
humidity = frame[4]
print("%s, type: %d, id: %02Xh, flags: %Xh, temp: %3.1f C, humidity: %02d" % \
(t.ctime(), typ, id, flags, temp, humidity) )
influx_json = influx_json_template.copy()
influx_json["tags"]["id"] = id
influx_json["fields"]["temp"] = temp
influx_json["fields"]["humidity"] = humidity
result = influx_client.write_points([influx_json])
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(SERVER, PORT, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.