commit 32b394b4962093c877735b45b1e26e580ced1064 Author: Joerg Lehmann Date: Fri Dec 30 17:39:55 2022 +0100 Initial commit diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..42f38e1 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.10-slim +ADD . /code +WORKDIR /code +RUN pip install --root-user-action ignore -r requirements.txt +CMD ["python", "mqtt2log.py"] diff --git a/mqtt2log.py b/mqtt2log.py new file mode 100755 index 0000000..557d501 --- /dev/null +++ b/mqtt2log.py @@ -0,0 +1,65 @@ +import re +import json +from typing import NamedTuple +from datetime import datetime + +import paho.mqtt.client as mqtt + +MQTT_ADDRESS = 'mqtt.nbit.ch' +MQTT_USER = 'mqtt' +MQTT_PASSWORD = 'mqtt7355@' +MQTT_TOPIC = 'shellies/events/rpc' +MQTT_CLIENT_ID = 'MQTT_Logfile_Bridge' + +def on_connect(client, userdata, flags, rc): + """ The callback for when the client receives a CONNACK response from the server.""" + print('Connected with result code ' + str(rc)) + client.subscribe(MQTT_TOPIC) + +def _parse_mqtt_message(topic, payload): + print("_parse_mqtt_message") + payload = json.loads(payload) + src = payload.get('src','N/A') + if 'params' in payload.keys(): + ts = payload['params'].get('ts',-1) + if 'switch:0' in payload['params'].keys(): + if 'aenergy' in payload['params']['switch:0'].keys(): + if 'total' in payload['params']['switch:0']['aenergy'].keys(): + return "E,%.0f,%s,%.3f" % (ts,src,payload['params']['switch:0']['aenergy']['total']) + if 'apower' in payload['params']['switch:0'].keys(): + return "P,%.0f,%s,%.1f" % (ts,src,payload['params']['switch:0']['apower']) + else: + return None + +def write2file(msg): + now = datetime.now() # current date and time + filename = "/data/" + now.strftime("%Y%m%d") + ".log" + f = open(filename, "a") + f.write(msg + "\n") + f.close() + +def on_message(client, userdata, msg): + """The callback for when a PUBLISH message is received from the server.""" + #print(msg.topic + ' ' + str(msg.payload)) + result = _parse_mqtt_message(msg.topic, msg.payload.decode('utf-8')) + if result is None: + print("Couldn't parse sensor data!") + print(msg.payload.decode('utf-8')) + return + else: + write2file(result) + return + +def main(): + mqtt_client = mqtt.Client(MQTT_CLIENT_ID) + mqtt_client.username_pw_set(MQTT_USER, MQTT_PASSWORD) + mqtt_client.on_connect = on_connect + mqtt_client.on_message = on_message + + mqtt_client.connect(MQTT_ADDRESS, 1883) + mqtt_client.loop_forever() + + +if __name__ == '__main__': + print('MQTT to Logfile bridge') + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8579e8b --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +paho-mqtt