-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
362 lines (287 loc) · 10.7 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
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
from collections import OrderedDict
from events import EventTable
from flask import render_template
from flask import request
from flask import send_from_directory
from flask import Flask
from markupsafe import escape
from service import CRUDService
from utils import bits2int
from utils import config2dict
from utils import event2str
from utils import getSunriseTime
from utils import getSunsetTime
from utils import getWeekdays
from utils import int2bits
from utils import sqlrow2dict
from utils import timetuple2str
from utils import weekdays2bits
from utils import TIMED_EVENT_MODES
import os
import subprocess
import time
def create_app():
config = config2dict('config.json')
# absolute path to the codesend binary
# from https://github.com/ninjablocks/433Utils
codesendBinPath = config['codesend-bin-path']
if not os.path.isfile(codesendBinPath):
print('\n\n\033[1mcodesend binary not found!')
print('Set correct path in config.json\033[0m')
print('(See README.md for more information.)\n\n')
exit()
app = Flask(__name__,
template_folder='.',
static_url_path='')
import db
db.init_app(app)
@app.route('/')
def index():
return render_template('./index.html', title='Sloth Tools')
def sendCode(code, protocol, pulselength, iterations):
if not os.path.isfile(codesendBinPath):
return 'codesend binary not found'
args = ['sudo', codesendBinPath, code, protocol, pulselength]
FNULL = open(os.devnull, 'w')
for i in range(iterations):
proc = subprocess.Popen(args, stdout=FNULL)
proc.wait()
return 'sent ({0}x): {1}'.format(escape(iterations), escape(code))
def setNodeState(nodeId, state):
import db
db = db.get_db()
db.execute('UPDATE node SET state = ? WHERE id = ?;', (state, nodeId))
db.commit()
def switchNode(nodeId, state):
nodeService = CRUDService('node')
stateStr = 'codeOn'
if state == 0:
stateStr = 'codeOff'
node = nodeService.read(nodeId)
res = sendCode(node[stateStr], node['protocol'], node['pulselength'], node['iterations'])
if len(res) > 0:
setNodeState(node['id'], state)
return res
def toggleNode(nodeId):
nodeService = CRUDService('node')
node = nodeService.read(id=nodeId)
state = node['state']
res = switchNode(nodeId, abs(state - 1))
res += '<br/>'
time.sleep(1)
res += switchNode(nodeId, state)
return res
@app.route('/on')
def switchOn():
nodeId = request.args.get('id')
if nodeId is None:
res = ''
nodeService = CRUDService('node')
nodes = nodeService.read()
for node in nodes:
nodeRes = switchNode(node['id'], 1)
res += nodeRes + '<br/>'
else:
res = switchNode(nodeId, 1)
return res
@app.route('/off')
def switchOff():
nodeId = request.args.get('id')
if nodeId is None:
res = ''
nodeService = CRUDService('node')
nodes = nodeService.read()
for node in nodes:
nodeRes = switchNode(node['id'], 0)
res += nodeRes + '<br/>'
else:
res = switchNode(nodeId, 0)
return res
@app.route('/toggle')
def toggle():
nodeId = request.args.get('id')
if nodeId is None:
res = ''
nodeService = CRUDService('node')
nodes = nodeService.read()
for node in nodes:
nodeRes = toggleNode(node['id'])
res += nodeRes + '<br/>'
else:
res = toggleNode(nodeId)
return res
# node API
@app.route('/nodes')
def nodes():
nodeService = CRUDService('node')
nodes = nodeService.readAll(
order_by='sort_order', order_mode='ASC')
return render_template('./nodes.html', nodes=nodes)
@app.route('/node/create', methods=['GET', 'POST'])
def nodeCreate():
nodeService = CRUDService('node')
node = None
jsonData = request.get_json(silent=True)
if jsonData is not None:
node = jsonData
# get currently highest sort_order value
allNodes = nodeService.readAll(order_by='sort_order', order_mode='DESC')
if len(allNodes) > 0:
# to make sure new node is appended at the end
node['sort_order'] = allNodes[0]['sort_order'] + 1
else:
node['sort_order'] = 0
if nodeService.create(node):
return 'OK'
if node is None:
node = nodeService.getEmpty()
node['protocol'] = ''
node['pulselength'] = ''
node['iterations'] = '1'
return render_template(
'./node.html', node=node,
action='/node/create', method='POST',
title='Add node', submitLabel='Create')
@app.route('/node/read/<int:id>', methods=['GET'])
def nodeRead(id):
nodeService = CRUDService('node')
node = nodeService.read(id)
return dict(node)
@app.route('/node/update/<int:id>', methods=['GET', 'POST'])
def nodeUpdate(id):
node = None
nodeService = CRUDService('node')
jsonData = request.get_json(silent=True)
if jsonData is not None:
node = jsonData
if nodeService.update(node):
return 'OK'
if node is None:
node = nodeService.read(id)
actionUrl = '/node/update/{0}'.format(id)
return render_template(
'./node.html', node=node,
action=actionUrl, method='POST',
title='Update node [id:' + str(id) + ']', submitLabel='Update')
@app.route('/node/delete/<int:id>', methods=['DELETE'])
def nodeDelete(id):
nodeService = CRUDService('node')
nodeService.delete(id)
return 'OK'
@app.route('/node/reorder/<int:posFrom>/<int:posTo>', methods=['POST'])
def nodeReorder(posFrom, posTo):
# flips sort_order positions of two nodes
nodeService = CRUDService('node')
nodeFrom = dict(nodeService.readBy('sort_order', posFrom)[0])
nodeTo = dict(nodeService.readBy('sort_order', posTo)[0])
nodeTo['sort_order'] = -1
nodeService.update(nodeTo)
nodeFrom['sort_order'] = posTo
nodeService.update(nodeFrom)
nodeTo['sort_order'] = posFrom
nodeService.update(nodeTo)
return 'OK'
# event API
@app.route('/event/create/<int:nodeId>', methods=['GET', 'POST'])
def eventCreate(nodeId):
eventService = CRUDService('event')
event = None
jsonData = request.get_json(silent=True)
if jsonData is not None:
event = jsonData
event['nodeIdRef'] = nodeId
if event['switchOn'] == 'True':
event['switchOn'] = True
else:
event['switchOn'] = False
bits = weekdays2bits(event)
event['weekdays'] = bits2int(bits)
event['mode'] = TIMED_EVENT_MODES[event['mode']]
if eventService.create(event):
# update eventTable:
app.eventTable.loadFromDB()
return 'OK'
if event is None:
event = eventService.getEmpty()
event['weekdays'] = bits2int([] * 7) # all day
event['hour'] = 12
event['minute'] = 0
event['sunriseOffset'] = 0
event['sunsetOffset'] = 0
event['randomOffset'] = 0
nodeService = CRUDService('node')
node = nodeService.read(nodeId)
sunriseTime = getSunriseTime(config['longitude'], config['latitude'])
sunsetTime = getSunsetTime(config['longitude'], config['latitude'])
return render_template(
'./event.html', event=event, node=node,
action='/event/create/' + str(nodeId), method='POST',
sunrise=timetuple2str(sunriseTime),
sunset=timetuple2str(sunsetTime),
title='Add event for ' + node['title'], submitLabel='Create')
@app.route('/event/read/<int:id>', methods=['GET'])
def eventRead(id):
eventService = CRUDService('event')
event = eventService.read(id)
return dict(event)
@app.route('/event/bynode/<int:nodeId>', methods=['GET'])
def eventReadByNode(nodeId):
eventService = CRUDService('event')
rows = eventService.readBy('nodeIdRef', nodeId)
events = []
for row in rows:
event = sqlrow2dict(row)
event['hour'] = str(event['hour']).zfill(2)
event['minute'] = str(event['minute']).zfill(2)
event['asStr'] = event2str(event, html=False)
event['asHtml'] = event2str(event, html=True)
bits = int2bits(event['weekdays'])
event['weekdays'] = OrderedDict()
days = getWeekdays()
i = 0
for day in days:
event['weekdays'][day] = bits[i]
i += 1
events.append(event)
nodeService = CRUDService('node')
node = nodeService.read(nodeId)
return render_template('./events.html', events=events, node=node)
@app.route('/event/update/<int:id>', methods=['GET', 'POST'])
def eventUpdate(id):
event = None
eventService = CRUDService('event')
jsonData = request.get_json(silent=True)
if jsonData is not None:
event = jsonData
if eventService.update(event):
# update eventTable:
app.eventTable.loadFromDB()
return 'OK'
if event is None:
event = eventService.read(id)
actionUrl = '/event/update/{0}'.format(id)
return render_template(
'./event.html', event=event,
action=actionUrl, method='POST',
title='Update event', submitLabel='Update')
@app.route('/event/delete/<int:id>', methods=['DELETE'])
def eventDelete(id):
eventService = CRUDService('event')
eventService.delete(id)
# update eventTable:
app.eventTable.loadFromDB()
return 'OK'
@app.route('/static/<path:path>')
def sendStaticResources(path):
return send_from_directory('static', path)
with app.app_context():
app.eventTable = EventTable(app, config, switchNode, interval=10)
# make sure timer is stopped when server stops
def stopEventTimer():
app.eventTable.stopTimer()
import atexit
atexit.register(stopEventTimer)
return app
if __name__ == '__main__':
app = create_app()
app.run()