Esempio n. 1
0
class MeanTemp(PyTangoDevice, Readable):
    """Returns mean temperature of some channels of a MawiTherm VectorInput."""

    parameters = {
        'first':
        Param('First channel to include',
              type=intrange(1, 8),
              default=1,
              settable=True),
        'last':
        Param('Last channel to include',
              type=intrange(1, 8),
              default=8,
              settable=True),
    }

    def doRead(self, maxage=0):
        if self.first > self.last:
            return 0
        allchannels = self._dev.value[self.first - 1:self.last]
        return float(sum(allchannels) / len(allchannels))
Esempio n. 2
0
class ImageChannelMixin(DeviceMixinBase):
    """Mixin for channels that return images."""

    parameters = {
        'readresult':
        Param(
            'Storage for scalar results from image '
            'filtering, to be returned from doRead()',
            type=listof(float),
            settable=True,
            internal=True),
    }

    parameter_overrides = {
        'unit': Override(default='cts'),
        'fmtstr': Override(default='%d'),
        'preselection': Override(type=int),
    }

    # set this to an ArrayDesc instance, either as a class attribute
    # or dynamically as an instance attribute
    arraydesc = None

    def doRead(self, maxage=0):
        return self.readresult

    def readArray(self, quality):
        """This method should return the detector data array or `None` if no
        data is available.

        The *quality* parameter is one of the constants defined in the
        `nicos.core.constants` module:

        * LIVE is for intermediate data that should not be written to files.
        * INTERMEDIATE is for intermediate data that should be written.
        * FINAL is for final data.
        * INTERRUPTED is for data read after the counting was interrupted by
          an exception.

        For detectors which just supports FINAL images, e.g. Image plate
        detectors this method should return an array when *quality* is `FINAL`
        and `None` otherwise.  Most other detectors should also read out and
        return the data when *quality* is `INTERRUPTED`.
        """
        if self._sim_intercept:
            if self.arraydesc:
                return numpy.zeros(self.arraydesc.shape)
            return numpy.zeros(1)
        return self.doReadArray(quality)

    def doReadArray(self, quality):
        raise NotImplementedError('implement doReadArray in %s' %
                                  self.__class__.__name__)
Esempio n. 3
0
class CryopadPol(Moveable):
    """Controls the incoming or outgoing polarization direction."""

    attached_devices = {
        'cryopad': Attach('Underlying Cryopad device', BaseCryopad)
    }

    parameters = {
        'side':
        Param('Which side of the instrument is this device?',
              type=oneof('in', 'out'),
              mandatory=True),
    }

    parameter_overrides = {
        'unit': Override(mandatory=False, default=''),
    }

    valuetype = oneof('+x', '-x', '+y', '-y', '+z', '-z')

    def doRead(self, maxage=0):
        # NOTE: for now, we just return the latest target because it became
        # necessary to introduce corrections to nutator angles that cannot yet
        # be included reliably in the calculations, and would change the readout
        # here to "unknown".
        return self.target
        # cppos = self._attached_cryopad.read(maxage)
        # theta, chi = cppos[0:2] if self.side == 'in' else cppos[2:4]
        # for (pos, (goaltheta, goalchi)) in calc.DIRECTIONS.items():
        #     # fix chi = -179.5, goalchi = 180 situation
        #     diffchi = abs(chi - goalchi)
        #     chiok = diffchi < 0.5 or 359.5 < diffchi < 360.5
        #     # XXX: make precision configurable
        #     if abs(theta - goaltheta) < 0.5 and chiok:
        #         return pos
        # return 'unknown'

    def doStatus(self, maxage=0):
        st, text = multiStatus(self._adevs)
        if st == status.BUSY:
            return st, text
        if self.read(maxage) == 'unknown':
            return status.NOTREACHED, 'unknown polarization setting'
        return status.OK, 'idle'

    def doStart(self, pos):
        theta_chi = calc.DIRECTIONS[pos]
        cppos = self._attached_cryopad.target or (0, 0, 0, 0)
        if self.side == 'in':
            target = tuple(theta_chi) + cppos[2:4]
        else:
            target = cppos[0:2] + tuple(theta_chi)
        self._attached_cryopad.start(target)
