def main(*args): """Run a Tango gateway server from CLI arguments.""" # Create parser parser = argparse.ArgumentParser(prog='tango-gateway', description='Run a Tango gateway server') parser.add_argument( '--bind', '-b', metavar='ADDRESS', default='0.0.0.0', action=EnvDefault, envvar='TANGO_GATEWAY_BIND', help='Specify the bind address (default is all interfaces)') parser.add_argument('--port', '-p', metavar='PORT', default=10000, type=int, action=EnvDefault, envvar='TANGO_GATEWAY_PORT', help='Port for the server (default is 10000)') parser.add_argument('--tango', '-t', metavar='HOST', action=EnvDefault, envvar='TANGO_GATEWAY_HOST', help='Tango host (default is given by PyTango)') parser.add_argument('--verbose', '-v', action='store_true') # Parse arguments namespace = parser.parse_args(*args) # Check Tango database if tango is None: if namespace.tango: print("Warning: PyTango not available, cannot check database") namespace.tango = namespace.tango.split(":") else: parser.error("PyTango not available, " "the tango host has to be defined explicitely") else: if namespace.tango: host = namespace.tango.split(":")[0] port = namespace.tango.split(":")[1] db = tango.Database(host, port) else: db = tango.Database() namespace.tango = db.get_db_host(), int(db.get_db_port()) # Run the server return run_gateway_server(namespace.bind, namespace.port, namespace.tango, namespace.verbose)
def normalize_config(config): """ Take a 'loose' config and return a new config that conforms to the DSConfig format. Current transforms: - server instances (e.g. 'TangoTest/1') are split into a server level and an instance level (e.g. 'TangoTest' -> '1'). This is to convert "v1" format files to the "v2" format. - "devices" toplevel; allows to change *existing* devices by just adding them directly to a "devices" key in the config, instead of having to list out the server, instance and class (since this information can be gotten from the DB.) """ old_config = expand_config(config) new_config = SetterDict() if "servers" in old_config: new_config.servers = old_config["servers"] if "classes" in old_config: new_config.classes = old_config["classes"] if "devices" in old_config: db = tango.Database() for device, props in list(old_config["devices"].items()): try: info = db.get_device_info(device) except tango.DevFailed as e: sys.exit("Can't reconfigure device %s: %s" % (device, str(e[0].desc))) srv, inst = info.ds_full_name.split("/") new_config.servers[srv][inst][info.class_name][device] = props return new_config.to_dict()
def register_devices(): """.""" tango_db = tango.Database() logging.info("Registering devices!") device_info = tango.DbDevInfo() device_class = 'TestDevice1' # Name of device (/server?) class. device_info._class = device_class # Name of server instance device_info.server = "{}/1".format(device_class) # Generate names and add devices to the database. start_time = time.time() num_devices = 1 for index in range(num_devices): device_info.name = 'test/1/{:03d}'.format(index) tango_db.add_device(device_info) # Set properties tango_db.put_class_property(device_class, dict(version='1.0.0')) print('elapsed = {}'.format(time.time() - start_time))
def calendarclock(request): """Creates and returns a TANGO DeviceTestContext object. Parameters ---------- request: _pytest.fixtures.SubRequest A request object gives access to the requesting test context. """ if request is not None: logging.info(str(request)) properties = {} true_context = request.config.getoption("--true-context") if not true_context: tc = DeviceTestContext(CalendarClockDevice, properties=properties, process=True) tc.start() yield tc.device tc.stop() else: database = tango.Database() instance_list = database.get_device_exported_for_class( "CalendarClockDevice") for instance in instance_list.value_string: yield tango.DeviceProxy(instance) break
def delete_devices(): """.""" db = tango.Database() class_list = db.get_class_list('*') print('class list = ', class_list) server_list = db.get_server_list('*') print('server list = ', server_list)
class DatabaseTool: """Database manipulation for Andrew's experimental Tango device""" _server = "AndrewDev/test" _class = "AndrewDev" _name_string = "test/andrew_dev/dev{:d}" _count = 10 db = tango.Database() def add(self): """Add instances of the device to the DB""" dev_info = tango.DbDevInfo() dev_info.server = self._server dev_info._class = self._class for i in range(self._count): dev_info.name = self._name_string.format(i) self.db.add_device(dev_info) def delete(self): """Delete instances of the device from the DB""" for i in range(self._count): self.db.delete_device(self._name_string.format(i)) def list(self): """Return a list of all instances of the device in the DB""" return self.db.get_device_name(self._server, self._class).value_string
def get_devices(self): """ Helper that retuns a dict of devices for this server. :return: Returns a tuple of two elements: - dict<tango class name : list of device names> - dict<device names : tango class name> :rtype: tuple<dict, dict> """ if self.__util is None: import tango db = tango.Database() else: db = self.__util.get_database() server = self.server_instance dev_list = db.get_device_class_list(server) class_map, dev_map = {}, {} for class_name, dev_name in zip(dev_list[1::2], dev_list[::2]): dev_names = class_map.get(class_name) if dev_names is None: class_map[class_name] = dev_names = [] dev_name = dev_name.lower() dev_names.append(dev_name) dev_map[dev_name] = class_name return class_map, dev_map
def get_attribute_property(self, attr_name, prop_name=None): db = tango.Database() # db = self.device_proxy.get_device_db() apr = db.get_device_attribute_property(self.get_name(), attr_name) if prop_name is None: return apr[attr_name] return apr[attr_name][prop_name][0]
def __recreate_axes(server_name, manager_dev_name, axis_names, dev_map, db=None): db = db or tango.Database() curr_axes = {} for dev_class, dev_names in dev_map.items(): if not dev_class.startswith('BlissAxis_'): continue for dev_name in dev_names: curr_axis_name = dev_name.rsplit("/", 1)[-1] try: get_axis(curr_axis_name) except: elog.info("Error instantiating %s (%s):" % (curr_axis_name, dev_name)) traceback.print_exc() curr_axes[curr_axis_name] = dev_name, dev_class axis_names_set = set(axis_names) curr_axis_names_set = set(curr_axes) new_axis_names = axis_names_set.difference(curr_axis_names_set) old_axis_names = curr_axis_names_set.difference(axis_names_set) domain, family, member = manager_dev_name.split('/', 2) # remove old axes for axis_name in old_axis_names: dev_name, klass_name = curr_axes[axis_name] elog.debug('removing old axis %s (%s)' % (dev_name, axis_name)) db.delete_device(dev_name) # add new axes for axis_name in new_axis_names: dev_name = "%s/%s_%s/%s" % (domain, family, member, axis_name) info = tango.DbDevInfo() info.server = server_name info._class = 'BlissAxis_' + axis_name info.name = dev_name elog.debug('adding new axis %s (%s)' % (dev_name, axis_name)) db.add_device(info) # try to create alias if it doesn't exist yet try: db.get_device_alias(axis_name) except tango.DevFailed: elog.debug('registering alias for %s (%s)' % (dev_name, axis_name)) db.put_device_alias(dev_name, axis_name) axes, tango_classes = [], [] for axis_name in axis_names_set: axis = get_axis(axis_name) axes.append(axis) tango_class = __create_tango_axis_class(axis) tango_classes.append(tango_class) return axes, tango_classes
def run(self): """ worker thread """ if hasattr(tango.ApiUtil, 'cleanup'): tango.ApiUtil.cleanup() self.__db = tango.Database() self.stopServers() self.unregisterServers()
def get_property(ds, name): db = tango.Database() proplist = db.get_device_property(ds, name)[name] if len(proplist) > 1: prop = "\\n".join(proplist) else: prop = proplist[0] return prop
def __get_db(host_port=None): """host_port == None: Use current DB whatever it is or create default if doesn't exist host_port == '' : use default db. If it is not the current db, switch current db to it and return it host_port == ... : if ... is not the current db, switch current db to it and return it """ user_ns = get_user_ns() global _DB_SYMB db = user_ns.get(_DB_SYMB) if host_port is None: if db is None: host_port = __get_default_tango_host() elif host_port == '': host_port = __get_default_tango_host() else: host_port = host_port.strip().replace(" ", ":") if host_port.count(":") == 0: host_port += ":10000" if host_port is not None: host_port = str(host_port) if db is None: create_db = True elif host_port is None: create_db = False else: old_host_port = "%s:%s" % (db.get_db_host(), db.get_db_port()) create_db = old_host_port != host_port if create_db: try: db = tango.Database(*host_port.split(":")) user_ns["DB_NAME"] = host_port except Exception as e: if db: print("\nCould not access Database %s:" % host_port) print(str(e)) old_host_port = "%s:%s" % (db.get_db_host(), db.get_db_port()) print("Maintaining connection to Database", old_host_port) user_ns["DB_NAME"] = old_host_port else: print("\nCould not access any Database. Make sure:") print( "\t- .tangorc, /etc/tangorc or TANGO_HOST environment is defined." ) print("\t- the Database DS is running") user_ns["DB_NAME"] = "OFFLINE" # register the 'db' in the user namespace user_ns.update({_DB_SYMB: db}) return db
def __get_default_tango_host(): global _DFT_TANGO_HOST if _DFT_TANGO_HOST is None: try: db = tango.Database() _DFT_TANGO_HOST = "%s:%s" % (db.get_db_host(), db.get_db_port()) except: pass return _DFT_TANGO_HOST
def __init__(self, name, widget: QLabel, prop=None, refresh=False): self.property = prop if self.property is None: self.database = None else: self.database = tango.Database() self.property_value = None self.refresh = refresh super().__init__(name, widget, readonly=True)
def register(): """.""" db = tango.Database() device_info = tango.DbDevInfo() device_info.server = 'TestDeviceServer/1' device_info.name = 'test/test_device/0' device_info._class = 'TestDevice1' db.add_device(device_info)
def set_device_property(self, prop: str, value: str): prop = str(prop) try: db = tango.Database() # self.device_proxy.put_property({prop: value}) db.put_device_property(self.get_name(), {prop: [value]}) except: self.log_exception('Error writing property %s for %s' % (prop, self.get_name()))
def list_devices(): """List tango devices associated with the TestDeviceServer.""" db = tango.Database() server_instance = 'TestDeviceServer/1' device_class = 'TestDevice' devices = list(db.get_device_name(server_instance, device_class)) print('- No. registered devices: {}'.format(len(devices))) exported_devices = list(db.get_device_exported('test/*')) print('- No. running devices: {}'.format(len(exported_devices)))
def andrew_dev(): """Create DeviceProxy for tests""" database = tango.Database() instance_list = database.get_device_exported_for_class('AndrewDev') for instance in instance_list.value_string: try: return tango.DeviceProxy(instance) except tango.DevFailed: continue pytest.fail('failed to create proxy')
def delete_server(): """.""" db = tango.Database() server = 'TestDeviceServer/1' server_list = list(db.get_server_list(server)) if server in server_list: start_time = time.time() db.delete_server('TestDeviceServer/1') print('- Delete server: {:.4f} s'.format(time.time() - start_time))
def main(): import json from optparse import OptionParser usage = "Usage: %prog [term:pattern term2:pattern2...]" parser = OptionParser(usage=usage) parser.add_option("-p", "--no-properties", dest="properties", action="store_false", default=True, help="Exclude device properties") parser.add_option("-a", "--no-attribute-properties", dest="attribute_properties", action="store_false", default=True, help="Exclude attribute properties") parser.add_option("-l", "--no-aliases", dest="aliases", action="store_false", default=True, help="Exclude device aliases") parser.add_option("-d", "--dservers", dest="dservers", action="store_true", help="Include DServer devices") parser.add_option("-s", "--subdevices", dest="subdevices", action="store_true", default=False, help="Include __SubDevices property") parser.add_option("-c", "--class-properties", dest="class_properties", action="store_true", default=False, help="Include class properties") options, args = parser.parse_args() db = tango.Database() dbdata = get_db_data(db, args, properties=options.properties, class_properties=options.class_properties, attribute_properties=options.attribute_properties, aliases=options.aliases, dservers=options.dservers, subdevices=options.subdevices) print((json.dumps(dbdata, ensure_ascii=False, indent=4, sort_keys=True)))
def set_device_property(device_name: str, prop_name: str, value: str, db=None) -> bool: try: if db is None: db = tango.Database() db.put_device_property(device_name, {prop_name: [value]}) return True except: return False
def init_callback(): """Callback called post server initialisation""" global START_TIME db = tango.Database() elapsed = time.time() - START_TIME exported_devices = list(db.get_device_exported('test/*')) num_devices = len(exported_devices) file = open('results.txt', 'a') file.write(',{},{}\n'.format(elapsed, elapsed / num_devices)) print('>> Time taken to start devices: {:.4f} s ({:.4f} s/dev)'.format( elapsed, elapsed / num_devices))
def delete_server(): """Delete the TestDeviceServer from the tango db.""" db = tango.Database() db.set_timeout_millis(50000) server = 'TestDeviceServer/1' server_list = list(db.get_server_list(server)) if server in server_list: start_time = time.time() db.delete_server('TestDeviceServer/1') print('- Delete server: {:.4f} s'.format(time.time() - start_time))
def power_supply(request): """Create DeviceProxy for tests""" true_context = request.config.getoption("--true-context") if not true_context: with DeviceTestContext(PowerSupply) as proxy: yield proxy else: database = tango.Database() instance_list = database.get_device_exported_for_class("PowerSupply") for instance in instance_list.value_string: yield tango.DeviceProxy(instance) break
def list_devices(): """.""" db = tango.Database() server_instance = 'TestDeviceServer/1' device_class = 'TestDevice1' devices1 = list(db.get_device_name(server_instance, device_class)) device_class = 'TestDevice2' devices2 = list(db.get_device_name(server_instance, device_class)) print('- No. registered devices: {}'.format(len(devices1 + devices2))) exported_devices = list(db.get_device_exported('test/*')) print('- No. running devices: {}'.format(len(exported_devices)))
def event_receiver(request): """Create DeviceProxy for tests""" true_context = request.config.getoption("--true-context") if not true_context: with DeviceTestContext(EventReceiver, process=True) as proxy: yield proxy else: database = tango.Database() instance_list = database.get_device_exported_for_class("EventReceiver") for instance in instance_list.value_string: yield tango.DeviceProxy(instance) break
def activate(self): if not self.active: try: self.db = tango.Database() self.devProxy = tango.DeviceProxy(self.get_name()) self.active = True LOGGER.log(logging.DEBUG, "ADC %s activated" % self.get_name()) except: self.active = False self.timeout = time.time() + 10000 LOGGER.log(logging.ERROR, "ADC %s activation error" % self.get_name()) return self.active
def __init__(self, device=None): if device is None: device = inspect.stack()[1].frame.f_locals['self'].get_name() if isinstance(device, tango.server.Device): self.name = device.get_name() elif isinstance(device, str): self.name = device else: raise ValueError( 'Parameter should be string or tango.server.Device') self.db = tango.Database() names = self.db.get_device_property_list(self.name, '*').value_string self.data = {nm: self.get_device_property(nm) for nm in names}
def run(self): """ worker thread """ if hasattr(tango.ApiUtil, 'cleanup'): tango.ApiUtil.cleanup() self.__db = tango.Database() for device in self.__devices: self.register(**device) self.launch(**device) self.__stqueue.put( (tuple(self.__registered_servers), tuple(self.__registered_devices), tuple(self.__launched)))
def get_tango_device_attribute_property(device_name: str, attr_name: str, prop_name: str): try: database = get_tango_device_attribute_property.database except AttributeError: database = tango.Database() get_tango_device_attribute_property.database = database all_attr_prop = database.get_device_attribute_property(device_name, attr_name) all_prop = all_attr_prop[attr_name] if prop_name in all_prop: prop = all_prop[prop_name][0] else: prop = '' return prop