Skip to content

Instantly share code, notes, and snippets.

@petermolnar
Created November 2, 2022 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save petermolnar/f3d906b986d5895058730e46f6b6b110 to your computer and use it in GitHub Desktop.
Save petermolnar/f3d906b986d5895058730e46f6b6b110 to your computer and use it in GitHub Desktop.
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()
[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