-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
248 lines (198 loc) · 7.36 KB
/
main.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import json
import logging
import os.path
import requests
import signal
import sys
import time
import tornado.escape
import tornado.ioloop
import tornado.web
logging.basicConfig(level=logging.DEBUG)
from core.doorphone import DoorPhone
from core.callbacks import Callback
from core.handlers import HttpHandler, WebSocketHandler, SlackHandler, ApiHandler
app = None
class Application(tornado.web.Application, Callback):
"""
The main Application
"""
door_phone = None
door_settings = {}
door_api_keys = {}
def __init__(self) -> None:
"""
Init method
"""
# order matters
handlers = [
(r"/api/open/(.*)", ApiHandler),
(r"/door", WebSocketHandler),
(r"/slack/(.*)", SlackHandler),
(r"/(.*)", HttpHandler)
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
compiled_template_cache=False,
static_hash_cache=False,
serve_traceback=True
)
self.load_settings()
super(Application, self).__init__(handlers, **settings)
def set(self, key: str, value=None)-> None:
self.door_settings.update({"doorpi.%s" % key: value})
def get(self, key: str, default=None):
return self.door_settings.get("doorpi.%s" % key, default)
@staticmethod
def load(filename: str) -> dict:
"""
Loads a JSON file and returns a dict.
:param filename: The filename to load
:type filename: str
:return: A dictionary
:rtype: dict
"""
_dict = {}
try:
with open(filename, 'r') as file:
_dict = json.load(file)
except IOError as err:
logging.warning(str(err))
return _dict
def load_settings(self, signum=None, frame=None) -> None:
"""
Reloads configuration on sigusr1 (systemctl reload doorpi-agent.service)
:param signum: signature parameter
:param frame: signature parameter
"""
self.door_settings.update(Application.load('main.json'))
self.door_settings.update(Application.load('local_settings.json'))
self.door_api_keys.update(Application.load('apikeys.json'))
if signum is None:
self.door_settings.update(Application.load('last.json'))
if not self.get('last.ring'):
self.set('last.ring', '')
if not self.get('last.open'):
self.set('last.open', '')
def ring_callback(self, secret_key: str, first_ring: bool, follow_up: bool) -> None:
"""
Handle a ring event
:param secret_key: The key to open
:param first_ring: True if first ring
:param follow_up: True if follow-up ring within timeout
:type secret_key: str
:type first_ring: bool
:type follow_up: bool
"""
logging.debug("RINGCALLBACK for %s" % self.get('door.name'))
timestamp = time.time()
self.set('last.ring', "%s" % timestamp)
# Inform WebSocket Clients
payload = ({
"action": "ring",
"secret": "%s" % secret_key,
"timestamp": "%s" % timestamp
})
WebSocketHandler.send_update(tornado.escape.json_encode(payload))
# Inform Slack
if SlackHandler.validate(self):
if first_ring:
SlackHandler.send(self, "slack_1st_ring.json", "@here *DING DONG*", secret_key)
else:
SlackHandler.send(self, "slack_ring.json", "*DING DONG* ... *DING DONG*", secret_key)
def timeout_callback(self, runtime: int) -> None:
"""
Handle a timeout event
:param runtime: time in seconds from first ring
:type runtime: int
"""
logging.debug("TIMEOUTCALLBACK for %s after %s seconds" % (self.get('door.name'), runtime))
timestamp = time.time()
# Inform WebSocket Clients
payload = ({
"action": "timeout",
"timestamp": "%s" % timestamp
})
WebSocketHandler.send_update(tornado.escape.json_encode(payload))
# Inform Slack
if SlackHandler.validate(self):
SlackHandler.send(self, "slack_timeout.json", "Door wasn't opened after %s seconds." % runtime)
# Inform ThingSpeak
if self.get('thingspeak.writeAPIKey') and self.get('thingspeak.field.timeout'):
requests.get('https://api.thingspeak.com/update.json?api_key=%s&%s=%s' %
(self.get('thingspeak.writeAPIKey'), self.get('thingspeak.field.timeout'), runtime))
def open_callback(self, runtime: int) -> None:
"""
Handle a open event
:param runtime: time in seconds from first ring
:type runtime: int
"""
logging.debug("OPENCALLBACK for %s after %s seconds" % (self.get('door.name'), runtime))
timestamp = time.time()
self.set('last.open', "%s" % timestamp)
# Inform WebSocket Clients
payload = ({
"action": "open",
"timestamp": "%s" % timestamp
})
WebSocketHandler.send_update(tornado.escape.json_encode(payload))
# Inform Slack
if SlackHandler.validate(self):
SlackHandler.send(self, "slack_open.json", "Door was opened after %s seconds." % runtime)
# Inform ThingSpeak
if self.get('thingspeak.writeAPIKey') and self.get('thingspeak.field.open'):
requests.get('https://api.thingspeak.com/update.json?api_key=%s&%s=%s' %
(self.get('thingspeak.writeAPIKey'), self.get('thingspeak.field.open'), runtime))
def handle_sigterm(signum=None, frame=None):
"""
Saves current state on sigterm (systemctl stop doorpi-agent.service)
end exists.
:param signum: signature parameter
:param frame: signature parameter
"""
global app
with open('last.json', 'w') as file:
json.dump({
"doorpi.last.open": "%s" % app.get('last.open'),
"doorpi.last.ring": "%s" % app.get('last.ring')
}, file)
if DoorPhone.instance().timeout_thread is not None:
logging.debug("Stopping running DoorPhone.timeout_thread")
DoorPhone.instance().timeout_thread.stop()
tornado.ioloop.IOLoop.current().stop()
# Inform Slack
if SlackHandler.validate(app):
SlackHandler.send(app, "slack_doorpi.json", "DoorPI stopped")
sys.exit(0)
def main():
"""
Main entry point
"""
global app
app = Application()
DoorPhone(callback=app,
gpio_ring=int(app.get('gpio.ring', default=24)),
gpio_open=int(app.get('gpio.open', default=23)))
signal.signal(signal.SIGUSR1, app.load_settings)
signal.signal(signal.SIGTERM, handle_sigterm)
app.listen(port=app.get('listen.port'))
# Inform Slack
if SlackHandler.validate(app):
SlackHandler.send(app, "slack_doorpi.json", "DoorPI started (%s)" % app.get('slack.baseurl'))
try:
tornado.ioloop.IOLoop.current().start()
except KeyboardInterrupt:
handle_sigterm()
if __name__ == "__main__":
""" DoorPI Application """
main()
"""
th = TestHandler()
x = DoorPhone(ring_callback=th, timeout_callback=th)
time.sleep(1)
x.open_door("-")
x.simulate_ring()
time.sleep(1)
x.simulate_ring()
"""