Exemplo n.º 1
0
    def reader_hook(self, attribute, values):
        """This method will be executed by the ReaderProcess to process the queried data."""
        try:
            print('>' * 80)
            print(time.ctime() + ' In reader_hook(%s,[%d])' %
                  (attribute, len(values)))

            MAXDIM = 1024 * 1024 * 1024
            #First create the attributes
            epoch, data, aname = [], [], attribute.replace('/', '__')
            values = decimate_values(values)
            [(epoch.append(v[0]), data.append(v[1])) for v in values]
            writable = PyTango.AttrWriteType.READ

            #Adding time attribute
            m, atformat, dims = None, PyTango.SpectrumAttr, [MAXDIM]
            for d in data:
                if d is not None:
                    if fn.isSequence(d):
                        atformat, dims = PyTango.ImageAttr, [MAXDIM, MAXDIM]
                        m = d[0]
                    else:
                        m = d
                    break

            attype = PyTango.DevDouble if (
                fn.isNumber(m) or fn.isBool(m)) else PyTango.DevString
            self.add_attribute(
                PyTango.ImageAttr(aname, attype, writable, MAXDIM, MAXDIM),
                self.read_dyn_attr, None, self.is_dyn_attr_allowed)

            self.add_attribute(
                PyTango.SpectrumAttr(aname + '_t', PyTango.DevDouble, writable,
                                     MAXDIM), self.read_dyn_attr, None,
                self.is_dyn_attr_allowed)

            self.add_attribute(
                PyTango.SpectrumAttr(aname + '_d', PyTango.DevString, writable,
                                     MAXDIM), self.read_dyn_attr, None,
                self.is_dyn_attr_allowed)

            self.add_attribute(atformat(aname + '_r', attype, writable,
                                        *dims), self.read_dyn_attr, None,
                               self.is_dyn_attr_allowed)

            #Then add the data to Cache values, so IsDataReady will return True
            t = fn.now()
            self.RemoveCachedAttribute(attribute)
            self.AttrData[attribute] = (t, atformat, attype, values)
            print('Done: %s,%s,%s,%s,%d' %
                  (attribute, t, atformat, attype, len(values)))
        except:
            print(traceback.format_exc())
    def dyn_attr(self):
        for process in self.ProcessList:
            #self.debug_stream('dyn_attr(): Adding attributes for %s process'%process)
            aname = re.sub('[^0-9a-zA-Z]+', '_', process)
            for suffix,data_type,data_format,unit in\
                (('nprocesses',PyTango.DevLong,PyTango.SCALAR,None),
                 ('nthreads',PyTango.DevLong,PyTango.SCALAR,None),
                 ('pids',PyTango.DevLong,PyTango.SPECTRUM,None),
                 ('cpu',PyTango.DevDouble,PyTango.SCALAR,'%'),
                 ('mem',PyTango.DevDouble,PyTango.SCALAR,'MB'),
                 ('vmem',PyTango.DevDouble,PyTango.SCALAR,'MB'),
                 ('memRatio',PyTango.DevDouble,PyTango.SCALAR,'%'),
                 ('kbpm',PyTango.DevDouble,PyTango.SCALAR,'%'),
                ):
                #TODO: set the units
                if data_format == PyTango.SCALAR:
                    self.add_attribute(
                        PyTango.Attr(aname + '_' + suffix, data_type,
                                     PyTango.AttrWriteType.READ),
                        self.read_dyn_attr, None,
                        (lambda s, req_type, attr_name=aname + '_' + suffix:
                         True))
                    if self.UseEvents:
                        self.set_change_event(aname + '_' + suffix, True,
                                              False)

                elif data_format == PyTango.SPECTRUM:
                    self.add_attribute(
                        PyTango.SpectrumAttr(aname + '_' + suffix, data_type,
                                             PyTango.READ, 1000),
                        self.read_dyn_attr, None,
                        (lambda s, req_type, attr_name=aname + '_' + suffix:
                         True))
                    if self.UseEvents:
                        self.set_change_event(aname + '_' + suffix, True,
                                              False)
        #self._dyn_attr_build = True
        self.change_state(PyTango.DevState.ON)
        return
