forked from datenschuft/SMA-EM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhaautodiscover.py
65 lines (54 loc) · 2.04 KB
/
haautodiscover.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import json
import paho.mqtt.publish as publish
import os
# Input file path
input_json_file = "sampledata.json"
# MQTT broker configuration
MQTT_BROKER = os.getenv("MQTT_BROKER", "192.168.0.180") # Default to "127.0.0.1"
MQTT_PORT = int(os.getenv("MQTT_PORT", 1883)) # Default to 1883
#MQTT_USERNAME = os.getenv("MQTT_USERNAME", "your_username") # Default to "your_username"
#MQTT_PASSWORD = os.getenv("MQTT_PASSWORD", "your_password") # Default to "your_password"
DISCOVERY_PREFIX = "homeassistant"
DEVICE_NAME = "SMA Energy Meter"
MANUFACTURER = "SMA"
MODEL = "Energy Meter"
# Load JSON data
with open(input_json_file, "r") as file:
data = json.load(file)
# Generate MQTT discovery messages
messages = []
device_id = f"sma_{data['serial']}"
for key, value in data.items():
# Skip unit keys, handled with corresponding sensor keys
if key.endswith("unit"):
continue
# Determine unit of measurement (if available)
unit_key = f"{key}unit"
unit = data.get(unit_key, None)
# Define discovery topic and payload
discovery_topic = f"{DISCOVERY_PREFIX}/sensor/{device_id}/{key}/config"
payload = {
"name": key.capitalize(),
"state_topic": f"sma/data/{data['serial']}/{key}",
"unique_id": f"{device_id}_{key}",
"device": {
"identifiers": [device_id],
"manufacturer": MANUFACTURER,
"model": MODEL,
"name": DEVICE_NAME,
},
}
# Add attributes for energy counters
if "counter" in key: # Assuming energy counters contain "counter" in the key
payload.update({
"device_class": "energy",
"state_class": "total_increasing",
"unit_of_measurement": unit,
})
elif unit:
payload["unit_of_measurement"] = unit
# Add the payload to the messages list
messages.append((discovery_topic, json.dumps(payload), 0, True))
# Publish all messages to MQTT broker
publish.multiple(messages, hostname=MQTT_BROKER, port=MQTT_PORT)
print("MQTT discovery messages sent to Home Assistant.")