示例#1
0
 def subscribe(self, models=[]):
     """Set the currently subscribed list of models."""
     attrs = CaselessDict()
     taurusattrs = self._taurus_attributes
     for model in models:
         if self.device_validator.isValid(model):
             # for convenience, we subscribe to State for any devices
             modelstate = model + "/State"
             attrs[modelstate] = True
             if modelstate not in taurusattrs.keys():
                 try:
                     taurusattrs[modelstate] = Attribute(modelstate)
                 except TaurusException as e:
                     print "Failed to create Taurus Attribute for model %s! %s" % (
                         model, e)
         elif (self.attribute_validator.isValid(model)
               or self.eval_validator.isValid(model)):
             attrs[model] = True
             if model not in taurusattrs.keys():
                 try:
                     taurusattrs[model] = Attribute(model)
                 except TaurusException as e:
                     print "Failed to create Taurus Attribute for model %s! %s" % (
                         model, e)
                 except Exception as e:
                     print "Failed to create Taurus Attribute for model %s!" % (
                         model)
         else:
             print "Invalid Taurus model %s!?" % model
     self._attributes = attrs
     self._taurus_attributes = taurusattrs
示例#2
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
示例#3
0
 def setModel(self, model):
     if model:
         split_model = model.split("/")
         if len(split_model) < 4:
             self.status = Attribute("%s/Status" % model)
         else:
             self.status = Attribute(model)
         self.status.addListener(self.onStatusChange)
     else:
         self.status and self.status.removeListener(self.onStatusChange)
示例#4
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)
        if device:
            self.form.setModel(
                ["%s/%s" % (device, attribute) for attribute in self.attrs])

            #---- Partie qui correspond a l'appel de la bdd de Tango
            # avec types d'aimant etc ... on peut le faire a la main pour tester
            # pour le moment nous sommes obliges de sauter cette partie
            db_ok = False
            if db_ok:
                db = PyTango.Database()
                magnet = db.get_device_property(
                    device, "MagnetProxies")["MagnetProxies"][0]
                magnet_type = PyTango.Database().get_device_property(
                    magnet, "Type")["Type"][0]
            else:
                magnet_type = 'Dipole'

            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)
示例#5
0
 def __init__(self, name, keeper):
     self.name = name
     self.keepers = [keeper]
     self._last_time = 0
     self.last_value_event = None
     self.last_config_event = None
     self.attribute = Attribute(self.name)
     self.attribute.addListener(self)
示例#6
0
 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 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 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 setXModel(self, xModel):
        """Sets the taurus model for the x component"""
        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 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:&nbsp;' +
                               '<span class="value">%s</span>'
                               % value.value)
         self.finished.emit(self.model, html)
     except PyTango.DevFailed as e:
         print e
示例#11
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
示例#12
0
 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 AttributeError:
         print "Failed to subscribe to model %s!" % model
示例#13
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)
示例#14
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)
示例#15
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
示例#16
0
    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))
示例#17
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
示例#18
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)
示例#19
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
示例#20
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
示例#21
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
示例#22
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)
示例#23
0
 def attribute(self):
     return Attribute(self.name)
示例#24
0
def test1():
    import numpy
    from taurus import Attribute
    a = Attribute('sys/tg_test/1/ulong64_scalar')

    a.write(numpy.uint64(88))
示例#25
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
示例#26
0
 def ReadOne(self, axis):
     attr = Attribute(self._axes_taurus_attr[axis])
     return attr.read().value