예제 #1
0
    def test_dbrName(self):
        write( 'DBR Type Check')
        self.assertEqual(dbr.Name(dbr.STRING), 'STRING')
        self.assertEqual(dbr.Name(dbr.FLOAT),  'FLOAT')
        self.assertEqual(dbr.Name(dbr.ENUM), 'ENUM')
        self.assertEqual(dbr.Name(dbr.CTRL_CHAR), 'CTRL_CHAR')
        self.assertEqual(dbr.Name(dbr.TIME_DOUBLE), 'TIME_DOUBLE')
        self.assertEqual(dbr.Name(dbr.TIME_LONG), 'TIME_LONG')

        self.assertEqual(dbr.Name('STRING', reverse=True), dbr.STRING)
        self.assertEqual(dbr.Name('DOUBLE', reverse=True), dbr.DOUBLE)
        self.assertEqual(dbr.Name('CTRL_ENUM', reverse=True), dbr.CTRL_ENUM)
        self.assertEqual(dbr.Name('TIME_LONG', reverse=True), dbr.TIME_LONG)
예제 #2
0
def test_dbrName():
    write('DBR Type Check')
    assert dbr.Name(dbr.STRING) == 'STRING'
    assert dbr.Name(dbr.FLOAT) == 'FLOAT'
    assert dbr.Name(dbr.ENUM) == 'ENUM'
    assert dbr.Name(dbr.CTRL_CHAR) == 'CTRL_CHAR'
    assert dbr.Name(dbr.TIME_DOUBLE) == 'TIME_DOUBLE'
    assert dbr.Name(dbr.TIME_LONG) == 'TIME_LONG'

    assert dbr.Name('STRING', reverse=True) == dbr.STRING
    assert dbr.Name('DOUBLE', reverse=True) == dbr.DOUBLE
    assert dbr.Name('CTRL_ENUM', reverse=True) == dbr.CTRL_ENUM
    assert dbr.Name('TIME_LONG', reverse=True) == dbr.TIME_LONG
예제 #3
0
    def __on_connect(self, pvname=None, chid=None, conn=True):
        """Run callback for connection events."""
        # occassionally chid is still None (ie if a second PV is created
        # while __on_connect is still pending for the first one.)
        # Just return here, and connection will happen later
        if conn:
            self.chid = self._args['chid'] = dbr.chid_t(chid.value)

            # allow reduction of elements, via count argument
            count = self._args['nelm']
            if self._args['count'] is not None:
                count = min(count, self._args['count'])
            self._args['count'] = count

            self._args['host'] = 'localhost:00000'

            _ftype_ = dbr.Name(self.ftype).lower()
            self._args['type'] = _ftype_
            self._args['typefull'] = _ftype_
            self._args['ftype'] = dbr.Name(_ftype_, reverse=True)

            if self.auto_monitor is None:
                self.auto_monitor = count < AUTOMONITOR_MAXLENGTH

        for conn_cb in self.connection_callbacks:
            if hasattr(conn_cb, '__call__'):
                conn_cb(pvname=self.pvname, conn=conn, pv=self)
            elif not conn and self.verbose:
                write("PV '%s' disconnected." % pvname)

        # pv end of connect, force a read of access rights
        self.force_read_access_rights()

        # waiting until the very end until to set self.connected prevents
        # threads from thinking a connection is complete when it is actually
        # still in progress.
        self.connected = conn
        return
