예제 #1
0
    def create_listeners(self, attr_name, attr_info_list):
        self.info_stream("Creating Listeners ...")

        attr_to_proxy = attr_info_list[0]
        full_attr_to_proxy = self.LlrfDevice + '/' + attr_to_proxy
        taurus_attr = Attribute(full_attr_to_proxy)

        if len(attr_info_list) == 2:
            r_method = attr_info_list[1]
            self.dyn_attrs_dict[attr_name] = (taurus_attr, r_method)

        elif len(attr_info_list) == 3:
            r_method, w_method = attr_info_list[1::]
            self.dyn_attrs_dict[attr_name] = (taurus_attr, r_method, w_method)
            self.info_stream('w_method = %s' % w_method)

        self.info_stream('r_method = %s' % r_method)

        listener_name = attr_name + 'Listener'
        self.__dict__[listener_name] = taurus.core.TaurusListener(None)
        self.__dict__[listener_name].eventReceived = lambda a, b, c: self._dyn_attr_event_received(a,
                                                                                                   self.__dict__[listener_name],
                                                                                                   c,
                                                                                                   attr_name,
                                                                                                   r_method )
        taurus_attr.addListener(self.__dict__[listener_name])

        self.info_stream('attr_to_proxy = %s' % attr_to_proxy)
예제 #2
0
def test1():
    import numpy
    from taurus import Attribute

    a = Attribute("sys/tg_test/1/ulong64_scalar")

    a.write(numpy.uint64(88))
 def run(self):
     # TODO: This needs to be redone; maybe use string.template?
     try:
         attribute = Attribute(str(self.model) + "/State")
         if attribute:
             value = attribute.read()
             html = json.dumps('Value: ' +
                               '<span class="value">%s</span>'
                               % value.value)
         self.finished.emit(self.model, html)
     except PyTango.DevFailed as e:
         print e
예제 #4
0
    def init_device(self):

        try:
            self.attribute = Attribute(self.model)
            # 
            # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands
            # as defined in Command/Tango.py
            # 
            #if self.attribute.__class__ == taurus.core.tango.tangoattribute.TangoAttribute:
            #    dev = self.attribute.getParentObj()
            #    dp = dev.getHWObj()
            #    try:
            #        dp.subscribe_event = dp._subscribe_event
            #    except AttributeError:
            #        pass
            logging.getLogger("HWR").info("initialized")
        except DevFailed as traceback:
            self.imported = False
            return
        
        # read information
        try:
            self.info.minval, self.info.maxval = self.attribute._TangoAttribute__attr_config.getLimits()
            logging.getLogger("HWR").info("info initialized. Got minval=%s, maxval=%s" %(self.info.minval, self.info.maxval))
        except:
            logging.getLogger("HWR").info("info initialized. Cannot get limits")
       
        
        # prepare polling
        # if the polling value is a number set it as the taurus polling period
        if self.polling:
             if type(self.polling) == int:
                  self.attribute.changePollingPeriod(self.polling)
             
             self.attribute.addListener(self.objectListener)
    def __attribute_listener(self, evt_src, evt_type, evt_value):

        if evt_type in (PyTango.EventType.PERIODIC_EVENT,
                        PyTango.EventType.CHANGE_EVENT):
            name = evt_src.getNormalName()
            if name:
                print "attribute_listener", name
                attr = Attribute(name)
                fmt = attr.getFormat()
                unit = attr.getUnit()
                value = evt_value.value
                if evt_value.type is PyTango._PyTango.CmdArgType.DevState:
                    value_str = str(value)  # e.g. "ON"
                else:
                    value_str = fmt % value  # e.g. "2.40e-5"
                attr_type = str(evt_value.type)
                self.js.evaljs.emit("Synoptic.setAttribute('%s', '%s', '%s', '%s')" %
                                    (name, value_str, attr_type, unit))
 def __init__(self, name, callback):
     print self.__class__.__name__, name
     self.name = name
     self.callback = callback
     self._last_time = 0
     self.last_value_event = None
     self.last_config_event = None
     self.attribute = Attribute(self.name)
     self.attribute.addListener(self)
예제 #7
0
파일: panels.py 프로젝트: hayg25/PyQTDev
 def setModel(self, device):
     print self.__class__.__name__, "setModel", device
     TaurusWidget.setModel(self, device)
     self.device_and_state.setModel(device)
     self.status_area.setModel(device)
     if device:
         self.form.setModel(
             ["%s/%s" % (device, attribute) for attribute in self.attrs])
         attrname = "%s/%s" % (device, "Voltage")
         self.valuebar.setModel(attrname)
         # self.state_button.setModel(device)
         attr = Attribute(attrname)
         self.current_label.setText("%s [%s]" % (attr.label, attr.unit))
     else:
         self.form.setModel(None)
         self.valuebar.setModel(None)
 def _add_listener(self, model):
     try:
         listener = self.listeners[model] = Attribute(model)
         # to make loopkups more efficient, we also keep an "inverted"
         # mapping of listeners->models. But since some models may map
         # to the *same* listener (e.g. eval expressions), this must
         # be a one-to-many map.
         if listener in self.inverse_listeners:
             self.inverse_listeners[listener][model] = True
         else:
             self.inverse_listeners[listener] = CaselessDict([(model, True)
                                                              ])
         listener.addListener(self.handle_event)
         return listener
     except (TaurusException, AttributeError) as e:
         print "Failed to subscribe to model %s! %s" % (model, e)