Esempio n. 4
0
class VectorInput(BaseInput):
    """Vector input with high and low alarm limits"""

    parameters = {
        'limitmin': Param('Low alarm limit', listof(float), settable=True),
        'limitmax': Param('High alarm limit', listof(float), settable=True),
    }

    def doReadLimitmin(self):
        return map(float, self._GetListProperty('limitmin'))

    def doWriteLimitmin(self, value):
        self._dev.SetProperties(['limitmin', str(value)])
        return self.doReadLimitmin()

    def doReadLimitmax(self):
        return map(float, self._GetListProperty('limitmax'))

    def doWriteLimitmax(self, value):
        self._dev.SetProperties(['limitmax', str(value)])
        return self.doReadLimitmax()
Esempio n. 5
0
class ReadonlySwitcher(MappedReadable):
    """Same as the `Switcher`, but for read-only underlying devices."""

    attached_devices = {
        'readable': Attach('The continuous device which is read', Readable),
    }

    parameters = {
        'precision': Param('Precision for comparison', type=floatrange(0),
                           default=0),
    }

    parameter_overrides = {
        'fallback':  Override(userparam=False, type=none_or(str),
                              mandatory=False),
    }

    hardware_access = False

    def _readRaw(self, maxage=0):
        return self._attached_readable.read(maxage)

    def _mapReadValue(self, pos):
        prec = self.precision
        for name, value in self.mapping.items():
            if prec:
                if abs(pos - value) <= prec:
                    return name
            elif pos == value:
                return name
        if self.fallback is not None:
            return self.fallback
        raise PositionError(self, 'unknown position of %s' %
                            self._attached_readable)

    def doStatus(self, maxage=0):
        # if the underlying device is moving or in error state,
        # reflect its status
        move_status = self._attached_readable.status(maxage)
        if move_status[0] not in (status.OK, status.WARN):
            return move_status
        # otherwise, we have to check if we are at a known position,
        # and otherwise return an error status
        try:
            if self.read(maxage) == self.fallback:
                return status.NOTREACHED, 'unconfigured position of %s or '\
                    'still moving' % self._attached_readable
        except PositionError as e:
            return status.NOTREACHED, str(e)
        return status.OK, ''

    def doReset(self):
        self._attached_readable.reset()
Esempio n. 6
0
class Shutter(HasTimeout, Moveable):
    """Controlling the shutter."""

    valuetype = oneof('closed', 'open')

    parameters = {
        'waittime':
        Param('Additional time to wait before open',
              settable=True,
              unit='s',
              default=0),
    }

    attached_devices = {
        'output': Attach('output bits', Moveable),
        'input': Attach('input bits', Readable),
    }

    parameter_overrides = {
        'fmtstr': Override(default='%s'),
        'timeout': Override(default=10),
        'unit': Override(mandatory=False, default=''),
    }

    def doStatus(self, maxage=0):
        inputstatus = self._attached_input.read(maxage)
        if inputstatus == READ_OPEN:
            if self.target == 'open':
                return status.OK, 'idle'
            else:
                return status.WARN, 'open, but target=closed'
        elif inputstatus == READ_CLOSED:
            if self.target == 'closed':
                return status.OK, 'idle'
            else:
                return status.WARN, 'closed, but target=open'
        # HasTimeout will check for target reached
        return status.OK, 'idle'

    def doRead(self, maxage=0):
        inputstatus = self._attached_input.read(maxage)
        if inputstatus == READ_OPEN:
            return 'open'
        elif inputstatus == READ_CLOSED:
            return 'closed'
        return 'unknown'

    def doStart(self, target):
        session.delay(self.waittime)
        if target == 'open':
            self._attached_output.start(WRITE_OPEN)
        else:
            self._attached_output.start(WRITE_CLOSED)
