Example #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)
Example #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
Example #3
0
class StatusArea(TaurusWidget):

    """A (scrolling) text area that displays device status, or any other
    string attribute."""

    statusTrigger = QtCore.pyqtSignal(str)

    def __init__(self, parent=None, down_command=None, up_command=None, state=None):
        TaurusWidget.__init__(self, parent)
        self._setup_ui()

    def _setup_ui(self):

        hbox = QtGui.QVBoxLayout(self)
        self.setLayout(hbox)

        self.status_label = QtGui.QLabel("(No status has been read.)")
        self.status_label.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
        self.status_label.setWordWrap(True)
        self.status_label.setAlignment(QtCore.Qt.AlignTop)
        status_scroll_area = QtGui.QScrollArea()
        status_scroll_area.setMaximumSize(QtCore.QSize(100000, 100))
        status_scroll_area.setWidgetResizable(True)
        status_scroll_area.setWidget(self.status_label)
        hbox.addWidget(status_scroll_area)
        self.status = None

        self.statusTrigger.connect(self.updateStatus)

    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)

    def onStatusChange(self, evt_src, evt_type, evt_value):
        if evt_type in [PyTango.EventType.CHANGE_EVENT,
                        PyTango.EventType.PERIODIC_EVENT]:
            self.statusTrigger.emit(evt_value.value)

    def updateStatus(self, status):
        self.status_label.setText(status)
Example #4
0
class TaurusWebAttribute(object):
    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)

    def eventReceived(self, evt_src, evt_type, evt_value):

        # print(evt_value)

        if evt_type == TaurusEventType.Error:
            action = "ERROR"
            value = error_str(evt_value)
        else:
            if evt_type == TaurusEventType.Config:
                action = "CONFIG"
                value = format_config_event(evt_src)
                self.last_config_event = value
            else:
                self._last_time = evt_value.time.tv_sec
                action = "CHANGE"
                value = format_value_event(evt_value)
                self.last_value_event = value

        # self.callback(self.name, {"type": action, "data": {self.name: value}})
        # event = {"type": action, "data": value}
        try:
            for keeper in self.keepers:
                keeper.put(self.name, action, value)
        except QueueFull:
            print("Queue full!")
        # print(event)

    def addKeeper(self, keeper):
        self.keepers.append(keeper)

    def removeKeeper(self, keeper):
        self.keepers.remove(keeper)

    def clear(self):
        self.attribute.removeListener(self)
Example #5
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
Example #6
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
Example #7
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 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()
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())
Example #10
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())
Example #12
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)
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)
Example #14
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()