예제 #9
0
 def PreStartOneCT(self, axis):
     if Ni660XCTCtrl.PreStartOneCT(self, axis) and axis != 1:
         initial_pos_value = self.attributes[axis]['initialpos']
         self.attributes[axis]['initialpos'] = None
         if initial_pos_value is None:
             initial_pos_attr = self.attributes[axis]['initialposattr']
             if len(initial_pos_attr) > 0:
                 attr_value = Attribute(initial_pos_attr).read().value
                 try:
                     initial_pos_value = float(attr_value)
                 except ValueError:
                     msg = "initialPosAttr (%s) is not float" % initial_pos_attr
                     raise Exception(msg)
             else:
                 initial_pos_value = 0
         self.attributes[axis]["initialposvalue"] = initial_pos_value
     return True
예제 #10
0
    def init_device(self):

        try:
            self.attribute = Attribute(self.model)
            #
            # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands
            # as defined in Command/Tango.py
            #
            # if self.attribute.__class__ == taurus.core.tango.tangoattribute.TangoAttribute:
            #    dev = self.attribute.getParentObj()
            #    dp = dev.getHWObj()
            #    try:
            #        dp.subscribe_event = dp._subscribe_event
            #    except AttributeError:
            #        pass
            # logging.getLogger("HWR").debug("initialized")
        except DevFailed as traceback:
            self.imported = False
            return

        # read information
        try:
            if taurus.Release.version_info[0] == 3:
                ranges = self.attribute.getConfig().getRanges()
                if ranges is not None and ranges[0] != "Not specified":
                    self.info.minval = float(ranges[0])
                if ranges is not None and ranges[-1] != "Not specified":
                    self.info.maxval = float(ranges[-1])
            elif taurus.Release.version_info[0] > 3:  # taurus 4 and beyond
                minval, maxval = self.attribute.ranges()
                self.info.minval = minval.magnitude
                self.info.maxval = maxval.magnitude
        except BaseException:
            import traceback

            logging.getLogger("HWR").info("info initialized. Cannot get limits")
            logging.getLogger("HWR").info("%s" % traceback.format_exc())

        # prepare polling
        # if the polling value is a number set it as the taurus polling period

        if self.polling:
            if isinstance(self.polling, types.IntType):
                self.attribute.changePollingPeriod(self.polling)

            self.attribute.addListener(self.objectListener)
예제 #11
0
    def init_device(self):

        try:
            self.attribute = Attribute(self.model)
            #
            # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands
            # as defined in Command/Tango.py
            #
            #if self.attribute.__class__ == taurus.core.tango.tangoattribute.TangoAttribute:
            #    dev = self.attribute.getParentObj()
            #    dp = dev.getHWObj()
            #    try:
            #        dp.subscribe_event = dp._subscribe_event
            #    except AttributeError:
            #        pass
            #logging.getLogger("HWR").debug("initialized")
        except DevFailed, traceback:
            self.imported = False
            return
예제 #12
0
    def __get_t3_name(self, item):
        # check if the item is a device name or an attribute name
        try:
            proxy = Device(item)
        except TaurusException:
            try:
                proxy = Attribute(item)
            except TaurusException:
                raise KeyError(item)

        v = proxy.getNameValidator()
        params = v.getParams(proxy.getFullName())
        name = '{0}:{1}/{2}'.format(params['host'].split('.')[0],
                                    params['port'], params['devicename'])

        attr_name = params.get('attributename', None)
        if attr_name is not None:
            name = '{0}/{1}'.format(name, params['attributename'])

        return name
예제 #13
0
 def setModel(self, device):
     print self.__class__.__name__, "setModel", device
     TaurusWidget.setModel(self, device)
     self.device_and_state.setModel(device)
     if device:
         self.form.setModel(["%s/%s" % (device, attribute)
                             for attribute in self.attrs])
         db = PyTango.Database()
         magnet = db.get_device_property(device, "MagnetProxies")["MagnetProxies"][0]
         magnet_type = PyTango.Database().get_device_property(magnet, "Type")["Type"][0]
         self.magnet_type_label.setText("Magnet type: <b>%s</b>" % magnet_type)
         attrname = "%s/%s" % (device, "MainFieldComponent")
         self.valuebar.setModel(attrname)
         attr = Attribute(attrname)
         self.current_label.setText("%s [%s]" % (attr.label, attr.unit))
         self.status_area.setModel(device)
     else:
         self.form.setModel(None)
         self.valuebar.setModel(None)
         self.status_area.setModel(None)
예제 #14
0
    def setModel(self, attrs):
        if not attrs:
            for att, col in zip(self.attributes, self._columns):
                att and att.removeListener(col.event_received)
        else:
            try:
                TaurusWidget.setModel(self, attrs[0].rsplit("/", 1)[0])
                self.attributes = [Attribute(a) for a in attrs]

                self.table.setColumnCount(len(attrs))
                fmt = "%s [%s]"
                labels = []
                for a in self.attributes:
                    config = a.getConfig()
                    label = fmt % (config.getLabel(), config.getUnit())
                    labels.append(label)

                self.table.setHorizontalHeaderLabels(labels)
                header = self.table.horizontalHeader()
                header.setResizeMode(QtGui.QHeaderView.Stretch)

                # Check if there are any columns at all
                row_lengths = [len(a.read().value) for a in self.attributes
                               if a.read().quality == PyTango.AttrQuality.ATTR_VALID]
                if not any(row_lengths):
                    return None
                self.table.setRowCount(max(row_lengths))

                self._values = {}
                self._config = {}
                self._columns = []

                for i, att in enumerate(self.attributes):
                    # JFF: this is a workaround for a behavior in Taurus. Just
                    # adding a new listener to each attribute does not work, the
                    # previous ones get removed for some reason.
                    col = AttributeColumn(self, i)
                    self._columns.append(col)  # keep reference to prevent GC
                    att.addListener(col.event_received)
            except PyTango.DevFailed:
                pass