Esempio n. 7
0
class EKFMotor(SequencerMixin, Motor):
    """EKF CARESS motor."""

    parameters = {
        'stopdelay':
        Param('Delay before switching off air',
              type=int,
              settable=False,
              default=0,
              unit='s'),
    }

    hardware_access = True

    def doInit(self, mode):
        tmp = self.config.split()
        self._setROParam('stopdelay', 0)
        # set the sleep time in CARESS to 0 and restore the config line in
        # cache after initialization
        if int(tmp[1]) in [EKF_44520_ABS, EKF_44520_INCR] and \
           len(tmp) > 12 and int(tmp[12]) > 1:
            self._setROParam('stopdelay', int(tmp[12]))
            tmp[12] = '1'
            self._setROParam('config', ' '.join(tmp))
        Motor.doInit(self, mode)
        if int(tmp[1]) in [EKF_44520_ABS, EKF_44520_INCR] and \
           len(tmp) > 12 and int(tmp[12]) > 1:
            tmp[12] = '%d' % self.stopdelay
            self._setROParam('config', ' '.join(tmp))

    def _generateSequence(self, target):
        return [
            SeqCall(Motor.doStart, self, target),
            SeqCall(self._hw_wait),
            SeqSleep(self.stopdelay),
            SeqCall(Motor.doStop, self)
        ]

    def _hw_wait(self):
        # overridden: query Axis status, not HoveringAxis status
        while Motor.doStatus(self, 0)[0] == status.BUSY:
            session.delay(self._base_loop_delay)

    def doStart(self, target):
        if self._seq_is_running():
            self.stop()
            self.log.info('waiting for motor to stop...')
            self.wait()
        self._startSequence(self._generateSequence(target))

    def doStop(self):
        # stop only the axis, but the sequence has to run through
        Motor.doStop(self)
Esempio n. 8
0
class SH_Cylinder(Moveable):
    """PUMA specific device for the shutter cylinder."""

    attached_devices = {
        'io_ref': Attach('limit switches', Readable),
        'io_air': Attach('air in the open/close direction', Moveable),
        'io_pos': Attach('position stop, if in closed position, -1', Moveable),
    }

    parameters = {
        'timedelay':
        Param('Waiting time for the movement',
              type=float,
              default=3,
              settable=True,
              mandatory=False,
              unit='s'),
    }

    def doStart(self, position):
        if position == self.read(0):
            return

        if self._checkAir() != 1:
            raise NicosError(
                self, 'No air! Please open the shutter with the '
                'button near the door.')

        self._attached_io_air.move(0)
        session.delay(self.timedelay)

        if self._attached_io_ref.read(0) != 1:
            raise NicosError(self, 'Cannot close the shutter!')

        if position != -1:
            self._attached_io_pos.move(position)
            session.delay(self.timedelay)
            self._attached_io_air.move(1)
            session.delay(self.timedelay)

    def doRead(self, maxage=0):
        if self._attached_io_ref.read(0) == 1:
            return -1
        if self._attached_io_air.read(0) == 1:
            return self._attached_io_pos.read(0)

    def _checkAir(self):
        if self._attached_io_ref.read(0) == 1:
            self._attached_io_air.move(1)
            session.delay(self.timedelay)
            if self._attached_io_ref.read(0) == 1:
                return 0
        return 1
Esempio n. 9
0
class LokiSample(Sample):
    """Device that collects the various sample properties specific to
    samples at LoKI.
    """

    parameters = {
        'position':
        Param(
            'Mapping of devices to positions for driving to this'
            ' sample\'s position',
            type=dictof(str, anytype),
            settable=True),
        'thickness':
        Param('Sample thickness (info only)',
              type=float,
              settable=True,
              unit='mm',
              category='sample'),
        'comment':
        Param('Sample comment', type=str, settable=True, category='sample'),
    }
Esempio n. 10
0
class MCC2Poti(MCC2core, NicosCoder):
    """Class for the readout of a MCC2-A/D converter"""

    parameters = {
        'slope':     Param('Coder units per degree of rotation', type=float,
                           default=1, settable=True, unit='1/main',
                           prefercache=False),
        'zerosteps': Param('Coder steps at physical zero', type=int,
                           default=0, settable=True, prefercache=False),
        'coderbits': Param('Number of bits of ssi-encoder', default=10,
                           type=int, settable=False, mandatory=False,
                           prefercache=False),
    }

    def doRead(self, maxage=0):
        r = 'AD1R' if self.channel == 'X' else 'AD2R'
        return (float(self.comm(r)) - self.zerosteps) / self.slope

    def doSetPosition(self, pos):
        self.log.warning('No setPosition available! Request ignored....')
        return self.doRead(0)
