예제 #1
0
    def AddDevice(self, axis):
        """Add axis to the controller, basically creates a taurus device of
        the corresponding channel.
        """
        position_name = self.position_names[axis - 1]
        self.attributes[axis] = tg = {}
        try:
            ch_position = tg['ch_position'] = taurus.Device(position_name)
            prop_dict = ch_position.get_property(['deviceName', 'counterName'])
            attr = ch_position.getAttribute('OutputEventTerminal')
            counter_name = ni6602.get(prop_dict.get('counterName')[0])
            device_name = prop_dict.get('deviceName')[0]
            chn_str = "/%s/%s" % (device_name, counter_name.get("out"))
            attr.write(chn_str)
        except Exception as e:
            msg = 'Could not create taurus device: %s, details: %s' %\
                  (position_name, e)
            self._log.debug(msg)
        generator_name = self.generator_names[axis - 1]
        try:
            ch_generator = tg['ch_generator'] = taurus.Device(generator_name)
            prop_dict = ch_generator.get_property('counterName')
            attr = ch_generator.getAttribute('SourceTerminal')
            attr.write(chn_str)

        except Exception as e:
            msg = 'Could not create taurus device: %s, details: %s' %\
                  (generator_name, e)
            self._log.debug(msg)
        tg['resolution'] = .25
예제 #2
0
    def __init__(self, ui):
        super(QtGui.QMainWindow, self).__init__()
        self.ui = ui

        try:
            self.ui.setupUi(self)
            # Connect signals to our handlers
            self.updateStopBtn.connect(self.handle_updateStopBtn)
            self.updateGapLimits.connect(self.handle_updateGapLimits)
            self.updatePhaseLimits.connect(self.handle_updatePhaseLimits)
            self.updatePhaseMode.connect(self.handle_updatePhaseMode)
            self.updateAxesFlags.connect(self.handle_updateAxesFlags)

            # Initialize UI state
            self.ui.cmbPhase.setCurrentIndex(
                int(taurus.Device('$undulator').PhaseMode))
            self.ui.cmbGearUpper.setCurrentIndex(
                int(taurus.Device('$gearUp').isGeared))
            self.ui.cmbGearLower.setCurrentIndex(
                int(taurus.Device('$gearLow').isGeared))
            self.ui.tabMain.currentChanged.connect(self.handle_tabChange)
            self.handle_updateAxesFlags(taurus.Device('$undulator').AxesFlags)

            # Hide motors group-box
            self.ui.groupBoxMotors.setVisible(False)

        except Exception as e:
            QtGui.QMessageBox.critical(
                self, 'ID GUI',
                'Failed to initialize the ID GUI, please make sure the Tango devices are running and are configured properly.\n\n'
                + str(traceback.format_exception(*sys.exc_info())))
            exit(1)
예제 #3
0
def gearDown(geared):
    try:
        if geared == 1:
            #Enable gearing
            taurus.Device('$gearLow').SetGearedMode()
        else:
            #Disable gearing
            taurus.Device('$gearLow').SetIndependantMode()
    except:
        print "Lower gearing problem. Can not set gearing to: " + str(geared)
예제 #4
0
def gearUp(geared):
    try:
        if geared == 1:
            #Enable gearing
            taurus.Device('$gearUp').SetGearedMode()
        else:
            #Disable gearing
            taurus.Device('$gearUp').SetIndependantMode()
    except:
        pass
예제 #5
0
def handleStopAllBtn():
    und = taurus.Device('$undulator')

    if und.StopAll:
        und.toggleStopAll(False)
    else:
        und.toggleStopAll(True)
