Beispiel #1
0
 def _runMacro(self, xml, **kwargs):
     #kwargs like 'synch' are ignored in this re-implementation
     if self._spock_state != RUNNING_STATE:
         print "Unable to run macro: No connection to door '%s'" % self.getSimpleName()
         raise Exception("Unable to run macro: No connection")
     if xml is None:
         xml = self.getRunningXML()
     kwargs['synch'] = True
     try:
         return BaseDoor._runMacro(self, xml, **kwargs)
     except KeyboardInterrupt:
         self.write('\nCtrl-C received: Stopping... ')
         self.block_lines = 0
         self.command_inout("StopMacro")
         self.writeln("Done!")
     except PyTango.DevFailed, e:
         if is_non_str_seq(e.args) and \
            not isinstance(e.args, (str, unicode)):
             reason, desc = e.args[0].reason, e.args[0].desc
             macro_obj = self.getRunningMacro()
             if reason == 'MissingParam':
                 print "Missing parameter:", desc
                 print macro_obj.getInfo().doc
             elif reason == 'WrongParam':
                 print "Wrong parameter:", desc
                 print macro_obj.getInfo().doc
             elif reason == 'UnkownParamObj':
                 print "Unknown parameter:", desc
             elif reason == 'MissingEnv':
                 print "Missing environment:", desc
             elif reason in ('API_CantConnectToDevice', 'API_DeviceNotExported'):
                 self._updateState(self._old_sw_door_state, TaurusSWDevState.Shutdown, silent=True)
                 print "Unable to run macro: No connection to door '%s'" % self.getSimpleName()
             else:
                 print "Unable to run macro:", reason, desc
Beispiel #2
0
 def _processInput(self, input_data):
     pyos_inputhook_ptr = ctypes.c_void_p.in_dll(ctypes.pythonapi, "PyOS_InputHook")
     old_pyos_inputhook_ptr = pyos_inputhook_ptr.value
     pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
     ret = BaseDoor._processInput(self, input_data)
     pyos_inputhook_ptr.value = old_pyos_inputhook_ptr
     return ret
Beispiel #3
0
 def resultReceived(self, log_name, result):
     res = BaseDoor.resultReceived(self, log_name, result)
     self.emit(Qt.SIGNAL("resultUpdated"), res)
     # TODO: For Taurus 4 compatibility
     if hasattr(self, "resultUpdated"):
         self.resultUpdated.emit(res)
     return res
Beispiel #4
0
 def resultReceived(self, log_name, result):
     res = BaseDoor.resultReceived(self, log_name, result)
     self.emit(Qt.SIGNAL("resultUpdated"), res)
     # TODO: For Taurus 4 compatibility
     if hasattr(self, "resultUpdated"):
         self.resultUpdated.emit(res)
     return res
Beispiel #5
0
 def recordDataReceived(self, s, t, v):
     if genutils.get_pylab_mode() == "inline":
         if t not in CHANGE_EVTS: return
         res = BaseDoor.recordDataReceived(self, s, t, v)
         self.processRecordData(res)
     else:
         res = SpockBaseDoor.recordDataReceived(self, s, t, v)
     return res
Beispiel #6
0
 def recordDataReceived(self, s, t, v):
     if genutils.get_pylab_mode() == "inline":
         if t not in CHANGE_EVTS: return
         res = BaseDoor.recordDataReceived(self, s, t, v)
         self.processRecordData(res)
     else:
         res = SpockBaseDoor.recordDataReceived(self, s, t, v)
     return res
Beispiel #7
0
 def recordDataReceived(self, s, t, v):
     if t not in CHANGE_EVTS: return
     res = BaseDoor.recordDataReceived(self, s, t, v)
     self.emit(Qt.SIGNAL("recordDataUpdated"), res)
     # TODO: For Taurus 4 compatibility
     if hasattr(self, "recordDataUpdated"):
         self.recordDataUpdated.emit(res)
     return res
Beispiel #8
0
 def recordDataReceived(self, s, t, v):
     if t not in CHANGE_EVTS:
         return
     res = BaseDoor.recordDataReceived(self, s, t, v)
     self.emit(Qt.SIGNAL("recordDataUpdated"), res)
     # TODO: For Taurus 4 compatibility
     if hasattr(self, "recordDataUpdated"):
         self.recordDataUpdated.emit(res)
     return res
