forked from mxcube/mxcubecore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TacoDevice_MTSafe.py
653 lines (568 loc) · 19.2 KB
/
TacoDevice_MTSafe.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
#$Id: TacoDevice_MTSafe.py,v 1.5 2004/11/15 12:39:19 guijarro Exp $
from Taco import *
from threading import RLock
import weakref
import types
import sys
_global_lock = RLock()
def makeThreadSafeMethod(func):
def threadsafemethod(self, *args, **kwargs):
self._monitor_lockObj.acquire()
#print ">>%s: got lock" % func.__name__
try:
return func(self, *args, **kwargs)
finally:
self._monitor_lockObj.release()
#print "<<%s: released lock" % func.__name__
return threadsafemethod
class ThreadSafeMethodsMetaClass(type):
def __new__(meta, name, bases, dict):
methods = [ v for k,v in dict.items() if isinstance(v, types.FunctionType) and not v.__name__.startswith('__')]
for m in methods:
dict[m.__name__] = makeThreadSafeMethod(m)
dict["_monitor_lockObj"] = _global_lock #RLock()
return super(ThreadSafeMethodsMetaClass, meta).__new__(meta, name, bases, dict)
Dev_deb = [0]
# Dev_Exception = "TacoException"
Dev_Exception = RuntimeError
#--------------------------------------------------------------
# Tab_dev:
# dictionnary indexed with devices names (in lower case)
#
# { device_name1: { 'cobj' : C object,
# 'ref' : number of references to that object
# 'cmd' : { command_name : [cmd,in_type,out_type],
# command_name : [cmd,in_type,out_type],
# ...
# }
# },
# device_name2: { 'cobj' : C object,
# 'ref' : number of references to that object
# 'cmd' : { command_name : [cmd,in_type,out_type],
# command_name : [cmd,in_type,out_type],
# ...
# }
# }
# .....
Tab_dev = {}
#--------------------------------------------------------------
# Tab_devC:
# dictionnary indexed with data collector devices names (in lower case)
#
# { device_name1: { 'cobj' : C object,
# 'ref' : number of references to that object
# 'cmd' : { command_name : [cmd,out_type],
# command_name : [cmd,out_type],
# ...
# }
# },
# device_name2: { 'cobj' : C object,
# 'ref' : number of references to that object
# 'cmd' : { command_name : [cmd,out_type],
# command_name : [cmd,out_type],
# ...
# }
# }
# .....
# Dictionnary for the correspondance between type number (in ascii
# representation) and a string for user
Tab_dev_type= { '0' :'void ',
'1' :'boolean ',
'70':'unsigned short ',
'2' :'short ',
'71':'unsigned long ',
'3' :'long ',
'4' :'float ',
'5' :'double ',
'6' :'string ',
'27':'(long,float) ',
'7' :'(float,float) ',
'8' :'(short,float,float ',
'22':'(long,long) ',
'23':'(double,double) ',
'9' :'list of char ',
'24':'list of string ',
'72':'list of unsigned short ',
'10':'list of short ',
'69':'list of unsigned long ',
'11':'list of long ',
'12':'list of float ',
'68':'list of double ',
'25':'list of (float,float) ',
'73':'list of (short,float,float) ',
'45':'list of ((long,long) ',
'47':'opaque ',
'46':'((8 long),(8 float),(8 long))',
'54':'(long,long) ',
'55':'(long,float) '
}
Tab_dev_type_unk = '<unknown> '
Tab_dev_head = 'INPUT: OUTPUT: COMMAND:'
Tab_devC_head = 'OUTPUT: COMMAND:'
#--------------------------------------------------------------
def dev_debug(flag):
# input:
# flag: debug flag
# 0: no trace
# else: trace
#
# returns:
# - 0: error
# - 1: OK
#--------------------------------------------------------------
if type(flag) != int:
print("dev_debug: parameter not a number")
else :
Dev_deb[0] = flag
if (Dev_deb[0] != 0) :
print(" debug mode %d" % Dev_deb[0])
def dev_init(mdevname):
# input:
# mdevname: device name
#
# returns list:
# - [] if error
#
# - [devname,cpt]
# devname: mdevname in lowercase
# cpt: index in C device table
#--------------------------------------------------------------
# print 'dev_init: ' + mdevname
# print Dev_deb[0]
locname = mdevname.lower()
# try to find in Tab_dev list if name already
# found
if not locname in Tab_dev:
# have to import the device and create place in dict
try:
mpt = esrf_import(locname)
except:
# print error
# print "dev_init: error on importing device %s" % locname
raise Dev_Exception("dev_init: error on importing device %s" % locname)
else:
# create in Tab_dev
Tab_dev[locname] = { 'cobj': mpt }
Tab_dev[locname]['cmd'] = dev_query(locname)
if len(Tab_dev[locname]['cmd']) == 0:
raise Dev_Exception("Error on importing device %s" % locname)
if Dev_deb[0] == 1:
print('dev_init: leaving OK')
#print locname, Tab_dev[locname]
return locname, Tab_dev[locname]['cobj']
#--------------------------------------------------------------
def dev_initC(mdevname):
# input:
# mdevname: device name
#
# returns list:
# - [] if error
#
# - [devname,cpt]
# devname: mdevname in lowercase
# cpt: index in C device table
#--------------------------------------------------------------
locname=mdevname.lower()
# try to find in Tab_dev list if name already
# found
if not locname in Tab_dev:
# have to import the device and create place in dict
try :
mpt = esrf_dc_import(locname)
except:
# print error
# print "dev_initC: error on importing device %s" % locname
raise Dev_Exception("dev_initC: error on importing device %s" % locname)
else:
# create in Tab_dev
Tab_dev[locname] = { 'cobj': mpt }
Tab_dev[locname]['cmd'] = dev_queryC(locname)
if len(Tab_dev[locname]['cmd'])==0:
raise Dev_Exception("Error on importing data collector device %s" % locname)
if Dev_deb[0] == 1:
print('dev_initC: leaving OK')
return locname,Tab_dev[locname]['cobj']
def dev_query(mdevname):
"""
input:
mdevname: device name in lower case
returns dictionnary:
- {} if error
-{cmd_name:[cmd,in_type,out_type], ...}
cmd_name: command string
cmd: command numeric value
in_type: input type
out_type: output type"""
if mdevname in Tab_dev:
loc_c_pt = Tab_dev[mdevname]['cobj']
try:
return esrf_query(loc_c_pt)
except:
pass
#raise Dev_Exception
else:
raise Dev_Exception("dev_query: no device %s defined" % mdevname)
return {}
#--------------------------------------------------------------
def dev_queryC(mdevname):
# input:
# mdevname: device name in lower case
#
# returns dictionnary:
# - {} if error
#
# -{cmd_name:[cmd,out_type], ...}
# cmd_name: command string
# cmd: command numeric value
# out_type: output type
#--------------------------------------------------------------
try:
locdict = esrf_dc_info(mdevname)
except:
raise Dev_Exception("dev_queryC: error on query for device %s" % mdevname)
return {}
return locdict
#--------------------------------------------------------------
def dev_tcpudp(mdevname,mode):
# input:
# mdevname: device name in lower case
# mode: "tcp" or "udp"
#
# returns value:
# - 0 if error
# - 1 if OK
#--------------------------------------------------------------
if mdevname in Tab_dev:
loc_c_pt = Tab_dev[mdevname]['cobj']
if Dev_deb[0] == 1:
print(loc_c_pt)
if (mode != "tcp") and (mode != "udp"):
print('usage: dev_tcpudp(<device_name>,udp|tcp)')
return 0
try:
ret = esrf_tcpudp(loc_c_pt,mode)
except:
raise Dev_Exception("dev_tcpudp: error on esrf_tcpudp for device %s" % mdevname)
return 0
else:
print("dev_tcpudp: no device %s defined" % mdevname)
return 0
return 1
#--------------------------------------------------------------
def dev_timeout(mdevname,*mtime):
# input:
# mdevname: device name in lower case
# mtime: optional argument:
# - if not existing: read timeout required
# - if exists: time in second for setting timeout
#
# returns value:
# - 0 if error
# - time in sec (read or set) if OK
#--------------------------------------------------------------
if mdevname in Tab_dev:
loc_c_pt = Tab_dev[mdevname]['cobj']
if Dev_deb[0] == 1:
print(loc_c_pt)
if (mtime == ()):
print('dev_timeout readmode ')
try:
ret = esrf_timeout(loc_c_pt)
except:
raise Dev_Exception('error on esrf_timeout for device ' + mdevname)
return 0
return ret
else:
itime = mtime[0]
if type(itime) == int or type(itime) == float:
print('dev_timeout set mode %f' % itime)
try:
ret = esrf_timeout(loc_c_pt,itime)
except:
raise Dev_Exception('error on esrf_timeout for device ' + mdevname)
return 0
return ret
else:
print("dev_timeout: no device %s defined" % mdevname)
return 0
#--------------------------------------------------------------
def dev_getresource(mdevname,resname):
# input:
# mdevname: device name
# resname: resource name
#
# returns value packed as a string:
# - resource value if OK
# - None if error
#--------------------------------------------------------------
try:
ret = esrf_getresource(mdevname,resname)
except:
raise Dev_Exception("dev_getresource: error for device %s on resource %s" % (mdevname,resname))
return None
if (Dev_deb[0] == 1):
print("string length is %s" % len(ret))
return ret
#--------------------------------------------------------------
def dev_putresource(mdevname,resname,value):
# Sets a device resource
# input:
# mdevname: device name
# resname: resource name
# value: the resource value packed as a string
#
# returns value:
# - 1: if OK
# - 0: if error
#--------------------------------------------------------------
if type(value) != bytes:
print("dev_putresource: resource value must be packed as string")
try:
ret = esrf_putresource(mdevname,resname,value)
except:
raise Dev_Exception("dev_putresource: error for device %s on resource %s" % (mdevname,resname))
return 0
return 1
#--------------------------------------------------------------
def dev_delresource(mdevname,resname):
# removes a device resource
# input:
# mdevname: device name
# resname: resource name
#
# returns value:
# - 1: OK
# - 0: error
#--------------------------------------------------------------
try:
ret = esrf_delresource(mdevname,resname)
except:
raise Dev_Exception("dev_delresource: error for device %s on resource %s" % (mdevname,resname))
return 0
return 1
def dev_io(mdevname,mdevcommand,*parin,**kw):
# input:
# mdevname: device name in lower case
# parin: list of optional INPUT parameters
# kw: dictionnary of optional OUTPUT parameters
#
# returns value:
# - 1 : if no device ARGOUT or OUTPUT param provided
# - device ARGOUT : if device ARGOUT and no OUTPUT param
#
# in case of error, global variable DEV_ERR is set to 1
if Dev_deb[0] == 1:
print('in dev_io')
try:
loc_c_pt = Tab_dev[mdevname]['cobj']
except KeyError:
raise Dev_Exception("dev_io: no device %s defined" % mdevname)
else:
if Dev_deb[0] == 1:
print(loc_c_pt)
print(' devname : ' + mdevname)
print(' command : ' + mdevcommand)
print(' parin : %s' % (parin,))
print(' kw : %s' % (kw,))
try:
io_cmd = Tab_dev[mdevname]['cmd'][mdevcommand][0]
io_in = Tab_dev[mdevname]['cmd'][mdevcommand][1]
io_out = Tab_dev[mdevname]['cmd'][mdevcommand][2]
except KeyError:
raise AttributeError("dev_io: no command %s for device %s" % (mdevcommand,mdevname))
else:
if len(parin) == 1:
if type(parin[0]) == tuple:
parin = parin[0]
elif type(parin[0]) == list:
parin = tuple(parin[0])
if Dev_deb[0] == 1:
print('esrf_io arg:')
print((Tab_dev[mdevname]['cobj'],mdevcommand,io_cmd,io_in,io_out,0) + (parin, ))
print('esrf_io dict:')
print(kw)
try:
ret = esrf_io(Tab_dev[mdevname]['cobj'],mdevcommand,io_cmd,io_in,io_out,0, parin, **kw)
except:
raise Dev_Exception("Cannot execute esrf_io %s,%s"%(mdevname, mdevcommand))
else:
return ret
#--------------------------------------------------------------
def dev_ioC(mdevname,mdevcommand,**kw):
# input:
# mdevname: device name in lower case
# kw: dictionnary of optional OUTPUT parameters
#
# returns value:
# - 1 : if no device ARGOUT or OUTPUT param provided
# - device ARGOUT : if device ARGOUT and no OUTPUT param
#
# in case of error, global variable DEV_ERR is set to 1
#--------------------------------------------------------------
if Dev_deb[0] == 1:
print('in dev_ioC')
if mdevname in Tab_dev:
loc_c_pt = Tab_dev[mdevname]['cobj']
if Dev_deb[0] == 1:
print(loc_c_pt)
print(' devname : ' + mdevname)
print(' command : ' + mdevcommand)
print(' kw : %s' % (kw,))
# check now that parameters are correct
# then run the esrf_io commnd
# first check that command exists:
if mdevcommand in Tab_dev[mdevname]['cmd']:
io_cmd = Tab_dev[mdevname]['cmd'][mdevcommand][0]
io_in = 0 # void
io_out = Tab_dev[mdevname]['cmd'][mdevcommand][1]
parin2 = (Tab_dev[mdevname]['cobj'],mdevcommand,io_cmd,io_in,io_out,1) + ((),)
if Dev_deb[0] == 1:
print('esrf_io arg:')
print(parin2)
print('esrf_io dict:')
print(kw)
ret = None
try:
# kw={'out':2}
# kw = {}
ret = esrf_io(*parin2, **kw)
if Dev_deb[0] == 1:
print('returned from esrf_io: %s' % ret)
except:
raise Dev_Exception("esrf_ioC: error on device %s" % mdevname)
return ret
else:
print("dev_ioC: no command %s for device %s" % (mdevcommand,mdevname))
else:
print("dev_ioC: no device %s defined" % mdevname)
class TacoCall:
def __init__(self, devname, command):
self.devname = devname
self.command = command
def __repr__(self):
return "<TacoCall object %d: device %r, cmd %r>" % (id(self), self.devname, self.command)
def __call__(self, *args, **kwargs):
try:
_global_lock.acquire()
if Dev_deb[0] == 1:
print('in device_io')
print((self.devname, self.command) + (args, ) + (kwargs, ))
return dev_io(self.devname, self.command, *args, **kwargs)
finally:
_global_lock.release()
class TacoCallC:
def __init__(self, devname, command):
self.devname = devname
self.command = command
def __call__(self, *args, **kwargs):
try:
_global_lock.acquire()
if Dev_deb[0] == 1:
print('in device_io')
print((self.devname, self.command) + (args, ) + (kwargs, ))
return dev_ioC(self.devname, self.command, *args, **kwargs)
finally:
_global_lock.release()
_tacoDevices = {}
def TacoDevice(name, dc=False):
try:
dev = _TacoDevice(name, dc)
except Exception as err:
print(err)
return None
else:
dev.imported = 1
def deviceDestroyed(ref, name=dev.devname):
del _tacoDevices[name][_tacoDevices[name].index(ref)]
if len(_tacoDevices[name]) == 0:
del Tab_dev[name]
try:
_tacoDevices[dev.devname].append(weakref.ref(dev, deviceDestroyed))
except KeyError:
_tacoDevices[dev.devname] = [weakref.ref(dev, deviceDestroyed)]
return dev
#--------------------------------------------------------------
class _TacoDevice(object):
__metaclass__ = ThreadSafeMethodsMetaClass
def __init__(self, name, dc=False): # constructor
# print 'Welcome ' + name
self.__dc = dc
try:
self._monitor_lockObj.acquire()
self.devname = name
self.imported = 0
if dc:
Listout = dev_initC(name)
else:
Listout = dev_init(name)
self.devname = Listout[0]
self.ds_object = Listout[1]
if Dev_deb[0] == 1:
print(self.devname)
finally:
self._monitor_lockObj.release()
def __str__(self): # for print
print('ds device: ' + self.devname)
print(" imported: %d" % self.imported)
print(" device object : ")
print(self.ds_object)
return "0"
def CommandList(self):
if self.__dc:
locdict = dev_queryC(self.devname)
print(Tab_devC_head)
else:
locdict = dev_query(self.devname)
print(Tab_dev_head)
if len(locdict) > 0:
for mykey in list(locdict.keys()):
my_stringtype_in = "%d" % locdict[mykey][1]
my_stringtype_out = "%d" % locdict[mykey][2]
if my_stringtype_in in Tab_dev_type:
myin = Tab_dev_type[my_stringtype_in]
else:
myin = Tab_dev_type_unk
if my_stringtype_out in Tab_dev_type:
myout = Tab_dev_type[my_stringtype_out]
else:
myout = Tab_dev_type_unk
print("%s %s %s" % (myin,myout,mykey))
def tcp(self):
if self.imported == 1:
ret = dev_tcpudp(self.devname,"tcp")
if ret ==0:
print('error setting tcp on object' + self.devname)
def udp(self):
if self.imported == 1:
ret = dev_tcpudp(self.devname,"udp")
if ret ==0:
print('error setting udp on object' + self.devname)
def timeout(self,*mtime):
if self.imported == 1:
if mtime == ():
ret = dev_timeout(self.devname)
if Dev_deb[0] == 1:
print('timeout: %f' % ret)
return ret
else:
ret = dev_timeout(self.devname,mtime[0])
return ret
def __getattr__(self, name):
if name.startswith('__'):
raise AttributeError(name)
else:
try:
self._monitor_lockObj.acquire()
try:
test_if_command_exists = Tab_dev[self.devname]['cmd'][name][0]
except KeyError:
raise AttributeError(name)
else:
if self.__dc:
newTacoCall = TacoCallC(self.devname, name)
else:
newTacoCall = TacoCall(self.devname, name)
self.__dict__[name] = newTacoCall
return newTacoCall
finally:
self._monitor_lockObj.release()