/
server.py
200 lines (172 loc) · 6.39 KB
/
server.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
#!/usr/bin/python3
# Copyright 2015 Jetperch LLC
# This file is licensed under the MIT License
# http://opensource.org/licenses/MIT
# Requires Python 3.x with packages:
# pip3 install cherrypy ws4py requests Jinja2
#
import cherrypy
from cherrypy.lib import auth_digest
import requests
from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from ws4py.websocket import WebSocket
import yaml
import os
from jinja2 import Environment, PackageLoader
from collections import OrderedDict
MYDIR = os.path.dirname(os.path.abspath(__file__))
AUTH_FILE = os.path.join(MYDIR, 'auth.yaml')
STATIC_DIR = os.path.join(MYDIR, 'mcu_server', 'www', 'static')
def load_auth():
with open(AUTH_FILE, 'r') as f:
return yaml.load(f)
AUTH = load_auth()
# See http://www.ralph-heinkel.com/blog/category/web/
class Publisher(WebSocket):
SUBSCRIBERS = set()
def __init__(self, *args, **kwargs):
WebSocket.__init__(self, *args, **kwargs)
print('WebSocket created')
self.SUBSCRIBERS.add(self)
def received_message(self, msg):
if msg.is_text:
text = msg.data.decode('utf-8')
print('received_message: %s' % text)
else:
print('received_message: [binary_data]')
def closed(self, code, reason=None):
self.SUBSCRIBERS.remove(self)
@staticmethod
def publish(msg):
print('publish(%s)' % (msg))
for subscriber in Publisher.SUBSCRIBERS:
subscriber.send(msg)
def electricimp(mode='OFF'):
"""Control the Electric Imp device.
:param mode: The mode which is defined by the agent and is either
"OFF" or "rotate_hue".
"""
url = 'https://agent.electricimp.com/%s' % AUTH['electric_imp']['agent']
args = {'setMode': mode}
print('post to %s' % url)
requests.post(url, data=args)
def particle(mode='OFF'):
"""Control the Particle Core device.
:param mode: The mode which is defined by the Spark code and is either
"OFF" or "ROTATE_HUE".
"""
url = 'https://api.particle.io/v1/devices/%s/mode' % AUTH['particle']['device']
args = {'access_token': AUTH['particle']['token'],
'params': mode}
print('post to %s' % url)
requests.post(url, data=args)
class McuProtoServer(object):
def __init__(self):
# Map device identifier to a dict of configuration properties
# name: The user-meaningful device name.
# ide_name: The user-meaningful IDE name.
# ide_url: The URL for the IDE suitable for a web browser.
# permission: The current public permission: true is enabled.
# OFF: The callable to turn off the device.
# ON: The callable to turn on the device.
self.devices = OrderedDict([
('ElectricImp', {
'name': 'Electric Imp',
'ide_name': 'IDE',
'ide_url': 'https://ide.electricimp.com',
'permission': False,
'OFF': lambda: electricimp('OFF'),
'ON': lambda: electricimp('rotate_hue')
}),
('ParticleCore', {
'name': 'Particle Core',
'ide_name': 'IDE',
'ide_url': 'https://build.particle.io/build',
'permission': False,
'OFF': lambda: particle('OFF'),
'ON': lambda: particle('ROTATE_HUE')
}),
('CC3200', {
'name': 'CC3200',
'ide_name': 'Energia',
'ide_url': 'http://energia.nu/',
'permission': False,
'OFF': lambda: self.publish('CC3200_OFF'),
'ON': lambda: self.publish('CC3200_ON')
}),
('mbed', {
'name': 'FRDM-K64F',
'ide_name': 'mbed',
'ide_url': 'http://developer.mbed.org/compiler/',
'permission': False,
'OFF': lambda: self.publish('mbed_OFF'),
'ON': lambda: self.publish('mbed_ON')
}),
])
self.env = Environment(loader=PackageLoader('mcu_server', 'www'),
trim_blocks=True,
line_statement_prefix='@')
def render(self, page, **kwargs):
template = self.env.get_template(page)
return template.render(**kwargs)
@cherrypy.expose
def index(self):
return self.render('index.html', status='', devices=self.devices, auth=False)
@cherrypy.expose
def ws(self):
pass # delegate to handler
@cherrypy.expose
def control(self, device, action):
if device not in self.devices:
return 'device not found'
d = self.devices[device]
if not d['permission']:
return 'access denied'
if action not in d:
return 'control not found'
d[action]()
return 'done!'
def publish(self, msg):
Publisher.publish(msg)
return "Done!"
@cherrypy.expose
def auth(self, device=None):
if device is None:
status = ""
elif device in self.devices:
d = self.devices[device]
permissions = not d['permission']
d['permission'] = permissions
if not permissions:
print('Turning off %s' % d['name'])
d['OFF']()
status = "success"
else:
status = "Device not found: %s" % device
return self.render('index.html', status=status, devices=self.devices, auth=True)
if __name__ == '__main__':
cherrypy.config.update({
'server.socket_host': '0.0.0.0',
'server.socket_port': 8080
})
WebSocketPlugin(cherrypy.engine).subscribe()
cherrypy.tools.websocket = WebSocketTool()
cherrypy.tree.mount(McuProtoServer(), '/', {
'/ws': {
'tools.websocket.on': True,
'tools.websocket.handler_cls': Publisher,
},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': STATIC_DIR,
},
'/auth': {
'tools.auth_digest.on': True,
'tools.auth_digest.realm': 'localhost',
'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(AUTH['server']),
'tools.auth_digest.key': 'a565c27146791cfb',
},
})
cherrypy.engine.signals.subscribe()
cherrypy.engine.start()
cherrypy.engine.block()