def setModel(self, model): '''returns True if a curve could be set from the attribute. Flase otherwise''' if not model: self._xAttr = self._yAttr = None self.fromAttrBT.setEnabled(False) return attrs = str(model).split("|") self._yAttr = taurus.Attribute(attrs[-1]) if self._yAttr is None or len(attrs) not in (1, 2): self.error('Invalid model for %s' % str(self.__class__)) self.fromAttrBT.setEnabled(False) return if len(attrs) == 1: self._xAttr = None else: self._xAttr = taurus.Attribute(attrs[0]) # set the master curve from the attribute(s) ok = self.onFromAttr(quiet=True) # enable/disable the attribute I/O buttons self.fromAttrBT.setEnabled(True) enableWrite = (self._xAttr is None or self._xAttr.isWritable()) and self._yAttr.isWritable() self.toAttrBT.setEnabled(True) return ok
def __init__(self, composer): self.state = taurus.Attribute(composer + '/state') self.status = taurus.Attribute(composer + '/status') #self.pressure = taurus.Attribute(composer+'/averagepressure') self.last_state, self.last_status = None, None self.state.addListener(self.state_received) self.status.addListener(self.status_received)
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')
def setModel(self, ior, mot, firstcall=False,updateIOR=False): self.ior_model = ior self.mot_model = mot self.updateIOR = updateIOR self.firstcall = firstcall #If we triggered a change, have the labels really changed, if so set model updated = False if self.firstcall or self.updateIOR: options = [(option.split(":")[0], option.split(":")[1]) for option in (taurus.Attribute(ior+"/Labels").read().value).split()] if options != self.options: updated = True self.options = options for opt in self.options: self.dict[opt[0]] = opt[1] #self.comboBox.setValueNames(self.options) #set the IOR widget try: self.taurusForm.setCustomWidgetMap(getattr(tauruscustomsettings,'T_FORM_CUSTOM_WIDGET_MAP',{})) except NameError: self.taurusForm.setCustomWidgetMap(getattr(TaurusCustomSettings,'T_FORM_CUSTOM_WIDGET_MAP',{})) self.taurusForm.setModel([self.ior_model]) #set the motor widget try: self.taurusForm2.setCustomWidgetMap(getattr(tauruscustomsettings,'T_FORM_CUSTOM_WIDGET_MAP',{})) except NameError: self.taurusForm2.setCustomWidgetMap(getattr(TaurusCustomSettings,'T_FORM_CUSTOM_WIDGET_MAP',{})) self.taurusForm2.setModel([self.mot_model]) if self.firstcall: #make ior widget auto apply settings for widget in self.taurusForm: widget.writeWidget().setAutoApply(True) #connect combo box changes to method below #self.connect(self.comboBox, QtCore.SIGNAL('currentIndexChanged(const int &)'), self.indexChanged) #fill label #self.label.setModel(taurus.Attribute(ior+"/Value")) #get taurus attribute which is value and also motor pos self.position_ior = taurus.Attribute(ior+"/Value")
def test1(): n = 'eval:@c=taurus.core.evaluation.test.res.mymod.MyClass(987)/c.foo' a = taurus.Attribute(n) print("READ 1: ", a.read()) # print a.range print("WRITE+READ", a.write(Quantity(999, "m"))) print("READ 2: ", a.read(cache=False))
def test1(): import taurus # calculates free space in Gb a = taurus.Attribute( 'eval:@taurus.core.evaluation.test.res.dev_example.FreeSpaceDevice/getFreeSpace("/").to("GiB")' ) print "Free space: {:s}".format(a.read().rvalue), a.read().rvalue.units
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)
def test_TaurusValueCombobox(qtbot, model, names, value, expected): """Check that the TaurusValueComboBox is started with the right display See https://github.com/taurus-org/taurus/pull/1032 """ a = taurus.Attribute(model) a.write(value) w = TaurusValueComboBox() qtbot.addWidget(w) # ---------------------------------- # workaround: avoid PySide2 segfaults when adding quantity to combobox # https://bugreports.qt.io/browse/PYSIDE-683 if isinstance(value, UR.Quantity) and PYSIDE2: pytest.skip("avoid segfault due to PYSIDE-683 bug") # ---------------------------------- w.addValueNames(names) qtbot.wait_until(lambda: w.count() == len(names), timeout=3200) try: with qtbot.waitSignal(w.valueChangedSignal, timeout=3200): w.setModel(model) assert w.currentText() == expected finally: del a # set model to None as an attempt to avoid problems in atexit() with qtbot.waitSignal(w.valueChangedSignal, timeout=3200): w.setModel(None)
def read_attr(self, attr_fullname, expected={}, expected_dim=None): a = taurus.Attribute(attr_fullname) read_value = a.read() msg = ( 'read() for "{}" did not return an TaurusAttrValue ' + '(got a {})'.format(attr_fullname, read_value.__class__.__name__)) self.assertTrue(isinstance(read_value, TaurusAttrValue), msg) # Test attribute for k, exp in expected.iteritems(): try: got = getattr(a, k) except AttributeError: msg = ('The attribute "{}" does not provide info on {}'.format( attr_fullname, k)) self.fail(msg) msg = ('{} for "{}" should be "{}" (got {})'.format( attr_fullname, k, exp, got)) self.__assertValidValue(exp, got, msg) if expected_dim is not None: msg = ( 'The attribute "{}" dimension should be "{}", (got {})'.format( attr_fullname, expected_dim, a.data_format)) self.assertEqual(a.data_format, expected_dim, msg)
def processSrc(self, src): '''processes the src and sets the values of display, icon and ok attributes''' if src is None: self.display, self.icon, self.ok = '(Use indices)', Qt.QIcon( ), True return src = str(src).strip() # empty if src == '': self.display, self.icon, self.ok = '(Use indices)', Qt.QIcon( ), True return # for formulas if src.startswith('='): #@todo: evaluate/validate the expression self.display, self.icon, self.ok = src[1:].strip( ), Qt.QIcon.fromTheme('accessories-calculator'), True return # for tango attributes try: attr = taurus.Attribute(src) dev = attr.getParentObj() except TaurusException: self.display, self.icon, self.ok = src, Qt.QIcon.fromTheme( 'dialog-warning'), False return if not dev.isValidDev(): self.display, self.icon, self.ok = src, Qt.QIcon.fromTheme( 'network-error'), False return self.display, self.icon, self.ok = attr.getSimpleName(),\ Qt.QIcon('logos:taurus.png'), True
def run(self, snap_names): if len(snap_names) == 0: self.unsetEnv("PreScanSnapshot") return try: snap_items = self.getEnv("PreScanSnapshot") except UnknownEnv: raise RuntimeError("no pre-scan snapshot defined") snap_full_names = {} for i, item in enumerate(snap_items): snap_full_names[item[0]] = i for name in snap_names: obj = self.getObj(name) if obj is None: try: obj = taurus.Attribute(name) except taurus.TaurusException: raise ValueError("item is neither Pool element not " "Taurus attribute") elif obj.type == "MotorGroup": raise ValueError("MotorGroup item type is not accepted") rm_full_name = obj.fullname if rm_full_name not in snap_full_names.keys(): msg = "{} not in pre-scan snapshot".format(name) raise ValueError(msg) i = snap_full_names[rm_full_name] snap_items.pop(i) self.setEnv("PreScanSnapshot", snap_items)
def run(self, snap_names): def get_item_info(item): if isinstance(item, taurus.core.TaurusAttribute): return item.fullname, item.label else: return item.full_name, item.name try: snap_items = self.getEnv("PreScanSnapshot") except UnknownEnv: snap_items = [] snap_full_names = [item[0] for item in snap_items] new_snap_items = [] for name in snap_names: obj = self.getObj(name) if obj is None: try: obj = taurus.Attribute(name) except taurus.TaurusException: raise ValueError("item is neither Pool element not " "Taurus attribute") elif obj.type == "MotorGroup": raise ValueError("MotorGroup item type is not accepted") new_full_name, new_label = get_item_info(obj) if new_full_name in snap_full_names: msg = "{} already in pre-scan snapshot".format(name) raise ValueError(msg) new_snap_items.append((new_full_name, new_label)) self.setEnv("PreScanSnapshot", snap_items + new_snap_items)
def _initCurves(self, ntrends): """ Initializes new curves """ # self._removeFromLegend(self._legend) # remove previously existing curves from views self._updateViewBox(None) self._curves = [] if self._curveColors is None: self._curveColors = LoopList(CURVE_COLORS) self._curveColors.setCurrentIndex(-1) a = self._args kw = self._kwargs.copy() base_name = ( self.base_name() or taurus.Attribute(self.getModel()).getSimpleName() ) for i in range(ntrends): subname = "%s[%i]" % (base_name, i) kw["name"] = subname curve = TrendCurve(*a, **kw) if "pen" not in kw: curve.setPen(next(self._curveColors)) self._curves.append(curve) self._updateViewBox(self.getViewBox())
def setModel(self, ior): self.iorconfig_widget.setModel(ior) #See what motor we are dealing with - check attribute motor = (taurus.Attribute(ior+"/TangoAttribute").read().value).rsplit("/",1)[0] self.motorconfig_widget.setModel(motor) self.ioruser_widget.setModel(ior,motor,firstcall=True,updateIOR=True)
def setModel(self, model): try: attr = taurus.Attribute(model) except: return dev = attr.getParentObj() devname = dev.getFullName() TaurusDevButton.setModel(self, devname)
def goCommand(link, refPos, mPos, suffix): # Extract value for current motor position. mPos = float(str(mPos).replace(str(suffix), '')) try: #Calculate new position pos = mPos + float(refPos) #Send motor to new position taurus.Attribute(link).write(pos) except: print "Problem moving " + str(link)
def write_read_attr(self, attrname=None, setvalue=None, expected=None, expected_attrv=None, expectedshape=None): """check creation and correct write-and-read of an attribute""" if expected is None: expected = {} if expected_attrv is None: expected_attrv = {} name = '%s/%s' % (self.DEV_NAME, attrname) a = taurus.Attribute(name) if setvalue is None: read_value = a.read() else: a.write(setvalue) read_value = a.read(cache=False) msg = ('read() for "%s" did not return a TangoAttrValue (got a %s)' % (attrname, read_value.__class__.__name__)) self.assertTrue(isinstance(read_value, TangoAttrValue), msg) # Test attribute for k, exp in expected.iteritems(): try: got = getattr(a, k) except AttributeError: msg = ('The attribute, "%s" does not provide info on %s' % (attrname, k)) self.fail(msg) msg = ('%s for "%s" should be %r (got %r)' % (k, attrname, exp, got)) self.__assertValidValue(exp, got, msg) # Test attribute value for k, exp in expected_attrv.iteritems(): try: got = getattr(read_value, k) except AttributeError: msg = ('The read value for "%s" does not provide info on %s' % (attrname, k)) self.fail(msg) msg = ('%s for the value of %s should be %r (got %r)' % (k, attrname, exp, got)) self.__assertValidValue(exp, got, msg) if expectedshape is not None: msg = ('rvalue.shape for %s should be %r (got %r)' % (attrname, expectedshape, read_value.rvalue.shape)) self.assertEqual(read_value.rvalue.shape, expectedshape, msg)
def initPSHU(self): try: sh_attr_name = self.getEnv('PshuAttr') self.sh_timeout = self.getEnv('PshuTimeout') self.attr = taurus.Attribute(sh_attr_name) except Exception as e: msg = 'The macro use the environment variable PshuAttr which ' \ 'has the attribute name of the EPS to open the shutter, ' \ 'and the variable PshuTimeout with the timeout in seconds ' \ '\n{}'.format(e) raise RuntimeError(msg)
def getAttribute(self, resources, uri, expected_attr_uri): """ Helper for test the getAttribute method :param resources: list of tuple (map, priority) :param uri: res scheme uri. :param expected_attr_uri: a scheme uri """ self._load(resources) expected_attr = taurus.Attribute(expected_attr_uri) res_attr = self.resfactory.getAttribute(uri) msg = 'Attributes are different, expected %s, got %s' % (expected_attr, res_attr) self.assertIs(expected_attr, res_attr, msg)
def main(args): import sys, re, traceback, taurus assert len( args ) > 1, '\n\nUsage:\n\t> python panel.py [a/device/name or synoptic.jdw] [--attrs] [attr_regexps] --comms [comm_regexps]' model = args[1] taurus.setLogLevel(taurus.core.util.Logger.Debug) app = Qt.QApplication(args) form = None if re.match('[\w-]+/[\w-]+/[\w-]+.*', model): print 'loading a device panel' k, filters = '--attrs', fandango.defaultdict(list) for f in args[2:]: if f.startswith('--'): k = f.strip('-') else: filters[k].append(f) #(f,()) if k=='comms' else f) form = VaccaPanel(filters=filters) #palette=get_fullWhite_palette() form.setModel(model) elif model.lower().endswith('.jdw'): print 'loading a synoptic' form = taurus.qt.qtgui.graphic.TauJDrawSynopticsView( designMode=False, updateMode=taurus.qt.qtgui.graphic.TauJDrawSynopticsView. NoViewportUpdate) #FullViewportUpdate, : AWFUL CPU USAGE!!!!!!!! #MinimalViewportUpdate, : Qt Defaults #SmartViewportUpdate, : ? #BoundingRectViewportUpdate, : ? #NoViewportUpdate : Tau defaults form.setModel(model) models = form.get_item_list() for m in models: m = str(m) if m.count('/') == 2: m += '/state' period = 120000. try: taurus.Attribute(m).changePollingPeriod(period) except: print '(%s).changePollingPeriod(%s): Failed: %s' % ( m, period, traceback.format_exc()) print 'showing ...' form.show() sys.exit(app.exec_())
def getAlarmTimestamp(alarm,attr_value=None,use_taurus=True): """ Returns alarm activation timestamp (or 0) of an alarm object """ trace('panic.gui.getAlarmTimestamp(%s(%s),%s,%s)'%(type(alarm),alarm,attr_value,use_taurus)) #Not using API method, reusing last Taurus polled attribute instead try: if attr_value is None and use_taurus: attr_value = taurus.Attribute(alarm.device+'/ActiveAlarms').read() attr_value = getAttrValue(attr_value) return alarm.get_time(attr_value=attr_value) except: trace('getAlarmTimestamp(%s/%s): Failed!'%(alarm.device,alarm.tag)) trace(fandango.check_device(alarm.device) and traceback.format_exc()) return 0 #In case of error it must always return 0!!! (as it is used to set alarm.active)
def setModels(self, x, y): # create/get new components if x is None: newX = None else: newX = taurus.Attribute(x) newY = taurus.Attribute(y) # stop listening to previous components (if they are not the same as # the new) if self._xcomp is not None and self._xcomp is not newX: self._xcomp.removeListener(self) self._xcomp = newX if self._ycomp is not None and self._ycomp is not newY: self._ycomp.removeListener(self) self._ycomp = newY # start listening to new components if self._xcomp is not None: self._xcomp.addListener(self) self._ycomp.addListener(self) self.onCurveDataChanged() self.taurusparam.xModel = x self.taurusparam.yModel = y
def getAlarmTimestamp(alarm,attr_value=None,use_taurus=True): """ Returns alarm activation timestamp (or 0) of an alarm object """ #print 'panic.gui.getAlarmTimestamp(%s)'%(alarm.tag) #Not using API method, reusing last Taurus polled attribute instead #self.date = self.alarm.get_active() try: if attr_value is None and use_taurus: attr_value = taurus.Attribute(alarm.device+'/ActiveAlarms').read().value #self.get_ds().get().read_attribute('ActiveAlarms').value return alarm.get_time(attr_value=attr_value) except: print 'getAlarmTimestamp(%s/%s): Failed!'%(alarm.device,alarm.tag) #if fandango.check_device(alarm.device): print traceback.format_exc() return 0 #In case of error it must always return 0!!! (as it is used to set alarm.active)
def get_object(self, name=None, klass=None): '''check if Attribute returns the expected type''' if klass is None: klass = TaurusAttribute manager = taurus.Manager() scheme = manager.getScheme(name) supportedSchemes = manager.getPlugins().keys() if scheme not in supportedSchemes: self.skipTest('"%s" scheme not supported' % scheme) a = taurus.Attribute(name) msg = ('%s("%s") is not an instance of %s (it is %s)' % (taurus.Attribute.__name__, name, klass.__name__, a.__class__.__name__)) self.assertTrue(isinstance(a, klass), msg) return a
def test_cleanup_state_after_polling(): """ Ensure that polling the state Tango attribute does not keep device alive See Bug #999 (Also check case insensitivity) """ polling_period = .1 # seconds a = taurus.Attribute('sys/TG_TEST/1/STate') f = a.factory() a.activatePolling(polling_period * 1000, force=True) assert len(list(f.tango_attrs.keys())) == 1 assert len(list(f.tango_devs.keys())) == 1 a = None time.sleep(polling_period) assert len(list(f.tango_attrs.keys())) == 0 assert len(list(f.tango_devs.keys())) == 0
def updateModels(self, names): """Accepts a list of model names and updates the data items of class `itemClass` (provided in the constructor) attached to the plot. It creates and removes items if needed, and enforces the z-order according to that given in the `models` list """ # from names, construct an ordered dict with k=fullname, v=modelObj models = OrderedDict() for n in names: m = taurus.Attribute(n) models[m.getFullName()] = m # construct a dict and a list for current models and names currentModelItems = dict() currentModelNames = [] for item in self.plot_item.items: if isinstance(item, self.itemClass): fullname = item.getFullModelName() currentModelNames.append(fullname) currentModelItems[fullname] = item # remove existing curves from plot (but not discarding the object) # so that they can be re-added later in the correct z-order for k, v in currentModelItems.items(): # v.getViewBox().removeItem(v) # TODO: maybe needed for Y2 self.plot_item.removeItem(v) # ------------------------------------------------- # Workaround for bug in pyqtgraph 0.10.0 # (which is fixed in pyqtgraph's commit ee0ea5669) # TODO: remove this lines when pyqtgraph > 0.10.0 is released if self.legend is not None: self.legend.removeItem(v.name()) # ------------------------------------------------- # Add all curves (creating those that did not exist previously) # respecting the z-order for modelName, model in models.items(): if modelName in currentModelNames: item = currentModelItems[modelName] self.plot_item.addItem(item) # item.getViewBox().addItem(item) # TODO: maybe needed for Y2 else: # TODO support labels item = self.itemClass(name=model.getSimpleName()) item.setModel(modelName) self.plot_item.addItem(item)
def setSrc(self, src): '''processes the src and sets the values of _src, display, icon and ok attributes''' if src is None: self._src, self.display, self.icon, self.ok = '', '(Empty)', Qt.QIcon( ), True return src = str(src).strip() if src == self._src: return self._src = src # empty if src == '': self.display, self.icon, self.ok = '(Empty)', Qt.QIcon(), True return # TODO tango-centric. For tango devices try: dev = taurus.Device(src) if dev.getDeviceProxy() is not None: self.display, self.icon, self.ok = dev.getSimpleName( ), getElementTypeIcon(TaurusElementType.Device), True return else: self.display, self.icon, self.ok = src, Qt.QIcon.fromTheme( 'network-error'), False return except: # for tango attributes try: attr = taurus.Attribute(src) dev = attr.getParentObj() except TaurusException: self.display, self.icon, self.ok = src, Qt.QIcon.fromTheme( 'dialog-warning'), False return except Exception: # @todo: this catchall except is here as an emergency bugfix, but should probably be narrowed to PyTango DevFailed. self.display, self.icon, self.ok = src, Qt.QIcon.fromTheme( 'network-error'), False return if getSchemeFromName(attr.getFullName()) == "tango" and \ dev.getDeviceProxy() is None: self.display, self.icon, self.ok = src, Qt.QIcon.fromTheme( 'network-error'), False return self.display, self.icon, self.ok = attr.getSimpleName( ), getElementTypeIcon(TaurusElementType.Attribute), True
def write_read_conf(self, attr_name, cfg, value, expected): """ Helper for checking the write-and-read of the Tango attribute configuration (existing in Taurus). """ attr_fullname = '%s/%s' % (self.DEV_NAME, attr_name) attr = taurus.Attribute(attr_fullname) # write the property setattr(attr, cfg, value) # read the property got = getattr(attr, cfg) msg = '%s.%s from Taurus do not mach, expected %s read %s' %\ (attr_name, cfg, expected, got) map(self.__assertValidValue, got, expected, msg) msg = '%s.%s from Tango do not mach, expected %s read %s' %\ (attr_name, cfg, expected, got) tangovalue = self._getDecodePyTangoAttr(attr_name, cfg) map(self.__assertValidValue, got, tangovalue, msg)
def read_attr(self, attr_fullname, expected={}, expected_attrv={}, expectedshape=None): """check creation and correct read of an evaluationAttribute""" a = taurus.Attribute(attr_fullname) read_value = a.read() msg = ('read() for "{0}" did not return an EvaluationAttrValue ' + '(got a {1})').format(attr_fullname, read_value.__class__.__name__) self.assertTrue(isinstance(read_value, EvaluationAttrValue), msg) # Test attribute for k, exp in expected.items(): try: got = getattr(a, k) except AttributeError: msg = ('The attribute, "%s" does not provide info on %s' % (attr_fullname, k)) self.fail(msg) msg = ('%s for "%s" should be %r (got %r)' % (attr_fullname, k, exp, got)) self.__assertValidValue(exp, got, msg) # Test attribute value for k, exp in expected_attrv.items(): try: got = getattr(read_value, k) except AttributeError: msg = ('The read value for "%s" does not provide info on %s' % (attr_fullname, k)) self.fail(msg) msg = ('%s for "%s" should be %r (got %r)' % (attr_fullname, k, exp, got)) self.__assertValidValue(exp, got, msg) if expectedshape is not None: shape = numpy.shape(read_value.rvalue) msg = ('rvalue.shape for %s should be %r (got %r)' % (attr_fullname, expectedshape, shape)) self.assertEqual(shape, expectedshape, msg)
def get_disabled(self, force=False): val = None try: if not force and self.use_list: if not getattr(self, 'dis_attr', None): self.dis_attr = taurus.Attribute(self.device + '/DisabledAlarms') self.dis_attr.changePollingPeriod(REFRESH_TIME) val = any( re.split('[: ,;]', a)[0] == self.alarm.tag for a in (self.dis_attr.read().value or [])) else: val = taurus.Device(self.alarm.device).command_inout( 'CheckDisabled', self.alarm.tag) if force: self.alarmDisabled = val except: print fandango.log.except2str() #print 'In AlarmRow(%s).get_disabled(): %s'%(self.alarm.tag,val) return val