-
Notifications
You must be signed in to change notification settings - Fork 0
/
RtcWeb_Core.py
executable file
·561 lines (479 loc) · 12.9 KB
/
RtcWeb_Core.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2009-2014
Isao Hara
Intelligent Systems Research Institute,
National Institute of Advanced Industrial Science and Technology (AIST), Japan
All rights reserved.
Licensed under the MIT License (MIT)
http://www.opensource.org/licenses/MIT
'''
############### import libraries
import sys
import os
import traceback
import subprocess
import time
import utils
import OpenRTM_aist
import omniORB
from RTC import *
#########################################################################
#
# Class RtcWeb_Core
#
class RtcWeb_Core:
def __init__(self):
if hasattr(sys, "frozen"):
self._basedir = os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding()))
else:
self._basedir = os.path.dirname(__file__)
# self.parser = SEATML_Parser(self)
self.states = []
self.keys = {}
self.regkeys = {}
self.statestack = []
self.currentstate = "start"
self.adaptors = {}
self.adaptortype = {}
self._data = {}
self._datatype = {}
self._port = {}
self.popen = []
self.init_state = None
self._scriptfile = ["None"]
self.webServer = None
self.root = None
#
#
def exit(self):
print "Call RtcWeb_Core.exit"
return
##### Create Adaptors
#
# Create Adaptor, not use..
#
def createAdaptor(self, compname, tag):
try:
name = str(tag.get('name'))
type = tag.get('type')
self._logger.info(u"createAdaptor: " + type + ": " + name)
return -1
except:
self._logger.error(u"invalid parameters: " + type + ": " + name)
return -1
return 1
###########################
# Send Data
#
def send(self, name, data, code='utf-8'):
if isinstance(data, str) :
self._logger.info("sending message %s (to %s)" % (data, name))
else:
self._logger.info("sending message to %s" % (name,))
dtype = self.adaptortype[name][1]
if self.adaptortype[name][2]:
ndata = []
if type(data) == str :
for d in data.split(","):
ndata.append( convertDataType(dtype, d, code) )
self._data[name].data = ndata
else:
self._data[name] = data
elif dtype == str:
self._data[name].data = data.encode(code)
elif dtype == unicode:
self._logger.info("sending message to %s, %s" % (data,code))
self._data[name].data = unicode(data)
elif dtype == int or dtype == float :
self._data[name].data = dtype(data)
else:
try:
if type(data) == str :
self._data[name] = apply(dtype, eval(data))
else:
self._data[name] = data
except:
self._logger.error( "ERROR in send: %s %s" % (name , data))
try:
self._port[name].write(self._data[name])
except:
self._logger.error("Fail to sending message to %s" % (name,))
##################################
# Event processes
#
# onData: this method called in comming data
#
def onData(self, name, data):
try:
if isinstance(data, str):
if data :
data2 = parseData(data)
if data2 :
self.processOnDataIn(name, data2)
else :
self.processOnDataIn(name, data)
else:
self.processOnDataIn(name, data)
except:
self._logger.error(traceback.format_exc())
#
# main event process
#
#
# process for the cyclic execution
#
def processExec(self, sname=None, flag=False):
if sname is None : sname = self.currentstate
cmds = self.lookupWithDefault(sname, '', 'onexec', False)
if not cmds :
if flag :
self._logger.info("no command found")
return False
#
#
for c in cmds:
self.activateCommand(c, '')
return True
#
# Event process for data-in-event
def processOnDataIn(self, name, data):
self._logger.info("got input from %s" % (name,))
cmds = self.lookupWithDefault(self.currentstate, name, "ondata")
if not cmds:
self._logger.info("no command found")
return False
for c in cmds:
kond = c[0]
globals()['rtc_in_data'] = data
if kond[0] :
ffname = utils.findfile(kond[0])
if ffname :
execfile(ffname, globals())
# execfile(kond[0], globals())
if eval(kond[1], globals()):
for cmd in c[1]:
self.activateCommandEx(cmd, data)
return True
#
# Lookup Registered Commands with default
#
def lookupWithDefault(self, state, name, s, flag=True):
s=s.split(",")[0]
if flag:
self._logger.info('looking up...%s: %s' % (name,s,))
cmds = self.lookupCommand(state, name, s)
if not cmds:
cmds = self.lookupCommand(state, 'default', s)
if not cmds:
cmds = self.lookupCommand('all', name, s)
if not cmds:
cmds = self.lookupCommand('all', 'default', s)
return cmds
#
# Lookup Registered Commands
#
def lookupCommand(self, state, name, s):
cmds = []
regkeys = []
try:
cmds = self.keys[state+":"+name+":"+s]
except KeyError:
try:
regkeys = self.regkeys[state+":"+name]
except KeyError:
return None
for r in regkeys:
if r[0].match(s):
cmds = r[1]
break
return None
return cmds
#############################
# For STATE
#
# Get state infomation
#
def getStates(self):
return self.states
#
# set the begining state
#
def setStartState(self, name):
self.startstate = name
return
#
# Count the number of states
#
def countStates(self):
return len(self.states)
#
# check the named state
#
def inStates(self, name):
return ( self.states.count(name) > 0 )
#
# append the named state
#
def appendState(self, name):
self.states.extend([name])
return
#
# initilaize the begining state
#
def initStartState(self, name):
self.startstate = None
if self.states.count(name) > 0 :
self.startstate = name
else:
self.startstate = self.states[0]
self.stateTransfer(self.startstate)
self._logger.info("current state " + self.currentstate)
#
# create the named state
#
def create_state(self, name):
self.items[name] = []
if self.init_state == None:
self.init_state = name
return
###############################################
# State Transition for eSEAT
#
def stateTransfer(self, newstate):
try:
for c in self.keys[self.currentstate+":::onexit"]:
self.activateCommand(c)
except KeyError:
pass
try:
self.prev_state=self.currentstate
self.next_state=newstate
self.root.event_generate("<<state_transfer>>", when="tail")
except:
pass
self.currentstate = newstate
try:
for c in self.keys[self.currentstate+":::onentry"]:
self.activateCommand(c)
except KeyError:
pass
############ T A G Operations
#
# Execute <message>
#
def applyMessage(self, c):
name = c[1]
data = c[2]
encoding = c[3]
input_id = c[4]
try:
ad = self.adaptors[name]
if input_id :
if self.inputvar.has_key(input_id) :
data = self.inputvar[input_id].get()
elif self.stext.has_key(input_id) :
data = self.getLastLine(input_id, 1)
#
# Call 'send' method of Adaptor
#
if not encoding :
ad.send(name, data)
else :
ad.send(name, data, encoding)
#ad.send(host, data.encode(c[3]))
except KeyError:
if name :
self._logger.error("no such adaptor:" + name)
else :
self._logger.error("no such adaptor: None")
#
# Execute <statetransition>
#
def applyTransition(self, c):
func,data = c[1:]
if (func == "push"):
self.statestack.append(self.currentstate)
self.stateTransfer(data)
elif (func == "pop"):
if self.statestack.__len__() == 0:
self._logger.warn("state buffer is empty")
return
self.stateTransfer(self.statestack.pop())
else:
self._logger.info("state transition from "+self.currentstate+" to "+data)
self.stateTransfer(data)
#
# Execute <log>
#
def applyLog(self, c):
data = c[1]
self._logger.info(data)
#
# Execute <shell>
#
def applyShell(self, c):
name ,data = c[1:]
#
# execute shell command with subprocess
res = subprocess.Popen(data, shell=True)
self.popen.append(res)
#
# Call 'send' method of Adaptor
try:
ad = self.adaptors[name]
ad.send(name, res)
except KeyError:
if name :
self._logger.error("no such adaptor:" + name)
else:
self._logger.error("no such adaptor: None")
#
# Execute <script>
#
def applyScript(self, c, indata=None):
name,data,fname = c[1:]
globals()['rtc_result'] = None
globals()['rtc_in_data'] = indata
globals()['web_in_data'] = indata
#
# execute script or script file
if fname :
ffname = utils.findfile(fname)
if ffname :
execfile(ffname,globals())
try:
if data :
exec(data, globals())
except:
print data
#self._logger.error("Fail to execute script:" + name)
#
# Call 'send' method of Adaptor to send the result...
rtc_result = globals()['rtc_result']
if rtc_result == None :
pass
else:
try:
ad = self.adaptors[name]
ad.send(name, rtc_result)
except KeyError:
if name :
self._logger.error("no such adaptor:" + name)
else:
self._logger.error("no such adaptor: None")
########################
#
# Activate Lookuped Commands
#
def activateCommand(self, c, data=None):
if c[0] == 'c': self.applyMessage(c)
elif c[0] == 'l': self.applyLog(c)
elif c[0] == 'x': self.applyShell(c)
elif c[0] == 's': self.applyScript(c, data)
elif c[0] == 't': self.applyTransition(c)
#
#
def activateCommandEx(self, c, data):
if c[0] == 'c': c[3] = None
self.activateCommand(c, data)
##############################
# main loader
#
def loadXML(self, f):
self._logger.info("Start loadXML:"+f)
res = self.parser.load(f)
if res == 1 :
self._logger.error("===> XML Parser error")
if self.manager : self.manager.shutdown()
sys.exit(1)
#
# register commands into self.keys
#
def registerCommands(self, key, cmds):
self._logger.info("register key="+key)
self.keys[key] = cmds
def appendCommands(self, key, cmds):
self._logger.info(" append key="+key)
self.keys[key].append(cmds)
def registerCommandArray(self, tag, cmds):
if self.keys.keys().count(tag) == 0 :
self.registerCommands(tag, [cmds])
else :
self.appendCommands(tag, cmds)
##############################################
# Callback function for WebAdaptor
#
def callComet(self):
res = ""
return res
################################################
#
# Sub-process
#
def getSubprocessList(self):
res=[]
newlst=[]
for p in self.popen:
p.poll()
if p.returncode == None:
res.append(p.pid)
newlst.append(p)
self.popen = newlst
return res
#
#
#
def killSubprocess(self, pid=None):
for p in self.popen:
p.poll()
if pid == None or p.pid == pid :
p.terminate()
return
#
# Finalize
#
def finalizeRTC(self):
if self.root : self.root.quit()
return
#########################################################################
# F U N C T I O N S
#
# DataType for CORBA
#
def instantiateDataType(dtype):
if isinstance(dtype, int) : desc = [dtype]
elif isinstance(dtype, tuple) : desc = dtype
else :
desc=omniORB.findType(dtype._NP_RepositoryId)
if desc[0] in [omniORB.tcInternal.tv_alias ]: return instantiateDataType(desc[2])
if desc[0] in [omniORB.tcInternal.tv_short,
omniORB.tcInternal.tv_long,
omniORB.tcInternal.tv_ushort,
omniORB.tcInternal.tv_ulong,
omniORB.tcInternal.tv_boolean,
omniORB.tcInternal.tv_char,
omniORB.tcInternal.tv_octet,
omniORB.tcInternal.tv_longlong,
omniORB.tcInternal.tv_enum
]: return 0
if desc[0] in [omniORB.tcInternal.tv_float,
omniORB.tcInternal.tv_double,
omniORB.tcInternal.tv_longdouble
]: return 0.0
if desc[0] in [omniORB.tcInternal.tv_sequence,
omniORB.tcInternal.tv_array,
]: return []
if desc[0] in [omniORB.tcInternal.tv_string ]: return ""
if desc[0] in [omniORB.tcInternal.tv_wstring,
omniORB.tcInternal.tv_wchar
]: return u""
if desc[0] == omniORB.tcInternal.tv_struct:
arg = []
for i in range(4, len(desc), 2):
attr = desc[i]
attr_type = desc[i+1]
arg.append(instantiateDataType(attr_type))
return desc[1](*arg)
return None