예제 #6
0
def main():
    parser = argparse.ArgumentParser(
        description="Change Tango DB in Sardana measurement group "
                    "configurations"
    )
    parser.add_argument("pool", type=str,
                        help="Pool device name")
    parser.add_argument("tango_db_pqdn", action="store", type=str,
                        help="old Tango database e.g. tbl09:10000")
    parser.add_argument("tango_db_fqdn", action="store", type=str,
                        help="new Tango database e.g. tbl09.cells.es:10000")
    parser.add_argument("--verbose", action="store_true")
    args = parser.parse_args()
    registerExtensions()
    device = taurus.Device(args.pool)
    try:
        hwinfo = device.getHWObj().info()
    except tango.DevFailed:
        print("Pool {} is not exported. Hint: start the DS. Exiting...".format(
            args.pool))
        sys.exit(-1)
    dev_class = hwinfo.dev_class
    if dev_class == "Pool":
        change_mntgrp(device, args.tango_db_pqdn, args.tango_db_fqdn,
                      args.verbose)
    else:
        print("Invalid model, expected Pool. Exiting...")
        sys.exit(-1)
    print("IMPORTANT: now restart the {0} device server".format(dev_class))
예제 #7
0
    def _configureMotor(self, motor_name):
        if motor_name is None:
            motor_name = self.DefaultMotor

        if motor_name == self._last_motor_name:
            return

        # TODO: Implement verification of the motor if it is part of the
        #  controller.

        self._last_motor_name = motor_name
        motor = taurus.Device(self._last_motor_name)
        self._motor_axis = int(motor.get_property('axis')['axis'][0])
        attrs = motor.read_attributes(['step_per_unit', 'offset', 'sign'])
        values = [attr.value for attr in attrs]
        self._motor_spu, self._motor_offset, self._motor_sign = values

        if self._use_master_out:
            # remove previous connection and connect the new motor
            pmux = self._ipap.get_pmux()
            for p in pmux:
                if 'E0' in p:
                    self._ipap.clear_pmux('e0')
                    break
            self._ipap.add_pmux(self._motor_axis,
                                'e0',
                                pos=False,
                                aux=True,
                                hard=True)

            pmux = self._ipap.get_pmux()
            self._log.debug('_connectMotor PMUX={0}'.format(pmux))
예제 #8
0
 def run(self, ntriggers):
     ni_channel_name = self.getEnv('NITriggerChannel')
     channel = taurus.Device(ni_channel_name)
     channel.command_inout('Stop')
     if ntriggers > 0:
         channel.write_attribute("SampPerChan", int(ntriggers))
     channel.command_inout('Start')
예제 #9
0
def getAlarmReport(alarm,parent=None):
    print 'getAlarmReport(%s(%s))'%(type(alarm),alarm)
    try:
        if type(alarm) is panic.Alarm:
            alarm = alarm
        elif type(alarm) is str:
            alarm=panic.current()[alarm]
        else:
            alarm=str(alarm.path()).split('.',1)[0]
        details=''#<pre>'
        details+=str(taurus.Device(alarm.device).command_inout('GenerateReport',[alarm.tag])[0])
        #details+='\n\n<a href="'+str(tb.windowTitle())+'">'+str(tb.windowTitle())+'</a>'
        #details+='</pre>'
    except:
        details = "<h2>Unable to get Alarm details from %s/%s </h2>"%(alarm.device,alarm.tag)
        details += '\n\n'+ '-'*80 +'\n\n'+'<pre>%s</pre>'%traceback.format_exc()
    widget = Qt.QDialog(parent)
    widget.setLayout(Qt.QVBoxLayout())
    msg = 'Last %s report:'%alarm.tag
    widget.setWindowTitle(msg)
    print '%s\n%s'%(msg,details)
    widget.layout().addWidget(Qt.QLabel(msg))
    tb = Qt.QTextBrowser(widget)
    tb.setPlainText(details)
    tb.setMinimumWidth(350)
    widget.layout().addWidget(tb)
    widget.setMinimumWidth(350)
    bt = Qt.QDialogButtonBox(Qt.QDialogButtonBox.Ok,Qt.Qt.Horizontal,widget)
    widget.layout().addWidget(bt)
    bt.connect(bt,Qt.SIGNAL("accepted()"),widget.accept)
    return widget
