forked from andrewshilliday/garage-door-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.py
executable file
·430 lines (365 loc) · 16.2 KB
/
controller.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import time, syslog, uuid
import smtplib
import socket
import RPi.GPIO as gpio
import json
import httplib
import os
from twisted.internet import task
from twisted.internet import reactor
from twisted.internet.protocol import DatagramProtocol
from twisted.web import server
from twisted.web.static import File
from twisted.web.resource import Resource, IResource
from zope.interface import implements
from BaseHTTPServer import BaseHTTPRequestHandler
from StringIO import StringIO
from twisted.cred import checkers, portal
from twisted.web.guard import HTTPAuthSessionWrapper, DigestCredentialFactory, BasicCredentialFactory
class HttpPasswordRealm(object):
implements(portal.IRealm)
def __init__(self, myresource):
self.myresource = myresource
def requestAvatar(self, user, mind, *interfaces):
if IResource in interfaces:
return (IResource, self.myresource, lambda: None)
raise NotImplementedError()
class Door(object):
last_action = None
last_action_time = None
msg_sent = False
pb_iden = None
def __init__(self, doorId, config):
self.id = doorId
self.name = config['name']
self.relay_pin = config['relay_pin']
self.state_pin = config['state_pin']
self.time_to_close = config.get('time_to_close', 10)
self.time_to_open = config.get('time_to_open', 10)
self.openhab_name = config.get('openhab_name')
self.open_time = time.time()
gpio.setup(self.relay_pin, gpio.OUT)
gpio.setup(self.state_pin, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.output(self.relay_pin, True)
def get_state(self):
if gpio.input(self.state_pin) == 0:
return 'closed'
elif self.last_action == 'open':
if time.time() - self.last_action_time >= self.time_to_open:
return 'open'
else:
return 'opening'
elif self.last_action == 'close':
if time.time() - self.last_action_time >= self.time_to_close:
return 'open' # This state indicates a problem
else:
return 'closing'
else:
return 'open'
def toggle_relay(self):
state = self.get_state()
if (state == 'open'):
self.last_action = 'close'
self.last_action_time = time.time()
elif state == 'closed':
self.last_action = 'open'
self.last_action_time = time.time()
else:
self.last_action = None
self.last_action_time = None
gpio.output(self.relay_pin, False)
time.sleep(0.2)
gpio.output(self.relay_pin, True)
class Request(BaseHTTPRequestHandler):
def __init__(self, request_text):
self.rfile = StringIO(request_text)
self.raw_requestline = self.rfile.readline()
self.error_code = self.error_message = None
self.parse_request()
def send_error(self, code, message):
self.error_code = code
self.error_message = message
class Controller():
def __init__(self, config, subscriptions):
gpio.setwarnings(False)
gpio.cleanup()
gpio.setmode(gpio.BCM)
self.config = config
self.subscriptions = subscriptions
self.doors = [Door(n,c) for (n,c) in config['doors'].items()]
self.updateHandler = UpdateHandler(self)
for door in self.doors:
door.last_state = 'unknown'
door.last_state_time = time.time()
self.use_alerts = config['config']['use_alerts']
self.alert_type = config['alerts']['alert_type']
self.ttw = config['alerts']['time_to_wait']
if self.alert_type == 'smtp':
self.use_smtp = False
smtp_params = ("smtphost", "smtpport", "smtp_tls", "username",
"password", "to_email", "time_to_wait")
self.use_smtp = ('smtp' in config['alerts']) and set(smtp_params) == set(config['alerts']['smtp'])
syslog.syslog("we are using SMTP")
elif self.alert_type == 'pushbullet':
self.pushbullet_access_token = config['alerts']['pushbullet']['access_token']
syslog.syslog("we are using Pushbullet")
else:
self.alert_type = None
syslog.syslog("No alerts configured")
def status_check(self):
for door in self.doors:
new_state = door.get_state()
if (door.last_state != new_state):
syslog.syslog('%s: %s => %s' % (door.name, door.last_state, new_state))
door.last_state = new_state
door.last_state_time = time.time()
self.updateHandler.handle_updates()
if self.config['config']['use_openhab'] and (new_state == "open" or new_state == "closed"):
self.update_openhab(door.openhab_name, new_state)
if hasattr(self, "subscribe_handler") and (new_state == "open" or new_state == "closed"):
self.subscribe_handler.send_subscriptions(door.name)
if new_state == 'open' and not door.msg_sent and time.time() - door.open_time >= self.ttw:
if self.use_alerts:
title = "%s's garage door open" % door.name
message = "%s's garage door has been open for %s" % (door.name,
elapsed_time(int(time.time() - door.open_time)))
if self.alert_type == 'smtp':
self.send_email(title, message)
elif self.alert_type == 'pushbullet':
self.send_pushbullet(door, title, message)
door.msg_sent = True
if new_state == 'closed':
if self.use_alerts:
if door.msg_sent == True:
title = "%s's garage doors closed" % door.name
message = "%s's garage door is now closed after %s "% (door.name,
elapsed_time(int(time.time() - door.open_time)))
if self.alert_type == 'smtp':
self.send_email(title, message)
elif self.alert_type == 'pushbullet':
self.send_pushbullet(door, title, message)
door.open_time = time.time()
door.msg_sent = False
def send_email(self, title, message):
if self.use_smtp:
syslog.syslog("Sending email message")
config = self.config['alerts']['smtp']
server = smtplib.SMTP(config["smtphost"], config["smtpport"])
if (config["smtp_tls"] == "True") :
server.starttls()
server.login(config["username"], config["password"])
server.sendmail(config["username"], config["to_email"], message)
server.close()
def send_pushbullet(self, door, title, message):
syslog.syslog("Sending pushbutton message")
config = self.config['alerts']['pushbullet']
if door.pb_iden != None:
conn = httplib.HTTPSConnection("api.pushbullet.com:443")
conn.request("DELETE", '/v2/pushes/' + door.pb_iden, "",
{'Authorization': 'Bearer ' + config['access_token'], 'Content-Type': 'application/json'})
conn.getresponse()
door.pb_iden = None
conn = httplib.HTTPSConnection("api.pushbullet.com:443")
conn.request("POST", "/v2/pushes",
json.dumps({
"type": "note",
"title": title,
"body": message,
}), {'Authorization': 'Bearer ' + config['access_token'], 'Content-Type': 'application/json'})
door.pb_iden = json.loads(conn.getresponse().read())['iden']
def update_openhab(self, item, state):
syslog.syslog("Updating openhab")
config = self.config['openhab']
conn = httplib.HTTPConnection("%s:%s" % (config['server'], config['port']))
conn.request("PUT", "/rest/items/%s/state" % item, state)
conn.getresponse()
def toggle(self, doorId):
for d in self.doors:
if d.id == doorId:
syslog.syslog('%s: toggled' % d.name)
d.toggle_relay()
return
def get_clean_updates(self):
updates = {}
for d in self.doors:
updates[d.id] = d.last_state
return updates
def get_updates(self, lastupdate):
updates = []
for d in self.doors:
if d.last_state_time >= lastupdate:
updates.append((d.id, d.last_state, d.last_state_time))
return updates
def run(self):
task.LoopingCall(self.status_check).start(0.5)
root = File('www')
root.putChild('upd', self.updateHandler)
root.putChild('cfg', ConfigHandler(self))
root.putChild('status', StatusHandler(self))
if self.config['config']['use_auth']:
clk = ClickHandler(self)
args={self.config['site']['username']:self.config['site']['password']}
checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(**args)
realm = HttpPasswordRealm(clk)
p = portal.Portal(realm, [checker])
credentialFactory = BasicCredentialFactory("Garage Door Controller")
protected_resource = HTTPAuthSessionWrapper(p, [credentialFactory])
root.putChild('clk', protected_resource)
else:
root.putChild('clk', ClickHandler(self))
if self.config['config']['use_smartthings']:
self.subscribe_handler = SubscribeHandler(self)
root.putChild('subscribe', self.subscribe_handler)
site = server.Site(root)
reactor.listenTCP(self.config['site']['port'], site) # @UndefinedVariable
reactor.run() # @UndefinedVariable
class ClickHandler(Resource):
isLeaf = True
def __init__ (self, controller):
Resource.__init__(self)
self.controller = controller
def render(self, request):
door = request.args['id'][0]
self.controller.toggle(door)
request.setHeader('Content-Type', 'application/json')
return json.dumps({ 'response_code': 200 })
class StatusHandler(Resource):
isLeaf = True
def __init__(self, controller):
Resource.__init__(self)
self.controller = controller
def render_GET(self, request):
door = request.args['door'][0]
statuses = self.controller.get_clean_updates()
syslog.syslog("Sending status: " + door + ":" + statuses[door])
request.setHeader('Content-Type', 'application/json')
return json.dumps({ 'status': statuses[door], 'door': door, "type": "status", })
class SubscribeHandler(Resource):
isLeaf = True
def __init__(self, controller):
Resource.__init__(self)
self.controller = controller
def send_subscriptions(self, door):
statuses = self.controller.get_clean_updates()
if door in self.controller.subscriptions:
callback = self.controller.subscriptions[door]
host = callback.replace("http://", "").split('/')[0]
path = callback.replace("http://" + host, "")
conn = httplib.HTTPConnection(host)
syslog.syslog("Sending subscription: " + callback + " status: " + statuses[door])
conn.request("POST", path,
json.dumps({
"door": door,
"type": "subscription",
"status": statuses[door]
}), { 'Content-Type': 'application/json' })
try:
resp = conn.getresponse()
resp_body = resp.read()
syslog.syslog("subscription response: " + str(resp.status) + " " + resp_body)
except Error as e:
syslog.syslog("Error sending subscription: " + str(e))
def render_POST(self, request):
syslog.syslog("Got subscription POST with args: " + str(request.args))
door = request.args['door'][0]
callback = request.getHeader('x-callback')
self.controller.subscriptions[door] = callback
with open('subscriptions.json', 'w+') as f:
json.dump(self.controller.subscriptions, f)
statuses = self.controller.get_clean_updates()
request.setHeader('Content-Type', 'application/json')
if not statuses[door]:
request.setResponseCode(500)
return json.dumps({ 'error': 'Unable to find status for that door' })
request.setResponseCode(201)
return json.dumps({ 'status': statuses[door] })
class ConfigHandler(Resource):
isLeaf = True
def __init__ (self, controller):
Resource.__init__(self)
self.controller = controller
def render(self, request):
request.setHeader('Content-Type', 'application/json')
return json.dumps([(d.id, d.name, d.last_state, d.last_state_time)
for d in controller.doors])
class UpdateHandler(Resource):
isLeaf = True
def __init__(self, controller):
Resource.__init__(self)
self.delayed_requests = []
self.controller = controller
def handle_updates(self):
for request in self.delayed_requests:
updates = self.controller.get_updates(request.lastupdate)
if updates != []:
self.send_updates(request, updates)
self.delayed_requests.remove(request);
def format_updates(self, request, update):
response = json.dumps({'timestamp': int(time.time()), 'update':update})
if hasattr(request, 'jsonpcallback'):
return request.jsonpcallback +'('+response+')'
else:
return response
def send_updates(self, request, updates):
request.write(self.format_updates(request, updates))
request.finish()
def render(self, request):
# set the request content type
request.setHeader('Content-Type', 'application/json')
# set args
args = request.args
# set jsonp callback handler name if it exists
if 'callback' in args:
request.jsonpcallback = args['callback'][0]
# set lastupdate if it exists
if 'lastupdate' in args:
request.lastupdate = float(args['lastupdate'][0])
else:
request.lastupdate = 0
#print "request received " + str(request.lastupdate)
# Can we accommodate this request now?
updates = controller.get_updates(request.lastupdate)
if updates != []:
return self.format_updates(request, updates)
request.notifyFinish().addErrback(lambda x: self.delayed_requests.remove(request))
self.delayed_requests.append(request)
# tell the client we're not done yet
return server.NOT_DONE_YET
def elapsed_time(seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '):
"""
Takes an amount of seconds and turns it into a human-readable amount of time.
"""
# the formatted time string to be returned
time = []
# the pieces of time to iterate over (days, hours, minutes, etc)
# - the first piece in each tuple is the suffix (d, h, w)
# - the second piece is the length in seconds (a day is 60s * 60m * 24h)
parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52),
(suffixes[1], 60 * 60 * 24 * 7),
(suffixes[2], 60 * 60 * 24),
(suffixes[3], 60 * 60),
(suffixes[4], 60),
(suffixes[5], 1)]
# for each time piece, grab the value and remaining seconds, and add it to
# the time string
for suffix, length in parts:
value = seconds / length
if value > 0:
seconds = seconds % length
time.append('%s%s' % (str(value),
(suffix, (suffix, suffix + 's')[value > 1])[add_s]))
if seconds < 1:
break
return separator.join(time)
def load_subscriptions(config):
if os.path.isfile('subscriptions.json'):
return json.load(open('subscriptions.json'))
return {}
if __name__ == '__main__':
syslog.openlog('garage_controller')
config_file = open('config.json')
config = json.load(config_file)
subscriptions = load_subscriptions(config)
controller = Controller(config, subscriptions)
config_file.close()
controller.run()