Created
November 2, 2022 13:25
-
-
Save petermolnar/f3d906b986d5895058730e46f6b6b110 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import paho.mqtt.client as mqtt | |
import json | |
import requests | |
def on_connect(client, userdata, flags, rc): | |
print(f"Connected with result code {rc}") | |
client.subscribe("#") | |
def on_message(client, userdata, msg): | |
if ( | |
"SENSOR/gasmeter" not in msg.topic | |
and "SENSOR/electricitymeter" not in msg.topic | |
): | |
return | |
payload = json.loads(msg.payload.decode()) | |
data_to_send = [] | |
if "electricitymeter" in payload: | |
energy = payload["electricitymeter"]["energy"]["import"]["cumulative"] * 1000 | |
power = payload["electricitymeter"]["power"]["value"] * 1000 | |
data_to_send.append( | |
{ | |
"type": "command", | |
"param": "udevice", | |
"idx": "ID of an electricity meter virtual device", | |
"nvalue": 0, | |
"svalue": f"{power};{energy}", | |
} | |
) | |
elif "gasmeter" in payload: | |
usage = payload["gasmeter"]["energy"]["import"]["cumulativevol"] * 1000 | |
data_to_send.append( | |
{ | |
"type": "command", | |
"param": "udevice", | |
"idx": "ID of a counter(gas) meter virtual device", | |
"nvalue": 0, | |
"svalue": f"{usage}", | |
} | |
) | |
energy = payload["gasmeter"]["energy"]["import"]["cumulative"] * 1000 | |
data_to_send.append( | |
{ | |
"type": "command", | |
"param": "udevice", | |
"idx": "ID of a counter(energy) meter virtual device",, | |
"nvalue": 0, | |
"svalue": f"{usage}", | |
} | |
) | |
else: | |
return | |
for d in data_to_send: | |
req = requests.get( | |
"http://127.0.0.1:80/json.htm", | |
auth=('domoticz user', 'domoticz password'), | |
params = d | |
) | |
client = mqtt.Client(client_id="domoticz/glow") | |
client.on_connect = on_connect | |
client.on_message = on_message | |
# client.tls_set() | |
client.username_pw_set( | |
username="MQTT user", password="MQTT password" | |
) | |
client.connect("127.0.0.1", 1883) | |
client.loop_forever() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Unit] | |
Description=MQTT message converter for Domoticz | |
After=network.target | |
[Service] | |
ExecStart=/usr/bin/python3 /opt/domoticz/scripts/python/mqtt_message_converter.py | |
WorkingDirectory=/opt/domoticz/scripts/python | |
Type=simple | |
Restart=always | |
RestartSec=60s | |
User=domoticz | |
[Install] | |
WantedBy=multi-user.target |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment