-
Notifications
You must be signed in to change notification settings - Fork 0
/
ardupet.py
72 lines (52 loc) · 1.95 KB
/
ardupet.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
"""ArduPET is an office automation implementation. It is originally designed to
be use at the Tutorial Education Program (PET in pt-BR, hence the name) to turn
lamps on and off and unlock the door, while also checking the statuses.
Routes:
GET /lamp -- lists all lamps statuses
GET /lamp/<id> -- get the status of the lamp identified by <id>
PUT /lamp/<id> -- update the status of the lamp identified by <id>
GET /door -- get the status of the door
PUT /door -- unlock the door (unlocking relocks after some seconds)
"""
import flask
import serial
app = flask.Flask(__name__)
arduino = serial.Serial('/dev/ttyACM0', 9600)
LAMP_COUNT = 2
@app.route('/lamp', methods=['GET'])
def lamp_index():
"""Return a listing of all lamps statuses."""
return '', 501
@app.route('/lamp/<int:lamp_id>', methods=['GET', 'PUT'])
def lamp_status(lamp_id):
"""Read or update the status of a single lamp.
Keyword arguments:
id -- the id of the desired lamp.
"""
if lamp_id < 0 or lamp_id >= LAMP_COUNT:
flask.abort(404)
if flask.request.method == 'GET':
"""Bytes sent are: operation (r), target (l), id"""
call = ''.join(['r', 'l', chr(lamp_id)])
arduino.write(bytes(call, 'ASCII'))
status = ord(arduino.read())
return ''.join(['Lamp is ', 'on' if status else 'off']), 200
elif flask.request.method == 'PUT':
call = ''.join(['w', 'l', chr(lamp_id)])
arduino.write(bytes(call, 'ASCII'))
return '', 204
@app.route('/door', methods=['GET', 'PUT'])
def door_status():
"""Read the status or update (unlock) the door."""
if flask.request.method == 'GET':
"""Bytes sent are: operation (r), target(d), none (ignored)"""
call = ''.join(['r', 'd', '\0'])
arduino.write(bytes(call, 'ASCII'))
status = ord(arduino.read())
return ''.join(['Door is ', 'unlocked' if status else 'locked']), 200
elif flask.request.method == 'PUT':
call = ''.join(['w', 'd', '\0'])
arduino.write(bytes(call, 'ASCII'))
return '', 204
if __name__ == "__main__":
app.run(host='0.0.0.0')