forked from hansij66/dsmr2mqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hadiscovery.py
executable file
·151 lines (122 loc) · 5.09 KB
/
hadiscovery.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""
Send Home Assistant Auto Discovery MQTT messages
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import time
import threading
import json
import re
# Local imports
import config as cfg
import dsmr50 as dsmr
# Logging
import __main__
import logging
import os
script = os.path.basename(__main__.__file__)
script = os.path.splitext(script)[0]
logger = logging.getLogger(script + "." + __name__)
class Discovery(threading.Thread):
def __init__(self, stopper, mqtt, version):
"""
class init
Keyword arguments:
:param threading.Event() stopper:
:param mqtt.mqttclient() mqtt: reference to mqtt client
:param str version: version of the program
"""
logger.debug(">>")
super().__init__()
self.__stopper = stopper
self.__mqtt = mqtt
self.__version = version
self.__interval = 3600/cfg.HA_INTERVAL
self.__lastmqtt = 0
self.__listofjsondicts = list()
def __del__(self):
logger.debug(">>")
def __create_discovery_JSON(self):
"""
Create the HA/MQTT Autodiscovery messages
Returns:
None
"""
d = {} # d = dict() does not work....
# create device JSON
d["name"] = "dsmr reader"
d["unique_id"] = "dsmr-device"
d["state_topic"] = cfg.MQTT_TOPIC_PREFIX + "/status"
d["icon"] = "mdi:home-automation"
d["device"] = {"name": "dsmr reader",
"sw_version": self.__version,
"model": "P1 USB/dsmr-mqtt",
"manufacturer": "hansij66 @github.com",
"identifiers": ["dsmr"]
}
self.__listofjsondicts.append(d)
# iterate through all dsmr.defintions
for index in dsmr.definition:
# select definitions with discovery enabled
if int(dsmr.definition[index][dsmr.HA_DISCOVERY]):
d = {}
d["unique_id"] = dsmr.definition[index][dsmr.MQTT_TAG]
d["state_topic"] = cfg.MQTT_TOPIC_PREFIX + "/" + dsmr.definition[index][dsmr.MQTT_TOPIC]
d["name"] = dsmr.definition[index][dsmr.DESCRIPTION]
d["unit_of_measurement"] = re.match(".*\[(\w+)\].*", dsmr.definition[index][dsmr.DESCRIPTION]).group(1)
d["value_template"] = "{{value_json." + dsmr.definition[index][dsmr.MQTT_TAG] + "}}"
# https://www.home-assistant.io/integrations/sensor/
# https://developers.home-assistant.io/docs/core/entity/sensor/#long-term-statistics
if d["unit_of_measurement"] == "Wh":
d["device_class"] = "energy"
d["state_class"] = "total"
elif d["unit_of_measurement"] == "W":
d["device_class"] = "power"
#d["state_class"] = "measurement"
elif d["unit_of_measurement"] == "A":
d["device_class"] = "current"
elif d["unit_of_measurement"] == "V":
d["device_class"] = "voltage"
elif d["unit_of_measurement"] == "m3" or d["unit_of_measurement"] == "m\u00b3":
d["device_class"] = "gas"
d["state_class"] = "total"
# Homeassistant expects m3 and not liters
d["value_template"] = "{{value_json." + dsmr.definition[index][dsmr.MQTT_TAG] + "|float/1000|round(0)" + "}}"
else:
logger.warning(f"Unknown unit_of_measurement = {d['unit_of_measurement']}")
d["icon"] = dsmr.definition[index][dsmr.HA_ICON]
d["device"] = { "identifiers": [ "dsmr" ] }
self.__listofjsondicts.append(d)
def run(self):
"""
Returns:
None
"""
logger.debug(">>")
self.__create_discovery_JSON()
# infinite loop
if cfg.HA_DISCOVERY:
while not self.__stopper.is_set():
# calculate time elapsed since last MQTT
t_elapsed = int(time.time()) - self.__lastmqtt
if t_elapsed > self.__interval:
for dict in self.__listofjsondicts:
topic = "homeassistant/sensor/" + cfg.MQTT_TOPIC_PREFIX + "/" + dict["unique_id"] + "/config"
self.__mqtt.do_publish(topic, json.dumps(dict, separators=(',', ':')), retain=True)
self.__lastmqtt = int(time.time())
else:
# wait...
time.sleep(0.5)
# If configured, remove MQTT Auto Discovery configuration
if cfg.HA_DELETECONFIG:
for dict in self.__listofjsondicts:
topic = "homeassistant/sensor/" + cfg.MQTT_TOPIC_PREFIX + "/" + dict["unique_id"] + "/config"
self.__mqtt.do_publish(topic, "")