class TangoLimaVideo(BaseHardwareObjects.Device): def __init__(self, name): BaseHardwareObjects.Device.__init__(self, name) self.__brightnessExists = False self.__contrastExists = False self.__gainExists = False self.__gammaExists = False self.__polling = None self.scaling = pixmaptools.LUT.Scaling() def init(self): self.device = None try: self.device = DeviceProxy(self.tangoname) #try a first call to get an exception if the device #is not exported self.device.ping() except PyTango.DevFailed, traceback: last_error = traceback[-1] logging.getLogger('HWR').error("%s: %s", str(self.name()), last_error.desc) self.device = BaseHardwareObjects.Null() else:
class TangoCommand(CommandObject): def __init__(self, name, command, tangoname=None, username=None, **kwargs): CommandObject.__init__(self, name, username, **kwargs) self.command = command self.deviceName = tangoname self.device = None def init_device(self): try: self.device = DeviceProxy(self.deviceName) except PyTango.DevFailed as traceback: last_error = traceback[-1] logging.getLogger("HWR").error("%s: %s", str(self.name()), last_error["desc"]) self.device = None else: try: self.device.ping() except PyTango.ConnectionFailed: self.device = None raise ConnectionError def __call__(self, *args, **kwargs): self.emit("commandBeginWaitReply", (str(self.name()), )) if self.device is None: # TODO: emit commandFailed # beware of infinite recursion with Sample Changer # (because of procedure exception cleanup...) self.init_device() try: tangoCmdObject = getattr(self.device, self.command) ret = tangoCmdObject( *args) # eval('self.device.%s(*%s)' % (self.command, args)) except PyTango.DevFailed as error_dict: logging.getLogger("HWR").error("%s: Tango, %s", str(self.name()), error_dict) except Exception: logging.getLogger("HWR").exception( "%s: an error occured when calling Tango command %s", str(self.name()), self.command, ) else: self.emit("commandReplyArrived", (ret, str(self.name()))) return ret self.emit("commandFailed", (-1, self.name())) def abort(self): pass def setDeviceTimeout(self, timeout): if self.device is None: self.init_device() self.device.set_timeout_millis(timeout) def isConnected(self): return self.device is not None
class TangoLimaVideo(BaseHardwareObjects.Device): def __init__(self, name): BaseHardwareObjects.Device.__init__(self, name) self.__brightnessExists = False self.__contrastExists = False self.__gainExists = False self.__gammaExists = False self.__polling = None self.scaling = pixmaptools.LUT.Scaling() def init(self): self.device = None try: self.device = DeviceProxy(self.tangoname) # try a first call to get an exception if the device # is not exported self.device.ping() except PyTango.DevFailed, traceback: last_error = traceback[-1] logging.getLogger("HWR").error("%s: %s", str(self.name()), last_error.desc) self.device = BaseHardwareObjects.Null() else:
class TangoLimaVideo(BaseHardwareObjects.Device): def __init__(self, name): BaseHardwareObjects.Device.__init__(self, name) self.__brightnessExists = False self.__contrastExists = False self.__gainExists = False self.__gammaExists = False self.__polling = None self.scaling = pixmaptools.LUT.Scaling() def init(self): self.device = None try: self.device = DeviceProxy(self.tangoname) #try a first call to get an exception if the device #is not exported self.device.ping() except PyTango.DevFailed as traceback: last_error = traceback[-1] logging.getLogger('HWR').error("%s: %s", str(self.name()), last_error.desc) self.device = BaseHardwareObjects.Null() else: self.setExposure(self.getProperty("interval")/1000.0) self.device.video_mode = "BAYER_RG16" self.setIsReady(True) def imageType(self): return BayerType("RG16") def _get_last_image(self): img_data = self.device.video_last_image if img_data[0]=="VIDEO_IMAGE": header_fmt = ">IHHqiiHHHH" _, ver, img_mode, frame_number, width, height, _, _, _, _ = struct.unpack(header_fmt, img_data[1][:struct.calcsize(header_fmt)]) raw_buffer = numpy.fromstring(img_data[1][32:], numpy.uint16) self.scaling.autoscale_min_max(raw_buffer, width, height, pixmaptools.LUT.Scaling.BAYER_RG16) validFlag, qimage = pixmaptools.LUT.raw_video_2_image(raw_buffer, width, height, pixmaptools.LUT.Scaling.BAYER_RG16, self.scaling) if validFlag: return qimage def _do_polling(self, sleep_time): while True: qimage = self._get_last_image() self.emit("imageReceived", qimage, qimage.width(), qimage.height(), False) time.sleep(sleep_time) def connectNotify(self, signal): if signal=="imageReceived": if self.__polling is None: self.__polling = gevent.spawn(self._do_polling, self.device.video_exposure) ############# CONTRAST ################# def contrastExists(self): return self.__contrastExists ############# BRIGHTNESS ################# def brightnessExists(self): return self.__brightnessExists ############# GAIN ################# def gainExists(self): return self.__gainExists ############# GAMMA ################# def gammaExists(self): return self.__gammaExists ############# WIDTH ################# def getWidth(self): """tango""" return self.device.image_width def getHeight(self): """tango""" return self.device.image_height def setSize(self, width, height): """Set new image size Only takes width into account, because anyway we can only set a scale factor """ return def takeSnapshot(self, *args, **kwargs): """tango""" qimage = self._get_last_image() try: qimage.save(args[0], "PNG") except: logging.getLogger("HWR").exception("%s: could not save snapshot", self.name()) return False else: return True def setLive(self, mode): """tango""" if mode: self.device.video_live=True else: self.device.video_live=False def setExposure(self, exposure): self.device.video_exposure = exposure
class TangoLimaVideo(BaseHardwareObjects.Device): def __init__(self, name): BaseHardwareObjects.Device.__init__(self, name) self.__brightnessExists = False self.__contrastExists = False self.__gainExists = False self.__gammaExists = False self.__polling = None self._video_mode = None self._last_image = (0, 0, 0) # Dictionary containing conversion information for a given # video_mode. The camera video mode is the key and the first # index of the tuple contains the corresponding PIL mapping # and the second the desried output format. The image is # passed on as it is of the video mode is not in the dictionary self._FORMATS = { "RGB8": ("L", "BMP"), "RGB24": ("RGB", "BMP"), "RGB32": ("RGBA", "BMP"), "NO_CONVERSION": (None, None), } def init(self): self.device = None try: self._video_mode = self.get_property("video_mode", "RGB24") self.device = DeviceProxy(self.tangoname) # try a first call to get an exception if the device # is not exported self.device.ping() except PyTango.DevFailed as traceback: last_error = traceback[-1] logging.getLogger("HWR").error("%s: %s", str(self.name()), last_error.desc) self.device = BaseHardwareObjects.Null() else: if self.get_property("exposure_time"): self._sleep_time = float(self.get_property("exposure_time")) elif self.get_property("interval"): self._sleep_time = float( self.get_property("interval")) / 1000.0 if self.get_property("control_video", "True"): logging.getLogger("HWR").info("MXCuBE controlling video") if self.device.video_live: self.device.video_live = False self.device.video_mode = self._video_mode self.set_exposure(self._sleep_time) self.device.video_live = True else: logging.getLogger("HWR").info("MXCuBE NOT controlling video") self.set_is_ready(True) def get_last_image(self): return self._last_image def _do_polling(self, sleep_time): lima_tango_device = self.device while True: data, width, height = poll_image(lima_tango_device, self.video_mode, self._FORMATS) self._last_image = data, width, heigh self.emit("imageReceived", data, width, height, False) time.sleep(sleep_time) def connect_notify(self, signal): if signal == "imageReceived": if self.__polling is None: self.__polling = gevent.spawn(self._do_polling, self.device.video_exposure) def get_width(self): return self.device.image_width def get_height(self): return self.device.image_height def take_snapshot(self, path=None, bw=False): data, width, height = poll_image(self.device, self.video_mode, self._FORMATS) img = Image.frombytes("RGB", (width, height), data) if bw: img.convert("1") if path: img.save(path) return img def set_live(self, mode): curr_state = self.device.video_live if mode: if not curr_state: self.device.video_live = True else: if curr_state: self.device.video_live = False def set_exposure(self, exposure): self.device.video_exposure = exposure
class TangoChannel(ChannelObject): _tangoEventsQueue = queue.Queue() _eventReceivers = {} _tangoEventsProcessingTimer = gevent.get_hub().loop. async () # start Tango events processing timer _tangoEventsProcessingTimer.start(processTangoEvents) def __init__(self, name, attribute_name, tangoname=None, username=None, polling=None, timeout=10000, **kwargs): ChannelObject.__init__(self, name, username, **kwargs) self.attributeName = attribute_name self.deviceName = tangoname self.device = None self.value = Poller.NotInitializedValue self.polling = polling self.pollingTimer = None self.pollingEvents = False self.timeout = int(timeout) self.read_as_str = kwargs.get("read_as_str", False) self._device_initialized = gevent.event.Event() logging.getLogger("HWR").debug( "creating Tango attribute %s/%s, polling=%s, timeout=%d", self.deviceName, self.attributeName, polling, self.timeout) self.init_poller = Poller.poll( self.init_device, polling_period=3000, value_changed_callback=self.continue_init, error_callback=self.init_poll_failed, start_delay=100) def init_poll_failed(self, e, poller_id): self._device_initialized.clear() logging.warning( "%s/%s (%s): could not complete init. (hint: device server is not running, or has to be restarted)", self.deviceName, self.attributeName, self.name()) self.init_poller = self.init_poller.restart(3000) def continue_init(self, _): self.init_poller.stop() if type(self.polling) == int: Poller.poll(self.poll, polling_period=self.polling, value_changed_callback=self.update, error_callback=self.pollFailed) else: if self.polling == "events": # try to register event try: self.pollingEvents = True #logging.getLogger("HWR").debug("subscribing to CHANGE event for %s", self.attributeName) self.device.subscribe_event(self.attributeName, PyTango.EventType.CHANGE_EVENT, self, [], True) #except PyTango.EventSystemFailed: # pass except: logging.getLogger("HWR").exception( "could not subscribe event") self._device_initialized.set() def init_device(self): try: self.device = DeviceProxy(self.deviceName) except PyTango.DevFailed as traceback: self.imported = False last_error = traceback[-1] logging.getLogger('HWR').error("%s: %s", str(self.name()), last_error['desc']) else: self.imported = True try: self.device.ping() except PyTango.ConnectionFailed: self.device = None raise ConnectionError else: self.device.set_timeout_millis(self.timeout) # check that the attribute exists (to avoid Abort in PyTango grrr) if not self.attributeName.lower() in [ attr.name.lower() for attr in self.device.attribute_list_query() ]: logging.getLogger("HWR").error( "no attribute %s in Tango device %s", self.attributeName, self.deviceName) self.device = None def push_event(self, event): #logging.getLogger("HWR").debug("%s | attr_value=%s, event.errors=%s, quality=%s", self.name(), event.attr_value, event.errors,event.attr_value is None and "N/A" or event.attr_value.quality) if event.attr_value is None or event.err or event.attr_value.quality != PyTango.AttrQuality.ATTR_VALID: #logging.getLogger("HWR").debug("%s, receving BAD event... attr_value=%s, event.errors=%s, quality=%s", self.name(), event.attr_value, event.errors, event.attr_value is None and "N/A" or event.attr_value.quality) return else: pass #logging.getLogger("HWR").debug("%s, receiving good event", self.name()) ev = E(event) TangoChannel._eventReceivers[id(ev)] = saferef.safe_ref(self.update) TangoChannel._tangoEventsQueue.put(ev) TangoChannel._tangoEventsProcessingTimer.send() def poll(self): if self.read_as_str: value = self.device.read_attribute( self.attributeName, PyTango.DeviceAttribute.ExtractAs.String).value #value = self.device.read_attribute_as_str(self.attributeName).value else: value = self.device.read_attribute(self.attributeName).value return value def pollFailed(self, e, poller_id): emit_update = True if self.value is None: emit_update = False else: self.value = None try: self.init_device() except: pass poller = Poller.get_poller(poller_id) if poller is not None: poller.restart(1000) try: raise e except: logging.exception("%s: Exception happened while polling %s", self.name(), self.attributeName) if emit_update: # emit at the end => can raise exceptions in callbacks self.emit('update', None) def getInfo(self): self._device_initialized.wait(timeout=3) return self.device.get_attribute_config(self.attributeName) def update(self, value=Poller.NotInitializedValue): if value == Poller.NotInitializedValue: value = self.getValue() if type(value) == tuple: value = list(value) self.value = value self.emit('update', value) def getValue(self): self._device_initialized.wait(timeout=3) if self.read_as_str: value = self.device.read_attribute( self.attributeName, PyTango.DeviceAttribute.ExtractAs.String).value else: value = self.device.read_attribute(self.attributeName).value return value def setValue(self, newValue, wait=False): self.device.write_attribute(self.attributeName, newValue) #attr = PyTango.AttributeProxy(self.deviceName + "/" + self.attributeName) #a = attr.read() #a.value = newValue #attr.write(a) def isConnected(self): return self.device is not None
class TangoCommand(CommandObject): def __init__(self, name, command, tangoname=None, username=None, **kwargs): CommandObject.__init__(self, name, username, **kwargs) self.command = command self.deviceName = tangoname self.device = None def init_device(self): try: self.device = DeviceProxy(self.deviceName) except PyTango.DevFailed as traceback: last_error = traceback[-1] logging.getLogger("HWR").error( "%s: %s", str(self.name()), last_error["desc"] ) self.device = None else: try: self.device.ping() except PyTango.ConnectionFailed: self.device = None raise ConnectionError def __call__(self, *args, **kwargs): self.emit("commandBeginWaitReply", (str(self.name()),)) if self.device is None: # TODO: emit commandFailed # beware of infinite recursion with Sample Changer # (because of procedure exception cleanup...) self.init_device() try: tangoCmdObject = getattr(self.device, self.command) ret = tangoCmdObject( *args ) # eval('self.device.%s(*%s)' % (self.command, args)) except PyTango.DevFailed as error_dict: logging.getLogger("HWR").error( "%s: Tango, %s", str(self.name()), error_dict ) except BaseException: logging.getLogger("HWR").exception( "%s: an error occured when calling Tango command %s", str(self.name()), self.command, ) else: self.emit("commandReplyArrived", (ret, str(self.name()))) return ret self.emit("commandFailed", (-1, self.name())) def abort(self): pass def setDeviceTimeout(self, timeout): if self.device is None: self.init_device() self.device.set_timeout_millis(timeout) def isConnected(self): return self.device is not None
class TangoChannel(ChannelObject): _tangoEventsQueue = Queue.Queue() _eventReceivers = {} _tangoEventsProcessingTimer = gevent.get_hub().loop.async() # start Tango events processing timer _tangoEventsProcessingTimer.start(processTangoEvents) def __init__( self, name, attribute_name, tangoname=None, username=None, polling=None, timeout=10000, **kwargs ): ChannelObject.__init__(self, name, username, **kwargs) self.attributeName = attribute_name self.deviceName = tangoname self.device = None self.value = Poller.NotInitializedValue self.polling = polling self.pollingTimer = None self.pollingEvents = False self.timeout = int(timeout) self.read_as_str = kwargs.get("read_as_str", False) self._device_initialized = gevent.event.Event() logging.getLogger("HWR").debug( "creating Tango attribute %s/%s, polling=%s, timeout=%d", self.deviceName, self.attributeName, polling, self.timeout, ) self.init_device() self.continue_init(None) """ self.init_poller = Poller.poll(self.init_device, polling_period = 3000, value_changed_callback = self.continue_init, error_callback = self.init_poll_failed, start_delay=100) """ def init_poll_failed(self, e, poller_id): self._device_initialized.clear() logging.warning( "%s/%s (%s): could not complete init. (hint: device server is not running, or has to be restarted)", self.deviceName, self.attributeName, self.name(), ) self.init_poller = self.init_poller.restart(3000) def continue_init(self, _): # self.init_poller.stop() if isinstance(self.polling, types.IntType): self.raw_device = RawDeviceProxy(self.deviceName) Poller.poll( self.poll, polling_period=self.polling, value_changed_callback=self.update, error_callback=self.pollFailed, ) else: if self.polling == "events": # try to register event try: self.pollingEvents = True # logging.getLogger("HWR").debug("subscribing to CHANGE event for %s", self.attributeName) self.device.subscribe_event( self.attributeName, PyTango.EventType.CHANGE_EVENT, self, [], True, ) # except PyTango.EventSystemFailed: # pass except BaseException: logging.getLogger("HWR").exception("could not subscribe event") self._device_initialized.set() def init_device(self): try: self.device = DeviceProxy(self.deviceName) except PyTango.DevFailed as traceback: self.imported = False last_error = traceback[-1] logging.getLogger("HWR").error( "%s: %s", str(self.name()), last_error["desc"] ) else: self.imported = True try: self.device.ping() except PyTango.ConnectionFailed: self.device = None raise ConnectionError else: self.device.set_timeout_millis(self.timeout) # check that the attribute exists (to avoid Abort in PyTango grrr) if not self.attributeName.lower() in [ attr.name.lower() for attr in self.device.attribute_list_query() ]: logging.getLogger("HWR").error( "no attribute %s in Tango device %s", self.attributeName, self.deviceName, ) self.device = None def push_event(self, event): # logging.getLogger("HWR").debug("%s | attr_value=%s, event.errors=%s, quality=%s", self.name(), event.attr_value, event.errors,event.attr_value is None and "N/A" or event.attr_value.quality) if ( event.attr_value is None or event.err or event.attr_value.quality != PyTango.AttrQuality.ATTR_VALID ): # logging.getLogger("HWR").debug("%s, receving BAD event... attr_value=%s, event.errors=%s, quality=%s", self.name(), event.attr_value, event.errors, event.attr_value is None and "N/A" or event.attr_value.quality) return else: pass # logging.getLogger("HWR").debug("%s, receiving good event", self.name()) ev = E(event) TangoChannel._eventReceivers[id(ev)] = saferef.safe_ref(self.update) TangoChannel._tangoEventsQueue.put(ev) TangoChannel._tangoEventsProcessingTimer.send() def poll(self): if self.read_as_str: value = self.raw_device.read_attribute( self.attributeName, PyTango.DeviceAttribute.ExtractAs.String ).value # value = self.device.read_attribute_as_str(self.attributeName).value else: value = self.raw_device.read_attribute(self.attributeName).value return value def pollFailed(self, e, poller_id): self.emit("update", None) """ emit_update = True if self.value is None: emit_update = False else: self.value = None try: self.init_device() except: pass poller = Poller.get_poller(poller_id) if poller is not None: poller.restart(1000) try: raise e except: logging.exception("%s: Exception happened while polling %s", self.name(), self.attributeName) if emit_update: # emit at the end => can raise exceptions in callbacks self.emit('update', None) """ def getInfo(self): self._device_initialized.wait(timeout=3) return self.device.get_attribute_config(self.attributeName) def update(self, value=Poller.NotInitializedValue): if value == Poller.NotInitializedValue: value = self.getValue() if isinstance(value, types.TupleType): value = list(value) self.value = value self.emit("update", value) def getValue(self): self._device_initialized.wait(timeout=3) if self.read_as_str: value = self.device.read_attribute( self.attributeName, PyTango.DeviceAttribute.ExtractAs.String ).value else: value = self.device.read_attribute(self.attributeName).value return value def setValue(self, newValue): self.device.write_attribute(self.attributeName, newValue) # attr = PyTango.AttributeProxy(self.deviceName + "/" + self.attributeName) # a = attr.read() # a.value = newValue # attr.write(a) def isConnected(self): return self.device is not None