cleanup mqtt

This commit is contained in:
Joerg Lehmann 2023-02-03 20:38:27 +01:00
parent 704242eea5
commit 0422863ca8
4 changed files with 1 additions and 72 deletions

View File

@ -42,7 +42,7 @@ spec:
- mountPath: /mosquitto/log - mountPath: /mosquitto/log
name: mosquittolog name: mosquittolog
- name: mqtt2log - name: mqtt2log
image: localhost/mqtt2log:2022122901 image: registry.gitlab.com/drpuur/mqtt2log:2022123001
env: env:
- name: TZ - name: TZ
value: Europe/Zurich value: Europe/Zurich

View File

@ -1,5 +0,0 @@
FROM python:3.10
ADD . /code
WORKDIR /code
RUN pip install --root-user-action ignore -r requirements.txt
CMD ["python", "mqtt2log.py"]

View File

@ -1,65 +0,0 @@
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()

View File

@ -1 +0,0 @@
paho-mqtt