Exemplo n.º 1
0
    def _load_device(self, name, config):
        """Load a device either from a script or from an installed module"""

        if config is None:
            config_dict = {}
        elif isinstance(config, dict):
            config_dict = config
        elif config[0] == '#':
            # Allow passing base64 encoded json directly in the port string to ease testing.
            import base64
            config_str = str(base64.b64decode(config[1:]), 'utf-8')
            config_dict = json.loads(config_str)
        else:
            try:
                with open(config, "r") as conf:
                    data = json.load(conf)
            except IOError as exc:
                raise ArgumentError("Could not open config file",
                                    error=str(exc),
                                    path=config)

            if 'device' not in data:
                raise ArgumentError(
                    "Invalid configuration file passed to VirtualDeviceAdapter",
                    device_name=name,
                    config_path=config,
                    missing_key='device')

            config_dict = data['device']

        reg = ComponentRegistry()

        if name.endswith('.py'):
            _name, device_factory = reg.load_extension(
                name, class_filter=BaseVirtualDevice, unique=True)
            return _instantiate_virtual_device(device_factory, config_dict,
                                               self._loop)

        seen_names = []
        for device_name, device_factory in reg.load_extensions(
                'iotile.virtual_device',
                class_filter=BaseVirtualDevice,
                product_name="virtual_device"):
            if device_name == name:
                return _instantiate_virtual_device(device_factory, config_dict,
                                                   self._loop)

            seen_names.append(device_name)

        raise ArgumentError("Could not find virtual_device by name",
                            name=name,
                            known_names=seen_names)
Exemplo n.º 2
0
def instantiate_interface(virtual_iface, config):
    """Find a virtual interface by name and instantiate it

    Args:
        virtual_iface (string): The name of the pkg_resources entry point corresponding to
            the interface.  It should be in group iotile.virtual_interface
        config (dict): A dictionary with a 'interface' key with the config info for configuring
            this virtual interface.  This is optional.

    Returns:
        VirtualInterface: The instantiated subclass of VirtualInterface
    """

    # Allow the null virtual interface for testing
    if virtual_iface == 'null':
        return VirtualIOTileInterface()

    conf = {}
    if 'interface' in config:
        conf = config['interface']

    try:
        reg = ComponentRegistry()
        if virtual_iface.endswith('.py'):
            _name, iface = reg.load_extension(
                virtual_iface,
                class_filter=VirtualIOTileInterface,
                unique=True)
        else:
            _name, iface = reg.load_extensions(
                'iotile.virtual_interface',
                name_filter=virtual_iface,
                class_filter=VirtualIOTileInterface,
                unique=True)

        return iface(conf)
    except ArgumentError as err:
        print("ERROR: Could not load virtual interface (%s): %s" %
              (virtual_iface, err.msg))
        sys.exit(1)
Exemplo n.º 3
0
def instantiate_device(virtual_dev, config, loop):
    """Find a virtual device by name and instantiate it

    Args:
        virtual_dev (string): The name of the pkg_resources entry point corresponding to
            the device.  It should be in group iotile.virtual_device.  If virtual_dev ends
            in .py, it is interpreted as a python script and loaded directly from the script.
        config (dict): A dictionary with a 'device' key with the config info for configuring
            this virtual device.  This is optional.

    Returns:
        BaseVirtualDevice: The instantiated subclass of BaseVirtualDevice
    """
    conf = {}
    if 'device' in config:
        conf = config['device']

    # If we're given a path to a script, try to load and use that rather than search for an installed module
    try:
        reg = ComponentRegistry()

        if virtual_dev.endswith('.py'):
            _name, dev = reg.load_extension(virtual_dev,
                                            class_filter=BaseVirtualDevice,
                                            unique=True)
        else:
            _name, dev = reg.load_extensions('iotile.virtual_device',
                                             name_filter=virtual_dev,
                                             class_filter=BaseVirtualDevice,
                                             product_name="virtual_device",
                                             unique=True)

        return dev(conf)
    except ArgumentError as err:
        print("ERROR: Could not load virtual device (%s): %s" %
              (virtual_dev, err.msg))
        sys.exit(1)