Esempio n. 11
0
class CPULoad(Readable):

    parameters = {
        'interval':
        Param(
            'Interval for load detection',
            type=floatrange(0.1, 60),
            default=0.1,
            settable=False,
        ),
        'lastvalue':
        Param('Last obtained value',
              type=float,
              internal=True,
              mandatory=False,
              default=0.0),
    }

    def doInit(self, mode):
        if mode == SIMULATION:
            return
        # create only run ONE thread: in the poller
        # it may look stupid, as the poller already has a thread polling read()
        # now imagine several such devices in a setup.... not so stupid anymore
        if session.sessiontype == POLLER:
            self._thread = createThread('measure cpuload', self._run)

    def doWriteInterval(self, value):
        self.pollinterval = max(1, 2 * value)
        self.maxage = max(3, 5 * value)

    def doRead(self, maxage=0):
        return self.lastvalue

    def doStatus(self, maxage=0):
        return status.OK, ''

    def _run(self):
        while True:
            self._setROParam('lastvalue', psutil.cpu_percent(self.interval))
Esempio n. 12
0
class ReadOnlyPowerSupply(AnalogInput):
    """
    A power supply (voltage and current) device.
    """

    parameters = {
        'voltage':
        Param('Actual voltage',
              unit='V',
              type=float,
              settable=False,
              volatile=True),
        'current':
        Param('Actual current',
              unit='A',
              type=float,
              settable=False,
              volatile=True),
        'setpoint':
        Param(
            'Setpoint for value (voltage or current) on '
            'initialization depending on mode',
            type=float,
            settable=False)
    }

    def doInit(self, mode):
        if mode != SIMULATION and self.setpoint is not None:
            self._dev.value = self.setpoint

    def doReadVoltage(self):
        return self._dev.voltage

    def doReadCurrent(self):
        return self._dev.current

    def doPoll(self, n, maxage):
        if n % 5 == 0:
            self._pollParam('voltage', 1)
            self._pollParam('current', 1)
Esempio n. 13
0
class ProcDevice(Moveable):
    """
    A little device class which runs an external process and allows to
    wait for it to finish.
    """

    parameters = {'subprocess': Param('Path of subprocess to run',
                                      type=str, mandatory=True),
                  'args': Param('Arguments for the subprocess',
                                type=listof(str), mandatory=True), }

    parameter_overrides = {
        'unit': Override(description='(not used)', mandatory=False),
    }
    _subprocess = None

    def doStart(self, target):
        if self._subprocess is not None:
            raise InvalidValueError('Process is still running')

        fullargs = list(self.args)
        fullargs.insert(0, self.subprocess)
        self._subprocess = createSubprocess(fullargs)

    def doIsCompleted(self):
        if self._subprocess is None:
            return True
        ret = self._subprocess.poll()
        if ret is None:
            return False
        else:
            self._subprocess = None
            return True

    def doRead(self, maxage=0):
        return .0

    def doStop(self):
        if self._subprocess is not None:
            self._subprocess.terminate()
Esempio n. 14
0
class SINQAsciiSink(FileSink):
    """
    This is a filesink which writes scan data files in the SINQ ASCII format.
    The implementation strives to be as compatible as possible to the old
    format as written by SICS. SINQ ASCII files are constructed from a
    template file. This template file contains ASCII text which is copied
    verbatim to the output intermixed with place holder strings. These are
    replaced with data from NICOS. In addition, the actual data from the
    scan is collected and written too. The special placeholders recognized
    are:
    - !!VAR(dev,par)!! is replaced with the value of the parameter par of
                        device dev. Par can be missing and is then value.
    - !!DRIV(dev)!! replaced by the value of dev
    - !!ZERO(dev)!! replaced by the offset of dev. Dev must be a motor
    - !!SCRIPT(txt)!! replaced by the output of running script txt
    - !!DATE!!  replaced by the current date and time
    - !!FILE!! replaced by the original file path of the scan file
    - !!SCANZERO!! replaced by a list of zero points of the scanned devices
    There is some redundancy here but as the goal is to reuse the SICS template
    files as far as possible, this has to be accepted.

    One file per scan is written. This format is designed with single
    counters in mind, this is not for area detetcor data. Use the
    NexusFileSink for such data.

    """
    parameters = {
        'templatefile':
        Param('Path to SICS style template file', type=str, mandatory=True),
        'scaninfo':
        Param('Header text and nicos device for each scan point',
              type=listof(tupleof(str, nicosdev)),
              mandatory=True),
    }

    parameter_overrides = {
        'settypes': Override(default=[SCAN, SUBSCAN]),
    }

    handlerclass = SINQAsciiSinkHandler