예제 #4
0
    def _set_charval(self, val, call_ca=True):
        """Set the character representation of the value.

        intended only for internal use"""
        if val is None:
            self._args['char_value'] = 'None'
            return 'None'
        ftype = self._args['ftype']
        ntype = dbr.native_type(ftype)
        if ntype == dbr.STRING:
            self._args['char_value'] = val
            return val
        # char waveform as string
        if ntype == dbr.CHAR and self.count < AUTOMONITOR_MAXLENGTH:
            if HAS_NUMPY and isinstance(val, _np.ndarray):
                # a numpy array
                val = val.tolist()

                if not isinstance(val, list):
                    # a scalar value from numpy, tolist() turns it into a
                    # native python integer
                    val = [val.tolist()]
            else:
                try:
                    # otherwise, try forcing it into a list. this will fail for
                    # scalar types
                    val = list(val)
                except TypeError:
                    # and when it fails, make it a list of one scalar value
                    val = [val]

            if 0 in val:
                firstnull = val.index(0)
            else:
                firstnull = len(val)
            try:
                cval = ''.join([chr(i) for i in val[:firstnull]]).rstrip()
            except ValueError:
                cval = ''
            self._args['char_value'] = cval
            return cval

        cval = repr(val)
        if self.count > 1:
            try:
                length = len(val)
            except TypeError:
                length = 1
            cval = '<array size=%d, type=%s>' % (length,
                                                 dbr.Name(ftype).lower())
        elif ntype in (dbr.FLOAT, dbr.DOUBLE):
            if call_ca and self._args['precision'] is None:
                self.get_ctrlvars()
            try:
                prec = self._args['precision']
                fmt = "%%.%if"
                if 4 < abs(int(log10(abs(val + 1.e-9)))):
                    fmt = "%%.%ig"
                cval = (fmt % prec) % val
            except (ValueError, TypeError, ArithmeticError):
                cval = str(val)
        elif ntype == dbr.ENUM:
            if call_ca and self._args['enum_strs'] in ([], None):
                self.get_ctrlvars()
            try:
                cval = self._args['enum_strs'][val]
            except (TypeError, KeyError, IndexError):
                cval = str(val)

        self._args['char_value'] = cval
        return cval
예제 #5
0
    def __init__(self,
                 pvname,
                 callback=None,
                 form='time',
                 verbose=False,
                 auto_monitor=None,
                 count=None,
                 connection_callback=None,
                 connection_timeout=None,
                 access_callback=None):
        """."""
        dbase = _DATABASE.get(pvname)
        if dbase is None:
            raise Exception(
                'PV does not exist in local database. Configure database ' +
                'first with add_to_database module function.')
        self.pvname = pvname.strip()
        self.form = form.lower()
        self.verbose = verbose
        self.auto_monitor = auto_monitor
        self.ftype = None
        self.connected = False
        self.connection_timeout = connection_timeout
        if self.connection_timeout is None:
            self.connection_timeout = DEFAULT_CONNECTION_TIMEOUT
        self._args = {}.fromkeys(self._fields)
        self._args['pvname'] = self.pvname
        self._args['value'] = dbase.get('value',
                                        '' if dbase['type'] == 'str' else 0)
        self._args['count'] = count
        self._args['nelm'] = dbase.get('count', 1)
        self._args['type'] = 'unknown'
        self._args['typefull'] = 'unknown'
        self._args['access'] = 'unknown'
        self._args['severity'] = 0  # not simulated correctly
        self._args['status'] = 1  # not simulated correctly
        self._args['precision'] = dbase.get('prec')
        self._args['units'] = dbase.get('unit')
        self._args['upper_disp_limit'] = dbase.get('hilim')
        self._args['upper_disp_limit'] = dbase.get('lolim')
        self._args['upper_alarm_limit'] = dbase.get('high')
        self._args['upper_alarm_limit'] = dbase.get('low')
        self._args['upper_warning_limit'] = dbase.get('hihi')
        self._args['upper_warning_limit'] = dbase.get('lolo')
        self._args['upper_ctrl_limit'] = dbase.get('hilim')
        self._args['upper_ctrl_limit'] = dbase.get('lolim')
        self._args['enum_strs'] = dbase.get('enums')

        self.context = dbr.ECA_NORMAL

        self._pytype = _PYTYPES[dbase['type']]
        self.ftype = promote_type(dbase['type'],
                                  use_ctrl=self.form == 'ctrl',
                                  use_time=self.form == 'time')
        self._args['type'] = dbr.Name(self.ftype).lower()

        self.connection_callbacks = []
        if connection_callback is not None:
            self.connection_callbacks = [connection_callback]

        self.access_callbacks = []
        if access_callback is not None:
            self.access_callbacks = [access_callback]

        self.callbacks = {}
        self._conn_started = False
        if isinstance(callback, (tuple, list)):
            for i, thiscb in enumerate(callback):
                if hasattr(thiscb, '__call__'):
                    self.callbacks[i] = (thiscb, {})
        elif hasattr(callback, '__call__'):
            self.callbacks[0] = (callback, {})

        self._args['chid'] = dbr.chid_t(_randint(1, 10000000))
        self.__on_connect(pvname=pvname, chid=self._args['chid'])
        self.chid = self._args['chid']

        self._set_charval(self._args['value'], call_ca=False)

        self.__on_access_rights_event(read_access=True, write_access=True)

        pvid = (self.pvname, self.form, self.context)
        if pvid not in _PVCACHE_:
            _PVCACHE_[pvid] = self