Beispiel #9
0
 def _processRecordData(self, data):
     if data is None: return
     value = data.value
     size = len(value[1])
     if size > self._RECORD_DATA_THRESOLD:
         sizekb = size / 1024
         self.logReceived(self.Info, ['Received long data record (%d Kb)' % sizekb,
             'It may take some time to process. Please wait...'])
     return BaseDoor._processRecordData(self, data)
Beispiel #10
0
    def macroStatusReceived(self, s, t, v):
        res = BaseDoor.macroStatusReceived(self, s, t, v)
        if t == TaurusEventType.Error:
            macro = None
        else:
            macro = self.getRunningMacro()
        if macro is None:
            return

        self.macroStatusUpdated.emit((macro, res))
        return res
Beispiel #11
0
    def macroStatusReceived(self, s, t, v):
        res = BaseDoor.macroStatusReceived(self, s, t, v)
        if t == TaurusEventType.Error:
            macro = None
        else:
            macro = self.getRunningMacro()
        if macro is None:
            return

        self.macroStatusUpdated.emit((macro, res))
        return res
Beispiel #12
0
 def logReceived(self, log_name, output):
     res = BaseDoor.logReceived(self, log_name, output)
     log_name = log_name.lower()
     self.emit(Qt.SIGNAL("%sUpdated" % log_name), output)
     # TODO: For Taurus 4 compatibility
     try:
         recordDataUpdated = getattr(self, "%sUpdated" % log_name)
         recordDataUpdated.emit(output)
     except AttributeError:
         pass
     return res
Beispiel #13
0
 def logReceived(self, log_name, output):
     res = BaseDoor.logReceived(self, log_name, output)
     log_name = log_name.lower()
     self.emit(Qt.SIGNAL("%sUpdated" % log_name), output)
     # TODO: For Taurus 4 compatibility
     try:
         recordDataUpdated = getattr(self, "%sUpdated" % log_name)
         recordDataUpdated.emit(output)
     except AttributeError:
         pass
     return res
Beispiel #14
0
    def __init__(self):
        self._db = PyTango.Database()
        door_name = self.find_door()
        if not door_name:
            tkMessageBox.showerror("Error", "No Sardana door found.")
            sys.exit(1)
        print door_name
        door_full_name = "%s:%s/%s" % \
                (self._db.get_db_host(), self._db.get_db_port(), door_name)
        # Sardana door.
        self.door = BaseDoor(door_full_name)
        # Debug, Output stream of door log.
        self.debug = self.door.getLogObj('debug')
        self.output = self.door.getLogObj('output')

        self.device_classes = ["Motor", "LimaCCDs"]
        self.devices = []
        for class_type in self.device_classes:
            self.devices.extend(
                self._db.get_device_exported_for_class(
                    class_type).value_string)
Beispiel #15
0
 def macroStatusReceived(self, s, t, v):
     res = BaseDoor.macroStatusReceived(self, s, t, v)
     if t == TaurusEventType.Error:
         macro = None
     else:
         macro = self.getRunningMacro()
     if macro is None: return
     self.emit(Qt.SIGNAL("macroStatusUpdated"), (macro, res))
     # TODO: For Taurus 4 compatibility
     if hasattr(self, "macroStatusUpdated"):
         self.macroStatusUpdated.emit(res)
     return res
Beispiel #16
0
 def macroStatusReceived(self, s, t, v):
     res = BaseDoor.macroStatusReceived(self, s, t, v)
     if t == TaurusEventType.Error:
         macro = None
     else:
         macro = self.getRunningMacro()
     if macro is None:
         return
     self.emit(Qt.SIGNAL("macroStatusUpdated"), (macro, res))
     # TODO: For Taurus 4 compatibility
     if hasattr(self, "macroStatusUpdated"):
         self.macroStatusUpdated.emit(res)
     return res