예제 #15
0
    def setModel(self, devices, attributes=[]):
        if not devices:
            for dev, attrs in self.attributes.items():
                for att in attrs:
                    att and att.removeListener(
                        self._items[dev][att.name].event_received)
        else:
            try:
                # TaurusWidget.setModel(self, attrs[0].rsplit("/", 1)[0])
                attrnames = [a[0] if isinstance(a, tuple) else a
                             for a in attributes]
                self.attributes = dict((dev, [Attribute("%s/%s" % (dev, a))
                                              for a in attrnames])
                                       for dev in devices)

                self.table.setColumnCount(len(attributes) + 1)
                colnames = [a[1] if isinstance(a, tuple) else a
                            for a in attributes]
                labels = ["Device"] + colnames
                self.table.setHorizontalHeaderLabels(labels)
                header = self.table.horizontalHeader()
                header.setResizeMode(QtGui.QHeaderView.Stretch)

                # Check if there are any columns at all
                self.table.setRowCount(len(devices))

                for r, (dev, attrs) in enumerate(self.attributes.items()):
                    item = QtGui.QTableWidgetItem(dev)
                    item.setFlags(QtCore.Qt.ItemIsSelectable |
                                  QtCore.Qt.ItemIsEnabled)
                    self.table.setItem(r, 0, item)
                    for c, att in enumerate(attrs, 1):
                        # JFF: this is a workaround for a behavior in Taurus. Just
                        # adding a new listener to each attribute does not work, the
                        # previous ones get removed for some reason.
                        item = TableItem(self.trigger)
                        self.table.setItem(r, c, item)
                        att.addListener(item.event_received)

            except PyTango.DevFailed:
                pass
예제 #16
0
 def attribute(self):
     return Attribute(self.name)
class TaurusPlotDataItem(PlotDataItem, TaurusBaseComponent):
    """A taurus-ified PlotDataItem"""
    def __init__(self, *args, **kwargs):
        """
        Accepts same args and kwargs as PlotDataItem, plus:
        :param xModel: (str) Taurus model name for abscissas values.
                       Default=None
        :param yModel: (str) Taurus model name for ordinate values.
                       Default=None
        """
        xModel = kwargs.pop('xModel', None)
        yModel = kwargs.pop('yModel', None)
        PlotDataItem.__init__(self, *args, **kwargs)
        TaurusBaseComponent.__init__(self, 'TaurusBaseComponent')
        self._x = None
        self._y = None
        self.xModel = None
        if xModel is not None:
            self.setXModel(xModel)
        if yModel is not None:
            self.setModel(yModel)

        self.registerConfigProperty(self.getOpts, self.setOpts, 'opts')
        self.setModelInConfig(True)
        self.registerConfigProperty(self.getXModelName, self.setXModel,
                                    'XModel')

    def setXModel(self, xModel):
        if not xModel:
            if self.xModel is not None:
                self.xModel.removeListener(self)
            self.xModel = None
            return
        self.xModel = Attribute(xModel)
        self._x = self.xModel.read().rvalue
        self.xModel.addListener(self)

    def getXModelName(self):
        if self.xModel is None:
            return None
        else:
            return self.xModel.getFullName()

    def handleEvent(self, evt_src, evt_type, evt_value):
        if evt_type not in (TaurusEventType.Change, TaurusEventType.Periodic):
            return
        yModel = self.getModelObj()
        if yModel == evt_src and yModel is not None:
            self._y = evt_value.rvalue
        if self.xModel == evt_src and self.xModel is not None:
            self._x = evt_value.rvalue
        self.setData(x=self._x, y=self._y)

    def getOpts(self):
        from taurus.qt.qtgui.tpg import serialize_opts
        return serialize_opts(copy.copy(self.opts))

    def setOpts(self, opts):
        # creates QPainters (QPen or QBrush) from a pickle loaded file
        # for adapt the serialized objects into PlotDataItem properties

        from taurus.qt.qtgui.tpg import deserialize_opts
        self.opts = deserialize_opts(opts)

        # This is a workaround for the following pyqtgraph's bug:
        # https://github.com/pyqtgraph/pyqtgraph/issues/531
        if opts['connect'] == 'all':
            self.opts['connect'] = 'all'
        elif opts['connect'] == 'pairs':
            self.opts['connect'] = 'pairs'
        elif opts['connect'] == 'finite':
            self.opts['connect'] = 'finite'

    def getFullModelNames(self):
        return (self.getXModelName(), self.getFullModelName())
