6
8
from optparse import OptionParser
8
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
9
from SocketServer import ThreadingMixIn
9
from multiprocessing import Process
11
if sys.version_info >= (3,0):
12
from http.server import HTTPServer, BaseHTTPRequestHandler
13
from socketserver import ThreadingMixIn
15
from SocketServer import ThreadingMixIn
16
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
14
18
class MultiThreadedHTTPServer(ThreadingMixIn, HTTPServer):
17
21
class PcilibServerHandler(BaseHTTPRequestHandler):
21
#def __init__(s, pcilib, *args):
23
# BaseHTTPRequestHandler.__init__(s, *args)
23
def __init__(s, pcilib, *args):
25
BaseHTTPRequestHandler.__init__(s, *args)
26
28
s.send_response(200)
142
150
#parse command arguments and convert them to string
143
151
reg = str(data.get('reg', None))
144
152
bank = data.get('bank', None)
153
if(not bank is None):
150
value = pcilib.read_register(reg, bank)
158
value = s.pcilib.read_register(reg, bank)
151
159
except Exception as e:
152
160
s.error(str(e), data)
175
183
#parse command arguments and convert them to string
176
184
reg = str(data.get('reg', None))
177
value = str(data.get('value', None))
185
value = data.get('value', None)
178
186
bank = data.get('bank', None)
187
if(not bank is None):
183
pcilib.write_register(value, reg, bank)
191
s.pcilib.write_register(value, reg, bank)
184
192
except Exception as e:
185
193
s.error(str(e), data)
226
234
s.error('message doesnt contains "value" field, '
227
235
'which is required for "set_property" command', data)
230
238
#parse command arguments and convert them to string
231
239
prop = str(data.get('prop', None))
232
value = str(data.get('value', None))
240
value = data.get('value', None)
235
pcilib.set_property(value, prop)
243
s.pcilib.set_property(value, prop)
236
244
except Exception as e:
237
245
s.error(str(e), data)
252
260
#parse command arguments and convert them to string
253
261
lock_id = str(data.get('lock_id'))
255
#check if lock already setted
256
#if lock_id in PcilibServerHandler.locks:
257
# s.error('Lock with id: ' + lock_id +
258
# 'already setted by this server',
264
s.pcilib.lock(lock_id)
264
265
except Exception as e:
265
266
s.error(str(e), data)
268
PcilibServerHandler.locks.append(lock_id)
270
269
#Success! Create and send reply
271
270
s.wrapMessageAndSend({'status': 'ok'}, data)
296
295
elif(command == 'unlock'):
297
296
#check required arguments
298
#if not 'lock_id' in data:
299
# s.error('message doesnt contains "lock_id" field, '
300
# 'which is required for "unlock" command', data)
297
if not 'lock_id' in data:
298
s.error('message doesnt contains "lock_id" field, '
299
'which is required for "unlock" command', data)
303
302
#parse command arguments and convert them to string
304
#lock_id = str(data.get('lock_id'))
303
lock_id = str(data.get('lock_id'))
307
# pcilib.unlock(lock_id)
308
#except Exception as e:
309
# s.error(str(e), data)
312
#remove lock from locks list
313
#if lock_id in PcilibServerHandler.locks:
314
# PcilibServerHandler.locks.remove(lock_id)
306
s.pcilib.unlock(lock_id)
307
except Exception as e:
308
s.error(str(e), data)
316
311
#Success! Create and send reply
317
312
s.wrapMessageAndSend({'status': 'ok'}, data)
316
elif(command == 'get_scripts_list'):
319
scripts = s.pcilib.get_scripts_list()
320
except Exception as e:
321
s.error(str(e), data)
324
#Success! Create and send reply
325
s.wrapMessageAndSend({'status': 'ok', 'scripts': scripts}, data)
329
elif(command == 'run_script'):
330
#check required arguments
331
if not 'script_name' in data:
332
s.error('message doesnt contains "script_name" field, '
333
'which is required for "run_script" command', data)
335
#parse command arguments and convert them to string
336
script_name = str(data.get('script_name'))
337
value = data.get('value', None)
341
out = s.pcilib.run_script(script_name, value)
342
except Exception as e:
343
s.error(str(e), data)
346
#Success! Create and send reply
347
if(type(out) == bytearray or type(out) == bytes):
349
s.send_header('content-disposition', 'inline; filename=value')
350
s.send_header('content-type', 'application/octet-stream')
354
s.wrapMessageAndSend({'status': 'ok', 'value': out}, data)
321
358
#elif(command == 'lock_global'):
322
359
# #check if global_lock already setted by server
324
# if PcilibServerHandler.lock_global:
326
# s.error('global lock already setted by this server', data)
330
# pcilib.lock_global()
361
# s.pcilib.lock_global()
331
362
# except Exception as e:
332
363
# s.error(str(e), data)
335
# PcilibServerHandler.lock_global = 1
337
366
# #Success! Create and send reply
338
367
# s.wrapMessageAndSend({'status': 'ok'}, data)
342
371
#elif(command == 'unlock_global'):
344
# pcilib.unlock_global()
373
# s.pcilib.unlock_global()
345
374
# except Exception as e:
346
375
# s.error(str(e), data)
349
# PcilibServerHandler.lock_global = 0
351
378
# #Success! Create and send reply
352
379
# s.wrapMessageAndSend({'status': 'ok'}, data)
357
s.error('command "' + command + '" undefined', data)
383
s.error('command "' + command + '" undefined', data)
360
s.error('message doesnt contains "command" field, which is required', data)
364
#print str(s.headers['content-type'])
365
#print post_data['some']
386
s.error('message doesnt contains "command" field, which is required', data)
367
#"""open device context """
368
392
#def openPcilibInstance(s, device, model):
369
# pcilib = pcipywrap.create_pcilib_instance(device, model)
393
# s.pcilib = pcipywrap.create_pcilib_instance(device, model)
371
"""Send help message"""
372
396
def help(s, received_message = None):
373
397
usage = str('Usage:\n'
374
398
' Server receive commands via http GET with json packet.\n'
446
470
' lock_id: - lock id\n'
473
' command: get_scripts_list - Get aviable scripts with description\n'
476
' command: run_script - Run specified script\n'
478
' script_name: - script name (without extension)\n'
479
' value: - input value in json format\n'
450
out = {'status': 'ok', 'usage' : usage}
451
s.wrapMessageAndSend(out, received_message)
484
#send help as plain text
486
s.send_header('content-type', 'text/plain')
488
if sys.version_info >= (3,0):
489
s.wfile.write(bytes(usage, 'UTF-8'))
453
"""Send error message with text description"""
493
#Send error message with text description
454
494
def error(s, info, received_message = None):
466
506
if not received_message is None:
467
507
message['received_message'] = received_message
468
message['thread'] = threading.currentThread().getName()
469
s.wfile.write(json.dumps(message))
508
if sys.version_info >= (3,0):
509
s.wfile.write(bytes(json.dumps(message), 'UTF-8'))
511
s.wfile.write(json.dumps(message))
514
class ApiServer(MultiThreadedHTTPServer):
515
def __init__(self, device='/dev/fpga0', model=None, adress=('0.0.0.0', 9000)):
516
#redirect logs to exeption
517
pcilib.redirect_logs_to_exeption()
518
#pass Pcipywrap to to server handler
519
self.lib = pcilib.pcilib(device, model)
521
PcilibServerHandler(self.lib, *args)
522
MultiThreadedHTTPServer.__init__(self, adress, handler)
471
524
if __name__ == '__main__':
481
534
parser.add_option("-m", "--model", action="store",
482
535
type="string", dest="model", default=None,
483
536
help="Memory model (autodetected)")
484
538
opts = parser.parse_args()[0]
540
HOST_NAME = '0.0.0.0'
487
541
PORT_NUMBER = opts.port
488
542
MODEL = opts.model
489
543
DEVICE = opts.device
493
#Set enviroment variables, if it not setted already
494
if not 'APP_PATH' in os.environ:
496
file_dir = os.path.dirname(os.path.abspath(__file__))
497
APP_PATH = str(os.path.abspath(file_dir + '/../..'))
498
os.environ["APP_PATH"] = APP_PATH
500
if not 'PCILIB_MODEL_DIR' in os.environ:
501
os.environ['PCILIB_MODEL_DIR'] = os.environ["APP_PATH"] + "/xml"
503
if not 'LD_LIBRARY_PATH' in os.environ:
504
os.environ['LD_LIBRARY_PATH'] = os.environ["APP_PATH"] + "/pcilib"
508
#redirect logs to exeption
509
pcipywrap.__redirect_logs_to_exeption()
511
#pass Pcipywrap to to server handler
513
pcilib = pcipywrap.Pcipywrap(DEVICE, MODEL)
515
# PcilibServerHandler(lib, *args)
518
httpd = MultiThreadedHTTPServer((HOST_NAME, PORT_NUMBER), PcilibServerHandler)
520
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
546
httpd = ApiServer(DEVICE, MODEL, (HOST_NAME, PORT_NUMBER))
548
print(time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER))
522
551
httpd.serve_forever()
523
552
except KeyboardInterrupt:
524
#unlocking global lock
525
if PcilibServerHandler.lock_global:
527
PcilibServerHandler.lock_global = False
529
#delete created locks
530
for lock in PcilibServerHandler.locks:
532
del PcilibServerHandler.locks[:]
538
555
httpd.server_close()
539
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
557
print(time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER))