-
Notifications
You must be signed in to change notification settings - Fork 0
/
trannergy-mqtt.py
executable file
·208 lines (160 loc) · 5.68 KB
/
trannergy-mqtt.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/python3
"""
DESCRIPTION
Read Trannergy solar converter
Tested on raspberry pi4
4 Worker threads:
- serial port reader
- Trannergy telegram parser to MQTT messages
- MQTT client
- HA Discovery
V1.0.0:
- Initial version
V1.1.0
- Extend with high(er) frequent read out via tcpclient
inspired by: https://github.com/jbouwh/omnikdatalogger/blob/dev/apps/omnikdatalogger/omnik/plugin_client/tcpclient.py
V1.2.0
- Enabled homeassistant autodiscovery
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/>.
v1.3.0
- Update vor mqtt lib v5
"""
__version__ = "1.3.0"
__author__ = "Hans IJntema"
__license__ = "GPLv3"
import signal
import socket
import time
import sys
import threading
# Local imports
import config as cfg
import trannergy_serial as trannergy
import trannergy_parser as convert
import hadiscovery as ha
import mqtt as mqtt
import trannergy_tcpclient as tcpclient
from log import logger
logger.setLevel(cfg.loglevel)
# DEFAULT exit code
# status=1/FAILURE
__exit_code = 1
# ------------------------------------------------------------------------------------
# Instance running?
# ------------------------------------------------------------------------------------
import os
script=os.path.basename(__file__)
script=os.path.splitext(script)[0]
# Ensure that only one instance is started
if sys.platform == "linux":
lockfile = "\0" + script + "_lockfile"
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# Create an abstract socket, by prefixing it with null.
s.bind(lockfile)
logger.info( f"Starting {__file__}; version = {__version__}" )
except IOError as err:
logger.info( f"{lockfile} already running. Exiting; {err}" )
sys.exit(1)
def close():
"""
Args:
Returns:
None
"""
logger.info(f"Exitcode = {__exit_code} >>")
sys.exit(__exit_code)
# ------------------------------------------------------------------------------------
# LATE GLOBALS
# ------------------------------------------------------------------------------------
trigger = threading.Event()
t_threads_stopper = threading.Event()
t_mqtt_stopper = threading.Event()
# mqtt thread
t_mqtt = mqtt.MQTTClient(mqtt_broker=cfg.MQTT_BROKER,
mqtt_port=cfg.MQTT_PORT,
mqtt_client_id=cfg.MQTT_CLIENT_UNIQ,
mqtt_qos=cfg.MQTT_QOS,
mqtt_cleansession=True,
mqtt_protocol=mqtt.MQTTv5,
username=cfg.MQTT_USERNAME,
password=cfg.MQTT_PASSWORD,
mqtt_stopper=t_mqtt_stopper,
worker_threads_stopper=t_threads_stopper)
telegram = list()
# Select which reader will be used; setup SerialPort thread
try:
if cfg.INV_READER == "TCPCLIENT":
t_serial = tcpclient.TaskReadSerial(trigger, t_threads_stopper, telegram)
elif cfg.INV_READER == "LISTEN":
t_serial = trannergy.TaskReadSerial(trigger, t_threads_stopper, telegram)
else:
logger.error(f"Wrong READER specified {cfg.INV_READER}")
t_threads_stopper.set()
t_serial = None
except Exception as e:
logger.debug(f"Exception {e}")
t_threads_stopper.set()
t_serial = None
close(1)
# Telegram parser thread
t_parse = convert.ParseTelegrams(trigger, t_threads_stopper, t_mqtt, telegram)
# Send Home Assistant auto discovery MQTT's
t_discovery = ha.Discovery(t_threads_stopper, t_mqtt, __version__)
def exit_gracefully(signal, stackframe):
"""
Exit_gracefully
Keyword arguments:
:param int signal: the associated signalnumber
:param str stackframe: current stack frame
:return:
"""
logger.debug(f"Signal {signal}: >>")
# status=0/SUCCESS
__exit_code = 0
t_threads_stopper.set()
logger.info("<<")
def main():
logger.debug(">>")
# Set last will/testament
t_mqtt.will_set(cfg.MQTT_TOPIC_PREFIX + "/status", payload="interrupted", qos=cfg.MQTT_QOS, retain=True)
# Start all threads
t_mqtt.start()
t_parse.start()
t_discovery.start()
t_serial.start()
# Set status to online
t_mqtt.set_status(cfg.MQTT_TOPIC_PREFIX + "/status", "online", retain=True)
t_mqtt.do_publish(cfg.MQTT_TOPIC_PREFIX + "/sw-version", f"main={__version__}; mqtt={mqtt.__version__}", retain=True)
# block till t_serial stops receiving telegrams/exits
t_serial.join()
logger.debug("t_serial.join exited; set stopper for other threats")
t_threads_stopper.set()
# Set status to offline
t_mqtt.set_status(cfg.MQTT_TOPIC_PREFIX + "/status", "offline", retain=True)
# Todo check if MQTT queue is empty before setting stopper
# Use a simple delay of 1sec before closing mqtt
time.sleep(1)
t_mqtt_stopper.set()
logger.debug("<<" )
return
# ------------------------------------------------------------------------------------
# Entry point
# ------------------------------------------------------------------------------------
if __name__ == '__main__':
logger.debug("__main__: >>")
signal.signal(signal.SIGINT, exit_gracefully)
signal.signal(signal.SIGTERM, exit_gracefully)
# start main program
main()
logger.debug("__main__: <<")
close()