예제 #10
0
    def setModel(self, model):
        try:
            self.ioreg_dev = taurus.Device(model)
        except:
            return

        self.alias_label.setModel('%s/State?configuration=dev_alias' % model)
        self.value_label.setModel(model)

        # Empty previous buttons
        #self.ui.lo_buttons_write.
        for button in self.button_value_dict.keys():
            self.disconnect(button, Qt.SIGNAL('clicked'), self.writeValue)
            button.deleteLater()
        self.button_value_dict = {}

        labels = self.ioreg_dev.getAttribute('Labels').read().value
        labels_list = labels.split(' ')
        # Update the mapping
        for label_and_value in labels_list:
            label, value = label_and_value.split(':')
            button = Qt.QPushButton(label)
            self.button_value_dict[button] = value
            self.ui.lo_buttons_write.addWidget(button)
            self.connect(button, Qt.SIGNAL('clicked()'), self.writeValue)
예제 #11
0
    def setModel(self, model):
        '''
        reimplemented from :class:`TaurusWidget`. A door device name is 
        expected as the model
        '''
        TaurusWidget.setModel(self, model)
        if self.door is not None:
            self.disconnect(self.door, Qt.SIGNAL('macroStatusUpdated'),
                            self._statusUpdated)
            self.disconnect(self.door, Qt.SIGNAL('resultUpdated'),
                            self._resultUpdated)

            # disable management of Door Tango States
            self.door.getAttribute('State').removeListener(
                self.door_state_listener)
            self.disconnect(self.door_state_listener,
                            Qt.SIGNAL('doorStateChanged'),
                            self._doorStateChanged)
            self.door_state_listener = None

        try:
            self.door = taurus.Device(model)
        except:
            return

        self.connect(self.door, Qt.SIGNAL('macroStatusUpdated'),
                     self._statusUpdated)
        self.connect(self.door, Qt.SIGNAL('resultUpdated'),
                     self._resultUpdated)

        # Manage Door Tango States
        self.door_state_listener = DoorStateListener()
        self.connect(self.door_state_listener, Qt.SIGNAL('doorStateChanged'),
                     self._doorStateChanged)
        self.door.getAttribute('State').addListener(self.door_state_listener)
예제 #12
0
 def get_attrs_form(self, device, form=None, filters=None, parent=None):
     filters = filters or get_regexp_dict(
         TaurusDevicePanel._attribute_filter, device, ['.*'])
     self.trace('In TaurusDevicePanel.get_attrs_form(%s,%s)' %
                (device, filters))
     allattrs = sorted(
         str(a) for a in taurus.Device(device).get_attribute_list()
         if str(a).lower() not in ('state', 'status'))
     attrs = []
     for a in filters:
         for t in allattrs:
             if a and searchCl(a.strip(), t.strip()):
                 aname = '%s/%s' % (device, t)
                 if aname not in attrs:
                     attrs.append(aname)
     if attrs:
         #self.trace( 'Matching attributes are: %s' % str(attrs)[:100])
         if form is None:
             form = TaurusForm(parent)
         elif hasattr(form, 'setModel'):
             form.setModel([])
         # Configuring the TauForm:
         form.setWithButtons(False)
         form.setWindowTitle(device)
         try:
             form.setModel(attrs)
         except Exception:
             self.warning(
                 'TaurusDevicePanel.ERROR: Unable to setModel for TaurusDevicePanel.attrs_form!!: %s'
                 % traceback.format_exc())
         return form
     else:
         return None
    def AddDevice(self, axis):
        channel_name = self.channelDevNamesList[axis - 1]
        try:
            self.channels[axis] = taurus.Device(channel_name)
        except Exception as e:
            msg = 'Exception when it created the taurus devices: %s' % e
            self._log.error(msg)

        # check the current application type
        properties_names = ['applicationType', 'counterName', 'DeviceName']
        properties = self.channels[axis].get_property(properties_names)
        app_type = properties['applicationType'][0]

        counterName = properties['counterName'][0]
        deviceName = properties['DeviceName'][0]
        self.counterName[axis] = '/%s/%s' % (deviceName, counterName)
        self.index[axis] = 0
        self.aborted[axis] = False
        self.delay_counter[axis] = 0
        # For input channels, initialize cache.
        if axis != 1:
            if app_type != self.APP_TYPE:
                msg = 'ERROR, The channel %r has wrong application type, ' \
                      '%r != ' \
                      '%r' % (axis, app_type, self.APP_TYPE)
                self._log.error(msg)
            channel = self.channels[axis]
            channel.addListener(self.counterEventReceived)
            self.ch_configured[axis] = False
            self.attributes[axis] = {}
            for name in self.cached_attributes:
                self.attributes[axis][name] = None
 def __init__(self, inst, props, *args, **kwargs):
     if self.BUFFER_ATTR is None:
         msg = '%s does not define BUFFER_ATTR' % self.__class__.__name__
         raise Exception(msg)
     self.channelDevNamesList = self.channelDevNames.split(",")
     self.dataBuff = {}
     self.channels = {}
     self.counterName = {}
     self.index = {}
     self.delay_counter = {}
     self.aborted = {}
     self.attributes = {}
     self._repetitions = 0
     self.state = State.Unknown
     self.status = ""
     self.cards = {}
     self.card_configured = {}
     self.ch_configured = {}
     self.sev = SafeEvaluator()
     self._latency_time = self.latencyTime
     self.current_ch_configured = 0
     cards = self.sev.eval(self.connectTerms)
     for card_dev_name in cards.keys():
         value = cards[card_dev_name]
         card_dev = taurus.Device(card_dev_name)
         card_dev.addListener(self.cardEventReceived)
         self.cards[card_dev] = value
         self.card_configured[card_dev] = False