Exemplo n.º 3
0
    def initialize_dynamic_attributes(self):
        self.debug_stream('In initialize_dynamic_attributes()')
        if self.pv is not None:  # already initialized
            return
        # variables initialization
        READ_METHOD = self.read_attr
        WRITE_METHOD = self.write_attr
        if self.Host == []:
            self.Host = ''
        self.pv = {}
        pvs = {}

        try:
            # initialize libca library
            epics.ca.initialize_libca()

            # get pv names and build libca channels
            for pv_entry in self.ProcessVariables:
                pv_attr = pv_entry.split('\t')
                attr_name = None
                if len(pv_attr) == 1:
                    pv_name = pv_attr[0]
                elif len(pv_attr) == 2:
                    pv_name, attr_name = pv_attr
                else:
                    msg = 'Invalid entry in ProcessVariables device property:'\
                        ' %s' % pv_entry
                    self.error_stream(msg)
                    self._set_state(PyTango.DevState.FAULT, msg)
                    return
                # get host name if necessary
                if self.Host != '':
                    pv_full_name = '%s:%s' % (self.Host, pv_name)
                else:
                    pv_full_name = pv_name
                # create epics channel to PV (to increase performance do not
                # wait for a connection)
                ch_id = epics.ca.create_channel(
                    pv_full_name,
                    connect=False,
                    auto_cb=False)
                # build default attribute name (if not provided)
                if attr_name is None:
                    attr_name = self.epics2tango_name(pv_name)
                self.pv[attr_name] = [ch_id, pv_full_name]
                pvs[attr_name] = [ch_id]

            # connect PVs and get necessary info
            for name, data in pvs.items():
                connected = epics.ca.connect_channel(data[0])
                if not connected:
                    msg = 'At least one channel unreachable. Is hardware up?'
                    self.error_stream(msg)
                    self._set_state(PyTango.DevState.FAULT,
                                    msg, force_init=True)
                    return
            epics.ca.poll()  # wait for connections completion
            for name, data in pvs.items():
                data.append(epics.ca.field_type(data[0]))
                data.append(epics.ca.read_access(data[0]))
                data.append(epics.ca.write_access(data[0]))
                data.append(epics.ca.element_count(data[0]))

            # add dynamic attributes
            for attr_name, data in pvs.items():
                # find out tango type
                tango_type = self.epics2tango_type(data[1])
                if tango_type is None:
                    msg = 'Unknown type %s for PV %s' %\
                          (str(data[1]), self.pv[attr_name][1])
                    self.error_stream(msg)
                    self._set_state(PyTango.DevState.ALARM, msg)
                    del self.pv[attr_name]
                    continue
                # find out read/write access
                read_access = bool(data[2])
                write_access = bool(data[3])
                read_method = None
                write_method = None
                if read_access and write_access:
                    read_method = READ_METHOD
                    write_method = WRITE_METHOD
                    access_type = PyTango.AttrWriteType.READ_WRITE
                elif read_access and not write_access:
                    read_method = READ_METHOD
                    access_type = PyTango.AttrWriteType.READ
                elif not read_access and write_access:
                    write_method = WRITE_METHOD
                    access_type = PyTango.AttrWriteType.WRITE
                else:
                    msg = 'PV %s has neither read nor write permissions'\
                          % pv_full_name
                    self.error_stream(msg)
                    self._set_state(PyTango.DevState.FAULT, msg)
                    continue
                # find out dimension and build attribute
                dimension = data[4]
                if dimension > 1:
                    attr = PyTango.SpectrumAttr(
                        attr_name,
                        tango_type,
                        access_type,
                        dimension)
                else:
                    attr = PyTango.Attr(
                        attr_name,
                        tango_type,
                        access_type)
                properties = PyTango.UserDefaultAttrProp()
                # set description field with PV name
                properties.set_description(self.pv[attr_name][1])
                attr.set_default_properties(properties)
                # add attribute
                self.add_attribute(attr, read_method, write_method)
        except Exception as e:
            msg = 'Unable to create dynamic attributes'
            self.error_stream('%s: %s' % (msg, str(e)))
            self._set_state(PyTango.DevState.FAULT, msg)
        del pvs  # no longer used