예제 #18
0
 def onSelectionChanged(self, models):
     if self._oldModels in [None, []]:
         self._attrDict = {}
         for model in models:
             try:
                 attr = Attribute(model)
             except:
                 # old PyTango versions do not handle unicode
                 attr = Attribute(str(model))
             #force a read -> attr.read()
             attr.addListener(self)
             legend = qt.safe_str(attr.getNormalName())
             self._attrDict[legend] = attr
         self._oldModels = models
     else:
         keptModels = []
         newModels = []
         for model in models:
             if model in self._oldModels:
                 keptModels.append(model)
             else:
                 newModels.append(model)
         for model in self._oldModels:
             if model not in keptModels:
                 attr = Attribute(model)
                 attr.removeListener(self)
                 legend = qt.safe_str(attr.getNormalName())
                 if legend in self._attrDict:
                     del self._attrDict[legend]
                 print("Trying to remove ", legend)
                 self.removeCurve(legend, replot=False)
         for model in newModels:
             attr = Attribute(model)
             # attr.read()
             attr.addListener(self)
             legend = qt.safe_str(attr.getNormalName())
             self._attrDict[legend] = attr
         self._oldModels = keptModels + newModels
class TaurusAttribute(object):
    """This object is a listener for the taurus attribute value.
    When a attribute changes it sends an event. The event
    triggers a call to *eventReceived*. *eventReceived* will transform
    the change event into a JSON encoded string and sends this
    string through the web socket to the client"""

    def __init__(self, name, callback):
        print self.__class__.__name__, name
        self.name = name
        self.callback = callback
        self._last_time = 0
        self.last_value_event = None
        self.last_config_event = None
        self.attribute = Attribute(self.name)
        self.attribute.addListener(self)

    def eventReceived(self, evt_src, evt_type, evt_value):
        """Transforms the event into a JSON encoded string and sends this
        string into the web socket"""

        modelObj = evt_src
        data = {}
        if evt_type == TaurusEventType.Error:
            data["event_type"] = "error"
            data["error"] = error_str(evt_value)
        else:
            if evt_type == TaurusEventType.Config:
                modelObj = evt_src.getParentObj()
                data['event_type'] = "config"
                data['description'] = evt_src.description
                data['label'] = evt_src.label
                data["unit"] = evt_src.unit if evt_src.unit != "No unit" else ""
                data["format"] = evt_src.format
                self.last_config_event = data
            else:
                self._last_time = evt_value.time.tv_sec
                data["event_type"] = "value"
                value = evt_value.value
                quality = evt_value.quality
                fmt = evt_value.data_format
                if fmt == DataFormat._0D:
                    html = modelObj.displayValue(value)
                    if isinstance(value, PyTango._PyTango.DevState):
                        value = value.name
                    if isinstance(value, str):
                        html = value.replace("\n", "<br>")
                elif fmt in (DataFormat._1D, DataFormat._2D):
                    # bad, very bad performance! Don't worry for now
                    value = value.tolist()
                    html = "[...]"
                data['value'] = value
                data['html'] = html
                data['quality'] = str(quality)
                data['time'] = evt_value.time.tv_sec
                data['type'] = str(evt_value.type)  # can this change..?
                self.last_value_event = data

        data['model'] = modelObj.getNormalName()
        self.write_message(data)

    def write_message(self, message):
        self.callback(message)

    def clear(self):
        try:
            print "clear", self.attribute
            self.attribute.removeListener(self)
            del self.attribute

        except PyTango.DevFailed as e:
            print >>sys.stderr, "Could not unsubscribe %s: %r" % (self.name, e)
예제 #20
0
    def image(self, taurusmodel=None, **kwargs):
        """
        Extension to meth:`guiqwt.builder.PlotItemBuilder.image` to support passing a
        'taurusmodel' as a keyword argument instead passing 'data' or 'filename'.
        """
        if taurusmodel is None:
            image = guiqwt.builder.PlotItemBuilder.image(self, **kwargs)
        else:
            title = kwargs.get('title', taurusmodel)
            data = kwargs.get('data', None)
            filename = kwargs.get('filename', None)
            alpha_mask = kwargs.get('alpha_mask', None)
            alpha = kwargs.get('alpha', None)
            background_color = kwargs.get('background_color', None)
            colormap = kwargs.get('colormap', None)
            xdata = kwargs.get('xdata', [None, None])
            ydata = kwargs.get('ydata', [None, None])
            pixel_size = kwargs.get('pixel_size', None)
            interpolation = kwargs.get('interpolation', 'linear')
            eliminate_outliers = kwargs.get('eliminate_outliers', None)
            xformat = kwargs.get('xformat', '%.1f')
            yformat = kwargs.get('yformat', '%.1f')
            zformat = kwargs.get('zformat', '%.1f')
            forceRGB = kwargs.get('force_rgb', False)

            assert isinstance(xdata, (tuple, list)) and len(xdata) == 2
            assert isinstance(ydata, (tuple, list)) and len(ydata) == 2
            assert filename is None
            assert data is None

            param = ImageParam(title=_("Image"), icon='image.png')

            from taurus import Attribute
            if pixel_size is None:
                xmin, xmax = xdata
                ymin, ymax = ydata
            else:
                attr = Attribute(taurusmodel)
                valueobj = attr.read()
                data = getattr(valueobj, 'rvalue', numpy.zeros((1, 1)))
                attrdata = data
                if isinstance(data, Quantity):
                    attrdata = data.magnitude
                xmin, xmax, ymin, ymax = self.compute_bounds(attrdata,
                                                             pixel_size)

            self.set_image_param(param, title, alpha_mask, alpha, interpolation,
                                 background=background_color,
                                 colormap=colormap,
                                 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
                                 xformat=xformat, yformat=yformat,
                                 zformat=zformat)

            from taurus.core import DataType
            if forceRGB:
                if Attribute(taurusmodel).getType() == DataType.DevEncoded:
                    image = TaurusEncodedRGBImageItem(param)
                else:
                    image = TaurusRGBImageItem(param)
            else:
                if Attribute(taurusmodel).getType() == DataType.DevEncoded:
                    image = TaurusEncodedImageItem(param)
                else:
                    image = TaurusImageItem(param)
            image.setModel(taurusmodel)
            if eliminate_outliers is not None:
                image.set_lut_range(lut_range_threshold(image, 256,
                                                        eliminate_outliers))

        return image