예제 #15
0
    def run(self, channels, polarity):
        connect_list = []
        try:
            ni_device_name = self.getEnv('NI660XDsName')
        except Exception as e:
            self.error('You should declare the Ni660XDsName. %s' % e)

        ni_device = taurus.Device(ni_device_name)

        for chn in channels:
            chn = chn.upper()
            if 'RTSI' not in chn:
                # Change the channel name by its PFI
                dev_chn = chn.rsplit('/', 1)
                dev_chn[1] = NI660X_PFI[dev_chn[1]]
                chn = '/'.join(dev_chn)
            connect_list.append(chn)

        for pair in connect_list[1:]:
            cmd = [connect_list[0], pair]
            self.debug(cmd)
            ni_device.DisconnectTerms(cmd)

        # Include the last parameter DoNotInvertPolarity or InvertPolarity
        for pair in connect_list[1:]:
            cmd = [connect_list[0], pair, polarity]
            self.debug(cmd)
            ni_device.ConnectTerms(cmd)
예제 #16
0
    def __init__(self, inst, props, *args, **kwargs):
        """
        :param inst:
        :param props:
        :param args:
        :param kwargs:
        :return:
        """
        TriggerGateController.__init__(self, inst, props, *args, **kwargs)
        self._log.debug('IcePAPTriggerCtr init....')

        self._time_mode = False
        self._start_trigger_only = False
        self._use_master_out = self.UseMasterOut
        self._axis_info_list = list(map(str.strip, self.AxisInfos.split(',')))

        # Calculate the number of retries according to the timeout and the
        # default Tango timeout (3s)
        self._retries_nr = 3 // (self.Timeout + 0.1)
        if self._retries_nr == 0:
            self._retries_nr = 1
        self._retries_nr = int(self._retries_nr)
        self._ipap_ctrl = taurus.Device(self.IcepapController)
        properties = self._ipap_ctrl.get_property(['host', 'port'])
        host = properties['host'][0]
        port = int(properties['port'][0])
        self._ipap = icepap.IcePAPController(host=host,
                                             port=port,
                                             timeout=self.Timeout,
                                             auto_axes=True)
        self._last_motor_name = None
        self._motor_axis = None
        self._motor_spu = 1
        self._motor_offset = 0
        self._motor_sign = 1
예제 #17
0
 def contextMenuEvent(self, event):
     ''' This function is called when right clicking on qwt plot area. A pop up menu will be
     shown with the available options. '''
     self.info('TaurusPropTable.contextMenuEvent()')
     menu = Qt.QMenu(self)
     configDialogAction = menu.addAction("Add new property")
     self.connect(configDialogAction, Qt.SIGNAL("triggered()"),
                  self.addProperty)
     configDialogAction = menu.addAction("Delete property")
     self.connect(configDialogAction, Qt.SIGNAL("triggered()"),
                  self.deleteProperty)
     configDialogAction = menu.addAction("Edit property")
     self.connect(configDialogAction, Qt.SIGNAL("triggered()"),
                  self.editProperty)
     menu.addSeparator()
     cmd = 'updateDynamicAttributes' if 'DynamicAttributes' in self.list_prop else 'init'
     configDialogAction = menu.addAction("Execute " + cmd + "()")
     self.connect(
         configDialogAction,
         Qt.SIGNAL("triggered()"),
         lambda d=self.dev_name, c=cmd: vacca.utils.YesNoDialog(
             'Warning', 'Are you sure that %s supports %s() command?' %
             (self.dev_name, c)) and taurus.Device(d).command_inout(c))
     menu.exec_(event.globalPos())
     del menu