Exemplo n.º 4
0
 def __getAttrObj(self,
                  attrName,
                  definition,
                  channel=None,
                  function=None,
                  multiple=None):
     # TODO: image dimensions
     if self.__device is not None:
         if definition['dim'] == [0]:
             if 'writeCmd' in definition:
                 attr = PyTango.Attr(attrName, definition['type'],
                                     PyTango.READ_WRITE)
                 readmethod = AttrExc(getattr(self.__device, 'read_attr'))
                 writemethod = AttrExc(getattr(self.__device, 'write_attr'))
             else:
                 attr = PyTango.Attr(attrName, definition['type'],
                                     PyTango.READ)
                 readmethod = AttrExc(getattr(self.__device, 'read_attr'))
                 writemethod = None
         elif definition['dim'][0] == 1:
             if 'writeCmd' in definition:
                 attr = PyTango.SpectrumAttr(attrName, definition['type'],
                                             PyTango.READ_WRITE,
                                             definition['dim'][1])
                 readmethod = AttrExc(getattr(self.__device, 'read_attr'))
                 writemethod = AttrExc(getattr(self.__device, 'write_attr'))
             else:
                 attr = PyTango.SpectrumAttr(attrName, definition['type'],
                                             PyTango.READ,
                                             definition['dim'][1])
                 readmethod = AttrExc(getattr(self.__device, 'read_attr'))
                 writemethod = None
         else:
             raise AttributeError("Not supported multiple dimensions")
         # attribute properties
         aprop = PyTango.UserDefaultAttrProp()
         if 'unit' in definition:
             aprop.set_unit(latin1(definition['unit']))
         if 'min' in definition:
             aprop.set_min_value(str(definition['min']))
         if 'max' in definition:
             aprop.set_max_value(str(definition['max']))
         if 'format' in definition:
             format = latin1(definition['format'])
             if format.count("%") == 2:
                 format = format.replace('%', '', 1)
             aprop.set_format(format)
         if 'description' in definition:
             aprop.set_description(latin1(definition['description']))
         if 'label' in definition:
             aprop.set_label(latin1(definition['label']))
         if 'memorized' in definition:
             attr.set_memorized()
             attr.set_memorized_init(True)
         attr.set_default_properties(aprop)
         self.__device.add_attribute(attr,
                                     r_meth=readmethod,
                                     w_meth=writemethod)
         multiattr = self.__device.get_device_attr()
         attrId = multiattr.get_attr_ind_by_name(attrName)
         self._attributeIds[attrId] = attrName
     else:
         attrId = self._generateAttrId(attrName)
         attr = None
         aprop = None
     # self.debug_stream("Attribute %s has the id %s" % (attrName, attrId))
     self._attributeList.append(attrName)
     # prepare internal structure ---
     if channel is not None or function is not None or multiple is not None:
         if channel is not None:
             like = "channel"
             number = channel
         elif function is not None:
             like = "function"
             number = function
         elif multiple is not None and \
                 'scpiPrefix' in definition['multiple'] and\
                 'attrSuffix' in definition['multiple']:
             like = definition['multiple']['scpiPrefix']
             number = multiple
         else:
             raise AttributeError("Wrong definition of multiple attribute")
         self.__prepareChannelLikeAttr(like, number, definition, attrName)
     else:
         readCmd = definition['readCmd']
         if 'writeCmd' not in definition:
             # writeCmd = definition['writeCmd']
             definition['writeCmd'] = None
     if 'readFormula' not in definition:
         # readFormula = definition['readFormula']
         definition['readFormula'] = None
     # if 'writeFormula' not in definition:
     #     # writeFormula = definition['writeFormula']
     #     writeFormula = None
     # build internal structure ---
     if 'rampeable' in definition and definition['rampeable'] is True:
         self.__buildRWObj(attrName, attrId, definition, readmethod,
                           writemethod)
     if 'delayAfterWrite' not in definition:
         definition['delayAfterWrite'] = 0.0
     if definition['writeCmd'] is None:
         self.__buildROObj(attrName, attrId, definition)
     else:
         self.__buildRWObj(attrName, attrId, definition)
         if 'writeValues' in definition:
             self.__prepareWriteValues(attrName, definition, aprop, attr)
     return attr
