def getAttribute(self, attr_name, create_if_needed=True, **kwargs): """Obtain the object corresponding to the given attribute name. If the corresponding attribute already exists, the existing instance is returned. Otherwise a new instance is stored and returned. :param attr_name: (str) a valid attribute name URI :param create_if_needed: (bool) If True, the Attribute is created if it did not already exist. If False, None is returned if it did not exist :return: (taurus.core.tangoattribute.TangoAttribute) attribute object :raise: (taurus.core.taurusexception.TaurusException) if the given alias is invalid. """ attr = self.tango_attrs.get(attr_name) if attr is not None: return attr # Simple approach did not work. Lets build a proper device name validator = _Attribute.getNameValidator() groups = validator.getUriGroups(attr_name) if groups is None: raise TaurusException( ("Invalid Tango attribute name '%s'") % attr_name) full_attr_name, _, _ = validator.getNames(attr_name) if full_attr_name is None: raise TaurusException("Cannot find full name of '%s'" % attr_name) attr = self.tango_attrs.get(full_attr_name) if attr is None: dev_name = full_attr_name.rsplit('/', 1)[0] try: dev = self.getDevice(dev_name) if dev is not None: # Do another try in case the Device object created the attribute # itself. This happens for the 'state' attribute attr = self.tango_attrs.get(full_attr_name) if attr is not None: return attr try: attr_klass = self._getAttributeClass( attr_name=attr_name) kwargs['storeCallback'] = self._storeAttribute if not kwargs.has_key('pollingPeriod'): kwargs[ 'pollingPeriod'] = self.getDefaultPollingPeriod( ) attr = attr_klass(full_attr_name, dev, **kwargs) # attribute objects will register themselves in this factory # so there is no need to do it here except DoubleRegistration: attr = self.tango_attrs.get(full_attr_name) except: self.debug("Error creating attribute %s", attr_name, exc_info=1) raise return attr
def getDevice(self, dev_name, create_if_needed=True, **kw): """Obtain the object corresponding to the given tango device name. If the corresponding device already exists, the existing instance is returned. Otherwise a new instance is stored and returned. :param dev_name: (str) tango device name or tango alias for the device. It must be a valid Tango device URI. If authority is not explicit, the default Tango Database will be used :param create_if_needed: (bool) If True, the Device is created if it did not exist previously. If False, it returns None if it did not exist :return: (taurus.core.tango.TangoDevice) a device object :raise: (taurus.core.taurusexception.TaurusException) if the given dev_name is invalid. """ d = self.tango_devs.get(dev_name) if d is None: d = self.tango_alias_devs.get(dev_name) if d is not None: return d validator = _Device.getNameValidator() groups = validator.getUriGroups(dev_name) if groups is None: raise TaurusException("Invalid Tango device name '%s'" % dev_name) full_dev_name, _, _ = validator.getNames(dev_name) if full_dev_name is None: raise TaurusException("Cannot find full name of '%s'" % dev_name) d = self.tango_devs.get(full_dev_name) if not create_if_needed: return d if d is None: try: db = self.getAuthority(groups.get('authority')) dev_klass = self._getDeviceClass(db=db, devname=groups['devname']) kw['storeCallback'] = self._storeDevice kw['parent'] = db d = dev_klass(full_dev_name, **kw) # device objects will register themselves in this factory # so there is no need to do it here except DoubleRegistration: d = self.tango_devs.get(full_dev_name) except: self.debug("Error creating device %s", dev_name, exc_info=1) raise return d
def getAuthority(self, name=None): """ Obtain the object corresponding to the given database name or the default database if name is None. If the corresponding authority object already exists, the existing instance is returned. Otherwise a new instance is stored and returned. :param name: (str) database name string alias. If None, the default database is used :return: (taurus.core.tangodatabase.TangoAuthority) database object :raise: (taurus.core.taurusexception.TaurusException) if the given alias is invalid. """ ret = None if name is None: if self.dft_db is None: try: if self._default_tango_host is None: self.dft_db = _Authority() else: name = self._default_tango_host validator = _Authority.getNameValidator() groups = validator.getUriGroups(name) if groups is None: raise TaurusException( "Invalid default Tango authority name %s" % name) self.dft_db = _Authority(host=groups['host'], port=groups['port']) except: self.debug("Could not create Authority", exc_info=1) raise name = self.dft_db.getFullName() self.tango_db[name] = self.dft_db ret = self.dft_db else: ret = self.tango_db.get(name) if not ret is None: return ret validator = _Authority.getNameValidator() groups = validator.getUriGroups(name) if not validator.isValid(name): raise TaurusException("Invalid Tango authority name %s" % name) try: ret = _Authority(host=groups['host'], port=groups['port']) except: self.debug("Could not create Authority %s", groups['authority'], exc_info=1) if ret is not None: self.tango_db[name] = ret return ret
def getAttribute(self, attr_name, **kwargs): """Obtain the object corresponding to the given attribute name. If the corresponding attribute already exists, the existing instance is returned. Otherwise a new instance is stored and returned. The evaluator device associated to this attribute will also be created if necessary. :param attr_name: (str) the attribute name string. See :mod:`taurus.core.evaluation` for valid attribute names Any aditional keyword arguments will be passed directly to the constructor of `:class:EvaluationAttribute` :return: (EvaluationAttribute) @throws TaurusException if the given name is invalid. """ a = self.eval_attrs.get( attr_name, None) # first try with the given name if a is None: # if not, try with the full name validator = self.getAttributeNameValidator() names = validator.getNames(attr_name) if names is None or names[0] is None: raise TaurusException( "Invalid evaluation attribute name %s" % attr_name) fullname = names[0] a = self.eval_attrs.get(fullname, None) if a is None: # if the full name is not there, create one dev = self.getDevice(validator.getDeviceName(attr_name)) kwargs['storeCallback'] = self._storeAttr if not kwargs.has_key('pollingPeriod'): kwargs['pollingPeriod'] = self.getDefaultPollingPeriod() a = EvaluationAttribute(fullname, parent=dev, **kwargs) return a
def init(self, *args, **kwargs): """Singleton instance initialization.""" if PyTangoArchiving is None: raise TaurusException('PyTangoArchiving is not available') name = self.__class__.__name__ Logger.__init__(self, name) TaurusFactory.__init__(self)
def write(self, value, with_read=True): if not self.isWritable(): raise TaurusException('Attempt to write on read-only attribute %s', self.getFullName()) self._value_setter(value) self._value.wvalue = value if with_read: ret = self.read(cache=False) return ret
def __init__(self, name=None, parent=None): if name is None: t_f = taurus.Factory('tango') t_default_authority = t_f.get_default_tango_host() if t_default_authority is None: pytango_host = PyTango.ApiUtil.get_env_var("TANGO_HOST") host, port = pytango_host.split(':') t_default_authority = "//{0}:{1}".format( socket.getfqdn(host), port) name = '%s:%s' % (self._scheme, t_default_authority) TaurusAuthority.__init__(self, name, parent) v = TangoArchivingAuthorityNameValidator() groups = v.getUriGroups(name) if groups is None: raise TaurusException('Invalid name %s' % name) host = groups.get('host') port = groups.get('port') try: self._tangodb = PyTango.Database(host, port) except PyTango.DevFailed: raise TaurusException('Can not connect to the tango database')
def getAttribute(self, name): """ Obtain the attribute model object referenced by name. :param name: (str) name :return: (taurus.core.taurusattribute.TaurusAttribute) attribute object :raise: (taurus.core.taurusexception.TaurusException) if name is invalid """ groups = self.getAttributeNameValidator().getUriGroups(name) if groups is None: raise TaurusException('Invalid name "%s"' % name) res_name = groups['_resname'] value = self.getValue(res_name) return Manager().getAttribute(value)
def getAuthority(self, name=None): """Obtain the Epics (ca) authority object. :param name: (str) only a dummy authority ("ca://") is supported :return: (EpicsAuthority) """ if name is None: name = 'ca://' v = self.getAuthorityNameValidator() if not v.isValid(name): raise TaurusException("Invalid ca authority name %s" % name) if not hasattr(self, "_auth"): self._auth = EpicsAuthority(self.DEFAULT_AUTHORITY) return self._auth
def getAttribute(self, name): """ Reimplementation of the TaurusFactory method """ v = self.getAttributeNameValidator() if not v.isValid(name): msg = "Invalid {scheme} attribute name '{name}'".format( scheme=self.schemes[0], name=name) raise TaurusException(msg) fullname, _, _ = v.getNames(name) groups = v.getUriGroups(fullname) attr = self._attrs.get(fullname) if attr is not None: return attr try: # this works only if the devname is present in the attr full name # (not all schemes are constructed in this way) devname = v.getUriGroups(fullname)['devname'] dev = self.getDevice(devname) except: self.debug('Cannot get attribute parent from name "%s"', fullname) dev = None cls = self.elementTypesMap[TaurusElementType.Attribute] attr = cls(name=fullname, parent=dev) # Looking for the complementary if 'ts' in groups['query']: complementary = fullname.replace(';ts', '') else: complementary = fullname + ';ts' c_attr = self._attrs.get(complementary) if c_attr is not None: # Get data from the complementary attr._arch_values = c_attr._arch_values attr._arch_timestamps = c_attr._arch_timestamps else: # Get data from the archiving # TODO: Wait 1s to avoid core with PyTangoArchiving import time time.sleep(1) attr._read() # TODO: Use TaurusManager.addJob instead self._attrs[fullname] = attr return attr
def getDevice(self, dev_name): """Obtain the object corresponding to the given device name. If the corresponding device already exists, the existing instance is returned. Otherwise a new instance is stored and returned. :param dev_name: (str) the device name string. See :mod:`taurus.core.evaluation` for valid device names :return: (EvaluationDevice) @throws TaurusException if the given name is invalid. """ # try to see if the given name is already a known full_name d = self.eval_devs.get(dev_name, None) if d is None: # find the full_name and see if we already know it validator = self.getDeviceNameValidator() names = validator.getNames(dev_name) if names is None: raise TaurusException("Invalid evaluator device name %s" % dev_name) fullname, normalname, devname = names d = self.eval_devs.get(fullname, None) # if we do not know it, create the dev and store it in cache if d is None: groups = validator.getUriGroups(dev_name) if groups['_evalclass'] is not None: modulename, classname = groups['_evalclass'].rsplit('.', 1) try: m = __import__(modulename, globals(), locals(), [classname], -1) DevClass = getattr(m, classname) except: self.warning('Problem importing "%s"' % devname) raise else: DevClass = EvaluationDevice # Get authority (creating if necessary) auth_name = groups.get('authority') or self.DEFAULT_AUTHORITY authority = self.getAuthority(auth_name) # Create Device (and store it in cache via self._storeDev) d = DevClass(fullname, parent=authority, storeCallback=self._storeDev) return d
def getAuthority(self, name=None): """Obtain the EvaluationDatabase object. :param db_name: (str) this is ignored because only one database is supported :return: (EvaluationDatabase) """ if name is None: name = 'eval://localhost' v = self.getAuthorityNameValidator() if not v.isValid(name): raise TaurusException( "Invalid Evaluation authority name %s" % name) if not hasattr(self, "_auth"): self._auth = EvaluationAuthority(self.DEFAULT_AUTHORITY) return self._auth
def read(self, cache=True): if cache and self._last_value is not None: return self._last_value dev = self.getParentObj() # each time we need to open and close the file, otherwise the # file content is not updated with h5py.File(dev.filename) as h5file: data = h5file.get(self._attr_name) if data is None: msg = "Object %s does not exist" % self._attr_name raise TaurusException(msg) # we need to decode and copy the data while the file is still opened rvalue = self.decode(data) value = TaurusAttrValue() value.rvalue = rvalue value.time = TaurusTimeVal.now() self._last_value = value return value
def getDevice(self, dev_name): """Obtain the EpicsDevice object. :param dev_name: (str) only one dummy device ("") is supported :return: (EpicsDevice) .. todo:: epics.Device may be wrapped as taurus device... """ validator = self.getDeviceNameValidator() names = validator.getNames(dev_name) if names is None: raise TaurusException("Invalid epics device name %s" % dev_name) fullname = names[0] d = self.epics_devs.get(fullname, None) if d is None: # if the full name is not there, create one auth = self.getAuthority() d = EpicsDevice(fullname, parent=auth) self.epics_devs[fullname] = d return d
def Factory(scheme=None): """Returns the one and only Factory for the given scheme It is a shortcut to:: import taurus.core.taurusmanager manager = taurus.core.taurusmanager.TaurusManager() factory = manager.getFactory(scheme) :param scheme: a string representing the scheme. Default value is None meaning ``tango`` scheme :type scheme: str :return: a taurus factory :rtype: :class:`taurus.core.taurusfactory.TaurusFactory`""" manager = Manager() f = manager.getFactory(scheme=scheme) if f is None: from taurus.core.taurusexception import TaurusException if scheme is None: scheme = "default scheme '" + manager.default_scheme + "'" else: scheme = "'" + scheme + "'" raise TaurusException('Cannot create Factory for %s' % scheme) return f()
def getAttribute(self, attr_name): """Obtain the object corresponding to the given attribute name. If the corresponding attribute already exists, the existing instance is returned. Otherwise a new instance is stored and returned. The device associated to this attribute will also be created if necessary. :param attr_name: (str) the attribute name string. See :mod:`taurus.core.epics` for valid attribute names :return: (EpicsAttribute) @throws TaurusException if the given name is invalid. """ validator = self.getAttributeNameValidator() names = validator.getNames(attr_name) if names is None: raise TaurusException("Invalid epics attribute name %s" % attr_name) fullname = names[0] a = self.epics_attrs.get(fullname, None) if a is None: # if the full name is not there, create one a = EpicsAttribute(fullname, parent=None) # note: no parent! self.epics_attrs[fullname] = a return a
def poll(self): raise TaurusException('Archiving attributes do not support polling')
def write(self, value, with_read=True): raise TaurusException('Evaluation attributes are read-only')
def getDevice(self, dev_name): """Obtain the object corresponding to the given device name. If the corresponding device already exists, the existing instance is returned. Otherwise a new instance is stored and returned. :param dev_name: (str) the device name string. See :mod:`taurus.core.evaluation` for valid device names :return: (EvaluationDevice) @throws TaurusException if the given name is invalid. """ # try to see if the given name is already a known full_name d = self.eval_devs.get(dev_name, None) if d is None: # find the full_name and see if we already know it validator = self.getDeviceNameValidator() names = validator.getNames(dev_name) if names is None: raise TaurusException("Invalid evaluator device name %s" % dev_name) fullname, normalname, devname = names d = self.eval_devs.get(fullname, None) # if we do not know it, create the dev and store it in cache if d is None: groups = validator.getUriGroups(dev_name) DevClass = EvaluationDevice _safedict = {} if groups['_evaldotname'] is not None: modulename = groups.get('_evalmodname') classname = groups.get('_evalclassname') classargs = groups.get('_evalclassparenths') try: import importlib m = importlib.import_module(modulename) except: self.warning('Problem importing "%s"' % modulename) raise if classname == '*': # Add symbols from the module for key in dir(m): _safedict[key] = getattr(m, key) else: klass = getattr(m, classname) if classargs: # Instantiate and add the instance to the safe dict from taurus.core.util.parse_args import parse_args a, kw = parse_args(classargs, strip_pars=True) instancename = groups.get( '_evalinstname') or "self" instance = klass(*a, **kw) _safedict[instancename] = instance else: # Use given class instead of EvaluationDevice DevClass = klass # Get authority (creating if necessary) auth_name = groups.get('authority') or self.DEFAULT_AUTHORITY authority = self.getAuthority(auth_name) # Create Device (and store it in cache via self._storeDev) d = DevClass(fullname, parent=authority, storeCallback=self._storeDev) d.addSafe(_safedict, permanent=True) return d
def write(self, value, with_read=True): # TODO: implement it if you want to support writable attributes raise TaurusException('Attributes are read-only')