forked from poppy-project/puppet-master
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbouteillederouge.py
393 lines (309 loc) · 11.2 KB
/
bouteillederouge.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import os
import sys
import requests
import argparse
import subprocess
from threading import Thread
from flask import (Flask, request, Markup,
redirect, url_for,
render_template, flash,
send_from_directory, Response,
copy_current_request_context)
from pypot.creatures import installed_poppy_creatures
from poppyd import PoppyDaemon
if sys.version_info < (3, 3):
from urlparse import urlparse
else:
from urllib.parse import urlparse
parser = argparse.ArgumentParser(description='Serve the webinterface '
'for controlling Poppy robots')
parser.add_argument('--debug', action='store_true',
help='use the debug mode')
parser.add_argument('--test', action='store_true',
help='does not modify anything on your machine '
'(except from a config file in /tmp)')
parser.add_argument('--creature', choices=installed_poppy_creatures.keys(),
help='Which creature to use (by default will use the one set in the yaml config).')
args = parser.parse_args()
if args.test:
from dummy_pm import PuppetMaster
else:
from puppet_master import PuppetMaster
app = Flask(__name__)
app.secret_key = os.urandom(24)
if args.debug:
app.debug = True
if args.test:
if not args.creature:
print('You must choose a creature in test mode!\n')
parser.print_help()
sys.exit(1)
configfile = '/tmp/poppy_config.yaml'
subprocess.call(['python', 'bootstrap.py',
'--config-path', configfile,
'localhost', args.creature])
else:
configfile = os.path.expanduser('~/.poppy_config.yaml')
pidfile = '/tmp/puppet-master-pid.lock'
pm = PuppetMaster(DaemonCls=PoppyDaemon,
configfile=configfile,
pidfile=pidfile)
if os.path.exists(pidfile):
pm.force_clean()
if pm.config.robot.autoStart:
pm.start()
else:
with open(pm.config.info.logfile, 'w') as log:
log.write('Auto-start API disable ! \nShow configuration page for enable auto-start, or start manually.')
log.close()
number=int(pm.config.robot.virtualBot)
if number>0:
pm.clone(number)
@app.context_processor
def inject_robot_config():
return dict(robot=pm.config.robot,
info=pm.config.info,
wifi=pm.config.wifi,
hotspot=pm.config.hotspot,
clone=pm.nb_clone)
@app.after_request
def cache_buster(response):
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
@app.route('/')
def index():
if pm.config.robot.firstPage:
return render_template('opening.html')
else:
return render_template('index.html')
@app.route('/end_opening')
def end_opening():
pm.update_config('robot.firstPage', False)
return render_template('index.html')
@app.route('/monitor')
def monitor():
if not pm.running:
flash(Markup('> API is <b>not running</b>, start before use Monitor. > Show <a href="{}">logs</a> or <a onclick="refreshForMsg(\'{}\')">Start</a> now'.format(url_for('logs'),url_for('APIstart'))), 'alert')
return render_template(
'base-iframe.html',
iframe_src=url_for(
'base_static_monitor',
filename='{}.html'.format(pm.config.robot.creature)
)
)
@app.route('/monitor/<path:filename>')
def base_static_monitor(filename):
return send_from_directory(app.root_path + '/monitor/', filename)
@app.route('/snap')
def snap():
if not pm.running:
flash(Markup('> API is <b>not running</b>, start before use Snap. > Show <a href="{}">logs</a> or <a onclick="refreshForMsg(\'{}\')">Start</a> now'.format(url_for('logs'),url_for('APIstart'))), 'alert')
return render_template(
'base-iframe.html',
iframe_src=url_for('base_static_snap', filename='snap.html')
)
@app.route('/snap/<path:filename>')
def base_static_snap(filename):
return send_from_directory(app.root_path + '/snap/', filename)
@app.route('/jupyter')
def jupyter():
if pm.running:
flash(Markup('> API is <b>already running</b>, stop before instanciate the robot on python. > Show <a href="{}">logs</a> or <a onclick="refreshForMsg(\'{}\')">Stop</a> now'.format(url_for('logs'),url_for('APIstop'))), 'alert')
return render_template(
'base-iframe.html',
iframe_src='http://{}:8888'.format(urlparse(request.url_root).hostname)
)
@app.route('/settings')
def settings():
return render_template('settings.html')
@app.route('/settings_update', methods=['POST'])
def settings_update():
label= {'name': 'Hostname',
'firstPage':'State for first connection page',
'autoStart':'API auto-start',
'camera':'State of camera (when API start)',
'virtualBot':'Number of virtual instance',
'start':'State',
'ssid':'Name',
'psk':'Password'}
msg=''
for key, value in request.form.items() :
if value != '':
key=key.split('_')
value=value.replace(' ','')#prevent user mistake
if value == 'on': value = True
elif value == 'off': value = False
if value != getattr(getattr(pm.config, key[0]), key[1]):
pm.update_config('.'.join(key),value)
msg+='> {} of {} was changed.'.format(label[key[1]], key[0])
if key[1] == 'name' or key[0] == 'hotspot' or key[0] == 'wifi':
msg+=' <a href="{}">Restart network service</a> to apply (or wait next reboot).'.format(url_for('restart_network'))
msg+='<br>'
if msg == '': flash('> Nothing was changed!', 'warning')
else: flash(Markup(msg), 'success')
return ('', 204)
@app.route('/restart_network')
def restart_network():
pm.restart_network()
goback= request.referrer.replace(urlparse(request.url_root).hostname, pm.config.robot.name+'.local')
flash('> Network service was restarted', 'success')
return redirect(goback)
@app.route('/terminal')
def terminal():
if pm.running:
pm.stop()
return render_template(
'base-iframe.html',
iframe_src='http://{}:8888/terminals/poppy'.format(urlparse(request.url_root).hostname)
)
@app.route('/reboot')
def reboot():
pm.reboot()
flash('> Your {} will now be REBOOT in a few seconds.'.format(pm.config.info.board), 'success')
return ('', 204)
@app.route('/logs')
def logs():
try:
with open(pm.config.info.logfile) as f:
content = f.read()
except IOError:
content = 'No log found...'
return render_template('logs.html', logs_content=content)
@app.route('/update-logs')
def update_logs():
try:
with open(pm.config.update.logfile) as f:
content = f.read()
except IOError:
content = 'No log found...'
return render_template('update.html', update_logs_content=content)
@app.route('/APIreset')
def APIreset():
if pm.running:
pm.stop()
pm.start()
flash('> Your robot\'s API has been restarted.', 'success')
return ('', 204)
@app.route('/APIstart')
def APIstart():
if pm.running:
flash('> Your robot\'s API has already started.', 'warning')
else:
pm.start()
flash('> Your robot\'s API has been started.', 'success')
return ('', 204)
@app.route('/APIstop')
def APIstop():
if pm.running:
pm.stop()
flash('> Your robot\'s API has been stopped.', 'success')
else:
flash('> Your robot\'s API has already stopped.', 'warning')
return ('', 204)
@app.route('/update')
def update():
@copy_current_request_context
def update_in_bg():
success = pm.self_update()
if success:
flash('> Your robot is now up-to-date!', 'success')
else:
flash('> Update failed, check logs for details!', 'alert')
#flash msg probably does not work, check this after fixing updating bug
flash('> Your robot is currently updating. Please do not turn it off before it\'s done!', 'warning')
if not pm.is_updating:
Thread(target=update_in_bg).start()
return redirect(url_for('update_logs'))
@app.route('/updating')
def is_updating():
return 'true' if pm.is_updating else 'false'
@app.route('/done-updating')
def done_updating():
flash('> Your robot is now up-to-date!', 'success')
return redirect(url_for('index'))
@app.route('/switch_camera')
def switch_camera():
if pm.config.robot.camera:
pm.update_config('robot.camera', False)
flash('> Your robot camera is now turned off!', 'success')
else:
pm.update_config('robot.camera', True)
flash('> Your robot camera is now turned on!', 'success')
return ('', 204)
@app.route('/clone')
def clone():
pm.clone()
flash('> One more instance was launched', 'success')
return ('', 204)
@app.route('/configure-motors')
def configure_motors():
# Remove old poppy-configure output to avoid user confusion
try:
os.remove(pm.config.info.configMotorLog)
except OSError:
pass
return render_template('motor-configuration.html', motors=pm._get_robot_motor_list())
@app.route('/call_poppy_configure', methods=['POST'])
def call_poppy_configure():
motor = request.form['motor']
pm.update_config('robot.motors', motor)
return ('', 204)
@app.route('/ready-to-roll')
def ready_to_roll():
with open(pm.config.info.logfile) as f:
content = f.read()
if 'SnapRobotServer is now running on' not in content:
return 'KO'
try:
r = requests.get('http://{}:6969/motors/get/positions'.format(get_host()))
if r.status_code == 200:
return 'OK'
except:
pass
return 'KO'
@app.route('/shutdown')
def shutdown():
pm.shutdown()
flash('> Your {} will now be HALTED in a few seconds.'.format(pm.config.info.board), 'success')
return ('', 204)
@app.route('/api/raw_logs')
def raw_logs():
try:
with open(pm.config.info.logfile) as f:
content = f.read()
except IOError:
content = 'No log found...'
return Response(content, mimetype='text/plain')
@app.route('/api/raw_logs_vir', methods=['POST'])
def raw_logs_vir():
file= pm.config.info.virtualBotLog.replace('.log', '_{}.log'.format(request.form['id']))
try:
with open(file) as f:
content = f.read()
except IOError:
content = 'No log found...'
return Response(content, mimetype='text/plain')
@app.route('/api/update_raw_logs')
def update_raw_logs():
try:
with open(pm.config.update.logfile) as f:
content = f.read()
except IOError:
content = 'No log found...'
return Response(content, mimetype='text/plain')
@app.route('/api/configure_motors_logs')
def poppy_config_logs():
try:
with open(pm.config.info.configMotorLog) as f:
content = f.read()
except IOError:
content = ''
return Response(content, mimetype='text/plain')
def get_host():
host = pm.config.robot.name
host = host if host == 'localhost' else '{}.local'.format(host)
return host
if __name__ == "__main__":
app.run(host='0.0.0.0', port=2280)