예제 #18
0
    def setAlarmModel(self, alarm_object, use_list=True):
        """
        That's the place where you tell taurus to send the events to that object
        """
        #print 'AlarmRow(%s).setAlarmModel(%s)'%(self.getModel(),alarm_object)
        self.device = alarm_object.device
        self.use_list = use_list
        self.setModel(None)
        if use_list: self.model = alarm_object.device + '/' + 'ActiveAlarms'
        else:
            self.model = alarm_object.device + '/' + alarm_object.get_attribute(
            )
        #print'In AlarmRow(%s).setModel(%s,use_list=%s)'%(alarm_object.tag, self.model,use_list)

        self.alarm = alarm_object
        self.tag = alarm_object.tag
        self.alarm.counter = -1
        self.errors = 0
        self.alarm.active = None
        self.quality = None
        AlarmRow.ALL_ROWS[str(self.tag).lower()] = self
        self.setText('  ' + self.get_tag_text() + ' - loading ...')
        try:
            taurus.Device(
                alarm_object.device).set_timeout_millis(DEVICE_TIMEOUT)
        except:
            print(fandango.log.except2str())
        self.setModel(self.model)
        taurus.Attribute(self.model).changePollingPeriod(REFRESH_TIME)
예제 #19
0
파일: plot.py 프로젝트: MikeFalowski/VACCA
 def setModel(self, model):
     print '*' * 80
     self.info('VaccaProfilePlot.setModel(%s)' % model)
     print '*' * 80
     try:
         #if self._profile_loaded: return
         if fandango.isSequence(
                 model
         ) or 'attributename' in fandango.tango.parse_tango_model(model):
             self.info('setting an attribute model')
             TaurusPlot.setModel(self, model)  # model = model[0]# str(
             # model).rsplit('/',1)[0]
         else:
             self.info('setting a composer model')
             assert fandango.check_device(model)
             dev = taurus.Device(model)
             if all(a in map(str.lower, dev.get_attribute_list())
                    for a in ('ccgaxxis', 'ccgpressures', 'ipaxxis',
                              'ippressures', 'thermoaxxis', 'thermocouples',
                              'axxispositions', 'axxislabels')):
                 TaurusPlot.setModel(self, [])
                 setup_profile_plot(self, model)
             else:
                 self.warning('%s has not all required attributes' % model)
         if len(self._positions) and len(self._labels):
             self.info('Setting CustomXLabels ...')
             self.setAxisCustomLabels(Qwt5.QwtPlot.xBottom,
                                      zip(self._positions, self._labels),
                                      60)
     except Exception, e:
         self.warning('VaccaProfilePlot.setModel(%s) failed!: %s' %
                      (model, e))
예제 #20
0
def gapToRef(gap, center):
    try:
        # Set up array
        params = array('d', [float(gap), float(center)])
        # Send command with array as parameter
        taurus.Device('$undulator').CalibrateGap(params)
    except RuntimeError as e:
        print "Problem with gap to reference command." + e
예제 #21
0
 def run(self, dev):
     lima = taurus.Device(dev)
     value = lima.read_attribute("saving_next_number").value
     dir = lima.read_attribute("saving_directory").value
     prefix = lima.read_attribute("saving_prefix").value
     id = str("%04d" % value)
     suffix = lima.read_attribute("saving_suffix").value
     filename = dir + prefix + id + suffix
     return filename
예제 #22
0
    def setModel(self, model):
        try:
            self.ioreg_dev = taurus.Device(model)
        except:
            return

        self.alias_label.setModel('%s/State?configuration=dev_alias' % model)
        self.read_widget.setModel(model)
        self.write_widget.setModel(model)