예제 #21
0
 def ReadOne(self, axis):
     attr = Attribute(self._axes_taurus_attr[axis])
     return attr.read().value
예제 #22
0
class TaurusAttribute(object):
    """This object is a listener for the taurus attribute value.
    When a attribute changes it sends an event. The event
    triggers a call to *eventReceived*. *eventReceived* will transform
    the change event into a JSON encoded string and sends this
    string through the web socket to the client"""
    def __init__(self, name, callback):
        print self.__class__.__name__, name
        self.name = name
        self.callback = callback
        self._last_time = 0
        self.last_value_event = None
        self.last_config_event = None
        self.attribute = Attribute(self.name)
        self.attribute.addListener(self)

    def eventReceived(self, evt_src, evt_type, evt_value):
        """Transforms the event into a JSON encoded string and sends this
        string into the web socket"""

        modelObj = evt_src
        data = {}
        if evt_type == TaurusEventType.Error:
            data["event_type"] = "error"
            data["error"] = error_str(evt_value)
        else:
            if evt_type == TaurusEventType.Config:
                modelObj = evt_src.getParentObj()
                data['event_type'] = "config"
                data['description'] = evt_src.description
                data['label'] = evt_src.label
                data[
                    "unit"] = evt_src.unit if evt_src.unit != "No unit" else ""
                data["format"] = evt_src.format
                self.last_config_event = data
            else:
                self._last_time = evt_value.time.tv_sec
                data["event_type"] = "value"
                value = evt_value.value
                quality = evt_value.quality
                fmt = evt_value.data_format
                if fmt == DataFormat._0D:
                    html = modelObj.displayValue(value)
                    if isinstance(value, PyTango._PyTango.DevState):
                        value = value.name
                    if isinstance(value, str):
                        html = value.replace("\n", "<br>")
                elif fmt in (DataFormat._1D, DataFormat._2D):
                    # bad, very bad performance! Don't worry for now
                    value = value.tolist()
                    html = "[...]"
                data['value'] = value
                data['html'] = html
                data['quality'] = str(quality)
                data['time'] = evt_value.time.tv_sec
                data['type'] = str(evt_value.type)  # can this change..?
                self.last_value_event = data

        data['model'] = modelObj.getNormalName()
        self.write_message(data)

    def write_message(self, message):
        self.callback(message)

    def clear(self):
        try:
            print "clear", self.attribute
            self.attribute.removeListener(self)
            del self.attribute

        except PyTango.DevFailed as e:
            print >> sys.stderr, "Could not unsubscribe %s: %r" % (self.name,
                                                                   e)
예제 #23
0
 def ReadOne(self, axis):
     attr = Attribute(self._axes_taurus_attr[axis])
     return attr.read().value
예제 #24
0
 def onSelectionChanged(self, models):
     if self._oldModels in [None, []]:
         for model in models:
             attr = Attribute(model)
             #force a read -> attr.read()
             attr.addListener(self)
         self._oldModels = models
     else:
         keptModels = []
         newModels = []
         for model in models:
             if model in self._oldModels:
                 keptModels.append(model)
             else:
                 newModels.append(model)
         for model in self._oldModels:
             if model not in newModels:
                 attr = Attribute(model)
                 attr.removeListener(self)
                 legend = attr.getNormalName()
                 print("Trying to remove ", legend)
                 self.removeCurve(legend, replot=False)
         for model in newModels:
             attr = Attribute(model)
             # attr.read()
             attr.addListener(self)
         self._oldModels = keptModels + newModels
예제 #25
0
def test1():
    import numpy
    from taurus import Attribute
    a = Attribute('sys/tg_test/1/ulong64_scalar')

    a.write(numpy.uint64(88))
