-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.py
More file actions
93 lines (81 loc) · 2.78 KB
/
interface.py
File metadata and controls
93 lines (81 loc) · 2.78 KB
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
import json
from flask import Flask
API_VERSION = '0.0.1'
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, world!'
class DeviceType(object):
'An enum of device types.'
Switch, Radio, Select, Knob = range(4)
class Device(object):
'A IOT device.'
def __init__(self, id_number, device_type, state):
self.id_number = id_number
self.device_type = device_type
self._state = state
def id(self):
'The unique ID number of the device.'
return self.id_number
def type(self):
'The type of device.'
return self.device_type
def state(self):
'The current state of the device.'
return self._state
def update(self, new_state):
'Update the state of the device.'
self._state = new_state
def serialize_device(device):
'Convert a device object into JSON.'
return json.dumps({
'id' : device.id(),
'type' : device.type(),
'state' : device.state()
})
def deserialize_device(text):
'Convert JSON into a device object.'
table = json.loads(text)
return Device(table['id'],
table['type'],
table['state'])
DEVICES = [
Device(0, DeviceType.Switch, 0),
Device(1, DeviceType.Switch, 1),
]
@app.route('/api/<version>/devices', methods = ['GET'])
def list_devices(version):
'Return a JSON list of all device objects.'
return json.dumps([json.loads(serialize_device(device))
for device in DEVICES])
@app.route('/api/<version>/devices/<int:id_number>', methods = ['GET'])
def get_device(version, id_number):
'Return the device with the given ID number.'
for device in DEVICES:
if device.id() == id_number:
return serialize_device(device)
return json.dumps({
'error' : 'id',
'message' : 'There was no device with the given ID.',
})
@app.route('/api/<version>/devices/<int:id_number>', methods = ['POST'])
def update_device(version, id_number):
'Update the state of the device with the given ID number.'
for device in DEVICES:
if device.id() == id_number:
if device.state() == DeviceType.Switch:
if new_state in ('ON', 'OFF'):
device.update(new_state == 'ON')
return '' #needs to return OKAY
else:
return json.dumps({
'error' : 'state',
'message' : 'Switches must be \'ON\' or \'OFF\', but state was \'%s\'.' % (new_state,),
})
elif device.state() == DeviceType.Radio:
pass
elif device.state() == DeviceType.Select:
pass
elif device.state() == DeviceType.Knob:
if __name__ == '__main__':
app.run()