forked from matthijsvisser/kamstrup-402-mqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemon.py
executable file
·87 lines (69 loc) · 2.64 KB
/
daemon.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
#!/usr/bin/python
#
# Created by Matthijs Visser
import datetime
import time
import sys
import signal
import subprocess
import logging
import paho.mqtt.client as paho
import multiprocessing
import yaml
from kamstrup_meter import kamstrup
from mqtt_handler import MqqtHandler
from logging.handlers import TimedRotatingFileHandler
log = logging.getLogger("log")
log.setLevel(logging.DEBUG)
handler = TimedRotatingFileHandler('logs/debug.log', when="d", interval=1, backupCount=5)
formatter = logging.Formatter("[%(asctime)s %(filename)s %(funcName)s:%(lineno)4s - %(levelname)s - %(message)s]",
"%Y-%m-%d %H:%M:%S")
handler.setFormatter(formatter)
log.addHandler(handler)
with open("config.yaml", "r") as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.BaseLoader)
class KamstrupDaemon(multiprocessing.Process):
def __init__(self):
log.info('initializing daemon')
self.running = True
self.event_finished = multiprocessing.Event()
self.receive_queue = multiprocessing.Queue()
mqtt_cfg = cfg["mqtt"]
serial_cfg = cfg["serial_device"]
kamstrup_cfg = cfg["kamstrup"]
self.poll_interval = kamstrup_cfg["poll_interval"]
signal.signal(signal.SIGINT, self.signal_handler)
if (mqtt_cfg["retain"].lower() == "true"):
retain = True
else:
retain = False
if (mqtt_cfg["authentication"].lower() == "true"):
self.mqtt_handler = MqqtHandler(mqtt_cfg["host"], int(mqtt_cfg["port"]),
mqtt_cfg["client"], mqtt_cfg["topic"], retain, int(mqtt_cfg["qos"]),
True, mqtt_cfg["username"], mqtt_cfg["password"], mqtt_cfg["tls_enabled"],
mqtt_cfg["tls_ca_cert"], mqtt_cfg["tls_cert"], mqtt_cfg["tls_key"],
mqtt_cfg["tls_insecure"])
else:
self.mqtt_handler = MqqtHandler(mqtt_cfg["host"], int(mqtt_cfg["port"]),
mqtt_cfg["client"], mqtt_cfg["topic"], retain, int(mqtt_cfg["qos"]))
self.mqtt_handler.connect()
self.mqtt_handler.loop_start()
self.heat_meter = kamstrup(serial_cfg["com_port"], kamstrup_cfg["parameters"])
def signal_handler(self, signal, handler):
self.running = False
self.heat_meter.close()
self.mqtt_handler.loop_stop()
self.mqtt_handler.disconnect()
log.info('stopping daemon')
sys.exit(0)
def run(self):
while self.running:
values = self.heat_meter.run()
self.mqtt_handler.publish("values", str(values).replace("'", "\""))
log.info("Waiting {} minute(s) for the next meter readout".format(self.poll_interval))
time.sleep(int(self.poll_interval) * 60)
def main():
daemon = KamstrupDaemon()
daemon.run()
if __name__ == '__main__':
main()