Beispiel #17
0
 def _runMacro(self, xml, **kwargs):
     # kwargs like 'synch' are ignored in this re-implementation
     if self._spock_state != RUNNING_STATE:
         print("Unable to run macro: No connection to door '%s'" %
               self.getSimpleName())
         raise Exception("Unable to run macro: No connection")
     if self.stateObj.read().rvalue == PyTango.DevState.RUNNING:
         print("Another macro is running. Wait until it finishes...")
         raise Exception("Unable to run macro: door in RUNNING state")
     if xml is None:
         xml = self.getRunningXML()
     kwargs['synch'] = True
     try:
         return BaseDoor._runMacro(self, xml, **kwargs)
     except KeyboardInterrupt:
         self._handle_stop()
     except PyTango.DevFailed as e:
         if is_non_str_seq(e.args) and \
            not isinstance(e.args, str):
             reason, desc = e.args[0].reason, e.args[0].desc
             macro_obj = self.getRunningMacro()
             if reason == 'MissingParam':
                 print("Missing parameter:", desc)
                 print(macro_obj.getInfo().doc)
             elif reason == 'WrongParam':
                 print("Wrong parameter:", desc)
                 print(macro_obj.getInfo().doc)
             elif reason == 'UnkownParamObj':
                 print("Unknown parameter:", desc)
             elif reason == 'MissingEnv':
                 print("Missing environment:", desc)
             elif reason in ('API_CantConnectToDevice',
                             'API_DeviceNotExported'):
                 self._updateState(self._old_sw_door_state,
                                   TaurusSWDevState.Shutdown,
                                   silent=True)
                 print("Unable to run macro: No connection to door '%s'" %
                       self.getSimpleName())
             else:
                 print("Unable to run macro:", reason, desc)
Beispiel #18
0
class Tango(object):
    """Interact with Tango system.

    Attributes:
        _db: instance of Tango database.
        door: instance of Sardana door.
        debug: debug-level log stream of Sardana.
        output: output-level log stream of Sardana.
        device_classes (list of str): supported device classes.
        devices (str): all devices found under classes |device_classes|.

    """
    def __init__(self):
        self._db = PyTango.Database()
        door_name = self.find_door()
        if not door_name:
            tkMessageBox.showerror("Error", "No Sardana door found.")
            sys.exit(1)
        print door_name
        door_full_name = "%s:%s/%s" % \
                (self._db.get_db_host(), self._db.get_db_port(), door_name)
        # Sardana door.
        self.door = BaseDoor(door_full_name)
        # Debug, Output stream of door log.
        self.debug = self.door.getLogObj('debug')
        self.output = self.door.getLogObj('output')

        self.device_classes = ["Motor", "LimaCCDs"]
        self.devices = []
        for class_type in self.device_classes:
            self.devices.extend(
                self._db.get_device_exported_for_class(
                    class_type).value_string)

    def get_device_alias(self, device):
        """Return the alias of |device|."""
        return self._db.get_alias_from_device(device)

    def get_device_class(self, device):
        """Return the tango class of |device|."""
        return self._db.get_class_for_device(device)

    def is_sardana_running(self):
        """Return True if sardana is at state ON instead of RUNNING, OFF."""
        return self.door.getState() == PyTango.DevState.RUNNING

    def find_door(self):
        """Return door name. Return None if not found.

        Find door under server pattern MacroServer*.

        """
        server_list = self._db.get_server_list('MacroServer/*').value_string
        for server in server_list:
            server_devs = self._db.get_device_class_list(server).value_string
            devs, classes = server_devs[0::2], server_devs[1::2]
            for idx, class_ in enumerate(classes):
                if class_.lower() == "door":
                    return devs[idx]
        return None

    def run_macro(self, command):
        """Run macro on Sardana.

        Args:
            command (list of str): macro encapsulated in list, eg. ["wa"].

        """
        self.output.clearLogBuffer()
        self.debug.clearLogBuffer()
        self.door.runmacro(command)
        # Wait for attribute change finish.
        while not self.debug.getLogBuffer():
            time.sleep(0.05)
        while self.is_sardana_running():
            time.sleep(0.05)
        for idx, dev in enumerate(devs):
            if dev.lower() == door_name.lower():
                if classes[idx] == "Door":
                    return True
                else:
                    return False
    return False


DOOR_NAME = "cfeld/door/cfeld-pcx27083.01"
if not is_door(DOOR_NAME):
    print "not door"
    sys.exit(1)
db = PyTango.Database()
door_full_name = "%s:%s/%s" % (db.get_db_host(), db.get_db_port(), DOOR_NAME)
door = BaseDoor(door_full_name)
output = door.getLogObj('output')
debug = door.getLogObj('debug')