예제 #26
0
class SardanaChannel(ChannelObject, SardanaObject):

    def __init__(self, name, attribute_name, username=None, uribase = None, polling=None, **kwargs):

        super(SardanaChannel, self).__init__(name,username,**kwargs)
 
        class ChannelInfo(object):
            def __init__(self):
                super(ChannelInfo, self).__init__()

        self.attributeName = attribute_name
        self.model = os.path.join( uribase, attribute_name )
        self.attribute = None

        self.value = None
        self.polling = polling

        self.info = ChannelInfo()
        self.info.minval = None
        self.info.maxval = None

        logging.getLogger("HWR").debug("creating Sardana model %s, polling=%s", self.model, polling)

        self.init_device()

    def init_device(self):

        try:
            self.attribute = Attribute(self.model)
            # 
            # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands
            # as defined in Command/Tango.py
            # 
            #if self.attribute.__class__ == taurus.core.tango.tangoattribute.TangoAttribute:
            #    dev = self.attribute.getParentObj()
            #    dp = dev.getHWObj()
            #    try:
            #        dp.subscribe_event = dp._subscribe_event
            #    except AttributeError:
            #        pass
            logging.getLogger("HWR").info("initialized")
        except DevFailed as traceback:
            self.imported = False
            return
        
        # read information
        try:
            self.info.minval, self.info.maxval = self.attribute._TangoAttribute__attr_config.getLimits()
            logging.getLogger("HWR").info("info initialized. Got minval=%s, maxval=%s" %(self.info.minval, self.info.maxval))
        except:
            logging.getLogger("HWR").info("info initialized. Cannot get limits")
       
        
        # prepare polling
        # if the polling value is a number set it as the taurus polling period
        if self.polling:
             if type(self.polling) == int:
                  self.attribute.changePollingPeriod(self.polling)
             
             self.attribute.addListener(self.objectListener)

    def getValue(self):
        return self._readValue()

    def setValue(self, newValue, wait=False):
        self._writeValue(newValue)
 
    def _writeValue(self, newValue):
        self.attribute.write(newValue)
            
    def _readValue(self):
        value = self.attribute.read().value
        return value
            
    def getInfo(self):
        return self.info

    def update(self, event):

        data = event.event[2]
        
        try:
            newvalue = data.value

            if newvalue == None:
                newvalue = self.getValue()
    
            if type(newvalue) == tuple:
                newvalue = list(newvalue)
    
            self.value = newvalue
            self.emit('update', self.value)
        except AttributeError:
            # No value in data... this is probably a connection error
            pass

    def isConnected(self):
        return self.attribute is not None

    def channelListener(self,*args):
        ev = AttributeEvent(args)
        SardanaChannel._eventReceivers[id(ev)] = saferef.safe_ref(self.update)
        SardanaChannel._eventsQueue.put(ev)
        SardanaChannel._eventsProcessingTimer.send()
예제 #27
0
 def onSelectionChanged(self, models):
     if self._oldModels in [None, []]:
         self._attrDict = {}
         for model in models:
             try:
                 attr = Attribute(model)
             except:
                 # old PyTango versions do not handle unicode
                 attr = Attribute(str(model))
             #force a read -> attr.read()
             attr.addListener(self)
             legend = qt.safe_str(attr.getNormalName())
             self._attrDict[legend] = attr
         self._oldModels = models
     else:
         keptModels = []
         newModels = []
         for model in models:
             if model in self._oldModels:
                 keptModels.append(model)
             else:
                 newModels.append(model)
         for model in self._oldModels:
             if model not in keptModels:
                 attr = Attribute(model)
                 attr.removeListener(self)
                 legend = qt.safe_str(attr.getNormalName())
                 if legend in self._attrDict:
                     del self._attrDict[legend]
                 print("Trying to remove ", legend)
                 self.removeCurve(legend, replot=False)
         for model in newModels:
             attr = Attribute(model)
             # attr.read()
             attr.addListener(self)
             legend = qt.safe_str(attr.getNormalName())
             self._attrDict[legend] = attr
         self._oldModels = keptModels + newModels
예제 #28
0
class SardanaChannel(ChannelObject, SardanaObject):
    def __init__(
        self, name, attribute_name, username=None, uribase=None, polling=None, **kwargs
    ):

        super(SardanaChannel, self).__init__(name, username, **kwargs)

        class ChannelInfo(object):
            def __init__(self):
                super(ChannelInfo, self).__init__()

        self.attributeName = attribute_name
        self.model = os.path.join(uribase, attribute_name)
        self.attribute = None

        self.value = None
        self.polling = polling

        self.info = ChannelInfo()
        self.info.minval = None
        self.info.maxval = None

        self.init_device()

    def init_device(self):

        try:
            self.attribute = Attribute(self.model)
            #
            # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands
            # as defined in Command/Tango.py
            #
            # if self.attribute.__class__ == taurus.core.tango.tangoattribute.TangoAttribute:
            #    dev = self.attribute.getParentObj()
            #    dp = dev.getHWObj()
            #    try:
            #        dp.subscribe_event = dp._subscribe_event
            #    except AttributeError:
            #        pass
            # logging.getLogger("HWR").debug("initialized")
        except DevFailed as traceback:
            self.imported = False
            return

        # read information
        try:
            if taurus.Release.version_info[0] == 3:
                ranges = self.attribute.getConfig().getRanges()
                if ranges is not None and ranges[0] != "Not specified":
                    self.info.minval = float(ranges[0])
                if ranges is not None and ranges[-1] != "Not specified":
                    self.info.maxval = float(ranges[-1])
            elif taurus.Release.version_info[0] > 3:  # taurus 4 and beyond
                minval, maxval = self.attribute.ranges()
                self.info.minval = minval.magnitude
                self.info.maxval = maxval.magnitude
        except BaseException:
            import traceback

            logging.getLogger("HWR").info("info initialized. Cannot get limits")
            logging.getLogger("HWR").info("%s" % traceback.format_exc())

        # prepare polling
        # if the polling value is a number set it as the taurus polling period

        if self.polling:
            if isinstance(self.polling, types.IntType):
                self.attribute.changePollingPeriod(self.polling)

            self.attribute.addListener(self.objectListener)

    def getValue(self):
        return self._readValue()

    def setValue(self, newValue):
        self._writeValue(newValue)

    def _writeValue(self, newValue):
        self.attribute.write(newValue)

    def _readValue(self):
        value = self.attribute.read().value
        return value

    def getInfo(self):
        try:
            b = dir(self.attribute)
            self.info.minval, self.info.maxval = (
                self.attribute._TangoAttribute__attr_config.getLimits()
            )
        except BaseException:
            import traceback

            logging.getLogger("HWR").info("%s" % traceback.format_exc())
        return self.info

    def update(self, event):

        data = event.event[2]

        try:
            newvalue = data.value

            if newvalue is None:
                newvalue = self.getValue()

            if isinstance(newvalue, types.TupleType):
                newvalue = list(newvalue)

            self.value = newvalue
            self.emit("update", self.value)
        except AttributeError:
            # No value in data... this is probably a connection error
            pass

    def isConnected(self):
        return self.attribute is not None

    def channelListener(self, *args):
        ev = AttributeEvent(args)
        SardanaChannel._eventReceivers[id(ev)] = saferef.safe_ref(self.update)
        SardanaChannel._eventsQueue.put(ev)
        SardanaChannel._eventsProcessingTimer.send()
