-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrun.py
76 lines (62 loc) · 2.2 KB
/
run.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
from flask import Flask, request, render_template, redirect
import time
import twilio.twiml
app = Flask(__name__)
sensor_states = {}
allowed_sensor_ids = [u'upstairs-wc', u'downstairs-wc', u'sidestairs-wc']
allowed_sensor_vals = [u'0', u'1']
@app.route("/debug")
def set_status():
global sensor_states
now = int(time.time())
sensor_states = {u'upstairs-wc':{u'status':u'0', u'updated':now}, u'downstairs-wc':{u'status':u'1', u'updated':now}, u'sidestairs-wc':{u'status':u'0', u'updated':now}}
return redirect('/')
@app.route("/twilio/voice", methods=['POST'])
def twilio_voice():
"""Respond to incoming Twilio voice phone requests."""
resp = twilio.twiml.Response()
resp.say(get_sensor_state_msg('upstairs-wc'))
return str(resp)
@app.route("/twilio/text", methods=['POST'])
def twilio_text():
"""Respond to incoming Twilio SMS text message requests."""
resp = twilio.twiml.Response()
resp.sms(get_sensor_state_msg('upstairs-wc'))
return str(resp)
@app.route("/update", methods=['POST'])
def update_state():
"""Update state following request from remote sensor."""
if 'sensor_id' not in request.form or 'sensor_val' not in request.form:
return ""
sensor_id = request.form['sensor_id']
if sensor_id not in allowed_sensor_ids:
return ""
sensor_val = request.form['sensor_val']
if sensor_val not in allowed_sensor_vals:
return ""
sensor_time = int(time.time())
global sensor_states
sensor_states[sensor_id] = {'status': sensor_val, 'updated': sensor_time}
return ""
@app.route("/states", methods=['GET'])
def show_state():
global sensor_states
return str(sensor_states)
@app.route("/", methods=['GET'])
def web_state():
global sensor_states
now = int(time.time())
return render_template('index.html', sensors=sensor_states, time=now)
def get_sensor_state_msg(sensor_id):
global sensor_states
sensor = sensor_states[sensor_id]
state = sensor.get('status')
if state == '0':
return 'The bathroom is vacant.'
elif state == '1':
return 'The bathroom is occupied.'
else:
return 'The bathroom is undefined.'
if __name__ == '__main__':
app.debug = True
app.run()