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 init(self): self.distance_motor_hwobj = self.getObjectByRole("distance_motor") self.devname = self.getProperty("tangoname") try: self.latency_time = float(self.getProperty("latency_time")) except Exception: self.latency_time = None if self.latency_time is None: logging.getLogger("HWR").debug( "Cannot obtain latency time from Pilatus XML. Using %s" % self.default_latency_time) self.latency_time = self.default_latency_time self.devspecific = self.getProperty("device_specific") exp_time_limits = self.getProperty("exposure_limits") self.exp_time_limits = map(float, exp_time_limits.strip().split(",")) self.device = DeviceProxy(self.devname) self.device_specific = DeviceProxy(self.devspecific) self.device.set_timeout_millis(30000) self.beamx_chan = self.get_channel_object("beamx") self.beamy_chan = self.get_channel_object("beamy")
def init(self): self.device = None try: self._video_mode = self.getProperty("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.getProperty("exposure_time"): self._sleep_time = float(self.getProperty("exposure_time")) elif self.getProperty("interval"): self._sleep_time = float(self.getProperty("interval")) / 1000.0 if self.getProperty("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.setIsReady(True)
def init(self): sc3_pucks = self.getProperty('sc3_pucks', True) for i in range(8): cell = Cell(self, i + 1, sc3_pucks) self._addComponent(cell) self.robot = self.getProperty('tango_device') if self.robot: self.robot = DeviceProxy(self.robot) self.exporter_addr = self.getProperty('exporter_address') if self.exporter_addr: self.swstate_attr = self.addChannel( { 'type': 'exporter', 'exporter_address': self.exporter_addr, 'name': 'swstate' }, 'State') self.controller = self.getObjectByRole('controller') self.prepareLoad = self.getCommandObject('moveToLoadingPosition') self.timeout = 3 self.gripper_types = { -1: "No Gripper", 1: "UNIPUCK", 2: "MINISPINE", 3: "FLIPPING", 4: "UNIPUCK_DOUBLE", 5: "PLATE" } return SampleChanger.init(self)
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:
def init(self): """Initialise properties and polling""" super(BlissHutchTrigger, self).init() self._bliss_obj = self.getObjectByRole("controller") tango_device = self.getProperty("pss_tango_device") try: self._proxy = DeviceProxy(tango_device) except DevFailed as _traceback: last_error = _traceback[-1] msg = f"{self.name()}: {last_error['desc']}" raise RuntimeError(msg) pss = self.getProperty("pss_card_ch") try: self.card, self.channel = map(int, pss.split("/")) except AttributeError: msg = f"{self.name()}: cannot find PSS number" raise RuntimeError(msg) # polling interval [s] self._polling_interval = self.getProperty("polling_interval", 5) self._pss_value = self.get_pss_value() # enable by default self.update_value(self.VALUES.ENABLED) self._poll_task = spawn(self._do_polling)
def init(self): sc3_pucks = self.getProperty("sc3_pucks", True) for i in range(8): cell = Cell(self, i + 1, sc3_pucks) self._addComponent(cell) self.robot = self.getProperty("tango_device") if self.robot: self.robot = DeviceProxy(self.robot) self.exporter_addr = self.getProperty("exporter_address") if self.exporter_addr: self.swstate_attr = self.addChannel( { "type": "exporter", "exporter_address": self.exporter_addr, "name": "swstate", }, "State", ) self.controller = self.getObjectByRole("controller") self.prepareLoad = self.getCommandObject("moveToLoadingPosition") self.timeout = 3 self.gripper_types = { -1: "No Gripper", 1: "UNIPUCK", 2: "MINISPINE", 3: "FLIPPING", 4: "UNIPUCK_DOUBLE", 5: "PLATE", } return SampleChanger.init(self)
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
def init(self): controller = self.getObjectByRole("controller") self.musst = controller.musst self.shutter = self.getDeviceByRole("shutter") self.factor = self.getProperty("current_photons_factor") self.shutter.connect("shutterStateChanged", self.shutterStateChanged) self.tg_device = DeviceProxy(self.getProperty("tango_device")) self.counts_reading_task = self._read_counts_task(wait=False)
def init(self): controller = self.getObjectByRole("controller") self.musst = controller.musst self.energy_motor = self.getDeviceByRole("energy") self.shutter = self.getDeviceByRole("shutter") self.factor = self.getProperty("current_photons_factor") self.shutter.connect("shutterStateChanged", self.shutterStateChanged) self.tg_device = DeviceProxy("id30/keithley_massif1/i0") self.counts_reading_task = self._read_counts_task(wait=False)
def retrieve_attributes(): device_fqdn = bottle.request.GET["device_fqdn"] print "retrieving attributes from", device_fqdn if not device_fqdn in DEVICES: device_proxy = DeviceProxy(device_fqdn) DEVICES[device_fqdn] = device_proxy else: device_proxy = DEVICES[device_fqdn] attributes_list = [attr.name for attr in device_proxy.attribute_list_query()] return json.dumps(attributes_list)
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 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()
def init(self): self.counter = DeviceProxy(self.getProperty("url")) try: self.threshold = map(float, self.getProperty("threshold").split()) except AttributeError: self.threshold = [0, 9999] self.shutter = self.getDeviceByRole("shutter") self.aperture = self.getObjectByRole("aperture") fname = self.getProperty("calibrated_diodes_file") self.flux_calc = CalculateFlux() self.flux_calc.init(fname) self.shutter.connect("shutterStateChanged", self.shutterStateChanged) self.counts_reading_task = self._read_counts_task(wait=False)
def test_hdf5_lima(): config_xml = """ <config> <controller class="mockup"> <axis name="m0"> <steps_per_unit value="10000"/> <!-- degrees per second --> <velocity value="10"/> <acceleration value="100"/> </axis> </controller> </config>""" emotion.load_cfg_fromstring(config_xml) m0 = emotion.get_axis("m0") chain = AcquisitionChain() emotion_master = SoftwarePositionTriggerMaster(m0, 5, 10, 5, time=5) lima_dev = DeviceProxy("id30a3/limaccd/simulation") params = { "acq_nb_frames": 5, "acq_expo_time": 3 / 10.0, "acq_trigger_mode": "INTERNAL_TRIGGER_MULTI" } lima_acq_dev = LimaAcquisitionMaster(lima_dev, **params) chain.add(emotion_master, lima_acq_dev) file_organizer = Hdf5Organizer(root_path='/tmp') toto = Container('toto', file_organizer=file_organizer) dm = ScanRecorder('test_acq', toto) scan = Scan(chain, dm) scan.prepare() scan.start()
def test_lima(): config_xml = """ <config> <controller class="mockup"> <axis name="m0"> <steps_per_unit value="10000"/> <!-- degrees per second --> <velocity value="10"/> <acceleration value="100"/> </axis> </controller> </config>""" emotion.load_cfg_fromstring(config_xml) m0 = emotion.get_axis("m0") def cb(*args, **kwargs): print args, kwargs chain = AcquisitionChain() emotion_master = SoftwarePositionTriggerMaster(m0, 5, 10, 10, time=5) lima_dev = DeviceProxy("id30a3/limaccd/simulation") params = { "acq_nb_frames": 10, "acq_expo_time": 3 / 10.0, "acq_trigger_mode": "INTERNAL_TRIGGER_MULTI" } lima_acq_dev = LimaAcquisitionMaster(lima_dev, **params) dispatcher.connect(cb, sender=lima_acq_dev) chain.add(emotion_master, lima_acq_dev) scan = Scan(chain) scan.run() m0.wait_move() print m0.velocity() == 10
def test_lima_basler(): config = beacon_get_config() m0 = config.get("bcumot2") m0.velocity(360) m0.acceleration(720) chain = AcquisitionChain() nb_points = 4 emotion_master = SoftwarePositionTriggerMaster(m0, 0, 360, nb_points, time=1) tango_host = "lid00limax:20000" lima_dev = DeviceProxy("//%s/id00/limaccds/basler_bcu" % tango_host) params = { "acq_nb_frames": nb_points, "acq_expo_time": 10e-3, "acq_trigger_mode": "INTERNAL_TRIGGER_MULTI" } lima_acq_dev = LimaAcquisitionMaster(lima_dev, **params) chain.add(emotion_master, lima_acq_dev) hdf5_writer = hdf5.Writer(root_path='/tmp') toto = Container('test_lima_basler') scan = Scan(chain, name='test_acq', parent=toto, writer=hdf5_writer) scan.run()
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 init(self): self.distance_motor_hwobj = self.getObjectByRole("distance_motor") self.devname = self.getProperty("tangoname") try: self.latency_time = float(self.getProperty("latency_time")) except BaseException: self.latency_time = None if self.latency_time is None: logging.getLogger("HWR").debug( "Cannot obtain latency time from Pilatus XML. Using %s" % self.default_latency_time ) self.latency_time = self.default_latency_time self.devspecific = self.getProperty("device_specific") exp_time_limits = self.getProperty("exposure_limits") self.exp_time_limits = map(float, exp_time_limits.strip().split(",")) self.device = DeviceProxy(self.devname) self.device_specific = DeviceProxy(self.devspecific) self.device.set_timeout_millis(30000) self.beamx_chan = self.getChannelObject("beamx") self.beamy_chan = self.getChannelObject("beamy")
def _monitor(self): self.tg_device = None while True: if self.tg_device is None: self.tg_device = DeviceProxy(self.get_property("tangoname")) try: temp = self.tg_device.Gas_temp except Exception: self.tg_device = None else: # if n2level != self.n2level: # self.n2level = n2level # self.emit("levelChanged", (n2level, )) if temp != self.temp: self.temp = temp self.emit("temperatureChanged", (temp, 0)) # if cryo_status != self.cryo_status: # self.cryo_status = cryo_status # self.emit("cryoStatusChanged", (CRYO_STATUS[cryo_status], )) # if dry_status != self.dry_status: # self.dry_status = dry_status # if dry_status != 9999: # self.emit("dryStatusChanged", (CRYO_STATUS[dry_status], )) # if sdry_status != self.sdry_status: # self.sdry_status = sdry_status # if sdry_status != 9999: # self.emit("sdryStatusChanged", (CRYO_STATUS[sdry_status], )) time.sleep(3)
def init_device(self): try: self.device = DeviceProxy(self.deviceName) except PyTango.DevFailed, traceback: last_error = traceback[-1] logging.getLogger('HWR').error("%s: %s", str(self.name()), last_error['desc']) self.device = None
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)
class ID23PhotonFlux(Equipment): def __init__(self, *args, **kwargs): Equipment.__init__(self, *args, **kwargs) self.threshold = [] def init(self): self.counter = DeviceProxy(self.getProperty("url")) try: self.threshold = map(float,self.getProperty("threshold").split()) except AttributeError: self.threshold = [0, 9999] self.shutter = self.getDeviceByRole("shutter") self.energy_motor = self.getObjectByRole("energy") self.aperture = self.getObjectByRole("aperture") fname = self.getProperty("calibrated_diodes_file") self.flux_calc = CalculateFlux() self.flux_calc.init(fname) self.shutter.connect("shutterStateChanged", self.shutterStateChanged) self.counts_reading_task = self._read_counts_task(wait=False) @task def _read_counts_task(self): old_counts = None while True: counts = self._get_counts() if counts != old_counts: old_counts = counts self.countsUpdated(counts) time.sleep(1) def _get_counts(self): try: self.counter.MeasureSingle() counts = abs(self.counter.ReadData) if counts < self.threshold[0] or counts > self.threshold[1]: counts = 0 except AttributeError, TypeError: counts = 0 logging.getLogger("HWR").exception("%s: could not get counts", self.name()) try: egy = self.energy_motor.getCurrentEnergy()*1000.0 calib = self.flux_calc.calc_flux_coef(egy) except: logging.getLogger("HWR").exception("%s: could not get energy", self.name()) else: if self.aperture is None: aperture_coef = 1 else: try: aperture_coef = self.aperture.getApertureCoef() except: aperture_coef = 1. counts = math.fabs(counts * calib[0] * aperture_coef)*10e6 return counts
def init(self): sc3_pucks = self.get_property("sc3_pucks", True) for i in range(8): cell = Cell(self, i + 1, sc3_pucks) self._add_component(cell) self.robot = self.get_property("tango_device") if self.robot: self.robot = DeviceProxy(self.robot) self.exporter_addr = self.get_property("exporter_address") if self.exporter_addr: self.swstate_attr = self.add_channel( { "type": "exporter", "exporter_address": self.exporter_addr, "name": "swstate", }, "State", ) self.controller = self.get_object_by_role("controller") self.prepareLoad = self.get_command_object("moveToLoadingPosition") self.timeout = 3 self.gripper_types = { -1: "No Gripper", 1: "UNIPUCK", 2: "MINISPINE", 3: "FLIPPING", 4: "UNIPUCK_DOUBLE", 5: "PLATE", } SampleChanger.init(self) # self._set_state(SampleChangerState.Disabled) self._update_selection() self.state = self._read_state()
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()
class DataChannel(object): def __init__(self,dataset): self._dataset = dataset self._device_proxy = None self._image_mode = { 0 : numpy.uint8, 1 : numpy.uint16, 2 : numpy.uint32, 4 : numpy.int8, 5 :numpy.int16 , 6 : numpy.int32 , } def get(self,from_index,to_index = None): cnx = self._dataset._data._cnx() url = self._dataset._data.url_server if url is None: # data is no more available raise RuntimeError('dataset is no more available') current_lima_acq = int(cnx.get(url)) (lima_acq_nb,acq_nb_buffer, LastImageAcquired,LastCounterReady, LastImageSaved) = [int(x) for x in cnx.hmget(self.db_name, 'lima_acq_nb', 'acq_nb_buffer', 'LastImageAcquired', 'LastCounterReady', 'LastImageSaved')] if to_index is None: #first we try to get image directly from the server if current_lima_acq == lima_acq_nb and DeviceProxy: # current acquisition if LastImageAcquired < from_index: # image is not yet available raise RuntimeError('image is not yet available') #should be still in server memory if acq_nb_buffer > LastImageAcquired - from_index: try: if self._device_proxy is None: self._device_proxy = DeviceProxy(url) raw_msg = self._device_proxy.readImage(from_index) return self._tango_unpack(raw_msg[-1]) except: # As it's asynchronous, image seams to be no # more available so read it from file return self._read_from_file(from_index) else: return self._read_from_file(from_index) else: raise NotImplementedError('Not yet done')
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:
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 init(self): # cmdToggle = self.get_command_object('toggle') # cmdToggle.connectSignal('connected', self.connected) # cmdToggle.connectSignal('disconnected', self.disconnected) # Connect to device FP_Parser defined "tangoname" in the xml file try: # self.Attenuatordevice = SimpleDevice(self.getProperty("tangoname"), verbose=False) self.Attenuatordevice = DeviceProxy(self.getProperty("tangoname")) except Exception: self.errorDeviceInstance(self.getProperty("tangoname")) try: # self.Attenuatordevice = SimpleDevice(self.getProperty("tangoname"), verbose=False) self.Constdevice = DeviceProxy(self.getProperty("tangoname_const")) except Exception: self.errorDeviceInstance(self.getProperty("tangoname_const")) # Connect to device Primary slit horizontal defined "tangonamePs_h" in the # xml file try: # self.Ps_hdevice = SimpleDevice(self.getProperty("tangonamePs_h"), verbose=False) self.Ps_hdevice = DeviceProxy(self.getProperty("tangonamePs_h")) except Exception: self.errorDeviceInstance(self.getProperty("tangonamePs_h")) # Connect to device Primary slit vertical defined "tangonamePs_v" in the # xml file try: # self.Ps_vdevice = SimpleDevice(self.getProperty("tangonamePs_v"), verbose=False) self.Ps_vdevice = DeviceProxy(self.getProperty("tangonamePs_v")) except Exception: self.errorDeviceInstance(self.getProperty("tangonamePs_v")) if self.deviceOk: self.connected() self.chanAttState = self.get_channel_object("State") self.chanAttState.connectSignal("update", self.attStateChanged) self.chanAttFactor = self.get_channel_object("TrueTrans_FP") self.chanAttFactor.connectSignal("update", self.attFactorChanged)
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 ID30A3PhotonFlux(Equipment): def __init__(self, *args, **kwargs): Equipment.__init__(self, *args, **kwargs) def init(self): controller = self.getObjectByRole("controller") self.musst = controller.musst self.energy_motor = self.getDeviceByRole("energy") self.shutter = self.getDeviceByRole("shutter") self.factor = self.getProperty("current_photons_factor") self.shutter.connect("shutterStateChanged", self.shutterStateChanged) self.tg_device = DeviceProxy(self.getProperty("tango_device")) self.counts_reading_task = self._read_counts_task(wait=False) @task def _read_counts_task(self): old_counts = None while True: counts = self._get_counts() if counts != old_counts: old_counts = counts self.countsUpdated(counts) time.sleep(1) def _get_counts(self): """gain = 20 #20uA keithley_voltage = 2 musst_voltage = int("".join([x for x in self.musst.putget("#?CHCFG CH5") if x.isdigit()])) musst_fs = float(0x7FFFFFFF) counts = abs((gain/keithley_voltage)*musst_voltage*int(self.musst.putget("#?VAL CH5"))/musst_fs) """ #try: self.tg_device.MeasureSingle() counts = abs(self.tg_device.ReadData) * 1E6 return counts def connectNotify(self, signal): if signal == "valueChanged": self.emitValueChanged() def shutterStateChanged(self, _): self.countsUpdated(self._get_counts()) def updateFlux(self, _): self.countsUpdated(self._get_counts(), ignore_shutter_state=True) def countsUpdated(self, counts, ignore_shutter_state=False): if not ignore_shutter_state and self.shutter.getShutterState( ) != "opened": self.emitValueChanged(0) return flux = counts * self.factor self.emitValueChanged("%1.3g" % flux) """ try: counts = counts[self.index] except TypeError: logging.getLogger("HWR").error("%s: counts is None", self.name()) return flux = None try: egy = self.energy_motor.getPosition()*1000.0 except: logging.getLogger("HWR").exception("%s: could not get energy", self.name()) else: try: calib_dict = self.calibration_chan.getValue() if calib_dict is None: logging.getLogger("HWR").error("%s: calibration is None", self.name()) else: calibs = [(float(c["energy"]), float(c[self.counter])) for c in calib_dict.itervalues()] calibs.sort() E = [c[0] for c in calibs] C = [c[1] for c in calibs] except: logging.getLogger("HWR").exception("%s: could not get calibration", self.name()) else: try: aperture_coef = self.aperture.getApertureCoef() except: aperture_coef = 1 if aperture_coef <= 0: aperture_coef = 1 calib = numpy.interp([egy], E, C) flux = counts * calib * aperture_coef #logging.getLogger("HWR").debug("%s: flux-> %f * %f=%f , calib_dict=%r", self.name(), counts, calib, counts*calib, calib_dict) self.emitValueChanged("%1.3g" % flux) """ def getCurrentFlux(self): return self.current_flux def emitValueChanged(self, flux=None): if flux is None: self.current_flux = None self.emit("valueChanged", ("?", )) else: self.current_flux = flux self.emit("valueChanged", (self.current_flux, ))
class TangoEMot(Controller): def __init__(self, name, config, axes, encoders): Controller.__init__(self, name, config, axes, encoders) # Gets DS name from xml config. self.ds_name = self.config.get("ds_name") # tests if DS is responding. def initialize(self): pass def finalize(self): pass def initialize_axis(self, axis): self.axis_proxy = DeviceProxy(self.ds_name) axis.config.set("steps_per_unit", self.axis_proxy.steps_per_unit) axis.config.set("acceleration", self.axis_proxy.ReadConfig("acceleration")) axis.config.set("velocity", self.axis_proxy.ReadConfig("velocity")) def initialize_encoder(self, encoder): self.encoder_proxy = DeviceProxy(self.ds_name) encoder.config.config_dict.update({"steps_per_unit": {"value": self.encoder_proxy.steps_per_unit}}) def read_position(self, axis): """ Returns the position (measured or desired) taken from controller in *controller unit* (steps for example). """ return self.axis_proxy.position * axis.steps_per_unit def read_encoder(self, encoder): return self.encoder_proxy.Measured_Position * encoder.steps_per_unit def read_velocity(self, axis): _vel = self.axis_proxy.velocity * abs(axis.steps_per_unit) return _vel def set_velocity(self, axis, new_velocity): self.axis_proxy.velocity = new_velocity / abs(axis.steps_per_unit) def read_acctime(self, axis): return self.axis_proxy.acctime def set_acctime(self, axis, new_acc_time): self.axis_proxy.acctime = new_acc_time def read_acceleration(self, axis): return self.axis_proxy.acceleration * abs(axis.steps_per_unit) def set_acceleration(self, axis, new_acceleration): self.axis_proxy.acceleration = new_acceleration / abs(axis.steps_per_unit) def state(self, axis): _state = self.axis_proxy.state() if _state == DevState.ON: return AxisState("READY") elif _state == DevState.MOVING: return AxisState("MOVING") else: return AxisState("READY") def prepare_move(self, motion): pass def start_one(self, motion): """ Called on a single axis motion, returns immediately, positions in motor units """ self.axis_proxy.position = float(motion.target_pos / motion.axis.steps_per_unit) def stop(self, axis): self.axis_proxy.Abort() def home_search(self, axis): self.axis_proxy.GoHome() def home_state(self, axis): return self.state(axis)
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 ALBAPilatus(AbstractDetector, HardwareObject): """Detector class. Contains all information about detector - states are 'OK', and 'BAD' - status is busy, exposing, ready, etc. - physical property is RH for pilatus, P for rayonix """ def __init__(self, name): AbstractDetector.__init__(self) HardwareObject.__init__(self, name) self.distance_motor_hwobj = None self.default_distance = None self.default_distance_limits = None self.default_latency_time = 0.003 self.exp_time_limits = None self.headers = {} def init(self): self.distance_motor_hwobj = self.getObjectByRole("distance_motor") self.devname = self.getProperty("tangoname") try: self.latency_time = float(self.getProperty("latency_time")) except BaseException: self.latency_time = None if self.latency_time is None: logging.getLogger("HWR").debug( "Cannot obtain latency time from Pilatus XML. Using %s" % self.default_latency_time ) self.latency_time = self.default_latency_time self.devspecific = self.getProperty("device_specific") exp_time_limits = self.getProperty("exposure_limits") self.exp_time_limits = map(float, exp_time_limits.strip().split(",")) self.device = DeviceProxy(self.devname) self.device_specific = DeviceProxy(self.devspecific) self.device.set_timeout_millis(30000) self.beamx_chan = self.getChannelObject("beamx") self.beamy_chan = self.getChannelObject("beamy") def start_acquisition(self): self.device.startAcq() def stop_acquisition(self): self.device.abortAcq() def get_distance(self): """Returns detector distance in mm""" if self.distance_motor_hwobj is not None: return float(self.distance_motor_hwobj.getPosition()) else: return self.default_distance def move_distance(self, value): if self.distance_motor_hwobj is not None: self.distance_motor_hwobj.move(value) def wait_move_distance_done(self): self.distance_motor_hwobj.wait_end_of_move() def get_distance_limits(self): """Returns detector distance limits""" if self.distance_motor_hwobj is not None: return self.distance_motor_hwobj.getLimits() else: return self.default_distance_limits def get_threshold(self): return self.device_specific.threshold def get_threshold_gain(self): return self.device_specific.threshold_gain def has_shutterless(self): """Return True if has shutterless mode""" return True def get_beam_centre(self): """Returns beam center coordinates""" beam_x = 0 beam_y = 0 try: beam_x = self.beamx_chan.getValue() beam_y = self.beamy_chan.getValue() except BaseException: pass return beam_x, beam_y def get_manufacturer(self): return self.getProperty("manufacturer") return "Dectris" def get_model(self): return self.getProperty("model") def get_detector_type(self): return self.getProperty("type") def get_default_exposure_time(self): return self.getProperty("default_exposure_time") def get_minimum_exposure_time(self): return self.getProperty("minimum_exposure_time") def get_exposure_time_limits(self): """Returns exposure time limits as list with two floats""" return self.exp_time_limits def get_file_suffix(self): return self.getProperty("file_suffix") def get_pixel_size(self): return self.getProperty("px"), self.getProperty("py") # methods for data collection def set_energy_threshold(self): eugap_ch = self.getChannelObject("eugap") try: currentenergy = eugap_ch.getValue() except BaseException: currentenergy = 12.6 det_energy = self.get_threshold() # threshold = det_energy / 2. # limitenergy = threshold / 0.8 if round(currentenergy, 6) < 7.538: currentenergy = 7.538 kev_diff = abs(det_energy - currentenergy) if kev_diff > 1.2: logging.getLogger("HWR").debug( "programming energy_threshold on pilatus to: %s" % currentenergy ) # if self.wait_standby(): # self.device_specific.energy_threshold = currentenergy def get_latency_time(self): return self.latency_time def wait_standby(self, timeout=300): t0 = time.time() while self.device_specific.cam_state == "STANDBY": if time.time() - t0 > timeout: print("timeout waiting for Pilatus to be on STANDBY") return False time.sleep(0.1) return True def prepare_acquisition(self, dcpars): self.set_energy_threshold() # self.wait_standby() osc_seq = dcpars["oscillation_sequence"][0] file_pars = dcpars["fileinfo"] basedir = file_pars["directory"] prefix = "%s_%s_" % (file_pars["prefix"], file_pars["run_number"]) first_img_no = osc_seq["start_image_number"] nb_frames = osc_seq["number_of_images"] exp_time = osc_seq["exposure_time"] fileformat = "CBF" trig_mode = "EXTERNAL_TRIGGER" # latency_time = 0.003 logging.getLogger("HWR").debug( " Preparing detector (dev=%s) for data collection" % self.devname ) logging.getLogger("HWR").debug(" /saving directory: %s" % basedir) logging.getLogger("HWR").debug(" /prefix : %s" % prefix) logging.getLogger("HWR").debug(" /saving_format : %s" % fileformat) logging.getLogger("HWR").debug(" /trigger_mode : %s" % trig_mode) logging.getLogger("HWR").debug(" /acq_nb_frames : %s" % nb_frames) logging.getLogger("HWR").debug( " /acq_expo_time : %s" % str(exp_time - self.latency_time) ) logging.getLogger("HWR").debug(" /latency_time : %s" % self.latency_time) self.device.write_attribute("saving_mode", "AUTO_FRAME") self.device.write_attribute("saving_directory", basedir) self.device.write_attribute("saving_prefix", prefix) self.device.write_attribute("saving_format", fileformat) # set ROI and header in limaserver # TODO TrigList = [ "INTERNAL_TRIGGER", "EXTERNAL_TRIGGER", "EXTERNAL_TRIGGER_MULTI", "EXTERNAL_GATE", "EXTERNAL_START_STOP", ] self.device.write_attribute("acq_trigger_mode", trig_mode) self.device.write_attribute("acq_expo_time", exp_time - self.latency_time) self.device.write_attribute("latency_time", self.latency_time) return True def prepare_collection(self, nb_frames, first_img_no): logging.getLogger("HWR").debug( "ALBAPilatus. preparing collection. nb_images: %s, first_no: %s" % (nb_frames, first_img_no) ) self.device.write_attribute("acq_nb_frames", nb_frames) self.device.write_attribute("saving_next_number", first_img_no) self.device.prepareAcq() return True def start_collection(self): self.start_acquisition() def stop_collection(self): self.stop_acquisition() def set_image_headers(self, image_headers, angle_info): nb_images = image_headers["nb_images"] angle_inc = image_headers["Angle_increment"] start_angle = image_headers["Start_angle"] startangles_list = list() ang_start, ang_inc, spacing = angle_info for i in range(nb_images): startangles_list.append("%0.4f deg." % (ang_start + spacing * i)) headers = list() for i, sa in enumerate(startangles_list): header = ( "_array_data.header_convention PILATUS_1.2\n" "# Detector: PILATUS 6M, S/N 60-0108, Alba\n" "# %s\n" "# Pixel_size 172e-6 m x 172e-6 m\n" "# Silicon sensor, thickness 0.000320 m\n" % time.strftime("%Y/%b/%d %T") ) # Acquisition values (headers dictionary) but overwrites start angle image_headers["Start_angle"] = sa for key, value in image_headers.iteritems(): if key == "nb_images": continue header += "# %s %s\n" % (key, value) headers.append("%d : array_data/header_contents|%s;" % (i, header)) self.device.write_attribute("saving_header_delimiter", ["|", ";", ":"]) self.device.resetCommonHeader() self.device.resetFrameHeaders() self.device.setImageHeader(headers)
class ALBAPilatus(AbstractDetector, HardwareObject): """Detector class. Contains all information about detector - states are 'OK', and 'BAD' - status is busy, exposing, ready, etc. - physical property is RH for pilatus, P for rayonix """ def __init__(self, name): AbstractDetector.__init__(self) HardwareObject.__init__(self, name) self.distance_motor_hwobj = None self.default_distance = None self.default_distance_limits = None self.default_latency_time = 0.003 self.exp_time_limits = None self.headers = {} def init(self): self.distance_motor_hwobj = self.getObjectByRole("distance_motor") self.devname = self.getProperty("tangoname") try: self.latency_time = float(self.getProperty("latency_time")) except Exception: self.latency_time = None if self.latency_time is None: logging.getLogger("HWR").debug( "Cannot obtain latency time from Pilatus XML. Using %s" % self.default_latency_time) self.latency_time = self.default_latency_time self.devspecific = self.getProperty("device_specific") exp_time_limits = self.getProperty("exposure_limits") self.exp_time_limits = map(float, exp_time_limits.strip().split(",")) self.device = DeviceProxy(self.devname) self.device_specific = DeviceProxy(self.devspecific) self.device.set_timeout_millis(30000) self.beamx_chan = self.get_channel_object("beamx") self.beamy_chan = self.get_channel_object("beamy") def start_acquisition(self): self.device.startAcq() def stop_acquisition(self): self.device.abortAcq() def wait_move_distance_done(self): self.distance_motor_hwobj.wait_end_of_move() def get_threshold(self): return self.device_specific.threshold def get_threshold_gain(self): return self.device_specific.threshold_gain def has_shutterless(self): """Return True if has shutterless mode""" return True def get_beam_centre(self): """Returns beam center coordinates""" beam_x = 0 beam_y = 0 try: beam_x = self.beamx_chan.getValue() beam_y = self.beamy_chan.getValue() except Exception: pass return beam_x, beam_y def get_manufacturer(self): return self.getProperty("manufacturer") return "Dectris" def get_model(self): return self.getProperty("model") def get_detector_type(self): return self.getProperty("type") def get_default_exposure_time(self): return self.getProperty("default_exposure_time") def get_minimum_exposure_time(self): return self.getProperty("minimum_exposure_time") def get_exposure_time_limits(self): """Returns exposure time limits as list with two floats""" return self.exp_time_limits def get_file_suffix(self): return self.getProperty("file_suffix") def get_pixel_size(self): return self.getProperty("px"), self.getProperty("py") # methods for data collection def set_energy_threshold(self): eugap_ch = self.get_channel_object("eugap") try: currentenergy = eugap_ch.getValue() except Exception: currentenergy = 12.6 det_energy = self.get_threshold() # threshold = det_energy / 2. # limitenergy = threshold / 0.8 if round(currentenergy, 6) < 7.538: currentenergy = 7.538 kev_diff = abs(det_energy - currentenergy) if kev_diff > 1.2: logging.getLogger("HWR").debug( "programming energy_threshold on pilatus to: %s" % currentenergy) # if self.wait_standby(): # self.device_specific.energy_threshold = currentenergy def get_latency_time(self): return self.latency_time def wait_standby(self, timeout=300): t0 = time.time() while self.device_specific.cam_state == "STANDBY": if time.time() - t0 > timeout: print("timeout waiting for Pilatus to be on STANDBY") return False time.sleep(0.1) return True def prepare_acquisition(self, dcpars): self.set_energy_threshold() # self.wait_standby() osc_seq = dcpars["oscillation_sequence"][0] file_pars = dcpars["fileinfo"] basedir = file_pars["directory"] prefix = "%s_%s_" % (file_pars["prefix"], file_pars["run_number"]) first_img_no = osc_seq["start_image_number"] nb_frames = osc_seq["number_of_images"] exp_time = osc_seq["exposure_time"] fileformat = "CBF" trig_mode = "EXTERNAL_TRIGGER" # latency_time = 0.003 logging.getLogger("HWR").debug( " Preparing detector (dev=%s) for data collection" % self.devname) logging.getLogger("HWR").debug(" /saving directory: %s" % basedir) logging.getLogger("HWR").debug(" /prefix : %s" % prefix) logging.getLogger("HWR").debug(" /saving_format : %s" % fileformat) logging.getLogger("HWR").debug(" /trigger_mode : %s" % trig_mode) logging.getLogger("HWR").debug(" /acq_nb_frames : %s" % nb_frames) logging.getLogger("HWR").debug(" /acq_expo_time : %s" % str(exp_time - self.latency_time)) logging.getLogger("HWR").debug(" /latency_time : %s" % self.latency_time) self.device.write_attribute("saving_mode", "AUTO_FRAME") self.device.write_attribute("saving_directory", basedir) self.device.write_attribute("saving_prefix", prefix) self.device.write_attribute("saving_format", fileformat) # set ROI and header in limaserver # TODO TrigList = [ "INTERNAL_TRIGGER", "EXTERNAL_TRIGGER", "EXTERNAL_TRIGGER_MULTI", "EXTERNAL_GATE", "EXTERNAL_START_STOP", ] self.device.write_attribute("acq_trigger_mode", trig_mode) self.device.write_attribute("acq_expo_time", exp_time - self.latency_time) self.device.write_attribute("latency_time", self.latency_time) return True def prepare_collection(self, nb_frames, first_img_no): logging.getLogger("HWR").debug( "ALBAPilatus. preparing collection. nb_images: %s, first_no: %s" % (nb_frames, first_img_no)) self.device.write_attribute("acq_nb_frames", nb_frames) self.device.write_attribute("saving_next_number", first_img_no) self.device.prepareAcq() return True def start_collection(self): self.start_acquisition() def stop_collection(self): self.stop_acquisition() def set_image_headers(self, image_headers, angle_info): nb_images = image_headers["nb_images"] angle_inc = image_headers["Angle_increment"] start_angle = image_headers["Start_angle"] startangles_list = list() ang_start, ang_inc, spacing = angle_info for i in range(nb_images): startangles_list.append("%0.4f deg." % (ang_start + spacing * i)) headers = list() for i, sa in enumerate(startangles_list): header = ("_array_data.header_convention PILATUS_1.2\n" "# Detector: PILATUS 6M, S/N 60-0108, Alba\n" "# %s\n" "# Pixel_size 172e-6 m x 172e-6 m\n" "# Silicon sensor, thickness 0.000320 m\n" % time.strftime("%Y/%b/%d %T")) # Acquisition values (headers dictionary) but overwrites start angle image_headers["Start_angle"] = sa for key, value in image_headers.items(): if key == "nb_images": continue header += "# %s %s\n" % (key, value) headers.append("%d : array_data/header_contents|%s;" % (i, header)) self.device.write_attribute("saving_header_delimiter", ["|", ";", ":"]) self.device.resetCommonHeader() self.device.resetFrameHeaders() self.device.setImageHeader(headers)
class BlissHutchTrigger(AbstractNState): """Read the state of the hutch from the PSS and take actions.""" def __init__(self, name): super(BlissHutchTrigger, self).__init__(name) self._bliss_obj = None self._proxy = None self.card = None self.channel = None self._pss_value = None self._nominal_value = None self._polling_interval = None self._poll_task = None def init(self): """Initialise properties and polling""" super(BlissHutchTrigger, self).init() self._bliss_obj = self.getObjectByRole("controller") tango_device = self.getProperty("pss_tango_device") try: self._proxy = DeviceProxy(tango_device) except DevFailed as _traceback: last_error = _traceback[-1] msg = f"{self.name()}: {last_error['desc']}" raise RuntimeError(msg) pss = self.getProperty("pss_card_ch") try: self.card, self.channel = map(int, pss.split("/")) except AttributeError: msg = f"{self.name()}: cannot find PSS number" raise RuntimeError(msg) # polling interval [s] self._polling_interval = self.getProperty("polling_interval", 5) self._pss_value = self.get_pss_value() # enable by default self.update_value(self.VALUES.ENABLED) self._poll_task = spawn(self._do_polling) def _do_polling(self): """Do the polling of the PSS system""" while True: self._update_value(self.get_pss_value()) sleep(self._polling_interval) def get_value(self): """The value corresponds to activate/deactivate the hutch trigger polling. Returns: (ValueEnum): Last set value. """ return self._nominal_value def set_value(self, value, timeout=0): super(BlissHutchTrigger, self).set_value(value, timeout=0) def _set_value(self, value): """Set the hutch trigger enable/disable value Args: value (ValueEnum): ENABLED/DISABLED. """ self._nominal_value = value self.emit("valueChanged", (value,)) def get_pss_value(self): """Get the interlock value Returns: (bool): 0 = Hutch interlocked, 1 = Hutch not interlocked. """ _ch1 = self._proxy.GetInterlockState([self.card - 1, 2 * (self.channel - 1)])[0] _ch2 = self._proxy.GetInterlockState( [self.card - 1, 2 * (self.channel - 1) + 1] )[0] return _ch1 & _ch2 def _update_value(self, value=None): """Check if the pss value has changed (door opens/closes). Args: value (bool): The value """ if self._nominal_value == self.VALUES.ENABLED: if value is None: value = self.get_pss_value() if self._pss_value != value: self._pss_value = value # now do the action self.hutch_actions(1 - value) def hutch_actions(self, enter, **kwargs): """Take action as function of the PSS state Args: enter(bool): True if entering hutch (interlock state = 1) """ msg = "%s hutch" % ("Entering" if enter else "Leaving") logging.getLogger("user_level_log").info(msg) self._bliss_obj.hutch_actions(enter, hutch_trigger=True, **kwargs)
def prepare_intensity_monitors(self): i1 = DeviceProxy("id30/keithley_massif3/i1") i0 = DeviceProxy("id30/keithley_massif3/i0") i1.autorange = False i1.range = i0.range
class ID23PhotonFlux(Equipment): def __init__(self, *args, **kwargs): Equipment.__init__(self, *args, **kwargs) self.threshold = [] def init(self): self.counter = DeviceProxy(self.getProperty("url")) try: self.threshold = map(float, self.getProperty("threshold").split()) except AttributeError: self.threshold = [0, 9999] self.shutter = self.getDeviceByRole("shutter") self.aperture = self.getObjectByRole("aperture") fname = self.getProperty("calibrated_diodes_file") self.flux_calc = CalculateFlux() self.flux_calc.init(fname) self.shutter.connect("shutterStateChanged", self.shutterStateChanged) self.counts_reading_task = self._read_counts_task(wait=False) @task def _read_counts_task(self): old_counts = None while True: counts = self._get_counts() if counts != old_counts: old_counts = counts self.countsUpdated(counts) time.sleep(1) def _get_counts(self): try: self.counter.MeasureSingle() counts = abs(self.counter.ReadData) if counts < self.threshold[0] or counts > self.threshold[1]: counts = 0 except AttributeError: counts = 0 logging.getLogger("HWR").exception("%s: could not get counts", self.name()) try: egy = HWR.beamline.energy.get_value() * 1000.0 calib = self.flux_calc.calc_flux_coef(egy) except Exception: logging.getLogger("HWR").exception("%s: could not get energy", self.name()) else: if self.aperture is None: aperture_coef = 1 else: try: aperture_coef = self.aperture.getApertureCoef() except Exception: aperture_coef = 1.0 counts = math.fabs(counts * calib[0] * aperture_coef) * 10e6 return counts def connectNotify(self, signal): if signal == "valueChanged": self.emitValueChanged() def shutterStateChanged(self, _): self.countsUpdated(self._get_counts()) def updateFlux(self, _): self.countsUpdated(self._get_counts(), ignore_shutter_state=False) def countsUpdated(self, counts, ignore_shutter_state=False): self.emitValueChanged("%1.3g" % counts) def get_value(self): self.updateFlux("dummy") return self.current_flux def emitValueChanged(self, flux=None): if flux is None: self.current_flux = None self.emit("valueChanged", ("?", )) else: self.current_flux = flux self.emit("valueChanged", (self.current_flux, ))
def initialize(self): # Get a proxy on Insertion Device device server of the beamline. self.device = DeviceProxy(self.ds_name)
class Undulator(Controller): def __init__(self, name, config, axes, encoders): Controller.__init__(self, name, config, axes, encoders) self.axis_info = dict() try: self.ds_name = self.config.get("ds_name") except: elog.debug("no 'ds_name' defined in config for %s" % name) """ Controller initialization actions. """ def initialize(self): # Get a proxy on Insertion Device device server of the beamline. self.device = DeviceProxy(self.ds_name) """ Axes initialization actions. """ def initialize_axis(self, axis): attr_pos_name = axis.config.get("attribute_position", str) attr_vel_name = axis.config.get("attribute_velocity", str) attr_acc_name = axis.config.get("attribute_acceleration", str) self.axis_info[axis] = {"attr_pos_name": attr_pos_name, "attr_vel_name": attr_vel_name, "attr_acc_name": attr_acc_name} elog.debug("axis initilized--------------------------") """ Actions to perform at controller closing. """ def finalize(self): pass def _set_attribute(self, axis, attribute_name, value): self.device.write_attribute(self.axis_info[axis][attribute_name], value) def _get_attribute(self, axis, attribute_name): return self.device.read_attribute(self.axis_info[axis][attribute_name]).value def start_one(self, motion, t0=None): self._set_attribute(motion.axis, "attr_pos_name", float(motion.target_pos / motion.axis.steps_per_unit)) def read_position(self, axis): """ Returns the position taken from controller in controller unit (steps). """ return self._get_attribute(axis, "attr_pos_name") """ VELOCITY """ def read_velocity(self, axis): """ Returns the current velocity taken from controller in motor units. """ return self._get_attribute(axis, "attr_vel_name") def set_velocity(self, axis, new_velocity): """ <new_velocity> is in motor units """ self._set_attribute(axis, "attr_vel_name", new_velocity) """ ACCELERATION """ def read_acceleration(self, axis): return self._get_attribute(axis, "attr_acc_name") def set_acceleration(self, axis, new_acceleration): self._set_attribute(axis, "attr_acc_name", new_acceleration) """ STATE """ def state(self, axis): _state = self.device.state() if _state == DevState.ON: return AxisState("READY") elif _state == DevState.MOVING: return AxisState("MOVING") else: return AxisState("READY") """ Must send a command to the controller to abort the motion of given axis. """ def stop(self, axis): self.device.abort() def stop_all(self, *motion_list): self.device.abort() def get_info(self, axis): info_str = "" info_str = "DEVICE SERVER : %s \n" % self.ds_name info_str += self.ds.state() + "\n" info_str += "status=\"%s\"\n" % str(self.ds.status()).strip() info_str += "state=%s\n" % self.ds.state() info_str += "mode=%s\n" % str(self.ds.mode) info_str += ("undu states= %s" % " ".join(map(str, self.ds.UndulatorStates))) return info_str
class FlexHCD(SampleChanger): __TYPE__ = "HCD" def __init__(self, *args, **kwargs): super(FlexHCD, self).__init__(self.__TYPE__, True, *args, **kwargs) def init(self): sc3_pucks = self.getProperty("sc3_pucks", True) for i in range(8): cell = Cell(self, i + 1, sc3_pucks) self._addComponent(cell) self.robot = self.getProperty("tango_device") if self.robot: self.robot = DeviceProxy(self.robot) self.exporter_addr = self.getProperty("exporter_address") if self.exporter_addr: self.swstate_attr = self.addChannel( { "type": "exporter", "exporter_address": self.exporter_addr, "name": "swstate", }, "State", ) self.controller = self.getObjectByRole("controller") self.prepareLoad = self.getCommandObject("moveToLoadingPosition") self.timeout = 3 self.gripper_types = { -1: "No Gripper", 1: "UNIPUCK", 2: "MINISPINE", 3: "FLIPPING", 4: "UNIPUCK_DOUBLE", 5: "PLATE", } return SampleChanger.init(self) @task def prepare_load(self): if self.controller: self.controller.hutch_actions(condition=True) else: self.prepareLoad() @task def prepare_centring(self): if self.controller: self.controller.hutch_actions(condition=False, sc_loading=True) else: gevent.sleep(2) self.getCommandObject("unlockMinidiffMotors")(wait=True) self.getCommandObject("prepareCentring")(wait=True) def prepareCentring(self): self.prepare_centring() def getSampleProperties(self): return (Pin.__HOLDER_LENGTH_PROPERTY__,) def getBasketList(self): basket_list = [] # put here only the baskets that exist, not all the possible ones # if self.exporter_addr: # basket_list = for cell in self.getComponents(): for basket in cell.getComponents(): if isinstance(basket, Basket): basket_list.append(basket) return basket_list def _doChangeMode(self, *args, **kwargs): return def _doUpdateInfo(self): # self._updateSelection() self._updateState() def _doScan(self, component, recursive=True, saved={"barcodes": None}): return def _execute_cmd(self, cmd, *args, **kwargs): timeout = kwargs.pop("timeout", None) if args: cmd_str = "flex.%s(%s)" % (cmd, ",".join(map(repr, args))) else: cmd_str = "flex.%s()" % cmd cmd_id = self.robot.eval(cmd_str) if not cmd_id: cmd_id = self.robot.eval(cmd_str) with gevent.Timeout( timeout, RuntimeError("Timeout while executing %s" % repr(cmd_str)) ): while True: if self.robot.is_finished(cmd_id): break gevent.sleep(0.2) res = self.robot.get_result(cmd_id) if res: res = cPickle.loads(base64.decodestring(res)) if isinstance(res, Exception): raise res else: return res def _execute_cmd_exporter(self, cmd, *args, **kwargs): timeout = kwargs.pop("timeout", 900) if args: args_str = "%s" % "\t".join(map(repr, args)) if kwargs.pop("command", None): exp_cmd = self.addCommand( { "type": "exporter", "exporter_address": self.exporter_addr, "name": "%s" % cmd, }, "%s" % cmd, ) if args: ret = exp_cmd(args_str) else: ret = exp_cmd() if kwargs.pop("attribute", None): exp_attr = self.addChannel( { "type": "exporter", "exporter_address": self.exporter_addr, "name": "%s" % cmd, }, "%s" % cmd[3:], ) if cmd.startswith("get"): return exp_attr.getValue() if cmd.startswith("set"): ret = exp_attr.setValue(args_str) self._wait_ready(timeout=timeout) return ret def _ready(self): return self.swstate_attr.getValue() == "Ready" def _wait_ready(self, timeout=None): err_msg = "Timeout waiting for sample changer to be ready" # None means infinite timeout <=0 means default timeout if timeout is not None and timeout <= 0: timeout = self.timeout with gevent.Timeout(timeout, RuntimeError(err_msg)): while not self._ready(): time.sleep(0.5) def _doSelect(self, component): if isinstance(component, Cell): cell_pos = component.getIndex() + 1 elif isinstance(component, Basket) or isinstance(component, Pin): cell_pos = component.getCellNo() if self.exporter_addr: self._execute_cmd_exporter("moveDewar", cell_pos, command=True) else: self._execute_cmd("moveDewar", cell_pos) self._updateSelection() @task def load_sample( self, holderLength, sample_id=None, sample_location=None, sampleIsLoadedCallback=None, failureCallback=None, prepareCentring=True, ): cell, basket, sample = sample_location sample = self.getComponentByAddress(Pin.getSampleAddress(cell, basket, sample)) return self.load(sample) def chained_load(self, old_sample, sample): if self.exporter_addr: unload_load_task = gevent.spawn( self._execute_cmd_exporter, "loadSample", sample.getCellNo(), sample.getBasketNo(), sample.getVialNo(), command=True, ) else: unload_load_task = gevent.spawn( self._execute_cmd, "chainedUnldLd", [ old_sample.getCellNo(), old_sample.getBasketNo(), old_sample.getVialNo(), ], [sample.getCellNo(), sample.getBasketNo(), sample.getVialNo()], ) gevent.sleep(15) err_msg = "Timeout waiting for sample changer to be in safe position" while not unload_load_task.ready(): if self.exporter_addr: loading_state = self._execute_cmd_exporter( "getCurrentLoadSampleState", attribute=True ) if "on_gonio" in loading_state: self._setLoadedSample(sample) with gevent.Timeout(20, RuntimeError(err_msg)): while not self._execute_cmd_exporter( "getRobotIsSafe", attribute=True ): gevent.sleep(0.5) return True else: loading_state = str( self._execute_cmd("sampleStatus", "LoadSampleStatus") ) if "on_gonio" in loading_state: self._setLoadedSample(sample) with gevent.Timeout(20, RuntimeError(err_msg)): while ( not self._execute_cmd( "get_robot_cache_variable", "data:dioRobotIsSafe" ) == "true" ): gevent.sleep(0.5) return True gevent.sleep(1) logging.getLogger("HWR").info("unload load task done") for msg in self.get_robot_exceptions(): logging.getLogger("HWR").error(msg) return self._check_pin_on_gonio() def _check_pin_on_gonio(self): if self.exporter_addr: _on_gonio = self._execute_cmd_exporter("pin_on_gonio", command=True) else: _on_gonio = self._execute_cmd("pin_on_gonio") if _on_gonio: # finish the loading actions self.prepare_centring() return True else: logging.getLogger("HWR").info("reset loaded sample") self._resetLoadedSample() # if self.controller: # self.controller.hutch_actions(release_interlock=True) return False def reset_loaded_sample(self): if self.exporter_addr: self._execute_cmd_exporter("reset_loaded_position", command=True) else: self._execute_cmd("reset_loaded_position") self._resetLoadedSample() def get_robot_exceptions(self): if self.exporter_addr: """ return self._execute_cmd_exporter('getRobotExceptions', attribute=True) """ return "" else: return self._execute_cmd("getRobotExceptions") @task def load(self, sample): self.prepare_load(wait=True) self.enable_power() try: res = SampleChanger.load(self, sample) finally: for msg in self.get_robot_exceptions(): logging.getLogger("HWR").error(msg) if res: self.prepareCentring() return res @task def unload_sample( self, holderLength, sample_id=None, sample_location=None, successCallback=None, failureCallback=None, ): cell, basket, sample = sample_location sample = self.getComponentByAddress(Pin.getSampleAddress(cell, basket, sample)) return self.unload(sample) @task def unload(self, sample): self.prepare_load(wait=True) self.enable_power() try: SampleChanger.unload(self, sample) finally: for msg in self.get_robot_exceptions(): logging.getLogger("HWR").error(msg) def get_gripper(self): if self.exporter_addr: gripper_type = self._execute_cmd_exporter( "get_gripper_type", attribute=True ) else: gripper_type = self._execute_cmd("get_gripper_type") return self.gripper_types.get(gripper_type, "?") def get_available_grippers(self): grippers = [] if self.exporter_addr: ret = sorted( self._execute_cmd_exporter("getSupportedGrippers", attribute=True) ) for gripper in ret: grippers.append(self.gripper_types[gripper]) return grippers @task def change_gripper(self, gripper=None): self.prepare_load(wait=True) self.enable_power() if self.exporter_addr: if gripper: self._execute_cmd_exporter("setGripper", gripper, command=True) else: self._execute_cmd_exporter("changeGripper", command=True) else: self._execute_cmd("changeGripper") @task def home(self): self.prepare_load(wait=True) self.enable_power() if self.exporter_addr: self._execute_cmd_exporter("homeClear", command=True) else: self._execute_cmd("homeClear") @task def enable_power(self): if not self.exporter_addr: self._execute_cmd("enablePower", 1) @task def defreeze(self): self.prepare_load(wait=True) self.enable_power() if self.exporter_addr: self._execute_cmd_exporter("defreezeGripper", command=True) else: self._execute_cmd("defreezeGripper") def _doLoad(self, sample=None): self._updateState() if self.exporter_addr: load_task = gevent.spawn( self._execute_cmd_exporter, "loadSample", sample.getCellNo(), sample.getBasketNo(), sample.getVialNo(), command=True, ) else: load_task = gevent.spawn( self._execute_cmd, "loadSample", sample.getCellNo(), sample.getBasketNo(), sample.getVialNo(), ) gevent.sleep(5) err_msg = "Timeout waiting for sample changer to be in safe position" while not load_task.ready(): if self.exporter_addr: loading_state = self._execute_cmd_exporter( "getCurrentLoadSampleState", attribute=True ) if "on_gonio" in loading_state: self._setLoadedSample(sample) with gevent.Timeout(20, RuntimeError(err_msg)): while not self._execute_cmd_exporter( "getRobotIsSafe", attribute=True ): gevent.sleep(0.5) return True else: loading_state = str( self._execute_cmd("sampleStatus", "LoadSampleStatus") ) if "on_gonio" in loading_state: self._setLoadedSample(sample) with gevent.Timeout(20, RuntimeError(err_msg)): while ( not self._execute_cmd( "get_robot_cache_variable", "data:dioRobotIsSafe" ) == "true" ): gevent.sleep(0.5) return True gevent.sleep(1) if self.exporter_addr: loaded_sample = self._execute_cmd_exporter( "get_loaded_sample", attribute=True ) else: loaded_sample = self._execute_cmd("get_loaded_sample") if loaded_sample == ( sample.getCellNo(), sample.getBasketNo(), sample.getVialNo(), ): self._setLoadedSample(sample) return True return self._check_pin_on_gonio() def _doUnload(self, sample=None): loaded_sample = self.getLoadedSample() if loaded_sample is not None and loaded_sample != sample: raise RuntimeError("Cannot unload another sample") if self.exporter_addr: self._execute_cmd_exporter( "unloadSample", sample.getCellNo(), sample.getBasketNo(), sample.getVialNo(), command=True, ) loaded_sample = self._execute_cmd_exporter( "get_loaded_sample", attribute=True ) else: self._execute_cmd( "unloadSample", sample.getCellNo(), sample.getBasketNo(), sample.getVialNo(), ) loaded_sample = self._execute_cmd("get_loaded_sample") if loaded_sample == (-1, -1, -1): self._resetLoadedSample() if self.controller: self.controller.hutch_actions(release_interlock=True) return True return False def _doAbort(self): if self.exporter_addr: self._execute_cmd_exporter("abort", command=True) else: self._execute_cmd("abort") def _doReset(self): if self.exporter_addr: self._execute_cmd_exporter("homeClear", command=True) else: self._execute_cmd("homeClear") def clearBasketInfo(self, basket): return self._reset_basket_info(basket) def _reset_basket_info(self, basket): pass def clearCellInfo(self, cell): return self._reset_cell_info(cell) def _reset_cell_info(self, cell): pass def _updateState(self): # see if the command exists for exporter if not self.exporter_addr: defreezing = self._execute_cmd("isDefreezing") if defreezing: self._setState(SampleChangerState.Ready) try: state = self._readState() except Exception: state = SampleChangerState.Unknown self._setState(state) def isSequencerReady(self): if self.prepareLoad: cmdobj = self.getCommandObject return all( [cmd.isSpecReady() for cmd in (cmdobj("moveToLoadingPosition"),)] ) return True def _readState(self): # should read state from robot if self.exporter_addr: state = self.swstate_attr.getValue().upper() else: state = "RUNNING" if self._execute_cmd("robot.isBusy") else "STANDBY" if state == "STANDBY" and not self.isSequencerReady(): state = "RUNNING" state_converter = { "ALARM": SampleChangerState.Alarm, "FAULT": SampleChangerState.Fault, "RUNNING": SampleChangerState.Moving, "READY": SampleChangerState.Ready, "STANDBY": SampleChangerState.Ready, } return state_converter.get(state, SampleChangerState.Unknown) def _isDeviceBusy(self, state=None): if state is None: state = self._readState() return state not in ( SampleChangerState.Ready, SampleChangerState.Loaded, SampleChangerState.Alarm, SampleChangerState.Disabled, SampleChangerState.Fault, SampleChangerState.StandBy, ) def _isDeviceReady(self): state = self._readState() return state in (SampleChangerState.Ready, SampleChangerState.Charging) def _waitDeviceReady(self, timeout=None): with gevent.Timeout(timeout, Exception("Timeout waiting for device ready")): while not self._isDeviceReady(): gevent.sleep(0.01) def _updateSelection(self): if self.exporter_addr: sample_cell, sample_puck, sample = self._execute_cmd_exporter( "get_loaded_sample", attribute=True ) cell = sample_cell puck = sample_puck else: cell, puck = self._execute_cmd("get_cell_position") sample_cell, sample_puck, sample = self._execute_cmd("get_loaded_sample") for c in self.getComponents(): i = c.getIndex() if cell == i + 1: self._setSelectedComponent(c) break # find sample for s in self.getSampleList(): if s.getCoords() == (sample_cell, sample_puck, sample): self._setLoadedSample(s) # self._setSelectedSample(s) return for s in self.getSampleList(): s._setLoaded(False) self._setSelectedSample(None) def prepare_hutch(self, **kwargs): if self.exporter_addr: return user_port = kwargs.get("user_port") robot_port = kwargs.get("robot_port") if user_port is not None: self._execute_cmd("robot.user_port(user_port)") if robot_port is not None: self._execute_cmd("robot.robot_port(robot_port)")
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 FlexHCD(SampleChanger): __TYPE__ = "HCD" def __init__(self, *args, **kwargs): super(FlexHCD, self).__init__(self.__TYPE__, True, *args, **kwargs) def init(self): sc3_pucks = self.getProperty("sc3_pucks", True) for i in range(8): cell = Cell(self, i + 1, sc3_pucks) self._add_component(cell) self.robot = self.getProperty("tango_device") if self.robot: self.robot = DeviceProxy(self.robot) self.exporter_addr = self.getProperty("exporter_address") """ if self.exporter_addr: self.swstate_attr = self.add_channel( { "type": "exporter", "exporter_address": self.exporter_addr, "name": "swstate", }, "State", ) """ self.controller = self.getObjectByRole("controller") self.prepareLoad = self.get_command_object("moveToLoadingPosition") self.timeout = 3 self.gripper_types = { -1: "No Gripper", 1: "UNIPUCK", 2: "MINISPINE", 3: "FLIPPING", 4: "UNIPUCK_DOUBLE", 5: "PLATE", } return SampleChanger.init(self) @task def prepare_load(self): if self.controller: self.controller.hutch_actions(condition=True) else: self.prepareLoad() @task def _prepare_centring_task(self): if self.controller: self.controller.hutch_actions(condition=False, sc_loading=True) else: gevent.sleep(2) self.get_command_object("unlockMinidiffMotors")(wait=True) self.get_command_object("prepareCentring")(wait=True) def prepare_centring(self): self._prepare_centring_task() def get_sample_properties(self): return (Pin.__HOLDER_LENGTH_PROPERTY__,) def get_basket_list(self): basket_list = [] # put here only the baskets that exist, not all the possible ones # if self.exporter_addr: # basket_list = for cell in self.get_components(): for basket in cell.get_components(): if isinstance(basket, Basket): basket_list.append(basket) return basket_list def _do_change_mode(self, *args, **kwargs): return def _do_update_info(self): # self._update_selection() self._update_state() def _do_scan(self, component, recursive=True, saved={"barcodes": None}): return def _execute_cmd(self, cmd, *args, **kwargs): timeout = kwargs.pop("timeout", None) if args: cmd_str = "flex.%s(%s)" % (cmd, ",".join(map(repr, args))) else: cmd_str = "flex.%s()" % cmd cmd_id = self.robot.eval(cmd_str) if not cmd_id: cmd_id = self.robot.eval(cmd_str) with gevent.Timeout( timeout, RuntimeError("Timeout while executing %s" % repr(cmd_str)) ): while True: if self.robot.is_finished(cmd_id): break gevent.sleep(0.2) res = self.robot.get_result(cmd_id) if res: res = pickle.loads(base64.decodestring(res)) if isinstance(res, Exception): raise res else: return res def _execute_cmd_exporter(self, cmd, *args, **kwargs): ret = None timeout = kwargs.pop("timeout", 900) if args: args_str = "%s" % "\t".join(map(repr, args)) if kwargs.pop("command", None): exp_cmd = self.add_command( { "type": "exporter", "exporter_address": self.exporter_addr, "name": "%s" % cmd, }, "%s" % cmd, ) if args: ret = exp_cmd(args_str) else: ret = exp_cmd() if kwargs.pop("attribute", None): exp_attr = self.add_channel( { "type": "exporter", "exporter_address": self.exporter_addr, "name": "%s" % cmd, }, "%s" % cmd[3:], ) if cmd.startswith("get"): return exp_attr.getValue() if cmd.startswith("set"): ret = exp_attr.setValue(args_str) self._wait_ready(timeout=timeout) return ret def _ready(self): # return self.swstate_attr.getValue() == "Ready" return True def _wait_ready(self, timeout=None): err_msg = "Timeout waiting for sample changer to be ready" # None means infinite timeout <=0 means default timeout if timeout is not None and timeout <= 0: timeout = self.timeout with gevent.Timeout(timeout, RuntimeError(err_msg)): while not self._ready(): time.sleep(0.5) def _do_select(self, component): if isinstance(component, Cell): cell_pos = component.get_index() + 1 elif isinstance(component, Basket) or isinstance(component, Pin): cell_pos = component.get_cell_no() if self.exporter_addr: self._execute_cmd_exporter("moveDewar", cell_pos, command=True) else: self._execute_cmd("moveDewar", cell_pos) self._update_selection() @task def load_sample( self, holderLength, sample_id=None, sample_location=None, sampleIsLoadedCallback=None, failureCallback=None, prepareCentring=True, ): cell, basket, sample = sample_location sample = self.get_component_by_address(Pin.get_sample_address(cell, basket, sample)) return self.load(sample) def chained_load(self, old_sample, sample): if self.exporter_addr: unload_load_task = gevent.spawn( self._execute_cmd_exporter, "load_sample", sample.get_cell_no(), sample.get_basket_no(), sample.get_vial_no(), command=True, ) else: unload_load_task = gevent.spawn( self._execute_cmd, "chainedUnldLd", [ old_sample.get_cell_no(), old_sample.get_basket_no(), old_sample.get_vial_no(), ], [sample.get_cell_no(), sample.get_basket_no(), sample.get_vial_no()], ) gevent.sleep(15) err_msg = "Timeout waiting for sample changer to be in safe position" while not unload_load_task.ready(): if self.exporter_addr: loading_state = self._execute_cmd_exporter( "getCurrentLoadSampleState", attribute=True ) if "on_gonio" in loading_state: self._set_loaded_sample(sample) with gevent.Timeout(20, RuntimeError(err_msg)): while not self._execute_cmd_exporter( "getRobotIsSafe", attribute=True ): gevent.sleep(0.5) return True else: loading_state = str( self._execute_cmd("sampleStatus", "LoadSampleStatus") ) if "on_gonio" in loading_state: self._set_loaded_sample(sample) with gevent.Timeout(20, RuntimeError(err_msg)): while ( not self._execute_cmd( "get_robot_cache_variable", "data:dioRobotIsSafe" ) == "true" ): gevent.sleep(0.5) return True gevent.sleep(1) logging.getLogger("HWR").info("unload load task done") for msg in self.get_robot_exceptions(): logging.getLogger("HWR").error(msg) return self._check_pin_on_gonio() def _check_pin_on_gonio(self): if self.exporter_addr: _on_gonio = self._execute_cmd_exporter("pin_on_gonio", command=True) else: _on_gonio = self._execute_cmd("pin_on_gonio") if _on_gonio: # finish the loading actions self._prepare_centring_task() return True else: logging.getLogger("HWR").info("reset loaded sample") self._reset_loaded_sample() # if self.controller: # self.controller.hutch_actions(release_interlock=True) return False def reset_loaded_sample(self): if self.exporter_addr: self._execute_cmd_exporter("reset_loaded_position", command=True) else: self._execute_cmd("reset_loaded_position") self._reset_loaded_sample() def get_robot_exceptions(self): if self.exporter_addr: """ return self._execute_cmd_exporter('getRobotExceptions', attribute=True) """ return "" else: return self._execute_cmd("getRobotExceptions") @task def load(self, sample): self.prepare_load(wait=True) self.enable_power() try: res = SampleChanger.load(self, sample) finally: for msg in self.get_robot_exceptions(): logging.getLogger("HWR").error(msg) if res: self.prepare_centring() return res @task def unload_sample( self, holderLength, sample_id=None, sample_location=None, successCallback=None, failureCallback=None, ): cell, basket, sample = sample_location sample = self.get_component_by_address(Pin.get_sample_address(cell, basket, sample)) return self.unload(sample) @task def unload(self, sample): self.prepare_load(wait=True) self.enable_power() try: SampleChanger.unload(self, sample) finally: for msg in self.get_robot_exceptions(): logging.getLogger("HWR").error(msg) def get_gripper(self): if self.exporter_addr: gripper_type = self._execute_cmd_exporter( "get_gripper_type", attribute=True ) else: gripper_type = self._execute_cmd("get_gripper_type") return self.gripper_types.get(gripper_type, "?") def get_available_grippers(self): grippers = [] if self.exporter_addr: ret = sorted( self._execute_cmd_exporter("getSupportedGrippers", attribute=True) ) for gripper in ret: grippers.append(self.gripper_types[gripper]) return grippers @task def change_gripper(self, gripper=None): self.prepare_load(wait=True) self.enable_power() if self.exporter_addr: if gripper: self._execute_cmd_exporter("setGripper", gripper, command=True) else: self._execute_cmd_exporter("changeGripper", command=True) else: self._execute_cmd("changeGripper") @task def home(self): self.prepare_load(wait=True) self.enable_power() if self.exporter_addr: self._execute_cmd_exporter("homeClear", command=True) else: self._execute_cmd("homeClear") @task def enable_power(self): if not self.exporter_addr: self._execute_cmd("enablePower", 1) @task def defreeze(self): self.prepare_load(wait=True) self.enable_power() if self.exporter_addr: self._execute_cmd_exporter("defreezeGripper", command=True) else: self._execute_cmd("defreezeGripper") def _do_load(self, sample=None): self._update_state() if self.exporter_addr: load_task = gevent.spawn( self._execute_cmd_exporter, "load_sample", sample.get_cell_no(), sample.get_basket_no(), sample.get_vial_no(), command=True, ) else: load_task = gevent.spawn( self._execute_cmd, "load_sample", sample.get_cell_no(), sample.get_basket_no(), sample.get_vial_no(), ) gevent.sleep(5) err_msg = "Timeout waiting for sample changer to be in safe position" while not load_task.ready(): if self.exporter_addr: loading_state = self._execute_cmd_exporter( "getCurrentLoadSampleState", attribute=True ) if "on_gonio" in loading_state: self._set_loaded_sample(sample) with gevent.Timeout(20, RuntimeError(err_msg)): while not self._execute_cmd_exporter( "getRobotIsSafe", attribute=True ): gevent.sleep(0.5) return True else: loading_state = str( self._execute_cmd("sampleStatus", "LoadSampleStatus") ) if "on_gonio" in loading_state: self._set_loaded_sample(sample) with gevent.Timeout(20, RuntimeError(err_msg)): while ( not self._execute_cmd( "get_robot_cache_variable", "data:dioRobotIsSafe" ) == "true" ): gevent.sleep(0.5) return True gevent.sleep(1) if self.exporter_addr: loaded_sample = self._execute_cmd_exporter( "get_loaded_sample", attribute=True ) else: loaded_sample = self._execute_cmd("get_loaded_sample") if loaded_sample == ( sample.get_cell_no(), sample.get_basket_no(), sample.get_vial_no(), ): self._set_loaded_sample(sample) return True return self._check_pin_on_gonio() def _do_unload(self, sample=None): loaded_sample = self.get_loaded_sample() if loaded_sample is not None and loaded_sample != sample: raise RuntimeError("Cannot unload another sample") if self.exporter_addr: self._execute_cmd_exporter( "unload_sample", sample.get_cell_no(), sample.get_basket_no(), sample.get_vial_no(), command=True, ) loaded_sample = self._execute_cmd_exporter( "get_loaded_sample", attribute=True ) else: self._execute_cmd( "unload_sample", sample.get_cell_no(), sample.get_basket_no(), sample.get_vial_no(), ) loaded_sample = self._execute_cmd("get_loaded_sample") if loaded_sample == (-1, -1, -1): self._reset_loaded_sample() if self.controller: self.controller.hutch_actions(release_interlock=True) return True return False def _do_abort(self): if self.exporter_addr: self._execute_cmd_exporter("abort", command=True) else: self._execute_cmd("abort") def _do_reset(self): if self.exporter_addr: self._execute_cmd_exporter("homeClear", command=True) else: self._execute_cmd("homeClear") def clear_basket_info(self, basket): return self._reset_basket_info(basket) def _reset_basket_info(self, basket): pass def clear_cell_info(self, cell): return self._reset_cell_info(cell) def _reset_cell_info(self, cell): pass def _update_state(self): # see if the command exists for exporter if not self.exporter_addr: defreezing = self._execute_cmd("isDefreezing") if defreezing: self._set_state(SampleChangerState.Ready) try: state = self._read_state() except Exception: state = SampleChangerState.Unknown self._set_state(state) def is_sequencer_ready(self): if self.prepareLoad: cmdobj = self.get_command_object return all( [cmd.isSpecReady() for cmd in (cmdobj("moveToLoadingPosition"),)] ) return True def _read_state(self): # should read state from robot if self.exporter_addr: # state = self.swstate_attr.get_value().upper() state = self._execute_cmd_exporter("State", attrubute=True) else: state = "RUNNING" if self._execute_cmd("robot.isBusy") else "STANDBY" if state == "STANDBY" and not self.is_sequencer_ready(): state = "RUNNING" state = "READY" state_converter = { "ALARM": SampleChangerState.Alarm, "FAULT": SampleChangerState.Fault, "RUNNING": SampleChangerState.Moving, "READY": SampleChangerState.Ready, "STANDBY": SampleChangerState.Ready, } return state_converter.get(state, SampleChangerState.Unknown) def _is_device_busy(self, state=None): if state is None: state = self._read_state() return state not in ( SampleChangerState.Ready, SampleChangerState.Loaded, SampleChangerState.Alarm, SampleChangerState.Disabled, SampleChangerState.Fault, SampleChangerState.StandBy, ) def _is_device_ready(self): state = self._read_state() return state in (SampleChangerState.Ready, SampleChangerState.Charging) def _wait_device_ready(self, timeout=None): with gevent.Timeout(timeout, Exception("Timeout waiting for device ready")): while not self._is_device_ready(): gevent.sleep(0.01) def _update_selection(self): if self.exporter_addr: sample_cell, sample_puck, sample = self._execute_cmd_exporter( "get_loaded_sample", attribute=True ) cell = sample_cell puck = sample_puck else: cell, puck = self._execute_cmd("get_cell_position") sample_cell, sample_puck, sample = self._execute_cmd("get_loaded_sample") for c in self.get_components(): i = c.get_index() if cell == i + 1: self._set_selected_component(c) break # find sample for s in self.get_sample_list(): if s.get_coords() == (sample_cell, sample_puck, sample): self._set_loaded_sample(s) # self._set_selected_sample(s) return for s in self.get_sample_list(): s._set_loaded(False) self._set_selected_sample(None) def prepare_hutch(self, **kwargs): if self.exporter_addr: return user_port = kwargs.get("user_port") robot_port = kwargs.get("robot_port") if user_port is not None: self._execute_cmd("robot.user_port(user_port)") if robot_port is not None: self._execute_cmd("robot.robot_port(robot_port)")
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
def initialize_axis(self, axis): self.axis_proxy = DeviceProxy(self.ds_name) axis.config.set("steps_per_unit", self.axis_proxy.steps_per_unit) axis.config.set("acceleration", self.axis_proxy.ReadConfig("acceleration")) axis.config.set("velocity", self.axis_proxy.ReadConfig("velocity"))