forked from andrewshilliday/garage-door-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.py
executable file
·427 lines (364 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
"""Software to monitor and control garage doors via a raspberry pi."""
import time, syslog, uuid
import smtplib
import RPi.GPIO as gpio
import json
import httplib
import urllib
import subprocess
from twisted.internet import task
from twisted.internet import reactor
from twisted.internet import ssl
from twisted.web import server
from twisted.web.static import File
from twisted.web.resource import Resource, IResource
from zope.interface import implements
from twisted.cred import checkers, portal
from twisted.web.guard import HTTPAuthSessionWrapper, BasicCredentialFactory
from email.mime.text import MIMEText
from email.utils import formatdate
from email.utils import make_msgid
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.state_pin_closed_value = config.get('state_pin_closed_value', 0)
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) == self.state_pin_closed_value:
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 Controller(object):
def __init__(self, config):
gpio.setwarnings(False)
gpio.cleanup()
gpio.setmode(gpio.BCM)
self.config = config
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")
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")
elif self.alert_type == 'pushover':
self.pushover_user_key = config['alerts']['pushover']['user_key']
syslog.syslog("we are using Pushover")
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 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
etime = elapsed_time(int(time.time() - door.open_time))
message = "%s's garage door has been open for %s" % (door.name, etime)
if self.alert_type == 'smtp':
self.send_email(title, message)
elif self.alert_type == 'pushbullet':
self.send_pushbullet(door, title, message)
elif self.alert_type == 'pushover':
self.send_pushover(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
etime = elapsed_time(int(time.time() - door.open_time))
message = "%s's garage door is now closed after %s "% (door.name, etime)
if self.alert_type == 'smtp':
self.send_email(title, message)
elif self.alert_type == 'pushbullet':
self.send_pushbullet(door, title, message)
elif self.alert_type == 'pushover':
self.send_pushover(door, title, message)
door.open_time = time.time()
door.msg_sent = False
def send_email(self, title, message):
try:
if self.use_smtp:
syslog.syslog("Sending email message")
config = self.config['alerts']['smtp']
message = MIMEText(message)
message['Date'] = formatdate()
message['From'] = config["username"]
message['To'] = config["to_email"]
message['Subject'] = config["subject"]
message['Message-ID'] = make_msgid()
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.as_string())
server.close()
except Exception as inst:
syslog.syslog("Error sending email: " + str(inst))
def send_pushbullet(self, door, title, message):
try:
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'})
response = conn.getresponse().read()
print(response)
door.pb_iden = json.loads(response)['iden']
except Exception as inst:
syslog.syslog("Error sending to pushbullet: " + str(inst))
def send_pushover(self, door, title, message):
try:
syslog.syslog("Sending Pushover message")
config = self.config['alerts']['pushover']
conn = httplib.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urllib.urlencode({
"token": config['api_key'],
"user": config['user_key'],
"title": title,
"message": message,
}), { "Content-type": "application/x-www-form-urlencoded" })
conn.getresponse()
except Exception as inst:
syslog.syslog("Error sending to pushover: " + str(inst))
def update_openhab(self, item, state):
try:
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()
except:
syslog.syslog("Error updating openhab: " + str(inst))
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_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 get_config_with_default(self, config, param, default):
if not config:
return default
if not param in config:
return default
return config[param]
def run(self):
task.LoopingCall(self.status_check).start(0.5)
root = File('www')
root.putChild('st', StatusHandler(self))
root.putChild('upd', self.updateHandler)
root.putChild('cfg', ConfigHandler(self))
root.putChild('upt', UptimeHandler(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))
site = server.Site(root)
if not self.get_config_with_default(self.config['config'], 'use_https', False):
reactor.listenTCP(self.config['site']['port'], site) # @UndefinedVariable
reactor.run() # @UndefinedVariable
else:
sslContext = ssl.DefaultOpenSSLContextFactory(self.config['site']['ssl_key'], self.config['site']['ssl_cert'])
reactor.listenSSL(self.config['site']['port_secure'], site, sslContext) # @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)
return 'OK'
class StatusHandler(Resource):
isLeaf = True
def __init__ (self, controller):
Resource.__init__(self)
self.controller = controller
def render(self, request):
door = request.args['id'][0]
for d in self.controller.doors:
if (d.id == door):
return d.last_state
return ''
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 self.controller.doors])
class UptimeHandler(Resource):
isLeaf = True
def __init__ (self, controller):
Resource.__init__(self)
def render(self,request):
request.setHeader('Content-Type', 'application/json')
uptime = subprocess.check_output(['uptime', '-p']).strip()
uptime = uptime.replace("up ", "")
uptime = uptime.split(",")[0].replace(",","").strip()
if (uptime == "up"):
uptime = "0 mins"
return json.dumps("Uptime: " + uptime)
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 = self.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)
if __name__ == '__main__':
syslog.openlog('garage_controller')
config_file = open('config.json')
controller = Controller(json.load(config_file))
config_file.close()
controller.run()