Esempio n. 15
0
class FlexRegulator(TemperatureController):
    """Temperature controller with varying setup for software and hardware
    regulation."""

    parameters = {
        'dummy':
        Param('Dummy input device', type=tangodev, mandatory=True),
        'configs':
        Param('Possible setups', type=dictof(str, entry), mandatory=True),
        'config':
        Param('Current configuration', type=str, volatile=True, settable=True),
    }

    def doReadConfig(self):
        props = self._dev.GetProperties()
        indev = props[props.index('indev') + 1]
        outdev = props[props.index('outdev') + 1]
        for (cfgname, config) in iteritems(self.configs):
            if config[0] == outdev:
                if config[1] is None:
                    if indev == self.dummy:
                        return cfgname
                elif indev == config[1][0]:
                    return cfgname
        return '<unknown>'

    def doWriteConfig(self, value):
        cfg = self.configs[value]
        props = ['outdev', cfg[0]]
        if cfg[1]:
            indev, outmin, outmax, initp, initi, initd = cfg[1]
            props += [
                'indev', indev, 'software', 'True', 'outmin',
                str(outmin), 'outmax',
                str(outmax), 'initpid',
                '[%s, %s, %s]' % (initp, initi, initd)
            ]
        else:
            props += ['indev', self.dummy, 'software', 'False']
        self._dev.SetProperties(props)
Esempio n. 16
0
class MasterSlaveMotor(Moveable):
    """Combined master slave motor with possibility to apply a scale to the
    slave motor."""

    attached_devices = {
        "master": Attach("Master motor controlling the movement", Moveable),
        "slave": Attach("Slave motor following master motor movement",
                        Moveable),
    }

    parameters = {
        "scale": Param("Factor applied to master target position as slave "
                       "position", type=float, default=1),
    }

    parameter_overrides = {
        "unit": Override(mandatory=False),
        "fmtstr": Override(default="%.3f %.3f"),
    }

    def _slavePos(self, pos):
        return self.scale * pos

    def doRead(self, maxage=0):
        return [self._attached_master.read(maxage),
                self._attached_slave.read(maxage)]

    def doStart(self, pos):
        self._attached_master.move(pos)
        self._attached_slave.move(self._slavePos(pos))

    def doIsAllowed(self, pos):
        faultmsgs = []
        messages = []
        for dev in [self._attached_master, self._attached_slave]:
            allowed, msg = dev.isAllowed(pos)
            msg = dev.name + ': ' + msg
            messages += [msg]
            if not allowed:
                faultmsgs += [msg]
        if faultmsgs:
            return False, ', '.join(faultmsgs)
        return True, ', '.join(messages)

    def doReadUnit(self):
        return self._attached_master.unit

    def valueInfo(self):
        return Value(self._attached_master.name, unit=self.unit,
                     fmtstr=self._attached_master.fmtstr), \
               Value(self._attached_slave.name, unit=self.unit,
                     fmtstr=self._attached_slave.fmtstr)
Esempio n. 17
0
class Beamstop(Moveable):
    """Switcher for the beamstop position.

    This switches the beamstop in or out; the "out" value is determined by
    the current resolution preset.
    """

    valuetype = oneof('out', 'in')

    attached_devices = {
        'moveable': Attach('Beamstop motor', HasPrecision),
        'resolution': Attach('Resolution device', Resolution),
    }

    parameters = {
        'outpos': Param('Position for "out"'),
    }

    parameter_overrides = {
        'unit': Override(mandatory=False, default=''),
    }

    def doRead(self, maxage=0):
        movpos = self._attached_moveable.read(maxage)
        if abs(movpos - self.outpos) <= self._attached_moveable.precision:
            return 'out'
        respos = self._attached_resolution.read(maxage)
        if respos != 'unknown':
            inpos = self._attached_resolution.presets[respos]['beamstop_x_in']
            if abs(movpos - inpos) <= self._attached_moveable.precision:
                return 'in'
        return 'unknown'

    def doStatus(self, maxage=0):
        code, text = Moveable.doStatus(self, maxage)
        if code == status.OK and self.read(maxage) == 'unknown':
            return status.NOTREACHED, 'unknown position'
        return code, text

    def _getWaiters(self):
        return [self._attached_moveable]

    def doStart(self, pos):
        if pos == 'out':
            self._attached_moveable.start(self.outpos)
            return
        respos = self._attached_resolution.target
        if respos != 'unknown':
            inpos = self._attached_resolution.presets[respos]['beamstop_x_in']
            self._attached_moveable.start(inpos)
        else:
            raise MoveError('no position for beamstop, resolution is unknown')
