forked from mxcube/mxcubecore
/
CommandContainer.py
726 lines (619 loc) · 26.1 KB
/
CommandContainer.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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
"""CommandContainer module
Classes:
- CommandContainer, a special mixin class to be used with
Hardware Objects. It defines a container
for command launchers and channels (see Command package).
- C*Object, command launcher & channel base class
"""
from __future__ import absolute_import
import weakref
import logging
from warnings import warn
from HardwareRepository.dispatcher import dispatcher
__author__ = "Matias Guijarro"
__version__ = 1.0
class ConnectionError(Exception):
pass
class CommandObject:
def __init__(self, name, username=None, **kwargs):
self._name = name
self._username = username
self._arguments = []
self._combo_arguments_items = {}
def name(self):
return self._name
def connectSignal(self, signalName, callableFunc):
try:
dispatcher.disconnect(callableFunc, signalName, self)
except BaseException:
pass
dispatcher.connect(callableFunc, signalName, self)
def emit(self, signal, *args):
signal = str(signal)
if len(args) == 1:
if isinstance(args[0], tuple):
args = args[0]
dispatcher.send(signal, self, *args)
def addArgument(
self, argName, argType, combo_items=None, onchange=None, valuefrom=None
):
arg_names = [arg[0] for arg in self._arguments]
if argName not in arg_names:
self._arguments.append((argName, argType.lower(), onchange, valuefrom))
if combo_items is not None:
self._combo_arguments_items[argName] = combo_items
def getArguments(self):
return self._arguments
def getComboArgumentItems(self, argName):
return self._combo_arguments_items[argName]
def userName(self):
return self._username or str(self.name())
def isConnected(self):
return False
class ChannelObject:
def __init__(self, name, username=None, **kwargs):
self._name = name
self._username = username
self._attributes = kwargs
self._onchange = None
self.__firstUpdate = True
def name(self):
return self._name
def connectSignal(self, signalName, callableFunc):
try:
dispatcher.disconnect(callableFunc, signalName, self)
except BaseException:
pass
dispatcher.connect(callableFunc, signalName, self)
def disconnectSignal(self, signalName, callableFunc):
try:
dispatcher.disconnect(callableFunc, signalName, self)
except BaseException:
pass
def connectNotify(self, signal):
if signal == "update" and self.isConnected():
self.emit(signal, self.getValue())
def emit(self, signal, *args):
signal = str(signal)
if len(args) == 1:
if isinstance(args[0], tuple):
args = args[0]
dispatcher.send(signal, self, *args)
def userName(self):
return self._username or str(self.name())
def isConnected(self):
return False
def update(self, value):
if self.__firstUpdate:
self.__firstUpdate = False
return
if self._onchange is not None:
cmd, container_ref = self._onchange
container = container_ref()
if container is not None:
cmdobj = container.get_command_object(cmd)
if cmdobj is not None:
cmdobj(value)
def getValue(self, force=False):
raise NotImplementedError
class CommandContainer:
"""Mixin class for generic command and channel containers"""
def __init__(self):
self.__commands = {}
self.__channels = {}
self.__commandsToAdd = []
self.__channelsToAdd = []
def __getattr__(self, attr):
try:
return self.__dict__["_CommandContainer__commands"][attr]
except KeyError:
raise AttributeError(attr)
def get_channel_object(self, channelName, optional=False):
channel = self.__channels.get(channelName)
if channel is None and not optional:
msg = "%s: Unable to get channel %s" % (self.name(), channelName)
logging.getLogger("user_level_log").error(msg)
# raise Exception(msg)
return channel
def get_channel_names_list(self):
return list(self.__channels.keys())
def add_channel(self, attributesDict, channel, addNow=True):
if not addNow:
self.__channelsToAdd.append((attributesDict, channel))
return
channelName = attributesDict["name"]
channelType = attributesDict["type"]
channelOnChange = attributesDict.get("onchange", None)
if channelOnChange is not None:
del attributesDict["onchange"]
channelValueFrom = attributesDict.get("valuefrom", None)
if channelValueFrom is not None:
del attributesDict["valuefrom"]
channelValueFrom = attributesDict.get("valuefrom", None)
del attributesDict["name"]
del attributesDict["type"]
newChannel = None
if self.__channels.get(channelName) is not None:
return self.__channels[channelName]
if channelType.lower() == "spec":
if "version" not in attributesDict:
try:
attributesDict["version"] = self.specversion
except AttributeError:
pass
try:
from HardwareRepository.Command.Spec import SpecChannel
newChannel = SpecChannel(channelName, channel, **attributesDict)
except BaseException:
logging.getLogger().error(
"%s: cannot add channel %s (hint: check attributes)",
self.name(),
channelName,
)
elif channelType.lower() == "taco":
if "taconame" not in attributesDict:
try:
attributesDict["taconame"] = self.taconame
except AttributeError:
pass
try:
from HardwareRepository.Command.Taco import TacoChannel
newChannel = TacoChannel(channelName, channel, **attributesDict)
except BaseException:
logging.getLogger().error(
"%s: cannot add channel %s (hint: check attributes)",
self.name(),
channelName,
)
elif channelType.lower() == "tango":
if "tangoname" not in attributesDict:
try:
attributesDict["tangoname"] = self.tangoname
except AttributeError:
pass
try:
from HardwareRepository.Command.Tango import TangoChannel
newChannel = TangoChannel(channelName, channel, **attributesDict)
except ConnectionError:
logging.getLogger().error(
"%s: could not connect to device server %s (hint: is it running ?)",
self.name(),
attributesDict["tangoname"],
)
raise ConnectionError
except BaseException:
logging.getLogger().exception(
"%s: cannot add channel %s (hint: check attributes)",
self.name(),
channelName,
)
elif channelType.lower() == "exporter":
if "exporter_address" not in attributesDict:
try:
attributesDict["exporter_address"] = self.exporter_address
except AttributeError:
pass
host, port = attributesDict["exporter_address"].split(":")
try:
attributesDict["address"] = host
attributesDict["port"] = int(port)
del attributesDict["exporter_address"]
from HardwareRepository.Command.Exporter import ExporterChannel
newChannel = ExporterChannel(channelName, channel, **attributesDict)
except BaseException:
logging.getLogger().exception(
"%s: cannot add exporter channel %s (hint: check attributes)",
self.name(),
channelName,
)
elif channelType.lower() == "epics":
try:
from HardwareRepository.Command.Epics import EpicsChannel
newChannel = EpicsChannel(channelName, channel, **attributesDict)
except BaseException:
logging.getLogger().exception(
"%s: cannot add EPICS channel %s (hint: check PV name)",
self.name(),
channelName,
)
elif channelType.lower() == "tine":
if "tinename" not in attributesDict:
try:
attributesDict["tinename"] = self.tinename
except AttributeError:
pass
try:
from HardwareRepository.Command.Tine import TineChannel
newChannel = TineChannel(channelName, channel, **attributesDict)
except BaseException:
logging.getLogger("HWR").exception(
"%s: cannot add TINE channel %s (hint: check attributes)",
self.name(),
channelName,
)
elif channelType.lower() == "sardana":
if "taurusname" not in attributesDict:
try:
attributesDict["taurusname"] = self.taurusname
except AttributeError:
pass
uribase = attributesDict["taurusname"]
try:
from HardwareRepository.Command.Sardana import SardanaChannel
logging.getLogger().debug(
"Creating a sardanachannel - %s / %s / %s",
self.name(),
channelName,
str(attributesDict),
)
newChannel = SardanaChannel(
channelName, channel, uribase=uribase, **attributesDict
)
logging.getLogger().debug("Created")
except BaseException:
logging.getLogger().exception(
"%s: cannot add SARDANA channel %s (hint: check PV name)",
self.name(),
channelName,
)
elif channelType.lower() == "mockup":
if "default_value" not in attributesDict:
try:
attributesDict["default_value"] = float(self.default_value)
except AttributeError:
pass
try:
from HardwareRepository.Command.Mockup import MockupChannel
newChannel = MockupChannel(channelName, channel, **attributesDict)
except BaseException:
logging.getLogger("HWR").exception(
"%s: cannot add Mockup channel %s (hint: check attributes)",
self.name(),
channelName,
)
if newChannel is not None:
if channelOnChange is not None:
newChannel._onchange = (channelOnChange, weakref.ref(self))
else:
newChannel._onchange = None
if channelValueFrom is not None:
newChannel._valuefrom = (channelValueFrom, weakref.ref(self))
else:
newChannel._valuefrom = None
self.__channels[channelName] = newChannel
return newChannel
else:
logging.getLogger().exception("Channel is None")
def set_channel_value(self, channel_name, value):
self.__channels[channel_name].setValue(value)
def get_channel_value(self, channel_name):
return self.__channels[channel_name].getValue()
def get_channels(self):
for chan in self.__channels.values():
yield chan
def get_command_object(self, cmd_name):
try:
return self.__commands.get(cmd_name)
except Exception as e:
return None
def get_commands(self):
for cmd in self.__commands.values():
yield cmd
def get_command_namesList(self):
return list(self.__commands.keys())
def add_command(self, arg1, arg2=None, addNow=True):
if not addNow:
self.__commandsToAdd.append((arg1, arg2))
return
newCommand = None
if isinstance(arg1, dict):
attributesDict = arg1
cmd = arg2
cmdName = attributesDict["name"]
cmdType = attributesDict["type"]
del attributesDict["name"]
del attributesDict["type"]
else:
attributesDict = {}
attributesDict.update(arg1.getProperties())
try:
cmdName = attributesDict["name"]
cmdType = attributesDict["type"]
cmd = attributesDict["toexecute"]
except KeyError as err:
logging.getLogger().error(
'%s: cannot add command: missing "%s" property',
self.name(),
err.args[0],
)
return
else:
del attributesDict["name"]
del attributesDict["type"]
del attributesDict["toexecute"]
if cmdType.lower() == "spec":
if "version" not in attributesDict:
try:
attributesDict["version"] = self.specversion
except AttributeError:
pass
try:
from HardwareRepository.Command.Spec import SpecCommand
newCommand = SpecCommand(cmdName, cmd, **attributesDict)
except BaseException:
logging.getLogger().exception(
'%s: could not add command "%s" (hint: check command attributes)',
self.name(),
cmdName,
)
elif cmdType.lower() == "taco":
if "taconame" not in attributesDict:
try:
attributesDict["taconame"] = self.taconame
except AttributeError:
pass
try:
from HardwareRepository.Command.Taco import TacoCommand
newCommand = TacoCommand(cmdName, cmd, **attributesDict)
except BaseException:
logging.getLogger().exception(
'%s: could not add command "%s" (hint: check command attributes)',
self.name(),
cmdName,
)
elif cmdType.lower() == "tango":
if "tangoname" not in attributesDict:
try:
attributesDict["tangoname"] = self.tangoname
except AttributeError:
pass
try:
from HardwareRepository.Command.Tango import TangoCommand
newCommand = TangoCommand(cmdName, cmd, **attributesDict)
except ConnectionError:
logging.getLogger().error(
"%s: could not connect to device server %s (hint: is it running ?)",
self.name(),
attributesDict["tangoname"],
)
raise ConnectionError
except BaseException:
logging.getLogger().exception(
'%s: could not add command "%s" (hint: check command attributes)',
self.name(),
cmdName,
)
elif cmdType.lower() == "exporter":
if "exporter_address" not in attributesDict:
try:
attributesDict["exporter_address"] = self.exporter_address
except AttributeError:
pass
host, port = attributesDict["exporter_address"].split(":")
try:
attributesDict["address"] = host
attributesDict["port"] = int(port)
del attributesDict["exporter_address"]
from HardwareRepository.Command.Exporter import ExporterCommand
newCommand = ExporterCommand(cmdName, cmd, **attributesDict)
except BaseException:
logging.getLogger().exception(
"%s: cannot add command %s (hint: check attributes)",
self.name(),
cmdName,
)
elif cmdType.lower() == "epics":
try:
from HardwareRepository.Command.Epics import EpicsCommand
newCommand = EpicsCommand(cmdName, cmd, **attributesDict)
except BaseException:
logging.getLogger().exception(
"%s: cannot add EPICS channel %s (hint: check PV name)",
self.name(),
cmdName,
)
elif cmdType.lower() == "sardana":
doorname = None
taurusname = None
cmdtype = None
door_first = False
tango_first = False
if "doorname" not in attributesDict:
try:
attributesDict["doorname"] = self.doorname
doorname = self.doorname
except AttributeError:
pass
else:
door_first = True
doorname = attributesDict["doorname"]
if "taurusname" not in attributesDict:
try:
attributesDict["taurusname"] = self.taurusname
taurusname = self.taurusname
except AttributeError:
pass
else:
tango_first = True
taurusname = attributesDict["taurusname"]
if "cmdtype" in attributesDict:
cmdtype = attributesDict["cmdtype"]
# guess what kind of command to create
if cmdtype is None:
if taurusname is not None and doorname is None:
cmdtype = "command"
elif doorname is not None and taurusname is None:
cmdtype = "macro"
elif doorname is not None and taurusname is not None:
if door_first:
cmdtype = "macro"
elif tango_first:
cmdtype = "command"
else:
cmdtype = "macro"
else:
logging.getLogger().error(
"%s: incomplete sardana command declaration. ignored",
self.name(),
)
from HardwareRepository.Command.Sardana import SardanaCommand, SardanaMacro
if cmdtype == "macro" and doorname is not None:
try:
newCommand = SardanaMacro(cmdName, cmd, **attributesDict)
except ConnectionError:
logging.getLogger().error(
"%s: could not connect to sardana door %s (hint: is it running ?)",
self.name(),
attributesDict["doorname"],
)
raise ConnectionError
except BaseException:
logging.getLogger().exception(
'%s: could not add command "%s" (hint: check command attributes)',
self.name(),
cmdName,
)
elif cmdtype == "command" and taurusname is not None:
try:
newCommand = SardanaCommand(cmdName, cmd, **attributesDict)
except ConnectionError:
logging.getLogger().error(
"%s: could not connect to sardana device %s (hint: is it running ?)",
self.name(),
taurusname,
)
raise ConnectionError
except BaseException:
logging.getLogger().exception(
'%s: could not add command "%s" (hint: check command attributes)',
self.name(),
cmdName,
)
else:
logging.getLogger().error(
"%s: incomplete sardana command declaration. ignored", self.name()
)
elif cmdType.lower() == "pool":
if "tangoname" not in attributesDict:
try:
attributesDict["tangoname"] = self.tangoname
except AttributeError:
pass
try:
from HardwareRepository.Command.Pool import PoolCommand
newCommand = PoolCommand(cmdName, cmd, **attributesDict)
except ConnectionError:
logging.getLogger().error(
"%s: could not connect to device server %s (hint: is it running ?)",
self.name(),
attributesDict["tangoname"],
)
raise ConnectionError
except BaseException:
logging.getLogger().exception(
'%s: could not add command "%s" (hint: check command attributes)',
self.name(),
cmdName,
)
elif cmdType.lower() == "tine":
if "tinename" not in attributesDict:
try:
attributesDict["tinename"] = self.tinename
except AttributeError:
pass
try:
from HardwareRepository.Command.Tine import TineCommand
newCommand = TineCommand(cmdName, cmd, **attributesDict)
except BaseException:
logging.getLogger().exception(
'%s: could not add command "%s" (hint: check command attributes)',
self.name(),
cmdName,
)
elif cmdType.lower() == "mockup":
try:
from HardwareRepository.Command.Mockup import MockupCommand
newCommand = MockupCommand(cmdName, cmd, **attributesDict)
except BaseException:
logging.getLogger().exception(
'%s: could not add command "%s" (hint: check command attributes)',
self.name(),
cmdName,
)
if newCommand is not None:
self.__commands[cmdName] = newCommand
if not isinstance(arg1, dict):
i = 1
for arg in arg1.getObjects("argument"):
onchange = arg.getProperty("onchange")
if onchange is not None:
onchange = (onchange, weakref.ref(self))
valuefrom = arg.getProperty("valuefrom")
if valuefrom is not None:
valuefrom = (valuefrom, weakref.ref(self))
try:
comboitems = arg["type"]["item"]
except IndexError:
try:
newCommand.addArgument(
arg.getProperty("name"),
arg.type,
onchange=onchange,
valuefrom=valuefrom,
)
except AttributeError:
logging.getLogger().error(
'%s, command "%s": could not add argument %d, missing type or name',
self.name(),
cmdName,
i,
)
continue
else:
if isinstance(comboitems, list):
combo_items = []
for item in comboitems:
name = item.getProperty("name")
value = item.getProperty("value")
if name is None or value is None:
logging.getLogger().error(
"%s, command '%s': could not add argument %d, missing combo item name or value",
self.name(),
cmdName,
i,
)
continue
else:
combo_items.append((name, value))
else:
name = comboitems.getProperty("name")
value = comboitems.getProperty("value")
if name is None or value is None:
combo_items = ((name, value),)
else:
logging.getLogger().error(
"%s, command '%s': could not add argument %d, missing combo item name or value",
self.name(),
cmdName,
i,
)
continue
newCommand.addArgument(
arg.getProperty("name"),
"combo",
combo_items,
onchange,
valuefrom,
)
i += 1
return newCommand
def _add_channels_and_commands(self):
[self.add_channel(*args) for args in self.__channelsToAdd]
[self.add_command(*args) for args in self.__commandsToAdd]
self.__channelsToAdd = []
self.__commandsToAdd = []
def execute_command(self, command_name, *args, **kwargs):
if command_name in self.__commands:
return self.__commands[command_name](*args, **kwargs)
else:
raise AttributeError