class TaurusPlotDataItem(PlotDataItem, TaurusBaseComponent):
    """A taurus-ified PlotDataItem"""

    def __init__(self, *args, **kwargs):
        """
        Accepts same args and kwargs as PlotDataItem, plus:
        :param xModel: (str) Taurus model name for abscissas values.
                       Default=None
        :param yModel: (str) Taurus model name for ordinate values.
                       Default=None
        :param colors: (generator) An infinite generator of QColor objects
        """
        xModel = kwargs.pop("xModel", None)
        yModel = kwargs.pop("yModel", None)
        colors = kwargs.pop("colors", LoopList(CURVE_COLORS))
        if "pen" not in kwargs:
            kwargs["pen"] = next(colors)
        PlotDataItem.__init__(self, *args, **kwargs)
        TaurusBaseComponent.__init__(self, "TaurusBaseComponent")
        self._x = None
        self._y = None
        self.xModel = None
        if xModel is not None:
            self.setXModel(xModel)
        if yModel is not None:
            self.setModel(yModel)

        self.registerConfigProperty(self.getOpts, self.setOpts, "opts")
        self.setModelInConfig(True)
        self.registerConfigProperty(
            self.getXModelName, self.setXModel, "XModel"
        )

    def setXModel(self, xModel):
        if self.xModel is not None:
            self.xModel.removeListener(self)

        if not xModel:
            self.xModel = None
            return

        self.xModel = Attribute(xModel)
        self.xModel.addListener(self)

    def getXModelName(self):
        if self.xModel is None:
            return None
        else:
            return self.xModel.getFullName()

    def handleEvent(self, evt_src, evt_type, evt_value):
        if evt_type not in (TaurusEventType.Change, TaurusEventType.Periodic):
            return
        yModel = self.getModelObj()
        if yModel == evt_src:
            if yModel is not None:
                self._y = evt_value.rvalue
            else:
                self._y = None
        if self.xModel == evt_src:
            if self.xModel is not None:
                self._x = evt_value.rvalue
            else:
                self._x = None
        try:
            self.setData(x=self._x, y=self._y)
        except Exception as e:
            self.debug("Could not set data. Reason: %r", e)

    def getOpts(self):
        from taurus_pyqtgraph import serialize_opts

        return serialize_opts(copy.copy(self.opts))

    def setOpts(self, opts):
        # creates QPainters (QPen or QBrush) from a pickle loaded file
        # for adapt the serialized objects into PlotDataItem properties

        from taurus_pyqtgraph import deserialize_opts

        self.opts = deserialize_opts(opts)

        # This is a workaround for the following pyqtgraph's bug:
        # https://github.com/pyqtgraph/pyqtgraph/issues/531
        if opts["connect"] == "all":
            self.opts["connect"] = "all"
        elif opts["connect"] == "pairs":
            self.opts["connect"] = "pairs"
        elif opts["connect"] == "finite":
            self.opts["connect"] = "finite"

    def getFullModelNames(self):
        return (self.getXModelName(), self.getFullModelName())