output.clearLogBuffer()
debug.clearLogBuffer()
# door.runmacro(["wa"])
# door.runmacro(["mv", "exp_dmy01", "0"])
door.runmacro(["mv", "motor/dummy_mot_ctrl/1", "0"])
# door.runmacro(["ascan", "exp_dmy01", "0", "1", "10", "0.2"])
# door.runmacro(["ascan", "motor/dummy_mot_ctrl/1", "0", "1", "10", "0.2"])
while not debug.getLogBuffer():
    print "empty"
    time.sleep(0.05)
while door.getState() == PyTango.DevState.RUNNING:
    print "running"
Beispiel #20
0
 def write(self, msg, stream=None):
     if not self.isConsoleReady():
         return
     return BaseDoor.write(self, msg, stream=stream)
Beispiel #21
0
 def stateChanged(self, s, t, v):
     old_sw_state = self._old_sw_door_state
     BaseDoor.stateChanged(self, s, t, v)
     new_sw_state = self._old_sw_door_state
     self._updateState(old_sw_state, new_sw_state)
Beispiel #22
0
 def recordDataReceived(self, s, t, v):
     if t not in CHANGE_EVTS:
         return
     res = BaseDoor.recordDataReceived(self, s, t, v)
     self.recordDataUpdated.emit(res)
     return res
Beispiel #23
0
 def stateChanged(self, s, t, v):
     old_sw_state = self._old_sw_door_state
     BaseDoor.stateChanged(self, s, t, v)
     new_sw_state = self._old_sw_door_state
     self._updateState(old_sw_state, new_sw_state)
Beispiel #24
0
 def resultReceived(self, log_name, result):
     res = BaseDoor.resultReceived(self, log_name, result)
     self.resultUpdated.emit(res)
     return res
Beispiel #25
0
 def preRunMacro(self, obj, parameters):
     return BaseDoor.preRunMacro(self, obj, self._preprocessParameters(parameters))
Beispiel #26
0
 def _onExperimentConfigurationChanged(self, *args):
     conf = copy.deepcopy(BaseDoor.getExperimentConfiguration(self))
     self.experimentConfigurationChanged.emit(conf)
Beispiel #27
0
 def runMacro(self, obj, parameters=[], synch=False):
     return BaseDoor.runMacro(self, obj, parameters=parameters, synch=synch)
Beispiel #28
0
 def logReceived(self, log_name, output):
     res = BaseDoor.logReceived(self, log_name, output)
     log_name = log_name.lower()
     recordDataUpdated = getattr(self, "%sUpdated" % log_name)
     recordDataUpdated.emit(output)
     return res
Beispiel #29
0
 def getExperimentConfiguration(self):
     self._prepare_connections()
     return BaseDoor.getExperimentConfiguration(self)
Beispiel #30
0
 def _onExperimentConfigurationChanged(self, *args):
     conf = copy.deepcopy(BaseDoor.getExperimentConfiguration(self))
     self.experimentConfigurationChanged.emit(conf)
Beispiel #31
0
 def preRunMacro(self, obj, parameters):
     return BaseDoor.preRunMacro(self, obj,
                                 self._preprocessParameters(parameters))
Beispiel #32
0
 def getExperimentConfiguration(self):
     self._prepare_connections()
     return BaseDoor.getExperimentConfiguration(self)
Beispiel #33
0
 def runMacro(self, obj, parameters=[], synch=False):
     return BaseDoor.runMacro(self, obj, parameters=parameters, synch=synch)
Beispiel #34
0
 def recordDataReceived(self, s, t, v):
     if t not in CHANGE_EVTS:
         return
     res = BaseDoor.recordDataReceived(self, s, t, v)
     self.recordDataUpdated.emit(res)
     return res
Beispiel #35
0
 def resultReceived(self, log_name, result):
     res = BaseDoor.resultReceived(self, log_name, result)
     self.resultUpdated.emit(res)
     return res
Beispiel #36
0
 def logReceived(self, log_name, output):
     res = BaseDoor.logReceived(self, log_name, output)
     log_name = log_name.lower()
     recordDataUpdated = getattr(self, "%sUpdated" % log_name)
     recordDataUpdated.emit(output)
     return res
Beispiel #37
0
 def write(self, msg, stream=None):
     if not self.isConsoleReady():
         return
     return BaseDoor.write(self, msg, stream=stream)