def prepare(self, integ_time, mnt_grp, **opts): self.print_value = False if mnt_grp is None: self.mnt_grp_name = self.getEnv('ActiveMntGrp') self.mnt_grp = self.getObj(self.mnt_grp_name, type_class=Type.MeasurementGroup) else: self.mnt_grp_name = mnt_grp.name self.mnt_grp = mnt_grp if self.mnt_grp is None: return names = self.mnt_grp.getChannelLabels() self.names = [[n] for n in names] self.channels = [] self.values = [] for channel_info in self.mnt_grp.getChannels(): full_name = channel_info["full_name"] channel = Device(full_name) self.channels.append(channel) value = channel.getValue(force=True) self.values.append([value]) valueObj = channel.getValueObj_() valueObj.subscribeEvent(self.counterChanged, channel)
class SardanaCommand(CommandObject): def __init__(self, name, command, taurusname=None, username=None, **kwargs): CommandObject.__init__(self, name, username, **kwargs) self.command = command self.taurusname = taurusname self.device = None logging.getLogger('HWR').debug("Creating command %s on device %s" % (self.command, self.taurusname)) def init_device(self): try: self.device = Device(self.taurusname) except DevFailed as traceback: last_error = traceback[-1] logging.getLogger('HWR').error("%s: %s", str(self.name()), last_error['desc']) self.device = None else: try: self.device.ping() except ConnectionFailed: self.device = None raise ConnectionError def __call__(self, *args, **kwargs): self.emit('commandBeginWaitReply', (str(self.name()), )) if self.device is None: self.init_device() try: cmdObject = getattr(self.device, self.command) ret = cmdObject(*args) except DevFailed as error_dict: logging.getLogger('HWR').error("%s: Tango, %s", str(self.name()), error_dict) except: logging.getLogger('HWR').exception( "%s: an error occured when calling Tango command %s", str(self.name()), self.command) else: self.emit('commandReplyArrived', (ret, str(self.name()))) return ret self.emit('commandFailed', (-1, self.name())) def abort(self): pass def isConnected(self): return self.device is not None
def onPauseMacro(self): door = Device(self.doorName()) doorState = door.getState() if doorState == PyTango.DevState.RUNNING: door.command_inout("PauseMacro") else: Qt.QMessageBox.warning(self, "Error while pausing macro", "It was not possible to pause macro, because state of the door was different than RUNNING")
def onStopMacro(self): door = Device(self.doorName()) doorState = door.getState() if doorState in (PyTango.DevState.RUNNING, PyTango.DevState.STANDBY): door.command_inout("StopMacro") else: Qt.QMessageBox.warning(self, "Error while stopping macro", "It was not possible to stop macro, because state of the door was different than RUNNING or STANDBY")
def stress_count(self, elements, repeats, synchronizer, synchronization): if (elements == ["_test_ct_1_1", "_test_0d_1_1"] and synchronizer == "_test_tg_1_1" and synchronization == AcqSynchType.Trigger and os.name == "nt"): self.skipTest("fails on Windows") mg_name = str(uuid.uuid1()) argin = [mg_name] + elements self.pool.CreateMeasurementGroup(argin) try: mg = Device(mg_name) mg.setSynchronizer(synchronizer, elements[0], apply=False) mg.setSynchronization(synchronization, elements[0]) for i in range(repeats): state, values = mg.count(.001) self.assertEqual(state, DevState.ON, "wrong state after measurement {}".format(i)) for channel_name, value in values.items(): msg = ("Value {} for {} is not numerical in " "measurement {}").format(value, channel_name, i) self.assertTrue(is_numerical(value), msg) finally: mg.cleanUp() if os.name != "nt": self.pool.DeleteElement(mg_name)
class SardanaCommand(CommandObject): def __init__(self, name, command, taurusname=None, username=None, **kwargs): CommandObject.__init__(self, name, username, **kwargs) self.command = command self.taurusname = taurusname self.device = None def init_device(self): try: self.device = Device(self.taurusname) except DevFailed as traceback: last_error = traceback[-1] logging.getLogger("HWR").error( "%s: %s", str(self.name()), last_error["desc"] ) self.device = None else: try: self.device.ping() except ConnectionFailed: self.device = None raise ConnectionError def __call__(self, *args, **kwargs): self.emit("commandBeginWaitReply", (str(self.name()),)) if self.device is None: self.init_device() try: cmdObject = getattr(self.device, self.command) ret = cmdObject(*args) except DevFailed as error_dict: logging.getLogger("HWR").error( "%s: Tango, %s", str(self.name()), error_dict ) except BaseException: logging.getLogger("HWR").exception( "%s: an error occured when calling Tango command %s", str(self.name()), self.command, ) else: self.emit("commandReplyArrived", (ret, str(self.name()))) return ret self.emit("commandFailed", (-1, self.name())) def abort(self): pass def isConnected(self): return self.device is not None
class AttrEnum(object): def __init__(self, devName, attrPrefix, *args, **kwargs): super(AttrEnum, self).__init__(*args, **kwargs) self._devName = devName self._attrPrefix = attrPrefix self._device = Device(self._devName) try: self._device.ping() except Exception as e: print("Can not work with %s" % devName) @property def options(self): try: return eval(self._device[self._attrPrefix+'_options'].value) except: return '[]' @options.setter def options(self, value): try: self._device[self._attrPrefix+'_options'] = value except Exception as e: raise TypeError("Those options can not be set (%s)" % e) @property def active(self): try: return self._device[self._attrPrefix+'_active'].value except: return None @active.setter def active(self, value): options = self.options if value in options: self._device[self._attrPrefix+'_active'] = value else: raise ValueError("%s is not in the list of options %s" % (value, options)) @property def numeric(self): try: return self._device[self._attrPrefix+'_numeric'].value except: return None @property def meaning(self): try: return self._device[self._attrPrefix+'_meaning'].value except: return None
def count(self, elements): argin = [self.mg_name] + elements self.pool.CreateMeasurementGroup(argin) try: self.mg = Device(self.mg_name) _, values = self.mg.count(1) for channel, value in values.iteritems(): msg = "Value for %s is not numerical" % channel self.assertTrue(is_numerical(value), msg) finally: self.pool.DeleteElement(self.mg_name)
def onPauseMacro(self): door = Device(self.doorName()) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if doorState == PyTango.DevState.RUNNING: door.command_inout("PauseMacro") else: Qt.QMessageBox.warning(self, "Error while pausing macro", "It was not possible to pause macro, because state of the door was different than RUNNING")
def onStopMacro(self): door = Device(self.doorName()) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if doorState in (PyTango.DevState.RUNNING, PyTango.DevState.STANDBY): door.command_inout("StopMacro") else: Qt.QMessageBox.warning(self, "Error while stopping macro", "It was not possible to stop macro, because state of the door was different than RUNNING or STANDBY")
def count(self, elements): mg_name = str(uuid.uuid1()) argin = [mg_name] + elements self.pool.CreateMeasurementGroup(argin) try: mg = Device(mg_name) _, values = mg.count(1) for channel, value in values.iteritems(): msg = "Value for %s is not numerical" % channel self.assertTrue(is_numerical(value), msg) finally: mg.cleanUp() self.pool.DeleteElement(mg_name)
def count(self, elements): mg_name = str(uuid.uuid1()) argin = [mg_name] + elements self.pool.CreateMeasurementGroup(argin) try: mg = Device(mg_name) _, values = mg.count(.1) for channel_name, value in values.iteritems(): msg = "Value (%s) for %s is not numerical" % \ (value, channel_name) self.assertTrue(is_numerical(value), msg) finally: mg.cleanUp() self.pool.DeleteElement(mg_name)
def onPlayMacro(self): door = Device(self.doorName()) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if doorState == PyTango.DevState.ON or doorState == PyTango.DevState.ALARM: self.setFocus() paramEditorModel = self.paramEditorModel() macroNode = paramEditorModel.root() id = macroNode.assignId() self.setMacroId(id) params, alerts = macroNode.toRun() xmlString = paramEditorModel.toXmlString() if len(alerts) > 0: Qt.QMessageBox.warning(self, "Macro parameters warning", alerts) return door.runMacro(xmlString) self.addToHistory() # door.runMacro(str(macroNode.name()), params) elif doorState == PyTango.DevState.STANDBY: door.command_inout("ResumeMacro") else: Qt.QMessageBox.warning( self, "Error while starting/resuming macro", "It was not possible to start/resume macro, because state of the door was different than ON/STANDBY" )
def fill_sardana_config(self, config): import sardana.spock profile = 'spockdoor' if not config.Spock: if hasattr(Qt.qApp, 'SDM'): dm = Qt.qApp.SDM.getDataModelProxy('doorName') if dm is not None: door_name = dm.getData() door = Device(door_name) dalias, dname = door.getSimpleName(), door.getNormalName() create_sardana_profile(dalias, dname) profile = dalias config.Spock.door_name = dname sardana.spock.load_config(config) return profile
def checkDoorState(self): door = Device(self.doorName()) doorState = door.getState() if doorState == PyTango.DevState.RUNNING: self.playMacroAction.setEnabled(False) self.pauseMacroAction.setEnabled(True) self.stopMacroAction.setEnabled(True) elif doorState == PyTango.DevState.ON or doorState == PyTango.DevState.ALARM: self.playMacroAction.setEnabled(True) self.pauseMacroAction.setEnabled(False) self.stopMacroAction.setEnabled(False) elif doorState == PyTango.DevState.STANDBY: self.playMacroAction.setEnabled(True) self.pauseMacroAction.setEnabled(False) self.stopMacroAction.setEnabled(True)
def init_device(self): try: self.device = Device(self.taurusname) except DevFailed as traceback: last_error = traceback[-1] logging.getLogger("HWR").error("%s: %s", str(self.name()), last_error["desc"]) self.device = None else: try: self.device.ping() except ConnectionFailed: self.device = None raise ConnectionError
def onPlayMacro(self): door = Device(self.doorName()) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if doorState == PyTango.DevState.ON or doorState == PyTango.DevState.ALARM: self.setFocus() paramEditorModel = self.paramEditorModel() macroNode = paramEditorModel.root() id = macroNode.assignId() self.setMacroId(id) params, alerts = macroNode.toRun() xmlString = paramEditorModel.toXmlString() if len(alerts) > 0: Qt.QMessageBox.warning( self, "Macro parameters warning", alerts) return door.runMacro(xmlString) self.addToHistory() # door.runMacro(str(macroNode.name()), params) elif doorState == PyTango.DevState.STANDBY: door.command_inout("ResumeMacro") else: Qt.QMessageBox.warning(self, "Error while starting/resuming macro", "It was not possible to start/resume macro, because state of the door was different than ON/STANDBY")
def init_device(self): self.door = Device(self.doorname) self.door.set_timeout_millis(10000) # # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands # as defined in Command/Tango.py # # if self.door.__class__ == taurus.core.tango.tangodevice.TangoDevice: # dp = self.door.getHWObj() # try: # dp.subscribe_event = dp._subscribe_event # except AttributeError: # pass if self.macroStatusAttr is None: self.macroStatusAttr = self.door.getAttribute("State") self.macroStatusAttr.addListener(self.objectListener)
def onDoorChanged(self, doorName): self.setDoorName(doorName) if self.doorName() == "": self.doorStateLed.setModel(None) return self.doorStateLed.setModel(self.doorName() + "/State") door = Device(doorName) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if doorState == PyTango.DevState.ON: self.playMacroAction.setText("Start macro") self.playMacroAction.setToolTip("Start macro") elif doorState == PyTango.DevState.STANDBY: self.playMacroAction.setText("Resume macro") self.playMacroAction.setToolTip("Resume macro")
def init_device(self): try: self.device = Device(self.taurusname) except DevFailed, traceback: last_error = traceback[-1] logging.getLogger('HWR').error("%s: %s", str(self.name()), last_error['desc']) self.device = None
def set_pool_names(self, pool_names): """Registers a new list of device pools in this manager :param pool_names: sequence of pool names :type pool_names: seq<str>""" for pool in self._pools.values(): elements_attr = pool.getAttribute("Elements") elements_attr.removeListener(self.on_pool_elements_changed) for name in pool_names: self.debug("Creating pool %s", name) pool = Device(name) if pool is None: self.error('Could not create Pool object for %s' % name) continue self._pools[name] = pool elements_attr = pool.getAttribute("Elements") elements_attr.addListener(self.on_pool_elements_changed)
def __init__(self, devName, attrPrefix, *args, **kwargs): super(AttrEnum, self).__init__(*args, **kwargs) self._devName = devName self._attrPrefix = attrPrefix self._device = Device(self._devName) try: self._device.ping() except Exception as e: print("Can not work with %s" % devName)
def checkDoorState(self): """Method used by "Check door state" action (available in the context menu). It is a workaround for situations when the event notification about the macro status does not reach the sequencer widget.""" door = Device(self.doorName()) doorState = door.getState() if doorState == PyTango.DevState.RUNNING: self.playSequenceAction.setEnabled(False) self.pauseSequenceAction.setEnabled(True) self.stopSequenceAction.setEnabled(True) elif doorState in (PyTango.DevState.ON, PyTango.DevState.ALARM): self.playSequenceAction.setEnabled(True) self.pauseSequenceAction.setEnabled(False) self.stopSequenceAction.setEnabled(False) elif doorState == PyTango.DevState.STANDBY: self.playSequenceAction.setEnabled(True) self.pauseSequenceAction.setEnabled(False) self.stopSequenceAction.setEnabled(True)
def checkDoorState(self): door = Device(self.doorName()) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if doorState == PyTango.DevState.RUNNING: self.playMacroAction.setEnabled(False) self.pauseMacroAction.setEnabled(True) self.stopMacroAction.setEnabled(True) elif doorState == PyTango.DevState.ON or doorState == PyTango.DevState.ALARM: self.playMacroAction.setEnabled(True) self.pauseMacroAction.setEnabled(False) self.stopMacroAction.setEnabled(False) elif doorState == PyTango.DevState.STANDBY: self.playMacroAction.setEnabled(True) self.pauseMacroAction.setEnabled(False) self.stopMacroAction.setEnabled(True)
def onDoorChanged(self, doorName): MacroExecutionWindow.onDoorChanged(self, doorName) if self._qDoor: Qt.QObject.disconnect( self._qDoor, Qt.SIGNAL("macroStatusUpdated"), self.taurusMacroExecutorWidget.onMacroStatusUpdated) if doorName == "": return self._qDoor = Device(doorName) Qt.QObject.connect(self._qDoor, Qt.SIGNAL("macroStatusUpdated"), self.taurusMacroExecutorWidget.onMacroStatusUpdated) self.taurusMacroExecutorWidget.onDoorChanged(doorName)
def onDoorChanged(self, doorName): MacroExecutionWindow.onDoorChanged(self, doorName) if self._qDoor: self._qDoor.macroStatusUpdated.disconnect( self.taurusMacroExecutorWidget.onMacroStatusUpdated) if doorName == "": return self._qDoor = Device(doorName) self._qDoor.macroStatusUpdated.connect( self.taurusMacroExecutorWidget.onMacroStatusUpdated) self.taurusMacroExecutorWidget.onDoorChanged(doorName)
def __get_t3_name(self, item): # check if the item is a device name or an attribute name try: proxy = Device(item) except TaurusException: try: proxy = Attribute(item) except TaurusException: raise KeyError(item) v = proxy.getNameValidator() params = v.getParams(proxy.getFullName()) name = '{0}:{1}/{2}'.format(params['host'].split('.')[0], params['port'], params['devicename']) attr_name = params.get('attributename', None) if attr_name is not None: name = '{0}/{1}'.format(name, params['attributename']) return name
def set(self, conf, mnt_grps=None): """Sets the ExperimentConfiguration dictionary.""" env = dict(ScanDir=conf.get('ScanDir'), ScanFile=conf.get('ScanFile'), DataCompressionRank=conf.get('DataCompressionRank', -1), ActiveMntGrp=conf.get('ActiveMntGrp'), PreScanSnapshot=conf.get('PreScanSnapshot')) if mnt_grps is None: mnt_grps = conf['MntGrpConfigs'].keys() self._door.putEnvironments(env) codec = CodecFactory().getCodec('json') for mnt_grp in mnt_grps: try: mnt_grp_cfg = conf['MntGrpConfigs'][mnt_grp] if mnt_grp_cfg is None: # a mntGrp to be deleted pool = self._getPoolOfElement(mnt_grp) pool.DeleteElement(mnt_grp) else: try: mnt_grp_dev = Device(mnt_grp) except: # if the mnt_grp did not already exist, create it now chconfigs = getChannelConfigs(mnt_grp_cfg) chnames, chinfos = zip(*chconfigs) # unzipping # We assume that all the channels belong to the same # pool! pool = self._getPoolOfElement(chnames[0]) pool.createMeasurementGroup([mnt_grp] + list(chnames)) mnt_grp_dev = Device(mnt_grp) # TODO when we start using measurement group extension change the # code below with the following: # mnt_grp.setConfiguration(mnt_grp_cfg) data = codec.encode(('', mnt_grp_cfg))[1] mnt_grp_dev.write_attribute('configuration', data) except Exception, e: from taurus.core.util.log import error error( 'Could not create/delete/modify Measurement group "%s": %s', mnt_grp, repr(e))
def stress_count(self, elements, repeats, synchronizer, synchronization): mg_name = str(uuid.uuid1()) argin = [mg_name] + elements self.pool.CreateMeasurementGroup(argin) try: mg = Device(mg_name) mg.setSynchronizer(synchronizer, elements[0], apply=False) mg.setSynchronization(synchronization, elements[0]) for i in range(repeats): state, values = mg.count(.001) self.assertEqual(state, DevState.ON, "wrong state after measurement {}".format(i)) for channel_name, value in values.items(): msg = ("Value {} for {} is not numerical in " "measurement {}").format(value, channel_name, i) self.assertTrue(is_numerical(value), msg) finally: mg.cleanUp() self.pool.DeleteElement(mg_name)
def onDoorChanged(self, doorName): self.setDoorName(doorName) if self.doorName() == "": self.doorStateLed.setModel(None) return self.doorStateLed.setModel(self.doorName() + "/State") door = Device(doorName) doorState = door.stateObj.rvalue if doorState == PyTango.DevState.ON: self.playMacroAction.setText("Start macro") self.playMacroAction.setToolTip("Start macro") elif doorState == PyTango.DevState.STANDBY: self.playMacroAction.setText("Resume macro") self.playMacroAction.setToolTip("Resume macro")
def init_device(self): try: self.device = Device(self.taurusname) except DevFailed as traceback: last_error = traceback[-1] logging.getLogger('HWR').error("%s: %s", str(self.name()), last_error['desc']) self.device = None else: try: self.device.ping() except ConnectionFailed: self.device = None raise ConnectionError
def checkDoorState(self): """Method used by "Check door state" action (available in the context menu). It is a workaround for situations when the event notification about the macro status does not reach the sequencer widget.""" door = Device(self.doorName()) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if doorState == PyTango.DevState.RUNNING: self.playSequenceAction.setEnabled(False) self.pauseSequenceAction.setEnabled(True) self.stopSequenceAction.setEnabled(True) elif doorState in (PyTango.DevState.ON, PyTango.DevState.ALARM): self.playSequenceAction.setEnabled(True) self.pauseSequenceAction.setEnabled(False) self.stopSequenceAction.setEnabled(False) elif doorState == PyTango.DevState.STANDBY: self.playSequenceAction.setEnabled(True) self.pauseSequenceAction.setEnabled(False) self.stopSequenceAction.setEnabled(True)
def onDoorChanged(self, doorName): self.setDoorName(doorName) if self.doorName() == "": self.doorStateLed.setModel(None) return self.doorStateLed.setModel(self.doorName() + "/State") door = Device(doorName) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if doorState == PyTango.DevState.ON: self.playSequenceAction.setText("Start sequence") self.playSequenceAction.setToolTip("Start sequence") self.playSequenceAction.setEnabled(False) self.pauseSequenceAction.setEnabled(False) self.stopSequenceAction.setEnabled(False) elif doorState == PyTango.DevState.STANDBY: self.playSequenceAction.setText("Resume sequence") self.playSequenceAction.setToolTip("Resume sequence") self.playSequenceAction.setEnabled(True) self.pauseSequenceAction.setEnabled(False) self.stopSequenceAction.setEnabled(True)
def set(self, conf, mnt_grps=None): """Sets the ExperimentConfiguration dictionary.""" if mnt_grps is None: mnt_grps = list(conf['MntGrpConfigs'].keys()) codec = CodecFactory().getCodec('json') msg_error = '' for mnt_grp in mnt_grps: try: mnt_grp_cfg = conf['MntGrpConfigs'][mnt_grp] if mnt_grp_cfg is None: # a mntGrp to be deleted pool = self._getPoolOfElement(mnt_grp) pool.DeleteElement(mnt_grp) else: try: # TODO: Fix incorrect implementation. It must check if # the measurement group is part of the Pools # controlled by the MacroServer. Otherwise, # it must raise an exception. mnt_grp_dev = Device(mnt_grp) except Exception: # if the mnt_grp did not already exist, create it now chconfigs = getChannelConfigs(mnt_grp_cfg) chnames, chinfos = list(zip(*chconfigs)) # unzipping # We assume that all the channels belong to the same # pool! pool = self._getPoolOfElement(chnames[0]) pool.createMeasurementGroup([mnt_grp] + list(chnames)) mnt_grp_dev = Device(mnt_grp) # TODO when we start using measurement group extension # change the code below with the following: # mnt_grp.setConfiguration(mnt_grp_cfg) data = codec.encode(('', mnt_grp_cfg))[1] mnt_grp_dev.write_attribute('configuration', data) except PyTango.DevFailed as df: # Take the description of the first exception. desc = df.args[0].desc desc = desc.replace('\r', '') desc = desc.replace('\n', '') msg_error += 'Measurement Group {0}:\n'\ '{1}\n\n'.format(mnt_grp, desc) if len(msg_error) > 0: raise RuntimeError(msg_error) # Send the environment changes env = dict(ScanDir=conf.get('ScanDir'), ScanFile=conf.get('ScanFile'), DataCompressionRank=conf.get('DataCompressionRank', -1), ActiveMntGrp=conf.get('ActiveMntGrp'), PreScanSnapshot=conf.get('PreScanSnapshot')) self._door.putEnvironments(env)
def prepare(self, integ_time, countable_elem, **opts): self.print_value = False if countable_elem is None: try: self.countable_elem_name = self.getEnv('ActiveMntGrp') except UnknownEnv: return self.countable_elem = self.getObj(self.countable_elem_name) else: self.countable_elem_name = countable_elem.name self.countable_elem = countable_elem if self.countable_elem is None: return self.channels = [] self.values = [] if self.countable_elem.type == Type.MeasurementGroup: names = self.countable_elem.getChannelLabels() self.names = [[n] for n in names] for channel_info in self.countable_elem.getChannels(): full_name = channel_info["full_name"] channel = Device(full_name) self.channels.append(channel) value = channel.getValue(force=True) self.values.append([value]) valueObj = channel.getValueObj_() valueObj.subscribeEvent(self.counterChanged, channel) else: channel = self.countable_elem self.names = [[channel.getName()]] channel = Device(channel.full_name) self.channels.append(channel) value = channel.getValue(force=True) self.values.append([value]) valueObj = channel.getValueObj_() valueObj.subscribeEvent(self.counterChanged, channel)
def init_device(self): self.door = Device(self.doorname) self.door.set_timeout_millis(10000) # # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands # as defined in Command/Tango.py # #if self.door.__class__ == taurus.core.tango.tangodevice.TangoDevice: # dp = self.door.getHWObj() # try: # dp.subscribe_event = dp._subscribe_event # except AttributeError: # pass if self.macroStatusAttr == None: self.macroStatusAttr = self.door.getAttribute("State") self.macroStatusAttr.addListener(self.objectListener)
def onPauseSequence(self): door = Device(self.doorName()) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if doorState == PyTango.DevState.RUNNING: door.command_inout("PauseMacro") else: Qt.QMessageBox.warning( self, "Error while pausing sequence", "It was not possible to pause sequence, " "because state of the door was different than RUNNING")
def onDoorChanged(self, doorName): self.setDoorName(doorName) if self.doorName() == "": self.doorStateLed.setModel(None) return self.doorStateLed.setModel(self.doorName() + "/State") door = Device(doorName) doorState = door.stateObj.rvalue if doorState == PyTango.DevState.ON: self.playSequenceAction.setText("Start sequence") self.playSequenceAction.setToolTip("Start sequence") self.playSequenceAction.setEnabled(False) self.pauseSequenceAction.setEnabled(False) self.stopSequenceAction.setEnabled(False) elif doorState == PyTango.DevState.STANDBY: self.playSequenceAction.setText("Resume sequence") self.playSequenceAction.setToolTip("Resume sequence") self.playSequenceAction.setEnabled(True) self.pauseSequenceAction.setEnabled(False) self.stopSequenceAction.setEnabled(True)
class TestMeasurementGroup(SarTestTestCase, TestCase): def setUp(self): SarTestTestCase.setUp(self) self.mg_name = str(uuid.uuid1()) registerExtensions() def count(self, elements): argin = [self.mg_name] + elements self.pool.CreateMeasurementGroup(argin) try: self.mg = Device(self.mg_name) _, values = self.mg.count(1) for channel, value in values.iteritems(): msg = "Value for %s is not numerical" % channel self.assertTrue(is_numerical(value), msg) finally: self.pool.DeleteElement(self.mg_name) def tearDown(self): SarTestTestCase.tearDown(self)
def onStopSequence(self): door = Device(self.doorName()) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if doorState in (PyTango.DevState.RUNNING, PyTango.DevState.STANDBY): door.command_inout("StopMacro") else: Qt.QMessageBox.warning( self, "Error while stopping sequence", "It was not possible to stop sequence, " "because state of the door was different than " "RUNNING or STANDBY")
def onPlaySequence(self): door = Device(self.doorName()) doorState = door.getState() if (doorState == PyTango.DevState.ON or doorState == PyTango.DevState.ALARM): first, last, ids = self.tree.prepareMacroIds() self.setFirstMacroId(first) self.setLastMacroId(last) self.setMacroIds(ids) self.tree.prepareMacroProgresses() self.setEmitExecutionStarted(True) door.runMacro(self.tree.toXmlString()) elif doorState == PyTango.DevState.STANDBY: door.command_inout("ResumeMacro") else: Qt.QMessageBox.warning( self, "Error while starting/resuming sequence", "It was not possible to start/resume sequence, " "because state of the door was different than ON/STANDBY")
def onPlaySequence(self): door = Device(self.doorName()) try: doorState = door.state() except TypeError: # TODO: For Taurus 4 adaptation doorState = door.getState() if (doorState == PyTango.DevState.ON or doorState == PyTango.DevState.ALARM): first, last, ids = self.tree.prepareMacroIds() self.setFirstMacroId(first) self.setLastMacroId(last) self.setMacroIds(ids) self.tree.prepareMacroProgresses() self.setEmitExecutionStarted(True) door.runMacro(self.tree.toXmlString()) elif doorState == PyTango.DevState.STANDBY: door.command_inout("ResumeMacro") else: Qt.QMessageBox.warning( self, "Error while starting/resuming sequence", "It was not possible to start/resume sequence, " "because state of the door was different than ON/STANDBY")
class SardanaMacro(CommandObject, SardanaObject): macroStatusAttr = None INIT, STARTED, RUNNING, DONE = range(4) def __init__(self, name, macro, doorname = None, username = None, **kwargs): super(SardanaMacro,self).__init__(name,username,**kwargs) self._reply_arrived_event = Event() self.macro_format = macro self.doorname = doorname self.door = None self.init_device() self.macrostate = SardanaMacro.INIT self.doorstate = None self.t0 = 0 def init_device(self): self.door = Device(self.doorname) self.door.set_timeout_millis(10000) # # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands # as defined in Command/Tango.py # #if self.door.__class__ == taurus.core.tango.tangodevice.TangoDevice: # dp = self.door.getHWObj() # try: # dp.subscribe_event = dp._subscribe_event # except AttributeError: # pass if self.macroStatusAttr == None: self.macroStatusAttr = self.door.getAttribute("State") self.macroStatusAttr.addListener(self.objectListener) def __call__(self, *args, **kwargs): self._reply_arrived_event.clear() self.result = None wait = kwargs.get('wait', False) if self.door is None: self.init_device() logging.getLogger('HWR').debug("Executing sardana macro: %s" % self.macro_format) try: fullcmd = self.macro_format % args except: logging.getLogger('HWR').info(" - Wrong format for macro arguments. Macro is %s / args are (%s)" % (self.macro_format, str(args))) return try: import time self.t0 = time.time() if (self.doorstate in ["ON","ALARM"]): self.door.runMacro( (fullcmd).split() ) self.macrostate = SardanaMacro.STARTED self.emit('commandBeginWaitReply', (str(self.name()), )) else: logging.getLogger('HWR').error("%s. Cannot execute. Door is not READY", str(self.name()) ) self.emit('commandFailed', (-1, self.name())) except TypeError: logging.getLogger('HWR').error("%s. Cannot properly format macro code. Format is: %s, args are %s", str(self.name()), self.macro_format, str(args)) self.emit('commandFailed', (-1, self.name())) except DevFailed, error_dict: logging.getLogger('HWR').error("%s: Cannot run macro. %s", str(self.name()), error_dict) self.emit('commandFailed', (-1, self.name())) except AttributeError, error_dict: logging.getLogger('HWR').error("%s: MacroServer not running?, %s", str(self.name()), error_dict) self.emit('commandFailed', (-1, self.name()))
def test_move(self): mot = Device("_test_mt_1_1") _, values = mot.move(1)
def onDoorChanged(self, door_name): door = Device(door_name) dalias, dname = door.getSimpleName(), door.getNormalName() create_sardana_profile(dalias, dname)
class SardanaMacro(CommandObject, SardanaObject): macroStatusAttr = None INIT, STARTED, RUNNING, DONE = list(range(4)) def __init__(self, name, macro, doorname = None, username = None, **kwargs): super(SardanaMacro,self).__init__(name,username,**kwargs) self._reply_arrived_event = Event() self.macro_format = macro self.doorname = doorname self.door = None self.init_device() self.macrostate = SardanaMacro.INIT self.doorstate = None self.t0 = 0 def init_device(self): self.door = Device(self.doorname) self.door.set_timeout_millis(10000) # # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands # as defined in Command/Tango.py # #if self.door.__class__ == taurus.core.tango.tangodevice.TangoDevice: # dp = self.door.getHWObj() # try: # dp.subscribe_event = dp._subscribe_event # except AttributeError: # pass if self.macroStatusAttr == None: self.macroStatusAttr = self.door.getAttribute("State") self.macroStatusAttr.addListener(self.objectListener) def __call__(self, *args, **kwargs): self._reply_arrived_event.clear() self.result = None wait = kwargs.get('wait', False) if self.door is None: self.init_device() logging.getLogger('HWR').debug("Executing sardana macro: %s" % self.macro_format) try: fullcmd = self.macro_format % args except: logging.getLogger('HWR').info(" - Wrong format for macro arguments. Macro is %s / args are (%s)" % (self.macro_format, str(args))) return try: import time self.t0 = time.time() if (self.doorstate in ["ON","ALARM"]): self.door.runMacro( (fullcmd).split() ) self.macrostate = SardanaMacro.STARTED self.emit('commandBeginWaitReply', (str(self.name()), )) else: logging.getLogger('HWR').error("%s. Cannot execute. Door is not READY", str(self.name()) ) self.emit('commandFailed', (-1, self.name())) except TypeError: logging.getLogger('HWR').error("%s. Cannot properly format macro code. Format is: %s, args are %s", str(self.name()), self.macro_format, str(args)) self.emit('commandFailed', (-1, self.name())) except DevFailed as error_dict: logging.getLogger('HWR').error("%s: Cannot run macro. %s", str(self.name()), error_dict) self.emit('commandFailed', (-1, self.name())) except AttributeError as error_dict: logging.getLogger('HWR').error("%s: MacroServer not running?, %s", str(self.name()), error_dict) self.emit('commandFailed', (-1, self.name())) except: logging.getLogger('HWR').exception("%s: an error occured when calling Tango command %s", str(self.name()), self.macro_format) self.emit('commandFailed', (-1, self.name())) if wait: logging.getLogger('HWR').debug("... start waiting...") t=gevent.spawn(endOfMacro, self) t.get() logging.getLogger('HWR').debug("... end waiting...") return def update(self, event): data = event.event[2] try: if type(data) != PyTango.DeviceAttribute: # Events different than a value changed on attribute. Taurus sends an event with attribute info # logging.getLogger('HWR').debug("==========. Got an event, but it is not an attribute . it is %s" % type(data)) logging.getLogger('HWR').debug("doorstate event. type is %s" % str(type(data))) return # Handling macro state changed event doorstate = str(data.value) logging.getLogger('HWR').debug("doorstate changed. it is %s" % str(doorstate)) if doorstate != self.doorstate: self.doorstate = doorstate # logging.getLogger('HWR').debug("self.doorstate is %s" % self.canExecute()) self.emit('commandCanExecute', (self.canExecute(),)) if (doorstate in ["ON","ALARM"]): # logging.getLogger('HWR').debug("Macroserver ready for commands") self.emit('commandReady', ()) else: # logging.getLogger('HWR').debug("Macroserver busy ") self.emit('commandNotReady', ()) if self.macrostate == SardanaMacro.STARTED and doorstate == "RUNNING": # logging.getLogger('HWR').debug("Macro server is running") self.macrostate = SardanaMacro.RUNNING elif self.macrostate == SardanaMacro.RUNNING and (doorstate in ["ON", "ALARM"]): logging.getLogger('HWR').debug("Macro execution finished") self.macrostate = SardanaMacro.DONE self.result = self.door.result self.emit('commandReplyArrived', (self.result, str(self.name()))) if doorstate == "ALARM": self.emit('commandAborted', (str(self.name()), )) self._reply_arrived_event.set() elif self.macrostate == SardanaMacro.DONE or self.macrostate == SardanaMacro.INIT: # already handled in the general case above pass else: logging.getLogger('HWR').debug("Macroserver state changed") self.emit('commandFailed', (-1, str(self.name()))) except ConnectionFailed: logging.getLogger('HWR').debug("Cannot connect to door %s" % self.doorname) self.emit('commandFailed', (-1, str(self.name()))) except: import traceback logging.getLogger('HWR').debug("SardanaMacro / event handling problem. Uggh. %s" % traceback.format_exc()) self.emit('commandFailed', (-1, str(self.name()))) def abort(self): if self.door is not None: logging.getLogger('HWR').debug("SardanaMacro / aborting macro") self.door.abortMacro() #self.emit('commandReady', ()) def isConnected(self): return self.door is not None def canExecute(self): return self.door is not None and ( self.doorstate in ["ON", "ALARM"] )