Exemplo n.º 5
0
 def __getAttrObj(self,
                  attrName,
                  definition,
                  channel=None,
                  function=None,
                  multiple=None):
     # TODO: image dimensions
     if definition['dim'] == [0]:
         if 'writeCmd' in definition:
             attr = PyTango.Attr(attrName, definition['type'],
                                 PyTango.READ_WRITE)
             readmethod = AttrExc(getattr(self.__device, 'read_attr'))
             writemethod = AttrExc(getattr(self.__device, 'write_attr'))
         else:
             attr = PyTango.Attr(attrName, definition['type'], PyTango.READ)
             readmethod = AttrExc(getattr(self.__device, 'read_attr'))
             writemethod = None
     elif definition['dim'][0] == 1:
         if 'writeCmd' in definition:
             attr = PyTango.SpectrumAttr(attrName, definition['type'],
                                         PyTango.READ_WRITE,
                                         definition['dim'][1])
             readmethod = AttrExc(getattr(self.__device, 'read_attr'))
             writemethod = AttrExc(getattr(self.__device, 'write_attr'))
         else:
             attr = PyTango.SpectrumAttr(attrName, definition['type'],
                                         PyTango.READ, definition['dim'][1])
             readmethod = AttrExc(getattr(self.__device, 'read_attr'))
             writemethod = None
     else:
         raise AttributeError("Not supported multiple dimensions")
     # attribute properties
     aprop = PyTango.UserDefaultAttrProp()
     if 'unit' in definition:
         aprop.set_unit(latin1(definition['unit']))
     if 'min' in definition:
         aprop.set_min_value(str(definition['min']))
     if 'max' in definition:
         aprop.set_max_value(str(definition['max']))
     if 'format' in definition:
         aprop.set_format(latin1(definition['format']))
     if 'description' in definition:
         aprop.set_description(latin1(definition['description']))
     if 'label' in definition:
         aprop.set_label(latin1(definition['label']))
     if 'memorized' in definition:
         attr.set_memorized()
         attr.set_memorized_init(True)
     attr.set_default_properties(aprop)
     self.__device.add_attribute(attr,
                                 r_meth=readmethod,
                                 w_meth=writemethod)
     self._attributeList.append(attrName)
     # prepare internal structure ---
     if channel or function or multiple:
         if channel:
             like = "channel"
         elif function:
             like = "function"
         elif multiple and 'scpiPrefix' in definition['multiple'] and\
                 'attrSuffix' in definition['multiple']:
             like = definition['multiple']['scpiPrefix']
         else:
             raise AttributeError("Wrong definition of multiple attribute")
         number = channel or function or multiple
         self.__prepareChannelLikeAttr(like, number, definition)
     else:
         readCmd = definition['readCmd']
         if 'writeCmd' not in definition:
             # writeCmd = definition['writeCmd']
             definition['writeCmd'] = None
     if 'readFormula' not in definition:
         # readFormula = definition['readFormula']
         definition['readFormula'] = None
     # if 'writeFormula' not in definition:
     #     # writeFormula = definition['writeFormula']
     #     writeFormula = None
     # build internal structure ---
     if definition['writeCmd'] is None:
         self.__buildROObj(attrName, definition)
     else:
         self.__buildRWObj(attrName, definition, readmethod, writemethod)
         if 'writeValues' in definition:
             self.__prepareWriteValues(attrName, definition, aprop, attr)
     return attr