Esempio n. 18
0
class WebcamSink(FileSink):
    """Copies a snapshot of a webcam to the data directory."""

    parameters = {
        'url': Param('URL of the image', type=str, mandatory=True),
    }

    parameter_overrides = {'settypes': Override(default=[POINT])}

    handlerclass = WebcamSinkHandler

    def isActive(self, dataset):
        return DataSink.isActive(self, dataset)
Esempio n. 19
0
class ResiSample(Sample):
    """Cell object representing sample geometry."""
    attached_devices = {'basedevice': Attach('the base device', ResiDevice)}
    parameters = {
        'lattice':
        Param('Lattice constants',
              type=vec3,
              settable=True,
              default=[5, 5, 5],
              unit='A',
              category='sample'),
        'angles':
        Param('Lattice angles',
              type=vec3,
              settable=True,
              default=[90, 90, 90],
              unit='deg',
              category='sample'),
    }

    def doRead(self, maxage=0):
        return repr(self._attached_basedevice.cell)
Esempio n. 20
0
class PNGLiveFileSink(ImageSink):
    """Writes (live) data to a PNG file, possibly with a log-10 color scale.

    Data is normalized to the highest-value pixel, and the used color map is
    the commonly used "Jet" colormap.

    This is not intended for data result storage, but to create images of the
    live measurement for quick view, e.g. in status monitors.
    """

    parameter_overrides = {
        'filenametemplate':
        Override(mandatory=False, userparam=False, default=['']),
    }

    parameters = {
        'interval':
        Param('Interval to write file to disk', unit='s', default=5),
        'filename':
        Param('File name for .png image', type=str, mandatory=True),
        'log10':
        Param('Use logarithmic counts for image', type=bool, default=False),
        'size':
        Param('Size of the generated image',
              unit='pixels',
              default=256,
              settable=True),
        'rgb':
        Param('Create RBG image', type=bool, default=True, mandatory=False),
        'histrange':
        Param('Range of histogram for scaling greyscale image',
              type=limits,
              default=(0.05, 0.95),
              settable=True,
              mandatory=False),
        'sumaxis':
        Param('Axis over which should be summed if data are 3D',
              type=intrange(1, 3),
              default=1,
              settable=False),
    }

    handlerclass = PNGLiveFileSinkHandler

    def doPreinit(self, mode):
        if PIL is None:
            self.log.error(_import_error)
            raise NicosError(
                self, 'Python Image Library (PIL) is not '
                'available. Please check whether it is installed '
                'and in your PYTHONPATH')

    def isActiveForArray(self, arraydesc):
        return len(arraydesc.shape) in (2, 3)
Esempio n. 21
0
class SpecialInput(BaseInput):
    """Base class for devices with a scalar 'limit' property"""

    parameters = {
        'limit': Param('Alarm limit', float, settable=True),
    }

    def doReadLimit(self):
        return float(self._getProperty('limit'))

    def doWriteLimit(self, value):
        self._dev.SetProperties(['limit', str(value)])
        return self.doReadLimit()
Esempio n. 22
0
class Dev3(HasLimits, HasOffset, Moveable):
    parameters = {
        'offsetsign': Param('Offset sign', type=int, settable=True),
    }

    def doRead(self, maxage=0):
        return self._val - self.offsetsign * self.offset

    def doStart(self, pos):
        self._val = pos + self.offsetsign * self.offset

    def doAdjust(self, old, new):
        self.offset += self.offsetsign * (old - new)
