-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
executable file
·172 lines (132 loc) · 4.82 KB
/
app.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
#!/usr/bin/env python3
import configparser
import logging
import signal # support ctrl-c
# matrix chatbot
from chatbot import Chatbot
# brandmeld-installatie
import brandmelder
logger = logging.getLogger(__name__)
#
# handle CTRL-C / stop signal
#
def signal_handler_stop(sig, frame):
global signal_handler_stop_count
global signal_handler_stop_callbacks
global signal_handler_stop_callbacks_last
logger.info('stopping by {} (ctrl-c/systemd stop/..) ({})'.format(str(signal.Signals(sig)), signal_handler_stop_count))
# CTRL-C hit count, set signal_handler_stop_count: to number of tries or -1.
if signal_handler_stop_count == 0:
# we are not wanted here anymore: let's erase our selfs
signal.signal(sig,signal.SIG_DFL)
# end try signal_handler_stop_callbacks_last
signal_handler_stop_callbacks = signal_handler_stop_callbacks_last
elif signal_handler_stop_count > 0:
# let's count down
signal_handler_stop_count = signal_handler_stop_count - 1
# stop main services:
while (len(signal_handler_stop_callbacks) != 0):
callback = signal_handler_stop_callbacks.pop()
logger.info('# signal_handler_stop_callbacks[ {} ]; exec: {} '.format(len(signal_handler_stop_callbacks), callback))
callback()
# global for self restart.
SELF_RESTART = False
# catch sig -HUP
def signal_handler_reload(sig, frame):
global SELF_RESTART
# set global variable
SELF_RESTART = True
logger.info('SIG HUP: (shutdown and) restart ourself ')
signal_handler_stop(sig, frame)
# import sys, os
# print ("RESTART: ", sys.argv[0], sys.argv, "(+ENV)" )
# os.execve(sys.argv[0], sys.argv, os.environ)
# quit()
#
# Main:
#
if __name__ == '__main__':
# register CTRL-C / CTRL-D
signal.signal(signal.SIGINT, signal_handler_stop)
signal_handler_stop_count = 1 # set to -1 for infinite
signal_handler_stop_callbacks = [] # callback function for exit.
signal_handler_stop_callbacks_last = [] # callback function for final exit.
signal.signal(signal.SIGTERM, signal_handler_stop)
signal.signal(signal.SIGHUP, signal_handler_reload)
# read config
config = configparser.ConfigParser()
with open('config.ini') as f:
config.read_file(f)
# set log output for stderr, get loglevel from config
logging.basicConfig(level=logging.getLevelName(config.get('main', 'loglevel', fallback = 'info').upper()))
#
# brandmeld-installatie message parser
#
bmi = brandmelder.LogReader()
# add exit callback: bmi.exit()
signal_handler_stop_callbacks.append(bmi.exit_graceful)
signal_handler_stop_callbacks_last.append(bmi.exit)
#
#
# Matrix Elelement chat bot
#
bot_conf = config['matrix-conf']
bot = Chatbot(
host=bot_conf.get('host'),
username=bot_conf.get('username'),
password=bot_conf.get('password'),
userid=bot_conf.get('userid'),
token=bot_conf.get('token'),
room=bot_conf.get('room'),
)
# add exit callback: bot.logout()
# signal_handler_stop_callbacks_last.append(bot.logout)
# print startup message:
startup_text = config.get('main','startup_text', fallback=None)
startup_html = config.get('main','startup_html', fallback=None)
if startup_text is not None or startup_html is not None:
bot.talk(body=startup_text, body_html=startup_html, notice=True)
# serial conf:
serial_conf = { 'port': config.get('serial','port'),
'baudrate': config.getint('serial','baudrate', fallback=-1), # use -1 for None
'timeout': config.getint('serial','timeout', fallback=1),
'encoding': config.get('serial','encoding', fallback=None)}
#
# Main loop: get messages from serial input
#
for message in bmi.serial_reader(serial_conf):
# send message over chat
if message.parent and 'matrix_event_id' in message.parent.meta:
# we have a child message with an previous send message: update parent:
bot.update_talk(
event_id=message.parent.meta['matrix_event_id'],
body=message.to_text(),
new_body=message.parent.to_text(),
new_body_html=message.parent.to_html(),
notice=(message.parent.prio == message.Priority.LOW),
)
else:
# simply snd message:
matrix = bot.talk(
body=message.to_text(),
body_html=message.to_html(),
notice=(message.prio == message.Priority.LOW),
)
message.meta['matrix_event_id'] = matrix['event_id']
# end of Main loop, exit when needed..
# print shutdown text:
shutdown_text = config.get('main','shutdown_text', fallback=None)
shutdown_html = config.get('main','shutdown_html', fallback=None)
if shutdown_text is not None or shutdown_html is not None:
bot.talk(body=shutdown_text, body_html=shutdown_html, notice=True)
# matrix exit:
bot.logout()
# serial close.
bmi.exit() # probably not needed, but no harm to do twice
# in case of SIGHUP:
if SELF_RESTART:
import sys, os
logger.info('SELF_RESTART : {} {}'.format(str(sys.argv[0]), str(sys.argv)))
os.execve(sys.argv[0], sys.argv, os.environ)
quit()
# vim: set noet ts=4 sw=4: