Esempio n. 1
0
    def run(self):
        """ Main loop
        """
        while not self._terminate:
            s = time.time()

            # Create an image with noise 100x120
            x = np.arange(100)
            y = np.arange(120)
            xx, yy = np.meshgrid(x, y)
            self.parent.gf.last_x0 = 20*np.random.rand()+40
            self.parent.gf.last_y0 = 20*np.random.rand()+40
            image = self.parent.gf.gaussian_2D(xx, yy, 10, 100, self.parent.gf.last_x0, self.parent.gf.last_y0, 10, 10)
            image += 10 * np.random.rand(*image.shape) - 5
            image = np.uint16(image)

            for a in self.img_attr:
                # Push fake events (just populate attributes that are really used by the handler)
                ev = PT.EventData()
                ev.attr_name = a
                val = PT.DeviceAttribute()
                val.name = a
                val.value = image
                ev.attr_value = val
                ev.err = False
                self.parent.tango_event.emit(ev)

            # Sleep to have a burst of events every 0.5s
            e = time.time() - s
            if e < 0.5:
                time.sleep(0.5 - e)
    def init_device(self):
        try:
            PseudoDev.init_device(self)

            if not self.check_Properties(['GaugeController', 'Channel']):
                self.init_error += "GaugeController,Channel properties are mandatory, edit them and launch Init()"
                self.error(self.init_error)
                self.set_state(PyTango.DevState.FAULT)
                return
            else:
                self.ChannelName = (self.Channel.split()[0] if fun.isString(
                    self.Channel) else fun.first(
                        c for c in self.Channel
                        if c.lower() not in ('State',
                                             'ChannelState'))).lower()
                targets = ['State', self.ChannelName, 'ChannelState']
                self.debug('Creating cache values for %s:%s' %
                           (self.GaugeController, targets))
                for attribute in targets:
                    da = PyTango.DeviceAttribute()
                    da.name, da.time, da.value = (
                        self.GaugeController + '/' +
                        attribute), PyTango.TimeVal.fromtimestamp(0), None
                    self.Cache[attribute] = da
                    self.Errors[attribute] = 0

                self.subscribe_external_attributes(self.GaugeController,
                                                   targets)

            self.info('Ready to accept request ...')
            self.info('-' * 80)
        except Exception, e:
            print 'Exception in %s.init_device():' % self.get_name()
            print traceback.format_exc()
            raise e
Esempio n. 3
0
    def add_polled_attribute(self, attr_name, period, subscriber_method=None):
        """
        Add a polled read attribute to the command_list. This is done by setting the recurrent option
        to True.

        :param attr_name: Name of the attribute
        :param period: Polling period
        :param subscriber_method: Optional callback method to call when the the attribute is done. Additionally
        device_command_cb is added as a subscriber.
        :return:
        """
        root.info("Adding attribute {0} with polling period {1} s".format(
            attr_name, period))
        with self.lock:
            attr = pt.DeviceAttribute()
            self.attribute_dict[attr_name] = attr
            dev_cmd = dc.DeviceCommand(attr_name,
                                       "read",
                                       self.device,
                                       recurrent=True,
                                       period=period)
            if subscriber_method is not None:
                dev_cmd.add_subscriber(subscriber_method)
            self.command_list.append(dev_cmd)
            dev_cmd.add_subscriber(self.device_command_cb)
            dev_cmd.start()
Esempio n. 4
0
    def __init__(self, attr=None, pytango_dev_attr=None, config=None):
        # config parameter is kept for backwards compatibility only
        TaurusAttrValue.__init__(self)
        if config is not None:
            from taurus.core.util.log import deprecated
            deprecated(dep='"config" kwarg', alt='"attr"', rel='4.0')
            attr = config
        if attr is None:
            self._attrRef = None
        else:
            self._attrRef = weakref.proxy(attr)
        self.config = self._attrRef  # bck-compat

        self._pytango_dev_attr = p = pytango_dev_attr
        if p is None:
            self._pytango_dev_attr = p = PyTango.DeviceAttribute()
            return

        if self._attrRef is None:
            return

        numerical = (PyTango.is_numerical_type(self._attrRef._tango_data_type,
                                               inc_array=True)
                     or p.type == PyTango.CmdArgType.DevUChar)

        if p.has_failed:
            self.error = PyTango.DevFailed(*p.get_err_stack())
        else:
            # spectra and images can be empty without failing
            if p.is_empty and self._attrRef.data_format != DataFormat._0D:
                dtype = FROM_TANGO_TO_NUMPY_TYPE.get(
                    self._attrRef._tango_data_type)
                if self._attrRef.data_format == DataFormat._1D:
                    shape = (0, )
                elif self._attrRef.data_format == DataFormat._2D:
                    shape = (0, 0)
                p.value = numpy.empty(shape, dtype=dtype)
                if not (numerical or self._attrRef.type == DataType.Boolean):
                    # generate a nested empty list of given shape
                    p.value = []
                    for _ in xrange(len(shape) - 1):
                        p.value = [p.value]

        rvalue = p.value
        wvalue = p.w_value
        if numerical:
            units = self._attrRef._units
            if rvalue is not None:
                rvalue = Quantity(rvalue, units=units)
            if wvalue is not None:
                wvalue = Quantity(wvalue, units=units)
        elif isinstance(rvalue, PyTango._PyTango.DevState):
            rvalue = DevState[str(rvalue)]

        self.rvalue = rvalue
        self.wvalue = wvalue
        self.time = p.time  # TODO: decode this into a TaurusTimeVal
        self.quality = quality_from_tango(p.quality)
Esempio n. 5
0
    def __init__(self, name, attr=None):
        self.name = name
        if attr is None:
            self.attr_result = pt.DeviceAttribute()
        else:
            self.attr_result = attr
        self.done = True

        self.subcriber_lock = threading.Lock()
        self.subscriber_list = list()
Esempio n. 6
0
 def setup_spectrometer(self):
     self.info_stream("Entering setup_camera")
     self.wavelengthvector_data = (self.central_wavelength + np.arange(
         -self.roi[2] / 2, self.roi[2] / 2) * self.dispersion) * 1e-9
     self.max_value = self.saturation_level
     wavelength_attr = tango.DeviceAttribute()
     wavelength_attr.name = "wavelengths"
     wavelength_attr.quality = tango.AttrQuality.ATTR_VALID
     wavelength_attr.value = self.wavelengthvector_data
     # wavelength_attr.data_format = tango.AttrDataFormat.SPECTRUM
     wavelength_attr.time = tango.time_val.TimeVal(time.time())
     max_value_attr = tango.DeviceAttribute()
     max_value_attr.name = "max_value"
     max_value_attr.quality = tango.AttrQuality.ATTR_VALID
     max_value_attr.value = self.max_value
     # max_value_attr.data_format = tango.AttrDataFormat.SCALAR
     max_value_attr.time = tango.time_val.TimeVal(time.time())
     with self.controller.state_lock:
         self.controller.camera_result["wavelengths"] = wavelength_attr
         self.controller.camera_result["max_value"] = max_value_attr
Esempio n. 7
0
    def init_device(self):
        try:
            PseudoDev.init_device(self)

            self.ChannelValue = None
            self.ChannelDate = 0

            if not self.check_Properties(['IonPumpController', 'Channel']):
                self.init_error += "IonPumpController and Channel properties are mandatory, edit them and launch Init()"
                self.error(self.init_error)
                self.set_state(PyTango.DevState.UNKNOWN)
                return
            else:
                self.ChannelName = fun.first(
                    c for c in self.Channel
                    if not fun.matchCl('(*state*|*status*)', c))
                targets = ['State', self.ChannelName.split('[')[0]]
                self.debug('Creating cache values for %s:%s' %
                           (self.IonPumpController, targets))
                for attribute in targets:
                    da = PyTango.DeviceAttribute()
                    da.name, da.time, da.value = (
                        self.IonPumpController + '/' +
                        attribute), PyTango.TimeVal.fromtimestamp(0), None
                    self.Cache[attribute] = da
                    self.Errors[attribute] = 0

                self.subscribe_external_attributes(self.IonPumpController,
                                                   targets)

            self.info('Ready to accept request ...')
            self.info('-' * 80)
        except Exception, e:
            self.init_error += traceback.format_exc()
            self.error(self.init_error)
            self.set_state(PyTango.DevState.UNKNOWN)
class AttributeClass(QtCore.QObject):
    attrSignal = QtCore.pyqtSignal(pt.device_attribute.DeviceAttribute)
    attrInfoSignal = QtCore.pyqtSignal(pt.AttributeInfoEx)

    def __init__(self,
                 name,
                 device,
                 minInterval=0.0,
                 slot=None,
                 eventType="thread",
                 getInfo=False,
                 rateLimit=False):
        """

        :param name:
        :param device:
        :param minInterval:
        :param slot:
        :param eventType: "thread": polling thread, "event": change event. pt.EventType.CHANGE_EVENT etc.
        :param getInfo:
        :param rateLimit:
        """
        super(AttributeClass, self).__init__()
        self.name = name
        self.device = device
        self.interval = minInterval
        self.getInfoFlag = getInfo

        if slot is not None:
            self.attrSignal.connect(slot)

        self.lastRead = 0
        self.eventType = eventType
        self.eventId = None
        self.attr = None
        self.attrLock = threading.Lock()
        self.signalPending = False
        self.rateLimit = rateLimit

        if eventType is None or eventType == "thread":
            self.readThread = threading.Thread(name=self.name,
                                               target=self.attr_read)
            self.stopThread = False
            self.startRead()
        elif eventType == "event":
            self.eventType = pt.EventType.CHANGE_EVENT
            self.subscribe_event()
        else:
            self.subscribe_event()

    def subscribe_event(self):
        self.eventId = self.device.subscribe_event(self.name,
                                                   self.eventType,
                                                   self.attr_read_event,
                                                   stateless=True)

    def unsubscribe_event(self):
        if self.eventId is not None:
            self.device.unsubscribe_event(self.eventId)

    def attr_read_event(self, event):
        if event.err is False:
            t = time.time()
            if (t - self.lastRead) > self.interval:
                if self.rateLimit is True:
                    with self.attrLock:
                        self.attrSignal.emit(event.attr_value)
                else:
                    self.attrSignal.emit(event.attr_value)
                self.lastRead = t

    def attr_read(self):
        replyReady = True
        while self.stopThread is False:
            if self.getInfoFlag is True:
                self.getInfoFlag = False
                try:
                    self.attrInfo = self.device.get_attribute_config(self.name)
                    self.attrInfoSignal.emit(self.attrInfo)

                except pt.DevFailed, e:
                    if e[0].reason == 'API_DeviceTimeOut':
                        print 'AttrInfo Timeout'
                    else:
                        print self.name, '  attrinfo error ', e[0].reason
                    self.attrInfo = pt.AttributeInfoEx()
                    self.attrInfoSignal.emit(self.attrInfo)
                except Exception, e:
                    print self.name, ' recovering from attrInfo ', str(e)
                    self.attrInfo = pt.AttributeInfoEx()
                    self.attrInfoSignal.emit(self.attrInfo)

            t = time.time()

            if t - self.lastRead > self.interval:
                self.lastRead = t
                try:
                    id = self.device.read_attribute_asynch(self.name)

                    replyReady = False
                except pt.DevFailed, e:
                    if e[0].reason == 'API_DeviceTimeOut':
                        print 'Timeout'
                    else:
                        print self.name, ' error ', e[0].reason
                    self.attr = pt.DeviceAttribute()
                    self.attr.quality = pt.AttrQuality.ATTR_INVALID
                    self.attr.value = None
                    self.attr.w_value = None
                    self.attrSignal.emit(self.attr)

                except Exception, e:
                    print self.name, ' recovering from ', str(e)
                    self.attr = pt.DeviceAttribute()
                    self.attr.quality = pt.AttrQuality.ATTR_INVALID
                    self.attr.value = None
                    self.attrSignal.emit(self.attr)
                        self.attr = self.device.read_attribute_reply(id)
                        replyReady = True
                        self.attrSignal.emit(self.attr)
                        print 'signal emitted', self.attr.value.shape
                        # Read only once if interval = None:
                        if self.interval == None:
                            self.stopThread = True
                            self.interval = 0.0
                    except pt.DevFailed, e:
                        if e[0].reason == 'API_AsynReplyNotArrived':
                            #                            print self.name, ' not replied'
                            time.sleep(0.1)
                        else:
                            replyReady = True
                            print 'Error reply ', self.name, str(e)
                            self.attr = pt.DeviceAttribute()
                            self.attr.quality = pt.AttrQuality.ATTR_INVALID
                            self.attr.value = None
                            self.attr.w_value = None
                            self.attrSignal.emit(self.attr)

            if self.interval is not None:
                time.sleep(self.interval)
            else:
                time.sleep(1)
        print self.name, ' waiting for final reply'
        finalTimeout = 1.0  # Wait max 1 s
        finalStartTime = time.time()
        finalTimeoutFlag = False
        while replyReady is False and finalTimeoutFlag is False:
            try:
    def calculate_spectrum(self, result):
        attr_image = result
        self.logger.debug("Calculating spectrum. Type image: {0}".format(
            type(attr_image)))
        with self.controller.state_lock:
            wavelengths = self.controller.camera_result["wavelengths"].value
            max_value = self.controller.camera_result["max_value"].value
        if attr_image is not None:
            quality = attr_image.quality
            a_time = attr_image.time
            spectrum = attr_image.value.sum(0)

            try:
                s_bkg = spectrum[0:10].mean()
                spec_bkg = spectrum - s_bkg
                l_peak = (spec_bkg * wavelengths).sum() / spec_bkg.sum()
                try:
                    dl_rms = np.sqrt(
                        (spec_bkg *
                         (wavelengths - l_peak)**2).sum() / spec_bkg.sum())
                    dl_fwhm = dl_rms * 2 * np.sqrt(2 * np.log(2))
                except RuntimeWarning:
                    dl_rms = None
                    dl_fwhm = None
                nbr_sat = np.double((attr_image.value >= max_value).sum())
                sat_lvl = nbr_sat / np.size(attr_image.value)
            except AttributeError:
                l_peak = 0.0
                dl_fwhm = 0.0
                sat_lvl = 0.0
                quality = tango.AttrQuality.ATTR_INVALID
            except ValueError:
                # Dimension mismatch
                l_peak = 0.0
                dl_fwhm = 0.0
                sat_lvl = 0.0
                quality = tango.AttrQuality.ATTR_INVALID
            self.logger.debug("Spectrum parameters calculated")
            attr = tango.DeviceAttribute()
            attr.name = "spectrum"
            attr.value = spectrum
            attr.time = a_time
            attr.quality = quality
            self.controller.camera_result["spectrum"] = attr
            attr = tango.DeviceAttribute()
            attr.name = "width"
            attr.value = dl_fwhm
            attr.time = a_time
            attr.quality = quality
            self.controller.camera_result["width"] = attr
            attr = tango.DeviceAttribute()
            attr.name = "peak"
            attr.value = l_peak
            attr.time = a_time
            attr.quality = quality
            self.controller.camera_result["peak"] = attr
            attr = tango.DeviceAttribute()
            attr.name = "satlvl"
            attr.value = sat_lvl
            attr.time = a_time
            attr.quality = quality
            self.controller.camera_result["satlvl"] = attr
    def attr_read(self):
        logger.debug("Entering attr_read for \"{0}\"".format(self.name))
        reply_ready = True
        while self.stop_thread_flag is False:
            if self.pause_read_flag is True:
                time.sleep(0.1)
            else:
                if self.get_info_flag is True:
                    self.get_info_flag = False
                    try:
                        self.attr_info = self.device.get_attribute_config(
                            self.name)
                        self.attrInfoSignal.emit(self.attr_info)

                    except pt.DevFailed as e:
                        if e.args[0].reason == 'API_DeviceTimeOut':
                            logger.debug('AttrInfo Timeout')
                        else:
                            logger.debug("{0} attrinfo error: {1}".format(
                                self.name, e.args[0].reason))
                        self.attr_info = pt.AttributeInfoEx()
                        self.attrInfoSignal.emit(self.attr_info)
                    except Exception as e:
                        logger.debug(
                            "{0} recovering from attrInfo error {1}".format(
                                self.name, str(e)))
                        self.attr_info = pt.AttributeInfoEx()
                        self.attrInfoSignal.emit(self.attr_info)

                t = time.time()

                if self.interval is None:
                    dt = 0
                else:
                    dt = self.interval
                if t - self.last_read_time > dt:
                    self.last_read_time = t
                    try:
                        reply_id = self.device.read_attribute_asynch(self.name)

                        reply_ready = False
                    except pt.DevFailed as e:
                        if e.args[0].reason == 'API_DeviceTimeOut':
                            logger.debug("Timeout")
                        else:
                            logger.debug(
                                "{0} read_attribute_asynch error: {1}".format(
                                    self.name, e.args[0].reason))
                        self.attr = pt.DeviceAttribute()
                        self.attr.quality = pt.AttrQuality.ATTR_INVALID
                        self.attr.value = None
                        self.attr.w_value = None
                        self.attrSignal.emit(self.attr)

                    except Exception as e:
                        logger.error("{0} recovering from {1}".format(
                            self.name, str(e)))
                        self.attr = pt.DeviceAttribute()
                        self.attr.quality = pt.AttrQuality.ATTR_INVALID
                        self.attr.value = None
                        self.attrSignal.emit(self.attr)

                    while reply_ready is False and self.stop_thread_flag is False:
                        try:
                            self.attr = self.device.read_attribute_reply(
                                reply_id)
                            reply_ready = True
                            # logger.debug("{0} Reply: {1}".format(self.name, self.attr))
                            self.attrSignal.emit(self.attr)
                            # Read only once if interval = None:
                            if self.interval is None:
                                self.stop_thread_flag = True
                                self.interval = 0.0
                        except pt.DevFailed as e:
                            logger.info("Exception e: {0}".format(e))
                            if isinstance(e, pt.AsynReplyNotArrived):
                                time.sleep(0.1)
                            else:
                                reply_ready = True
                                logger.debug("Error reply {0}: {1}".format(
                                    self.name, str(e)))
                                self.attr = pt.DeviceAttribute()
                                self.attr.quality = pt.AttrQuality.ATTR_INVALID
                                self.attr.value = None
                                self.attr.w_value = None
                                self.attrSignal.emit(self.attr)

                if self.interval is not None:
                    time.sleep(self.interval)
                else:
                    time.sleep(0.2)
        logger.debug("{0} waiting for final reply".format(self.name))
        final_timeout = 1.0  # Wait max 1 s
        final_start_time = time.time()
        final_timeout_flag = False
        while reply_ready is False and final_timeout_flag is False:
            try:
                self.attr = self.device.read_attribute_reply(reply_id)
                reply_ready = True
                self.attrSignal.emit(self.attr)
            except Exception as e:
                if e.args[0].reason == 'API_AsynReplyNotArrived':
                    time.sleep(0.1)
                else:
                    reply_ready = True
                    logger.debug("Error reply {0}: {1}".format(
                        self.name, str(e)))
                    self.attr = pt.DeviceAttribute()
                    self.attr.quality = pt.AttrQuality.ATTR_INVALID
                    self.attr.value = None
                    self.attr.w_value = None
                    self.attrSignal.emit(self.attr)
            if time.time() - final_start_time > final_timeout:
                final_timeout_flag = True
        if final_timeout_flag is False:
            logger.debug("{0}... Thread stopped".format(self.name))
        else:
            logger.debug("{0}... Thread timed out".format(self.name))