Esempio n. 23
0
class Sharpness(PostprocessPassiveChannel):

    parameters = {
        'thr3':
        Param('Threshold for 3x3 pixels',
              type=intrange(0, 1000),
              settable=True,
              userparam=True,
              default=25),
        'thr5':
        Param('Threshold for 5x5 pixels',
              type=intrange(0, 1000),
              settable=True,
              userparam=True,
              default=100),
        'thr7':
        Param('Threshold for 7x7 pixels',
              type=intrange(0, 1000),
              settable=True,
              userparam=True,
              default=400),
        'sig_log':
        Param('Sig log',
              type=floatrange(0, 1),
              settable=True,
              userparam=True,
              default=0.8),
    }

    def valueInfo(self):
        return Value(name=self.name, type='counter', fmtstr='%.3f'),

    def getReadResult(self, arrays, results, quality):
        arr = np.array(arrays[0], dtype=int)
        return [
            scharr_filter(
                gam_rem_adp_log(arr, self.thr3, self.thr5, self.thr7,
                                self.sig_log))
        ]
Esempio n. 24
0
class PowerSupply(HasTimeout, RampActuator):
    """
    A power supply (voltage and current) device.
    """

    parameters = {
        'voltage': Param('Actual voltage', unit='V',
                         type=float, settable=False, volatile=True),
        'current': Param('Actual current', unit='A',
                         type=float, settable=False, volatile=True),
    }

    def doReadVoltage(self):
        return self._dev.voltage

    def doReadCurrent(self):
        return self._dev.current

    def doPoll(self, n, maxage):
        if n % 5 == 0:
            self._pollParam('voltage', 1)
            self._pollParam('current', 1)
Esempio n. 25
0
class Authenticator(BaseAuthenticator):
    """Authenticates against oAuth2 server via Password Grant type.
    """

    parameters = {
        'tokenurl':
        Param('OAuth server token url to authenticate', type=str),
        'clientid':
        Param('OAuth client id', type=str),
        'keystoretoken':
        Param('Id used in the keystore for the OAuth client '
              'secret',
              type=str,
              default='oauth2server'),
    }

    def authenticate(self, username, password):
        secret = nicoskeystore.getCredential(self.keystoretoken)
        error = None
        try:
            oauth = OAuth2Session(client=LegacyApplicationClient(
                client_id=self.clientid))
            token = oauth.fetch_token(token_url=self.tokenurl,
                                      username=username,
                                      password=password,
                                      client_id=self.clientid,
                                      client_secret=secret)
        except Exception as err:
            # this avoids leaking credential details via tracebacks
            error = str(err)
        if error:
            raise AuthenticationError('exception during authenticate(): %s' %
                                      error)
        if not oauth.authorized:
            raise AuthenticationError('wrong password')
        return User(username, USER, {
            'token': token,
            'clientid': self.clientid
        })
Esempio n. 26
0
class LiveViewSink(BaseLiveViewSink):
    """Data live view sink."""

    handlerclass = LiveViewSinkHandler

    parameters = {
        'correctionfile':
        Param('Intensity correction file',
              type=str,
              settable=False,
              prefercache=False,
              default=''),
    }
Esempio n. 27
0
class HrptMono(ManualMove):
    """
    This is a mini extension to ManualMove which holds an additional
    settable parameter,
    the monochromator type
    """
    parameters = {
        'monotype':
        Param('Monochromator Type',
              type=str,
              settable=True,
              category='instrument')
    }
Esempio n. 28
0
class Leckmon(Readable):
    """Water supply leak monitor."""

    attached_devices = {
        'bus': Attach('Toni communication bus', ModBus),
    }

    parameters = {
        'addr': Param('Bus address of monitor', type=int, mandatory=True),
    }

    def doRead(self, maxage=0):
        return self._attached_bus.communicate('S?', self.addr)
Esempio n. 29
0
class FPGAFrequency(PyTangoDevice, Readable):
    """Provides the frequency readout of the counter card as a Readable."""

    parameters = {
        'multiplier': Param('Multiplier for return value', default=1.0),
    }

    parameter_overrides = {
        'unit': Override(mandatory=False, default='Hz'),
    }

    def doRead(self, maxage=0):
        return self._dev.DevFPGACountReadFreq() * self.multiplier
Esempio n. 30
0
class CollimationSlit(TwoAxisSlit):
    """Two-axis slit with an additional parameter for the "open" position."""

    parameters = {
        'openpos':
        Param('Position to move slit completely open',
              type=tupleof(float, float),
              default=(50.0, 50.0)),
    }

    parameter_overrides = {
        'fmtstr': Override(default='%.1f x %.1f'),
    }