7
from optparse import OptionParser
9
class PcilibServerHandler(BaseHTTPServer.BaseHTTPRequestHandler):
10
def __init__(s, pcilib, *args):
12
BaseHTTPServer.BaseHTTPRequestHandler.__init__(s, *args)
16
s.send_header('content-type', 'application/json')
20
length = int(s.headers['Content-Length'])
22
#deserialize input data
23
data = json.loads(s.rfile.read(length).decode('utf-8'))
26
command = data['command']
27
if(command == 'help'):
30
#elif(command == 'open'):
31
# #check required arguments
32
# if not 'device' in data:
33
# s.error('message doesnt contains "device" field, '
34
# 'which is required for "open" command', data)
36
# #parse command arguments and convert them to string
37
# device = str(data.get('device', None))
38
# model = data.get('model', None)
39
# if not model is None:
43
# s.openPcilibInstance(device, model)
44
# except Exception as e:
45
# s.error(str(e), data)
48
# #Success! Create and send reply
49
# s.send_response(200)
50
# s.send_header('content-type', 'application/json')
53
# out['status'] = 'ok'
54
# s.wrapMessageAndSend(out, data)
56
elif(command == 'get_registers_list'):
57
#parse command arguments and convert them to string
58
bank = data.get('bank', None)
64
registers = s.pcilib.get_registers_list(bank)
65
except Exception as e:
69
#Success! Create and send reply
71
s.send_header('content-type', 'application/json')
75
out['registers'] = registers
76
s.wrapMessageAndSend(out, data)
78
elif(command == 'get_register_info'):
79
#check required arguments
81
s.error('message doesnt contains "reg" field, '
82
'which is required for "get_register_info" command', data)
85
#parse command arguments and convert them to string
86
reg = str(data.get('reg', None))
87
bank = data.get('bank', None)
93
register = s.pcilib.get_register_info(reg, bank)
94
except Exception as e:
98
#Success! Create and send reply
100
s.send_header('content-type', 'application/json')
104
out['register'] = register
105
s.wrapMessageAndSend(out, data)
107
elif(command == 'get_property_list'):
108
#parse command arguments and convert them to string
109
branch = data.get('branch', None)
110
if not branch is None:
115
properties = s.pcilib.get_property_list(branch)
116
except Exception as e:
117
s.error(str(e), data)
120
#Success! Create and send reply
122
s.send_header('content-type', 'application/json')
126
out['properties'] = properties
127
s.wrapMessageAndSend(out, data)
129
elif(command == 'read_register'):
130
#check required arguments
131
if not 'reg' in data:
132
s.error('message doesnt contains "reg" field, '
133
'which is required for "read_register" command', data)
136
#parse command arguments and convert them to string
137
reg = str(data.get('reg', None))
138
bank = data.get('bank', None)
144
value = s.pcilib.read_register(reg, bank)
145
except Exception as e:
146
s.error(str(e), data)
149
#Success! Create and send reply
151
s.send_header('content-type', 'application/json')
156
s.wrapMessageAndSend(out, data)
158
elif(command == 'write_register'):
159
#check required arguments
160
if not 'reg' in data:
161
s.error('message doesnt contains "reg" field, '
162
'which is required for "write_register" command', data)
165
if not 'value' in data:
166
s.error('message doesnt contains "value" field, '
167
'which is required for "write_register" command', data)
170
#parse command arguments and convert them to string
171
reg = str(data.get('reg', None))
172
value = str(data.get('value', None))
173
bank = data.get('bank', None)
178
s.pcilib.write_register(value, reg, bank)
179
except Exception as e:
180
s.error(str(e), data)
183
#Success! Create and send reply
185
s.send_header('content-type', 'application/json')
189
s.wrapMessageAndSend(out, data)
191
elif(command == 'get_property'):
192
#check required arguments
193
if not 'prop' in data:
194
s.error('message doesnt contains "prop" field, '
195
'which is required for "get_property" command', data)
198
#parse command arguments and convert them to string
199
prop = str(data.get('prop', None))
203
value = s.pcilib.get_property(prop)
204
except Exception as e:
205
s.error(str(e), data)
208
#Success! Create and send reply
210
s.send_header('content-type', 'application/json')
215
s.wrapMessageAndSend(out, data)
217
elif(command == 'set_property'):
218
#check required arguments
219
if not 'prop' in data:
220
s.error('message doesnt contains "prop" field, '
221
'which is required for "set_property" command', data)
224
if not 'value' in data:
225
s.error('message doesnt contains "value" field, '
226
'which is required for "set_property" command', data)
229
#parse command arguments and convert them to string
230
prop = str(data.get('prop', None))
231
value = str(data.get('value', None))
234
s.pcilib.set_property(value, prop)
235
except Exception as e:
236
s.error(str(e), data)
239
#Success! Create and send reply
241
s.send_header('content-type', 'application/json')
245
s.wrapMessageAndSend(out, data)
249
s.error('command "' + command + '" undefined', data)
252
s.error('message doesnt contains "command" field, which is required', data)
256
#print str(s.headers['content-type'])
257
#print post_data['some']
259
"""open device context """
260
def openPcilibInstance(s, device, model):
261
s.pcilib = pcipywrap.create_pcilib_instance(device, model)
263
"""Send help message"""
264
def help(s, received_message = None):
266
s.send_header('content-type', 'application/json')
268
usage = str('Usage:\n'
269
' Server receive commands via http GET with json packet.\n'
270
' content-type should have value "application/json"\n'
271
' Server could handle only commands. to set command, you\n'
272
' should specify field "command" in packet with command name\n'
273
' List of commands:\n'
275
' command: help - Get help. This will return usage\n'
278
' command: open - Opens context of device. It will be reopened if already open.\n'
280
' device: - path to the device file [/dev/fpga0]\n'
282
' model: - specifies the model of hardware, autodetected if doesnt exists\n'
285
' command: get_registers_list - Returns the list of registers provided by the hardware model.\n'
287
' bank: - if set, only register within the specified bank will be returned\n'
290
' command: get_register_info - Returns the information about the specified register.\n'
292
' reg: - the name of the register\n'
294
' bank: - if set, only register within the specified bank will be returned\n'
297
' command: get_property_list - Returns the list of properties available under the specified path.\n'
299
' branch: - Path. If not set, will return the top-level properties\n'
302
' command: read_register - Reads the specified register.\n'
304
' reg: - the name of the register\n'
306
' bank: - if set, only register within the specified bank will be processed\n'
309
' command: write_register - Writes to specified register.\n'
311
' reg: - the name of the register\n'
312
' value: - the register value to write. Should be int, float or string (with number)\n'
314
' bank: - if set, only register within the specified bank will be processed\n'
317
' command: get_property - Reads / computes the property value.\n'
319
' prop: - full name including path\n'
322
' command: set_property - Writes the property value or executes the code associated with property.\n'
324
' prop: - full name including path\n'
325
' value: - the property value to write. Should be int, float or string (with number)\n'
327
out = {'status': 'ok', 'usage' : usage}
328
s.wrapMessageAndSend(out, received_message)
330
"""Send error message with text description"""
331
def error(s, info, received_message = None):
333
s.send_header('content-type', 'application/json')
337
out['status'] = 'error'
338
out['description'] = info
339
out['note'] = 'send {"command" : "help"} to get help'
340
s.wrapMessageAndSend(out, received_message)
342
def wrapMessageAndSend(s, message, received_message = None):
343
if not received_message is None:
344
message['received_message'] = received_message
345
s.wfile.write(json.dumps(message))
347
if __name__ == '__main__':
349
#parce command line options
350
parser = OptionParser()
351
parser.add_option("-p", "--port", action="store",
352
type="int", dest="port", default=9000,
353
help="Set server port (9000)")
354
parser.add_option("-d", "--device", action="store",
355
type="string", dest="device", default=str('/dev/fpga0'),
356
help="FPGA device (/dev/fpga0)")
357
parser.add_option("-m", "--model", action="store",
358
type="string", dest="model", default=None,
359
help="Memory model (autodetected)")
360
opts = parser.parse_args()[0]
363
PORT_NUMBER = opts.port
367
#Set enviroment variables, if it not setted already
368
if not 'APP_PATH' in os.environ:
370
file_dir = os.path.dirname(os.path.abspath(__file__))
371
APP_PATH = str(os.path.abspath(file_dir + '/../..'))
372
os.environ["APP_PATH"] = APP_PATH
374
if not 'PCILIB_MODEL_DIR' in os.environ:
375
os.environ['PCILIB_MODEL_DIR'] = os.environ["APP_PATH"] + "/xml"
377
if not 'LD_LIBRARY_PATH' in os.environ:
378
os.environ['LD_LIBRARY_PATH'] = os.environ["APP_PATH"] + "/pcilib"
380
#redirect logs to exeption
381
pcipywrap.__redirect_logs_to_exeption()
384
pcilib_server = BaseHTTPServer.HTTPServer
386
#pass Pcipywrap to to server handler
387
lib = pcipywrap.Pcipywrap(DEVICE, MODEL)
389
PcilibServerHandler(lib, *args)
391
httpd = pcilib_server((HOST_NAME, PORT_NUMBER), handler)
393
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
395
httpd.serve_forever()
396
except KeyboardInterrupt:
399
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)