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(): 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 = LimaAcquisitionDevice(lima_dev, **params) dispatcher.connect(cb, sender=lima_acq_dev) chain.add(emotion_master, lima_acq_dev) scan = Scan(chain, ScanRecorder()) scan.prepare() scan.start() m0.wait_move() print m0.velocity()==10
def __init__(self, device, npoints=1, acq_expo_time=1., acq_point_period=None, acq_mode=AcqMode.IntTrigMulti): name = type(device).__name__ self.acq_expo_time = acq_expo_time self.acq_mode = acq_mode self.first_trigger = None self.status = None self.last_point_ready = None self.last_error = None self.point_event = gevent.event.Event() self.point_event.set() if acq_mode in self.SoftTrigModes: trigger_type = self.SOFTWARE else: trigger_type = self.HARDWARE kwargs = dict(npoints=npoints, prepare_once=True, start_once=True, trigger_type=trigger_type) super(CT2AcquisitionMaster, self).__init__(device, name, **kwargs) dispatcher.connect(self.__on_event, sender=device)
def init_scans_callbacks(interpreter, output_queue): def new_scan_callback(scan_id, filename, scan_actuators, npoints, counters_list): output_queue.put( ( interpreter.get_last_client_uuid(), { "scan_id": scan_id, "filename": filename, "scan_actuators": scan_actuators, "npoints": npoints, "counters": counters_list, }, ) ) def update_scan_callback(scan_id, values): output_queue.put((interpreter.get_last_client_uuid(), {"scan_id": scan_id, "values": values})) def scan_end_callback(scan_id): output_queue.put((interpreter.get_last_client_uuid(), {"scan_id": scan_id})) # keep callbacks references output_queue.callbacks["scans"]["new"] = new_scan_callback output_queue.callbacks["scans"]["update"] = update_scan_callback output_queue.callbacks["scans"]["end"] = scan_end_callback dispatcher.connect(new_scan_callback, "scan_new", data_manager.DataManager()) dispatcher.connect(update_scan_callback, "scan_data", data_manager.DataManager()) dispatcher.connect(scan_end_callback, "scan_end", data_manager.DataManager())
def __init__(self, linkamDevice, filename): self._linkamDevice = linkamDevice self._scanFile = LinkamScanFile(filename) dispatcher.connect(self.handle_data_event, 'linkam_profile_data', linkamDevice) dispatcher.connect(self.handle_startstop_event, 'linkam_profile_start', linkamDevice) dispatcher.connect(self.handle_startstop_event, 'linkam_profile_end', linkamDevice)
def init_scans_callbacks(interpreter, output_queue): def new_scan_callback(scan_info): scan_actuators = scan_info['motors'] if len(scan_actuators) > 1: scan_actuators = scan_actuators[1:] data = (interpreter.get_last_client_uuid(), { "scan_id": scan_info["node_name"], "filename": scan_info['root_path'], "scan_actuators": [actuator.name for actuator in scan_actuators], "npoints": scan_info['npoints'], "counters": [ct.name for ct in scan_info['counters']] }) output_queue.put(data) def update_scan_callback(scan_info, values): value_list = [values[m.name] for m in scan_info['motors']] value_list += [values[c.name] for c in scan_info['counters']] if scan_info["type"] != "timescan": value_list = value_list[1:] data = (interpreter.get_last_client_uuid(), { "scan_id": scan_info["node_name"], "values": value_list }) output_queue.put(data) def scan_end_callback(scan_info): data = (interpreter.get_last_client_uuid(), { "scan_id": scan_info["node_name"] }) output_queue.put(data) # keep callbacks references output_queue.callbacks["scans"]["new"] = new_scan_callback output_queue.callbacks["scans"]["update"] = update_scan_callback output_queue.callbacks["scans"]["end"] = scan_end_callback dispatcher.connect(new_scan_callback, "scan_new", scan) dispatcher.connect(update_scan_callback, "scan_data", scan) dispatcher.connect(scan_end_callback, "scan_end", scan)
def init_scans_callbacks(interpreter, output_queue): def new_scan_callback(scan_info): scan_actuators = scan_info['motors'] if len(scan_actuators) > 1: scan_actuators = scan_actuators[1:] data = (interpreter.get_last_client_uuid(), {"scan_id": scan_info["node_name"], "filename": scan_info['root_path'], "scan_actuators": [actuator.name for actuator in scan_actuators], "npoints": scan_info['npoints'], "counters": [ct.name for ct in scan_info['counters']]}) output_queue.put(data) def update_scan_callback(scan_info, values): value_list = [values[m.name] for m in scan_info['motors']] value_list += [values[c.name] for c in scan_info['counters']] if scan_info["type"] != "timescan": value_list = value_list[1:] data = (interpreter.get_last_client_uuid(), {"scan_id": scan_info["node_name"], "values":value_list}) output_queue.put(data) def scan_end_callback(scan_info): data = (interpreter.get_last_client_uuid(), {"scan_id": scan_info["node_name"]}) output_queue.put(data) # keep callbacks references output_queue.callbacks["scans"]["new"] = new_scan_callback output_queue.callbacks["scans"]["update"] = update_scan_callback output_queue.callbacks["scans"]["end"] = scan_end_callback dispatcher.connect( new_scan_callback, "scan_new", scan) dispatcher.connect( update_scan_callback, "scan_data", scan) dispatcher.connect( scan_end_callback, "scan_end", scan)
def connect(self, signal, callback): dispatcher.connect(callback, signal, self)
def prepare(self): for acq_device in self.src_acq_devices_list: dispatcher.connect(self.new_data_received, "new_data", acq_device)
def __enter__(self): dispatcher.connect(self, sender=self.device) return self
def __init__(self): dispatcher.connect(self.__on_scan_new, 'scan_new', scan) dispatcher.connect(self.__on_scan_data, 'scan_data', scan) dispatcher.connect(self.__on_scan_end, 'scan_end', scan)
def __on_scan_new(self, scan_info): scan_info = dict(scan_info) self.term = term = Terminal(scan_info.get('stream')) scan_info = dict(scan_info) motors = scan_info['motors'] counters = scan_info['counters'] nb_points = scan_info['npoints'] if not scan_info['save']: scan_info['root_path'] = '<no saving>' col_labels = ['#'] real_motors = [] for motor in motors: motor_name = motor.name # replace time_stamp with elapsed_time if motor_name == 'timestamp': motor_name = 'dt' unit = 's' else: real_motors.append(motor) if term.is_a_tty: dispatcher.connect(self.__on_motor_position_changed, signal='position', sender=motor) unit = motor.config.get('unit', default=None) motor_label = motor_name if unit: motor_label += '({0})'.format(unit) col_labels.append(motor_label) for counter in counters: counter_label = counter.name unit = _find_unit(counter) if unit: counter_label += '({0})'.format(unit) col_labels.append(counter_label) self.col_labels = col_labels self.real_motors = real_motors self._point_nb = 0 if not scan_info['save']: scan_info['root_path'] = '<no file>' if scan_info['type'] == 'ct': return estimation = scan_info.get('estimation') if estimation: total = datetime.timedelta(seconds=estimation['total_time']) motion = datetime.timedelta(seconds=estimation['total_motion_time']) count = datetime.timedelta(seconds=estimation['total_count_time']) estimation_str = ', {0} (motion: {1}, count: {2})'.format(total, motion, count) else: estimation_str = '' other_counters = scan_info.get('other_counters', list()) if other_counters: not_shown_counters_str = 'Activated counters not shown: %s\n' % \ ', '.join((c.name for c in other_counters)) else: not_shown_counters_str = '' col_lens = map(lambda x: max(len(x), self.DEFAULT_WIDTH), col_labels) h_templ = ["{{0:>{width}}}".format(width=col_len) for col_len in col_lens] header = " ".join([templ.format(label) for templ, label in zip(h_templ, col_labels)]) header = self.HEADER.format(column_header=header, estimation_str=estimation_str, not_shown_counters_str=not_shown_counters_str, **scan_info) self.col_templ = ["{{0: >{width}g}}".format(width=col_len) for col_len in col_lens] print_(header)
def start(session_id, input_queue, output_queue, i): # restore default SIGINT behaviour def raise_kb_interrupt(interpreter=i): if not interpreter.kill(KeyboardInterrupt): raise KeyboardInterrupt gevent.signal(signal.SIGINT, raise_kb_interrupt) output_queue.callbacks = { "motor": dict(), "scans": dict(), "actuator": dict(), "shutter": dict() } init_scans_callbacks(i, output_queue) config = static_config.get_config() session = config.get(session_id) i.locals["resetup"] = functools.partial(session.setup, env_dict=i.locals, verbose=True) root_logger = logging.getLogger() custom_log_handler = LogHandler(output_queue) custom_log_handler.setFormatter( logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s')) root_logger.addHandler(custom_log_handler) while True: try: client_uuid, action, _ = input_queue.get() except EOFError: break if action == "syn": output_queue.put("ack") continue elif action == "synoptic": object_name, method_name = _ namespace = i.locals for name in object_name.split('.'): obj = namespace.get(name) namespace = dict(inspect.getmembers(obj)) if obj is not None: method = getattr(obj, method_name) if callable(method): gevent.spawn(method) elif action == "get_object": object_name = _[0] object_dict = dict() namespace = i.locals for name in object_name.split('.'): obj = namespace.get(name) namespace = dict(inspect.getmembers(obj)) if obj is not None: object_dict["type"] = get_object_type(obj) if object_dict["type"] == "motor": m = obj try: pos = "%.3f" % m.position() state = convert_state(m.state()) except: pos = None state = None object_dict.update({"state": state, "position": pos}) def state_updated(state, name=object_name): output_queue.put((None, { "name": name, "state": convert_state(state) })) def position_updated(pos, name=object_name, client_uuid=client_uuid): pos = "%.3f" % pos output_queue.put((None, { "name": name, "position": pos })) output_queue.callbacks["motor"][object_name] = ( state_updated, position_updated) dispatcher.connect(state_updated, "state", m) dispatcher.connect(position_updated, "position", m) elif object_dict["type"] == "actuator": try: state = obj.state() except: state = None object_dict.update({"state": convert_state(state)}) def state_updated(state, name=object_name): output_queue.put((None, { "name": name, "state": convert_state(state) })) output_queue.callbacks["actuator"][ object_name] = state_updated dispatcher.connect(state_updated, "state", obj) elif object_dict["type"] == "shutter": try: state = obj.state() except: state = None object_dict.update({"state": convert_state(state)}) def state_updated(state, name=object_name): output_queue.put((None, { "name": name, "state": convert_state(state) })) output_queue.callbacks["shutter"][ object_name] = state_updated dispatcher.connect(state_updated, "state", obj) output_queue.put((None, StopIteration(object_dict))) elif action == "get_objects": objects_by_type = get_objects_by_type(i.locals) pprint.pprint(objects_by_type) motors_list = list() for name, m in objects_by_type["motors"].iteritems(): try: pos = "%.3f" % m.position() state = convert_state(m.state()) except: pos = None state = None motors_list.append({ "name": m.name, "state": state, "position": pos }) def state_updated(state, name=name): output_queue.put((None, { "name": name, "state": convert_state(state) })) def position_updated(pos, name=name, client_uuid=client_uuid): pos = "%.3f" % pos output_queue.put((None, {"name": name, "position": pos})) output_queue.callbacks["motor"][name] = (state_updated, position_updated) dispatcher.connect(state_updated, "state", m) dispatcher.connect(position_updated, "position", m) motors_list = sorted(motors_list, cmp=lambda x, y: cmp(x["name"], y["name"])) counters_list = list() for name, cnt in objects_by_type["counters"].iteritems(): counters_list.append({"name": name}) actuators_list = list() for name, obj in objects_by_type["actuator"].iteritems(): try: state = obj.state() except: state = None actuators_list.append({ "name": name, "state": convert_state(state) }) def state_updated(state, name=name): output_queue.put((None, { "name": name, "state": convert_state(state) })) output_queue.callbacks["actuator"][name] = state_updated dispatcher.connect(state_updated, "state", obj) actuators_list = sorted(actuators_list, cmp=lambda x, y: cmp(x["name"], y["name"])) shutters_list = list() for name, obj in objects_by_type["shutter"].iteritems(): try: state = obj.state() except: state = None shutters_list.append({ "name": name, "state": convert_state(state) }) def state_updated(state, name=name): output_queue.put((None, { "name": name, "state": convert_state(state) })) output_queue.callbacks["shutter"][name] = state_updated dispatcher.connect(state_updated, "state", obj) shutters_list = sorted(shutters_list, cmp=lambda x, y: cmp(x["name"], y["name"])) output_queue.put((None, StopIteration({ "motors": motors_list, "counters": counters_list, "actuator": actuators_list, "shutter": shutters_list }))) elif action == "execute": code = _[0] if client_uuid is not None: if i.executed_greenlet and not i.executed_greenlet.ready(): output_queue.put( (client_uuid, StopIteration(RuntimeError("Server is busy.")))) continue def execution_done(executed_greenlet, output_queue=output_queue, client_uuid=client_uuid): try: res = executed_greenlet.get() except EOFError: output_queue.put((client_uuid, StopIteration(EOFError()))) except RuntimeError, error_string: output_queue.put( (client_uuid, StopIteration(RuntimeError(error_string)))) else: output_queue.put((client_uuid, StopIteration(None))) i.execute(client_uuid, code, wait=False).link(execution_done)
def start(session_id, input_queue, output_queue, i): # restore default SIGINT behaviour def raise_kb_interrupt(interpreter=i): if not interpreter.kill(KeyboardInterrupt): raise KeyboardInterrupt gevent.signal(signal.SIGINT, raise_kb_interrupt) output_queue.callbacks = { "motor": dict(), "scans": dict(), "actuator": dict(), "shutter": dict() } init_scans_callbacks(i, output_queue) config = static_config.get_config() session = config.get(session_id) i.locals["resetup"] = functools.partial(session.setup, env_dict=i.locals, verbose=True) root_logger = logging.getLogger() custom_log_handler = LogHandler(output_queue) custom_log_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) root_logger.addHandler(custom_log_handler) while True: try: client_uuid, action, _ = input_queue.get() except EOFError: break if action == "syn": output_queue.put("ack") continue elif action == "synoptic": object_name, method_name = _ namespace = i.locals for name in object_name.split('.'): obj = namespace.get(name) namespace = dict(inspect.getmembers(obj)) if obj is not None: method = getattr(obj, method_name) if callable(method): gevent.spawn(method) elif action == "get_object": object_name = _[0] object_dict = dict() namespace = i.locals for name in object_name.split('.'): obj = namespace.get(name) namespace = dict(inspect.getmembers(obj)) if obj is not None: object_dict["type"] = get_object_type(obj) if object_dict["type"] == "motor": m = obj try: pos = "%.3f" % m.position() state = convert_state(m.state()) except: pos = None state = None object_dict.update({"state": state, "position": pos}) def state_updated(state, name=object_name): output_queue.put((None, { "name":name, "state": convert_state(state)})) def position_updated(pos, name=object_name, client_uuid=client_uuid): pos = "%.3f" % pos output_queue.put((None, {"name":name, "position":pos})) output_queue.callbacks["motor"][object_name]=(state_updated, position_updated) dispatcher.connect(state_updated, "state", m) dispatcher.connect(position_updated, "position", m) elif object_dict["type"] == "actuator": try: state = obj.state() except: state = None object_dict.update({"state": convert_state(state)}) def state_updated(state, name=object_name): output_queue.put((None, {"name": name, "state": convert_state(state)})) output_queue.callbacks["actuator"][object_name]=state_updated dispatcher.connect(state_updated, "state", obj) elif object_dict["type"] == "shutter": try: state = obj.state() except: state = None object_dict.update({ "state": convert_state(state) }) def state_updated(state, name=object_name): output_queue.put((None, {"name":name, "state":convert_state(state)})) output_queue.callbacks["shutter"][object_name]=state_updated dispatcher.connect(state_updated, "state", obj) output_queue.put((None, StopIteration(object_dict))) elif action == "get_objects": objects_by_type = get_objects_by_type(i.locals) pprint.pprint(objects_by_type) motors_list = list() for name, m in objects_by_type["motors"].iteritems(): try: pos = "%.3f" % m.position() state = convert_state(m.state()) except: pos = None state = None motors_list.append({ "name": m.name, "state": state, "position": pos }) def state_updated(state, name=name): output_queue.put((None, { "name":name, "state": convert_state(state)})) def position_updated(pos, name=name, client_uuid=client_uuid): pos = "%.3f" % pos output_queue.put((None, {"name":name, "position":pos})) output_queue.callbacks["motor"][name]=(state_updated, position_updated) dispatcher.connect(state_updated, "state", m) dispatcher.connect(position_updated, "position", m) motors_list = sorted(motors_list, cmp=lambda x,y: cmp(x["name"],y["name"])) counters_list = list() for name, cnt in objects_by_type["counters"].iteritems(): counters_list.append({"name":name}) actuators_list = list() for name, obj in objects_by_type["actuator"].iteritems(): try: state = obj.state() except: state = None actuators_list.append({"name": name, "state": convert_state(state)}) def state_updated(state, name=name): output_queue.put((None, {"name": name, "state": convert_state(state)})) output_queue.callbacks["actuator"][name]=state_updated dispatcher.connect(state_updated, "state", obj) actuators_list = sorted(actuators_list, cmp=lambda x,y: cmp(x["name"],y["name"])) shutters_list = list() for name, obj in objects_by_type["shutter"].iteritems(): try: state = obj.state() except: state = None shutters_list.append({"name": name, "state": convert_state(state) }) def state_updated(state, name=name): output_queue.put((None, {"name":name, "state":convert_state(state)})) output_queue.callbacks["shutter"][name]=state_updated dispatcher.connect(state_updated, "state", obj) shutters_list = sorted(shutters_list, cmp=lambda x,y: cmp(x["name"],y["name"])) output_queue.put((None, StopIteration({ "motors": motors_list, "counters": counters_list, "actuator": actuators_list, "shutter": shutters_list }))) elif action == "execute": code = _[0] if client_uuid is not None: if i.executed_greenlet and not i.executed_greenlet.ready(): output_queue.put((client_uuid, StopIteration(RuntimeError("Server is busy.")))) continue def execution_done(executed_greenlet, output_queue=output_queue, client_uuid=client_uuid): try: res = executed_greenlet.get() except EOFError: output_queue.put((client_uuid, StopIteration(EOFError()))) except RuntimeError, error_string: output_queue.put((client_uuid, StopIteration(RuntimeError(error_string)))) else: output_queue.put((client_uuid, StopIteration(None))) i.execute(client_uuid, code, wait=False).link(execution_done)