예제 #23
0
 def run(self, high_time, low_time, ntriggers, idle_state, delay_time):
     ni_channel_name = self.getEnv('NITriggerChannel')
     channel = taurus.Device(ni_channel_name)
     channel.command_inout('Stop')
     channel.write_attribute("InitialDelayTime", delay_time)
     channel.write_attribute("HighTime", high_time)
     channel.write_attribute("LowTime", low_time)
     channel.write_attribute("SampPerChan", int(ntriggers))
     channel.write_attribute("IdleState", idle_state)
     channel.write_attribute("SampleTimingType", "Implicit")
예제 #24
0
def motorsOff():
    try:
        taurus.Device('$gapz1').Off()
        taurus.Device('$gapz2').Off()
        taurus.Device('$gapz3').Off()
        taurus.Device('$gapz4').Off()
        taurus.Device('$phasex1').Off()
        taurus.Device('$phasex2').Off()
        taurus.Device('$phasex3').Off()
        taurus.Device('$phasex4').Off()
    except:
        print "Error sending motorOn commands."
예제 #25
0
 def init_device(self):
     self.debug_stream("In init_device()")
     self.get_device_properties(self.get_device_class())
     self.attr_Position_read = 0.0
     self.attr_Velocity_read = 0.0
     self.attr_Limit_Switches_read = [False]
     #----- PROTECTED REGION ID(MotorInterface.init_device) ENABLED START -----#
     self.motor = taurus.Device(self.MotorModel)
     self.position = taurus.Attribute(self.MotorModel+'/Position')
     self.velocity = taurus.Attribute(self.MotorModel+'/Velocity')
     self.limit_switches = taurus.Attribute(self.MotorModel+'/Limit_Switches')
예제 #26
0
 def run(self):
     for i in range(100):
         if self.dev and self.dev._stop_flag:
             break
         print('In job; {} iteration'.format(i))
         for nb_dev in range(1, 5):
             dev = taurus.Device(DEV_NAME_PATTERN.format(nb_dev))
             dev["attr1"]
         time.sleep(.01)
     if self.dev:
         self.dev.set_state(PyTango.DevState.ON)
예제 #27
0
def tg_serv_exc():
    import PyTango
    import taurus
    dev = taurus.Device("sys/tg_test/1")
    try:
        dev.read_attribute("throw_exception")
    except PyTango.DevFailed:
        msgbox = TaurusMessageBox(*sys.exc_info())
        msgbox.exec_()
    except:
        msgbox = TaurusMessageBox(*sys.exc_info())
        msgbox.exec_()
예제 #28
0
 def getDevice(self, resources, uri, expected_attr_uri):
     """ Helper for test the getDevice method
     :param resources: list of tuple (map, priority)
     :param uri: res scheme uri.
     :param expected_attr_uri: a scheme uri
     """
     self._load(resources)
     expected_dev = taurus.Device(expected_attr_uri)
     res_dev = self.resfactory.getDevice(uri)
     msg = 'Devices are different, expected %s, got %s' % (expected_dev,
                                                           res_dev)
     self.assertIs(expected_dev, res_dev, msg)
예제 #29
0
def tg_serv_exc():
    """Shows a tango exception from a server in a TaurusMessagePanel"""
    import taurus
    dev = taurus.Device("sys/tg_test/1")
    try:
        dev.read_attribute("throw_exception")
    except PyTango.DevFailed:
        msgbox = TaurusMessagePanel(*sys.exc_info())
        QMessageDialog(msgbox).exec_()
    except:
        msgbox = TaurusMessagePanel(*sys.exc_info())
        QMessageDialog(msgbox).exec_()
예제 #30
0
def _cleanup_device(dev_name):
    factory = taurus.Factory()
    device = taurus.Device(dev_name)
    # tango_alias_devs contains any names in which we have referred
    # to the device, could be alias, short name, etc. pop all of them
    for k, v in factory.tango_alias_devs.items():
        if v is device:
            factory.tango_alias_devs.pop(k)
    full_name = device.getFullName()
    if full_name in factory.tango_devs:
        factory.tango_devs.pop(full_name)
    device.cleanUp()