예제 #30
0
class SardanaChannel(ChannelObject, SardanaObject):
    def __init__(self,
                 name,
                 attribute_name,
                 username=None,
                 uribase=None,
                 polling=None,
                 **kwargs):

        super(SardanaChannel, self).__init__(name, username, **kwargs)

        class ChannelInfo(object):
            def __init__(self):
                super(ChannelInfo, self).__init__()

        self.attributeName = attribute_name
        self.model = os.path.join(uribase, attribute_name)
        self.attribute = None

        self.value = None
        self.polling = polling

        self.info = ChannelInfo()
        self.info.minval = None
        self.info.maxval = None

        self.init_device()

    def init_device(self):

        try:
            self.attribute = Attribute(self.model)
            #
            # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands
            # as defined in Command/Tango.py
            #
            # if self.attribute.__class__ == taurus.core.tango.tangoattribute.TangoAttribute:
            #    dev = self.attribute.getParentObj()
            #    dp = dev.getHWObj()
            #    try:
            #        dp.subscribe_event = dp._subscribe_event
            #    except AttributeError:
            #        pass
            # logging.getLogger("HWR").debug("initialized")
        except DevFailed as traceback:
            self.imported = False
            return

        # read information
        try:
            if taurus.Release.version_info[0] == 3:
                ranges = self.attribute.getConfig().getRanges()
                if ranges is not None and ranges[0] != "Not specified":
                    self.info.minval = float(ranges[0])
                if ranges is not None and ranges[-1] != "Not specified":
                    self.info.maxval = float(ranges[-1])
            elif taurus.Release.version_info[0] > 3:  # taurus 4 and beyond
                minval, maxval = self.attribute.ranges()
                self.info.minval = minval.magnitude
                self.info.maxval = maxval.magnitude
        except BaseException:
            import traceback

            logging.getLogger("HWR").info(
                "info initialized. Cannot get limits")
            logging.getLogger("HWR").info("%s" % traceback.format_exc())

        # prepare polling
        # if the polling value is a number set it as the taurus polling period

        if self.polling:
            if isinstance(self.polling, types.IntType):
                self.attribute.changePollingPeriod(self.polling)

            self.attribute.addListener(self.objectListener)

    def getValue(self):
        return self._readValue()

    def setValue(self, newValue):
        self._writeValue(newValue)

    def _writeValue(self, newValue):
        self.attribute.write(newValue)

    def _readValue(self):
        value = self.attribute.read().value
        return value

    def getInfo(self):
        try:
            b = dir(self.attribute)
            self.info.minval, self.info.maxval = (
                self.attribute._TangoAttribute__attr_config.getLimits())
        except BaseException:
            import traceback

            logging.getLogger("HWR").info("%s" % traceback.format_exc())
        return self.info

    def update(self, event):

        data = event.event[2]

        try:
            newvalue = data.value

            if newvalue is None:
                newvalue = self.getValue()

            if isinstance(newvalue, types.TupleType):
                newvalue = list(newvalue)

            self.value = newvalue
            self.emit("update", self.value)
        except AttributeError:
            # No value in data... this is probably a connection error
            pass

    def isConnected(self):
        return self.attribute is not None

    def channelListener(self, *args):
        ev = AttributeEvent(args)
        SardanaChannel._eventReceivers[id(ev)] = saferef.safe_ref(self.update)
        SardanaChannel._eventsQueue.put(ev)
        SardanaChannel._eventsProcessingTimer.send()
예제 #31
0
class SardanaChannel(ChannelObject, SardanaObject):
    def __init__(self,
                 name,
                 attribute_name,
                 username=None,
                 uribase=None,
                 polling=None,
                 **kwargs):

        super(SardanaChannel, self).__init__(name, username, **kwargs)

        class ChannelInfo(object):
            def __init__(self):
                super(ChannelInfo, self).__init__()

        self.attributeName = attribute_name
        self.model = os.path.join(uribase, attribute_name)
        self.attribute = None

        self.value = None
        self.polling = polling

        self.info = ChannelInfo()
        self.info.minval = None
        self.info.maxval = None

        logging.getLogger("HWR").debug("creating Sardana model %s, polling=%s",
                                       self.model, polling)

        self.init_device()

    def init_device(self):

        try:
            self.attribute = Attribute(self.model)
            #
            # DIRTY FIX to make compatible taurus listeners and existence of Tango channels/commands
            # as defined in Command/Tango.py
            #
            #if self.attribute.__class__ == taurus.core.tango.tangoattribute.TangoAttribute:
            #    dev = self.attribute.getParentObj()
            #    dp = dev.getHWObj()
            #    try:
            #        dp.subscribe_event = dp._subscribe_event
            #    except AttributeError:
            #        pass
            logging.getLogger("HWR").info("initialized")
        except DevFailed as traceback:
            self.imported = False
            return

        # read information
        try:
            self.info.minval, self.info.maxval = self.attribute._TangoAttribute__attr_config.getLimits(
            )
            logging.getLogger("HWR").info(
                "info initialized. Got minval=%s, maxval=%s" %
                (self.info.minval, self.info.maxval))
        except:
            logging.getLogger("HWR").info(
                "info initialized. Cannot get limits")

        # prepare polling
        # if the polling value is a number set it as the taurus polling period
        if self.polling:
            if type(self.polling) == int:
                self.attribute.changePollingPeriod(self.polling)

            self.attribute.addListener(self.objectListener)

    def getValue(self):
        return self._readValue()

    def setValue(self, newValue, wait=False):
        self._writeValue(newValue)

    def _writeValue(self, newValue):
        self.attribute.write(newValue)

    def _readValue(self):
        value = self.attribute.read().value
        return value

    def getInfo(self):
        return self.info

    def update(self, event):

        data = event.event[2]

        try:
            newvalue = data.value

            if newvalue == None:
                newvalue = self.getValue()

            if type(newvalue) == tuple:
                newvalue = list(newvalue)

            self.value = newvalue
            self.emit('update', self.value)
        except AttributeError:
            # No value in data... this is probably a connection error
            pass

    def isConnected(self):
        return self.attribute is not None

    def channelListener(self, *args):
        ev = AttributeEvent(args)
        SardanaChannel._eventReceivers[id(ev)] = saferef.safe_ref(self.update)
        SardanaChannel._eventsQueue.put(ev)
        SardanaChannel._eventsProcessingTimer.send()