Dear Community,
I have got a script on Github, the script reads an Smart Meter through P1 Serial Connection and provide me the current power usage and some other details.
I want to add MQTT support to this Script, i have tried it with ChatGPT and it seems to work.
The Raspberry reads the Sensor and sends the data with MQTT to my HASSIO Mosquito Broker.
I have installed an MQTT Browser to my Laptop and connected to the Broker to check if the data looks good. Everything looks good.
But I have a Problem to create a sensor to add this to my Home Assistant.
Maybe someone could help me to create a working sensor template.
I have activated MQTT in home assistant, but now I have no idea what to do next.
Manual creation of a sensor ends with the error json_value not found and so on.
here is the original script:
import time
import json
from serial import Serial, PARITY_NONE, EIGHTBITS, STOPBITS_ONE
from decode import decrypt_frame, convert_to_dict, check_and_encode_frame
GLOBAL_UNICAST_ENC_KEY = "MYKEY"
GLOBAL_AUTHENTICATION_KEY = "MYKEY"
if __name__ == "__main__":
if GLOBAL_UNICAST_ENC_KEY == "":
raise RuntimeError("Please set the GLOBAL_UNICAST_ENC_KEY")
if GLOBAL_AUTHENTICATION_KEY == "":
raise RuntimeError("Please set the GLOBAL_AUTHENTICATION_KEY")
while True:
try:
with Serial('/dev/ttyUSB0', 115200, timeout=6.0,
bytesize=EIGHTBITS, parity=PARITY_NONE, stopbits=STOPBITS_ONE, rtscts=False) as ser:
data = ser.read(511)
if len(data) == 0:
print("Warte auf Smart Meter...")
continue
decrypted = decrypt_frame(GLOBAL_UNICAST_ENC_KEY, GLOBAL_AUTHENTICATION_KEY, data)
encoded_frame = check_and_encode_frame(decrypted)
response_as_dict = convert_to_dict(encoded_frame)
#print("Raw frame:\n" + str(data.hex()))
#print(json.dumps(response_as_dict, indent=2))
print("Wird aktuell geliefert: " + str(response_as_dict["1-0:1.7.0"]))
print("Wird aktuell eingespeist: " + str(response_as_dict["1-0:2.7.0"]))
print("Wurde geliefert (Zählerstand): " + str(response_as_dict["1-0:1.8.0"]))
print("Wurde eingespeist (Zählerstand): " + str(response_as_dict["1-0:2.8.0"]))
except Exception as e:
print(e)
time.sleep(1)
pass
Here is the Code with MQTT added
import time
import json
import paho.mqtt.client as mqtt
from serial import Serial, PARITY_NONE, EIGHTBITS, STOPBITS_ONE
from decode import decrypt_frame, convert_to_dict, check_and_encode_frame
GLOBAL_UNICAST_ENC_KEY = "MYKEY"
GLOBAL_AUTHENTICATION_KEY = "MYKEY"
MQTT_SERVER = "MQTT_SERVER_ADDRESS"
MQTT_PORT = 1883
MQTT_USERNAME = "MQTT_USERNAME"
MQTT_PASSWORD = "MQTT_PASSWORD"
MQTT_TOPIC = "MQTT_TOPIC"
def send_to_mqtt(payload):
client = mqtt.Client()
client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
client.connect(MQTT_SERVER, MQTT_PORT)
client.publish(MQTT_TOPIC, payload=payload, qos=0, retain=False)
client.disconnect()
if __name__ == "__main__":
if GLOBAL_UNICAST_ENC_KEY == "":
raise RuntimeError("Please set the GLOBAL_UNICAST_ENC_KEY")
if GLOBAL_AUTHENTICATION_KEY == "":
raise RuntimeError("Please set the GLOBAL_AUTHENTICATION_KEY")
while True:
try:
with Serial('/dev/ttyUSB0', 115200, timeout=6.0,
bytesize=EIGHTBITS, parity=PARITY_NONE, stopbits=STOPBITS_ONE, rtscts=False) as ser:
data = ser.read(511)
if len(data) == 0:
print("Warte auf Smart Meter...")
continue
decrypted = decrypt_frame(GLOBAL_UNICAST_ENC_KEY, GLOBAL_AUTHENTICATION_KEY, data)
encoded_frame = check_and_encode_frame(decrypted)
response_as_dict = convert_to_dict(encoded_frame)
payload = {
"current_delivery": response_as_dict["1-0:1.7.0"],
"current_feed_in": response_as_dict["1-0:2.7.0"],
"total_delivery": response_as_dict["1-0:1.8.0"],
"total_feed_in": response_as_dict["1-0:2.8.0"]
}
payload_str = json.dumps(payload)
send_to_mqtt(payload_str)
print("Wird aktuell geliefert: " + str(response_as_dict["1-0:1.7.0"]))
print("Wird aktuell eingespeist: " + str(response_as_dict["1-0:2.7.0"]))
print("Wurde geliefert (Zählerstand): " + str(response_as_dict["1-0:1.8.0"]))
print("Wurde eingespeist (Zählerstand): " + str(response_as_dict["1-0:2.8.0"]))
except Exception as e:
print(e)
time.sleep(1)
pass
Here is the Console Output on the PI
Here is the MQTT-Client output
i have tried it with this sensor config
sensor:
- platform: mqtt
state_topic: "smartmeter"
name: "Smart Meter Total Consumption"
unit_of_measurement: "kWh"
value_template: "{{ value_json['1-0:1.8.0'] | float / 1000 }}"
But every time this has ended with the
"UndefinedError: 'value_json' is undefined" error.
Hopefully there is someone who can help me to understand how mqtt sensors work.
thanks
Patrick