def test_read_input_counter(self): config = static.get_config() aa = config.get("thermo_sample") myval = aa.read() print "%s" % (myval) myvalcount = aa.counter.read() self.assertAlmostEqual(myval, myvalcount, places=1)
def main(): import argparse from bliss.config.static import get_config parser = argparse.ArgumentParser(description=__doc__.split('\n')[1]) parser.add_argument( 'name', help='server name as defined in the static configuration') parser.add_argument( '--log-level', default='WARNING', help='log level', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']) args = parser.parse_args() fmt = '%(asctime)-15s %(levelname)-5s %(name)s: %(message)s' level = getattr(logging, args.log_level.upper()) logging.basicConfig(format=fmt, level=level) config = get_config() server = create_server_from_config(config, args.name) try: server.serve_forever() except KeyboardInterrupt: print("\nCtrl-C Pressed. Bailing out...") try: server.terminate() print("Server terminated... I'll be back.") except: print("No terminate function for server or error in terminating.")
def test_set_stepval(self): SP = 23 config = static.get_config() bb = config.get("heater") bb.step(SP) val = bb.step() self.assertEqual(SP, val)
def test_read_output_counter(self): config = static.get_config() bb = config.get("heater") myval = bb.read() print "%s" % (myval) myvalcount = bb.counter.read() self.assertAlmostEqual(myval, myvalcount, places=1)
def test_read_output_counter(self): config = static.get_config() bb=config.get("heater") myval = bb.read() print "%s" % (myval) myvalcount = bb.counter.read() self.assertAlmostEqual(myval,myvalcount,places=1)
def return_synoptic_svg(session_id): s = static_config.get_config().get(session_id) svg = SYNOPTIC.get(session_id, {}).get('svg-file') if svg: return beacon.get_config_file(os.path.join(s._base_path, svg)) else: return ""
def test_loop_regulation(self): config = static.get_config() cc=config.get("sample_regulation") print "starting regulation" cc.on() print "Stopping regulation" cc.off()
def test_set_ramprate(self): SP=45 config = static.get_config() bb=config.get("heater") bb.ramprate(SP) val = bb.ramprate() self.assertEqual(SP,val)
def test_set_ramprate(self): SP = 45 config = static.get_config() bb = config.get("heater") bb.ramprate(SP) val = bb.ramprate() self.assertEqual(SP, val)
def open_session(session_id): client_id = str(uuid.uuid1()) if not session_id in INTERPRETER: cmds_queue,EXECUTION_QUEUE[session_id] = gipc.pipe() output_queue_from_interpreter, output_queue = gipc.pipe() RESULT[session_id] = dict() config = static_config.get_config() session = config.get(session_id) session_cfg = config.get_config(session.name) synoptic = session_cfg.get('synoptic') if synoptic: SYNOPTIC[session_id] = synoptic INTERPRETER[session_id] = gipc.start_process(interpreter.start_interpreter, args=(session_id, cmds_queue, output_queue), kwargs={"beacon_host": os.environ.get("BEACON_HOST"), "beacon_port": os.environ.get("BEACON_PORT") }) EXECUTION_QUEUE[session_id].put((None, "syn", (None,))) output_queue_from_interpreter.get() #ack OUTPUT_QUEUE[session_id] = dict() gevent.spawn(handle_output, session_id, output_queue_from_interpreter) RESULT[session_id][client_id] = gevent.event.AsyncResult() OUTPUT_QUEUE[session_id][client_id] = gevent.queue.Queue() root_path = os.path.dirname(os.path.abspath(__file__)) contents = file(os.path.join(root_path, "shell.html"), "r") template = Template(contents.read()) return template.render(client_uuid=repr(client_id))
def open_session(session_id): client_id = str(uuid.uuid1()) if not session_id in INTERPRETER: cmds_queue, EXECUTION_QUEUE[session_id] = gipc.pipe() output_queue_from_interpreter, output_queue = gipc.pipe() RESULT[session_id] = dict() config = static_config.get_config() session = config.get(session_id) session_cfg = config.get_config(session.name) synoptic = session_cfg.get('synoptic') if synoptic: SYNOPTIC[session_id] = synoptic INTERPRETER[session_id] = gipc.start_process( interpreter.start_interpreter, args=(session_id, cmds_queue, output_queue), kwargs={ "beacon_host": os.environ.get("BEACON_HOST"), "beacon_port": os.environ.get("BEACON_PORT") }) EXECUTION_QUEUE[session_id].put((None, "syn", (None, ))) output_queue_from_interpreter.get() #ack OUTPUT_QUEUE[session_id] = dict() gevent.spawn(handle_output, session_id, output_queue_from_interpreter) RESULT[session_id][client_id] = gevent.event.AsyncResult() OUTPUT_QUEUE[session_id][client_id] = gevent.queue.Queue() root_path = os.path.dirname(os.path.abspath(__file__)) contents = file(os.path.join(root_path, "shell.html"), "r") template = Template(contents.read()) return template.render(client_uuid=repr(client_id))
def init(self): self.username = self.turret_name cfg = static.get_config() self.turret = cfg.get(self.turret_name) self.connect(self.turret, "position", self.position_changed) self.connect(self.turret, "mode", self.mode_changed)
def test_set_stepval(self): SP=23 config = static.get_config() bb=config.get("heater") bb.step(SP) val = bb.step() self.assertEqual(SP,val)
def test_set_dwell(self): SP=12 config = static.get_config() bb=config.get("heater") bb.dwell(SP) val = bb.dwell() self.assertEqual(SP,val)
def test_loop_regulation(self): config = static.get_config() cc = config.get("sample_regulation") print "starting regulation" cc.on() print "Stopping regulation" cc.off()
def main(): import argparse from bliss.config.static import get_config parser = argparse.ArgumentParser(description=__doc__.split('\n')[1]) parser.add_argument('name', help='server name as defined in the static configuration') parser.add_argument('--log-level', default='WARNING', help='log level', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']) args = parser.parse_args() fmt = '%(asctime)-15s %(levelname)-5s %(name)s: %(message)s' level = getattr(logging, args.log_level.upper()) logging.basicConfig(format=fmt, level=level) config = get_config() server = create_server_from_config(config, args.name) try: server.serve_forever() except KeyboardInterrupt: print("\nCtrl-C Pressed. Bailing out...") try: server.terminate() print ("Server terminated... I'll be back.") except: print ("No terminate function for server or error in terminating.")
def test_set_dwell(self): SP = 12 config = static.get_config() bb = config.get("heater") bb.dwell(SP) val = bb.dwell() self.assertEqual(SP, val)
def test_read_input_counter(self): config = static.get_config() aa=config.get("thermo_sample") myval = aa.read() print "%s" % (myval) myvalcount = aa.counter.read() self.assertAlmostEqual(myval,myvalcount,places=1)
def get_motion_hook(name): cfg = get_config() if name.startswith('$'): name = name[1:] hook = cfg.get(name) if not isinstance(hook, MotionHook): raise TypeError("%s is not a MotionHook" % name) return hook
def init_device(self) : Device.init_device(self) self.set_state(tango.DevState.FAULT) self.get_device_properties(self.get_device_class()) config = static.get_config() self.__multiplexer = config.get(self.multiplexer_name) self.__multiplexer.load_program() self.set_state(tango.DevState.ON)
def test_kd(self): KW=1 config = static.get_config() cc=config.get("sample_regulation") print "Setting D to %f" % KW cc.kd(KW) myval = cc.kd() self.assertEqual(KW,myval)
def init(self): """Initialise the motor""" AbstractMotor.init(self) cfg = static.get_config() self.motor_obj = cfg.get(self.actuator_name) self.connect(self.motor_obj, "position", self.update_value) self.connect(self.motor_obj, "state", self.update_state) self.connect(self.motor_obj, "move_done", self.update_state)
def init_device(self): Device.init_device(self) self.set_state(tango.DevState.FAULT) self.get_device_properties(self.get_device_class()) config = static.get_config() self.__multiplexer = config.get(self.multiplexer_name) self.__multiplexer.load_program() self.set_state(tango.DevState.ON)
def test_kd(self): KW = 1 config = static.get_config() cc = config.get("sample_regulation") print "Setting D to %f" % KW cc.kd(KW) myval = cc.kd() self.assertEqual(KW, myval)
def reload(self): cfg = static.get_config() # this reloads *all* the configuration, hopefully it is not such # a big task and it can be left as simple as it is, if needed # we could selectively reload only parts of the config (e.g one # single object yml file) cfg.reload() self.config_dict = cfg.get_config(self.config_dict['name']) self._update_channel()
def init(self): self.motorState = BlissMotor.NOTINITIALIZED self.username = self.motor_name cfg = static.get_config() self.motor = cfg.get(self.motor_name) self.connect(self.motor, "position", self.positionChanged) self.connect(self.motor, "state", self.updateState) self.connect(self.motor, "move_done", self._move_done)
def get_ct2_dev(dev_name, in_config): global cfg if not cfg: cfg = get_config() else: cfg.reload() dev = cfg.get(dev_name) dev.input_config = in_config return dev
def reload(self): cfg = get_config() # this reloads *all* the configuration, hopefully it is not such # a big task and it can be left as simple as it is, if needed # we could selectively reload only parts of the config (e.g one # single object yml file) cfg.reload() self.config_dict = cfg.get_config(self.config_dict['name']) self._update_channel()
def initialize(session_name): config = static.get_config() user_ns = {"config": config} error_flag = False """ BLISS CLI welcome messages """ t = Terminal() # Version # TODO : define an elegant version numbering. _version = "version 0.01" # Hostname _hostname = platform.node() # Beacon host/port try: _host = get_default_connection()._host _port = str(get_default_connection()._port) except: _host = "UNKNOWN" _port = "UNKNOWN" # Conda environment try: _conda_env = "(in {t.blue}%s{t.normal} Conda environment)".format(t=t) % os.environ['CONDA_DEFAULT_ENV'] except KeyError: _conda_env = "" print_rainbow_banner() print_("") print_("Welcome to BLISS %s running on {t.blue}%s{t.normal} %s".format(t=t) % (_version, _hostname, _conda_env)) print_("Copyright (c) ESRF, 2015-2017") print_("-") print_("Connected to Beacon server on {t.blue}%s{t.normal} (port %s)".format(t=t) % (_host, _port)) """ Setup(s) """ if session_name is not None: session = config.get(session_name) print "%s: Executing setup..." % session.name try: session.setup(env_dict=user_ns, verbose=True) except Exception: error_flag = True sys.excepthook(*sys.exc_info()) else: session = None if error_flag: print "Warning: error(s) happened during setup, setup may not be complete." else: print_("Done.") print_("") return user_ns, session
def main(): # redirect to default session or to list if there is no default config = static_config.get_config() for name in config.names_list: c = config.get_config(name) if c.get('class') != 'Session': continue if c.get_inherited('plugin') != 'session': continue if c.get('default', False): bottle.redirect("/%s" % name) bottle.redirect("/sessions")
def sessions_list(): config = static_config.get_config() sessions = ["<ul>"] for name in config.names_list: c = config.get_config(name) if c.get('class') != 'Session': continue if c.get_inherited('plugin') != 'session': continue sessions.append("<li><a href='/%s'>%s</a></li>" % (name, name)) sessions.append("</ul>") return "<html><head><h3>BLISS sessions</h3><br></head><body>%s</body></html>" % "\n".join(sessions)
def sessions_list(): config = static_config.get_config() sessions = ["<ul>"] for name in config.names_list: c = config.get_config(name) if c.get('class') != 'Session': continue if c.get_inherited('plugin') != 'session': continue sessions.append("<li><a href='/%s'>%s</a></li>" % (name, name)) sessions.append("</ul>") return "<html><head><h3>BLISS sessions</h3><br></head><body>%s</body></html>" % "\n".join( sessions)
def init_device(self): Device.init_device(self) try: config = get_config() self.device = config.get(self.name) switch_state(self, DevState.ON, "Ready!") except Exception as e: msg = "Exception initializing device: {0}".format(e) self.error_stream(msg) switch_state(self, DevState.FAULT, msg)
def get_config(reload=False): global __config try: cfg = __config if reload: cfg.reload() return cfg except NameError: from bliss.config.static import get_config __config = get_config() return __config
def get_sessions_list(): """Return a list of available sessions found in config""" all_sessions = list() config = static.get_config() for name in config.names_list: c = config.get_config(name) if c.get("class") != "Session": continue if c.get_inherited("plugin") != "session": continue all_sessions.append(name) return all_sessions
def test_loop_output_ramp_stop(self): SP = 20 config = static.get_config() cc = config.get("sample_regulation") val = cc.output.read() print "Ramping (then stopping) from %s to %s" % (val, SP) cc.output.ramp(SP) gevent.sleep(3) print("Stopping") cc.output.stop() myval = cc.output.read() print "Now at: %s" % myval
def init(self, *args): cfg = static.get_config() session = cfg.get(self.getProperty("session")) session.setup(self.__dict__, verbose=True) self.__session_watcher = gevent.spawn(watch_session, self.getProperty("session"), self.__on_scan_new, self.__on_scan_data, self.__on_scan_end) self.__scan_data = dict()
def test_loop_set(self): SP = 18 config = static.get_config() cc = config.get("sample_regulation") val = cc.output.read() print "Direct setpoint from %s to %s" % (val, SP) cc.set(SP) cc.output.wait() myval = cc.output.read() print myval print "%s rounded to %s" % (myval, int(round(myval))) self.assertAlmostEqual(int(round(myval)), SP, places=1)
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--log-level', type=str, default='info', help='log level (debug, info, warning, error) [default: info]') parser.add_argument('--nb-points', type=int, help='number of points [default: 1000]', default=1000) parser.add_argument('--acq-time', type=float, default=1e-3, help='acquisition time [default: 0.001]') parser.add_argument('--p201', type=str, default="p201", help='P201 card configuration name [default: p201]') args = parser.parse_args() logging.basicConfig(level=getattr(logging, args.log_level.upper()), format="%(asctime)s %(levelname)s %(name)s: %(message)s") nb_points = args.nb_points acq_time = args.acq_time config = static.get_config() p201 = config.get(args.p201) p201_config = config.get_config(args.p201) channels = {} for counter in p201_config.get("counters", []): addr = counter['address'] enabled = counter.get('software enable', False) # skip internal masters and disabled channels if addr >= p201.COUNTERS[-2] or not enabled: continue name = counter.get('name', "c%d" % addr) channels[name] = addr print "The following counters (which have software enable=True) will be used: ", print ", ".join(sorted(channels.keys())) p201_master = P201AcquisitionMaster(p201, nb_points=nb_points, acq_expo_time=acq_time) p201_counters = P201AcquisitionDevice(p201, nb_points=nb_points, acq_expo_time=acq_time, channels=channels) chain = AcquisitionChain() chain.add(p201_master, p201_counters) scan = Scan(chain, ScanRecorder()) chain._tree.show() print("Prepare") scan.prepare() print("Start!") t = time.time() scan.start() dt = time.time() - t print("Finished (took %fs)!" % dt)
def __onReconfigure(self): card = self.__card cfg = get_config(reload=True) if card is None: return card.request_exclusive_access() card.set_interrupts() card.reset_FIFO_error_flags() card.reset() card.software_reset() card_cfg = cfg.get_config(self.__card.name) ct2_module.configure_card(self.__card, card_cfg)
def test_loop_set(self): SP=18 config = static.get_config() cc=config.get("sample_regulation") val = cc.output.read() print "Direct setpoint from %s to %s" % (val,SP) cc.set(SP) cc.output.wait() myval = cc.output.read() print myval print "%s rounded to %s" % (myval,int(round(myval))) self.assertAlmostEqual(int(round(myval)),SP,places=1)
def init_device(self): Device.init_device(self) try: if self.name: config = get_config() self.fuelcell = config.get(self.name) else: self.fuelcell = _FuelCell('Fuel Cell', dict(tcp=dict(url=self.url))) self.set_state(DevState.ON) self.set_status('Ready!') except Exception as e: self.set_state(DevState.FAULT) self.set_status('Error:\n' + str(e))
def test_output_set(self): SP=10 config = static.get_config() bb=config.get("heater") val = bb.read() print "Direct setpoint from %s to %s" % (val,SP) bb.set(SP) bb.wait() myval = bb.read() print "%s rounded to %s" % (myval,int(round(myval))) self.assertAlmostEqual(int(round(myval)),SP,places=1) myset = bb.set() self.assertAlmostEqual(int(round(myset)),SP,places=1)
def test_output_ramp(self): SP = 13 config = static.get_config() bb = config.get("heater") val = bb.read() print "Ramping from %s to %s" % (val, SP) bb.ramp(SP) print "Wait for end of setpoint (around %s seconds)" % ( int(abs(SP - val)) * 2) bb.wait() myval = bb.read() print "%s rounded to %s" % (myval, int(round(myval))) self.assertAlmostEqual(int(round(myval)), SP, places=1)
def test_output_ramp_abort(self): SP = 18 config = static.get_config() bb = config.get("heater") val = bb.read() print "Ramping (then aborting) from %s to %s" % (val, SP) bb.ramp(SP) #gevent.sleep(3) #time.sleep(3) print("Aborting") bb.abort() myval = bb.read() print "Now at: %s" % myval
def test_output_set(self): SP = 10 config = static.get_config() bb = config.get("heater") val = bb.read() print "Direct setpoint from %s to %s" % (val, SP) bb.set(SP) bb.wait() myval = bb.read() print "%s rounded to %s" % (myval, int(round(myval))) self.assertAlmostEqual(int(round(myval)), SP, places=1) myset = bb.set() self.assertAlmostEqual(int(round(myset)), SP, places=1)
def init(self, *args): cfg = static.get_config() session = cfg.get(self.getProperty("session")) session.setup(self.__dict__, verbose=True) self.__session_watcher = gevent.spawn( watch_session, self.getProperty("session"), self.__on_scan_new, self.__on_scan_data, self.__on_scan_end, ) self.__scan_data = dict()
def __init__(self,name,config_tree) : self.name = name self._boards = OrderedDict() self.__outputs = OrderedDict() all_config = static.get_config() for board in config_tree['boards']: board_name = board.get('name') self._boards[board_name] = all_config.get(board_name) for output_config in config_tree['outputs']: output = Output(self,output_config) self.__outputs[output.name()] = output self.__stat = HashObjSetting('multiplexer.%s' % name) self.__debug= False
def beacon(): args = [ '--port=%d' % BEACON_PORT, '--redis_port=7654', '--redis_socket=/tmp/redis_test.sock', '--db_path=' + BEACON_DB_PATH, '--posix_queue=0', '--tango_port=12345'] proc = subprocess.Popen(BEACON + args) time.sleep(0.5) # wait for beacon to be really started redis_db = redis.Redis(port=7654) redis_db.flushall() beacon_connection = connection.Connection("localhost", BEACON_PORT) client._default_connection = beacon_connection cfg = static.get_config() os.environ["TANGO_HOST"] = "localhost:12345" yield cfg proc.terminate()
def __call__(self, cli): config = get_config() axis = config.get(self.name) label = axis.config.get('label', default=self.name) unit = axis.config.get('unit', default='') state, position = axis.state(), axis.position() result = [] if cli.python_input.bliss_bar_format != 'compact': result.append((StatusToken, label + ': ')) if state == 'MOVING': token = StatusToken.Changing else: token = StatusToken.Ok value = '{0:.4}{1}'.format(position, unit) result.append((token, value)) return result
def initialize_bliss(info, db=None): shell_info = info['shell_info'] object_names = info['object_names'] server_type = info['server_type'] server_instance = info['server_instance'] server_name = server_type + '/' + server_instance cfg = get_config() temp_names = [] for name in object_names: obj_cfg = cfg.get_config(name) # if tango_server is defined it means it is manually added if 'tango_server' in obj_cfg: continue if obj_cfg.plugin == 'temperature': temp_names.append(name) objs, classes = recreate_bliss(server_name, info['manager_device_name'], temp_names, info['device_map'], db=db) return classes
def _load_config(env_dict, names_list=None, verbose=True): try: cfg = static.get_config() except: sys.excepthook(*sys.exc_info()) return cfg.reload() if names_list is None: names_list = cfg.names_list for item_name in names_list: if verbose: print "Initializing '%s`" % item_name try: o = cfg.get(item_name) except: sys.excepthook(*sys.exc_info()) else: env_dict[item_name] = o setattr(setup_globals, item_name, o) del o
def get_server_io_names(instance_name=None, typ='inputs'): if typ == 'inputs' or typ == 'outputs' or typ == 'ctrl_loops': pass else: print "Type %s not recognized. Exiting" % typ sys.exit(255) if instance_name is None: _, instance_name, _ = get_server_info() cfg = get_config() result = [] for item_name in cfg.names_list: item_cfg = cfg.get_config(item_name) if item_cfg.plugin == 'temperature' and \ instance_name in item_cfg.get('tango_server', ()): ctrl_inputs_cfg = item_cfg.parent.get(typ) or () for ctrl_input in ctrl_inputs_cfg: name = ctrl_input.get('name') or '' if name == item_name: result.append(item_name) return result