Example #1
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    _LOGGER.addFilter(HideSensitiveFilter(hass))

    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, "")) == "1"
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)
    cors_origins = conf.get(CONF_CORS_ORIGINS, [])

    server = HomeAssistantWSGI(hass,
                               development=development,
                               server_host=server_host,
                               server_port=server_port,
                               api_password=api_password,
                               ssl_certificate=ssl_certificate,
                               ssl_key=ssl_key,
                               cors_origins=cors_origins)

    hass.bus.listen_once(
        ha.EVENT_HOMEASSISTANT_START, lambda event: threading.Thread(
            target=server.start, daemon=True, name='WSGI-server').start())

    hass.wsgi = server
    hass.config.api = rem.API(
        server_host if server_host != '0.0.0.0' else util.get_local_ip(),
        api_password, server_port, ssl_certificate is not None)

    return True
Example #2
0
    def __init__(self, yaml_config):
        """Initialize the instance."""
        conf = yaml_config.get(DOMAIN, {})

        # Get the IP address that will be passed to the Echo during discovery
        self.host_ip_addr = conf.get(CONF_HOST_IP)
        if self.host_ip_addr is None:
            self.host_ip_addr = util.get_local_ip()
            _LOGGER.warning(
                "Listen IP address not specified, auto-detected address is %s",
                self.host_ip_addr)

        # Get the port that the Hue bridge will listen on
        self.listen_port = conf.get(CONF_LISTEN_PORT)
        if not isinstance(self.listen_port, int):
            self.listen_port = DEFAULT_LISTEN_PORT
            _LOGGER.warning("Listen port not specified, defaulting to %s",
                            self.listen_port)

        # Get domains that cause both "on" and "off" commands to map to "on"
        # This is primarily useful for things like scenes or scripts, which
        # don't really have a concept of being off
        self.off_maps_to_on_domains = conf.get(CONF_OFF_MAPS_TO_ON_DOMAINS)
        if not isinstance(self.off_maps_to_on_domains, list):
            self.off_maps_to_on_domains = DEFAULT_OFF_MAPS_TO_ON_DOMAINS

        # Get whether or not entities should be exposed by default, or if only
        # explicitly marked ones will be exposed
        self.expose_by_default = conf.get(CONF_EXPOSE_BY_DEFAULT,
                                          DEFAULT_EXPOSE_BY_DEFAULT)

        # Get domains that are exposed by default when expose_by_default is
        # True
        self.exposed_domains = conf.get(CONF_EXPOSED_DOMAINS,
                                        DEFAULT_EXPOSED_DOMAINS)
Example #3
0
    def setup(self, zeroconf_instance):
        """Set up bridge and accessory driver."""
        ip_addr = self._ip_address or get_local_ip()
        persist_file = get_persist_fullpath_for_entry_id(
            self.hass, self._entry_id)

        self.driver = HomeDriver(
            self.hass,
            self._entry_id,
            self._name,
            self._entry_title,
            loop=self.hass.loop,
            address=ip_addr,
            port=self._port,
            persist_file=persist_file,
            advertised_address=self._advertise_ip,
            zeroconf_instance=zeroconf_instance,
        )

        # If we do not load the mac address will be wrong
        # as pyhap uses a random one until state is restored
        if os.path.exists(persist_file):
            self.driver.load()
            self.driver.state.config_version += 1
            if self.driver.state.config_version > 65535:
                self.driver.state.config_version = 1

        self.driver.persist()
Example #4
0
def setup(hass, config=None):
    """ Sets up the HTTP API and debug interface. """

    if config is None or DOMAIN not in config:
        config = {DOMAIN: {}}

    api_password = util.convert(config[DOMAIN].get(CONF_API_PASSWORD), str)

    no_password_set = api_password is None

    if no_password_set:
        api_password = util.get_random_string()

    # If no server host is given, accept all incoming requests
    server_host = config[DOMAIN].get(CONF_SERVER_HOST, '0.0.0.0')

    server_port = config[DOMAIN].get(CONF_SERVER_PORT, SERVER_PORT)

    development = str(config[DOMAIN].get(CONF_DEVELOPMENT, "")) == "1"

    server = HomeAssistantHTTPServer((server_host, server_port),
                                     RequestHandler, hass, api_password,
                                     development, no_password_set)

    hass.bus.listen_once(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event: threading.Thread(target=server.start, daemon=True).start(
        ))

    hass.http = server
    hass.config.api = rem.API(util.get_local_ip(), api_password, server_port)

    return True
Example #5
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)

    # If no server host is given, accept all incoming requests
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, "")) == "1"
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)

    try:
        server = HomeAssistantHTTPServer(
            (server_host, server_port), RequestHandler, hass, api_password,
            development, ssl_certificate, ssl_key)
    except OSError:
        # If address already in use
        _LOGGER.exception("Error setting up HTTP server")
        return False

    hass.bus.listen_once(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event:
        threading.Thread(target=server.start, daemon=True,
                         name='HTTP-server').start())

    hass.http = server
    hass.config.api = rem.API(server_host if server_host != '0.0.0.0'
                              else util.get_local_ip(),
                              api_password, server_port,
                              ssl_certificate is not None)

    return True
Example #6
0
    def __init__(self, hass, conf):
        """Initialize the instance."""
        self.hass = hass
        self.type = conf.get(CONF_TYPE)
        self.numbers = None
        self.cached_states = {}

        if self.type == TYPE_ALEXA:
            _LOGGER.warning(
                'Emulated Hue running in legacy mode because type has been '
                'specified. More info at https://goo.gl/M6tgz8')

        # Get the IP address that will be passed to the Echo during discovery
        self.host_ip_addr = conf.get(CONF_HOST_IP)
        if self.host_ip_addr is None:
            self.host_ip_addr = util.get_local_ip()
            _LOGGER.info(
                "Listen IP address not specified, auto-detected address is %s",
                self.host_ip_addr)

        # Get the port that the Hue bridge will listen on
        self.listen_port = conf.get(CONF_LISTEN_PORT)
        if not isinstance(self.listen_port, int):
            self.listen_port = DEFAULT_LISTEN_PORT
            _LOGGER.info(
                "Listen port not specified, defaulting to %s",
                self.listen_port)

        if self.type == TYPE_GOOGLE and self.listen_port != 80:
            _LOGGER.warning("When targeting Google Home, listening port has "
                            "to be port 80")

        # Get whether or not UPNP binds to multicast address (239.255.255.250)
        # or to the unicast address (host_ip_addr)
        self.upnp_bind_multicast = conf.get(
            CONF_UPNP_BIND_MULTICAST, DEFAULT_UPNP_BIND_MULTICAST)

        # Get domains that cause both "on" and "off" commands to map to "on"
        # This is primarily useful for things like scenes or scripts, which
        # don't really have a concept of being off
        self.off_maps_to_on_domains = conf.get(CONF_OFF_MAPS_TO_ON_DOMAINS)
        if not isinstance(self.off_maps_to_on_domains, list):
            self.off_maps_to_on_domains = DEFAULT_OFF_MAPS_TO_ON_DOMAINS

        # Get whether or not entities should be exposed by default, or if only
        # explicitly marked ones will be exposed
        self.expose_by_default = conf.get(
            CONF_EXPOSE_BY_DEFAULT, DEFAULT_EXPOSE_BY_DEFAULT)

        # Get domains that are exposed by default when expose_by_default is
        # True
        self.exposed_domains = conf.get(
            CONF_EXPOSED_DOMAINS, DEFAULT_EXPOSED_DOMAINS)

        # Calculated effective advertised IP and port for network isolation
        self.advertise_ip = conf.get(
            CONF_ADVERTISE_IP) or self.host_ip_addr

        self.advertise_port = conf.get(
            CONF_ADVERTISE_PORT) or self.listen_port
Example #7
0
    def setup(self, zeroconf_instance):
        """Set up bridge and accessory driver."""
        self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                                        self.async_stop)
        ip_addr = self._ip_address or get_local_ip()
        persist_file = get_persist_fullpath_for_entry_id(
            self.hass, self._entry_id)

        self.driver = HomeDriver(
            self.hass,
            self._entry_id,
            self._name,
            loop=self.hass.loop,
            address=ip_addr,
            port=self._port,
            persist_file=persist_file,
            advertised_address=self._advertise_ip,
            zeroconf_instance=zeroconf_instance,
        )

        # If we do not load the mac address will be wrong
        # as pyhap uses a random one until state is restored
        if os.path.exists(persist_file):
            self.driver.load()
        else:
            self.driver.persist()
Example #8
0
    def setup(self, zeroconf_instance):
        """Set up bridge and accessory driver."""
        # pylint: disable=import-outside-toplevel
        from .accessories import HomeBridge, HomeDriver

        self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                                        self.async_stop)
        ip_addr = self._ip_address or get_local_ip()
        persist_file = get_persist_fullpath_for_entry_id(
            self.hass, self._entry_id)

        self.driver = HomeDriver(
            self.hass,
            self._entry_id,
            self._name,
            loop=self.hass.loop,
            address=ip_addr,
            port=self._port,
            persist_file=persist_file,
            advertised_address=self._advertise_ip,
            zeroconf_instance=zeroconf_instance,
        )

        # If we do not load the mac address will be wrong
        # as pyhap uses a random one until state is restored
        if os.path.exists(persist_file):
            self.driver.load()
        else:
            self.driver.persist()

        self.bridge = HomeBridge(self.hass, self.driver, self._name)
        if self._safe_mode:
            _LOGGER.debug("Safe_mode selected for %s", self._name)
            self.driver.safe_mode = True
Example #9
0
    async def async_step_pre_end(self, user_input=None):
        _LOGGER.info(f"Step pre end, user_input {user_input}")

        if user_input is not None:
            if user_input["clearcallbacks"]:
                await self.thisBridge.callback_remove_all()
                _LOGGER.debug("Clearing callbacks.")

            self.server_host = user_input["serverhost"]
            # else: raise error

            _LOGGER.info(f"server_hostname {self.server_host}")

            return self.async_create_entry(
                title=self.thisBridge.bridgeId,
                data={
                    "hostname": self.config_host,
                    "port": self.config_port,
                    "server_hostname": self.server_host,
                    "token": self.config_token,
                },
            )
        else:
            _LOGGER.info(f"Showing form because of {user_input}")
            autoDiscoveredIP = util.get_local_ip()

            return self.async_show_form(
                step_id="pre_end",
                data_schema=vol.Schema({
                    vol.Required("serverhost", default=autoDiscoveredIP):
                    str,
                    vol.Optional("clearcallbacks", default=True):
                    bool,
                }),
            )
Example #10
0
    def setup(self):
        """Set up bridge and accessory driver."""
        # pylint: disable=import-outside-toplevel
        from .accessories import HomeBridge, HomeDriver

        self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                                        self.async_stop)
        ip_addr = self._ip_address or get_local_ip()
        persist_file = get_persist_fullpath_for_entry_id(
            self.hass, self._entry_id)

        self.driver = HomeDriver(
            self.hass,
            self._entry_id,
            self._name,
            address=ip_addr,
            port=self._port,
            persist_file=persist_file,
            advertised_address=self._advertise_ip,
            interface_choice=self._interface_choice,
        )

        self.bridge = HomeBridge(self.hass, self.driver, self._name)
        if self._safe_mode:
            _LOGGER.debug("Safe_mode selected for %s", self._name)
            self.driver.safe_mode = True
Example #11
0
def setup(hass, config):
    """ Sets up the HTTP API and debug interface. """

    if not util.validate_config(config, {DOMAIN: [CONF_API_PASSWORD]},
                                _LOGGER):
        return False

    api_password = config[DOMAIN]['api_password']

    # If no server host is given, accept all incoming requests
    server_host = config[DOMAIN].get(CONF_SERVER_HOST, '0.0.0.0')

    server_port = config[DOMAIN].get(CONF_SERVER_PORT, rem.SERVER_PORT)

    development = config[DOMAIN].get(CONF_DEVELOPMENT, "") == "1"

    server = HomeAssistantHTTPServer((server_host, server_port),
                                     RequestHandler, hass, api_password,
                                     development)

    hass.listen_once_event(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event:
        threading.Thread(target=server.start, daemon=True).start())

    hass.listen_once_event(
        ha.EVENT_HOMEASSISTANT_STOP,
        lambda event: server.shutdown())

    # If no local api set, set one with known information
    if isinstance(hass, rem.HomeAssistant) and hass.local_api is None:
        hass.local_api = \
            rem.API(util.get_local_ip(), api_password, server_port)

    return True
Example #12
0
def setup(hass, config):
    """ Sets up the HTTP API and debug interface. """

    if not util.validate_config(config, {DOMAIN: [CONF_API_PASSWORD]},
                                _LOGGER):
        return False

    api_password = config[DOMAIN]['api_password']

    # If no server host is given, accept all incoming requests
    server_host = config[DOMAIN].get(CONF_SERVER_HOST, '0.0.0.0')

    server_port = config[DOMAIN].get(CONF_SERVER_PORT, rem.SERVER_PORT)

    development = config[DOMAIN].get(CONF_DEVELOPMENT, "") == "1"

    server = HomeAssistantHTTPServer((server_host, server_port),
                                     RequestHandler, hass, api_password,
                                     development)

    hass.listen_once_event(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event:
        threading.Thread(target=server.start, daemon=True).start())

    # If no local api set, set one with known information
    if isinstance(hass, rem.HomeAssistant) and hass.local_api is None:
        hass.local_api = \
            rem.API(util.get_local_ip(), api_password, server_port)

    return True
Example #13
0
async def async_setup_entry(hass, config_entry):
    """Set up an emulated roku server from a config entry."""
    config = config_entry.data

    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {}

    name = config[CONF_NAME]
    listen_port = config[CONF_LISTEN_PORT]
    host_ip = config.get(CONF_HOST_IP) or util.get_local_ip()
    advertise_ip = config.get(CONF_ADVERTISE_IP)
    advertise_port = config.get(CONF_ADVERTISE_PORT)
    upnp_bind_multicast = config.get(CONF_UPNP_BIND_MULTICAST)

    server = EmulatedRoku(
        hass,
        name,
        host_ip,
        listen_port,
        advertise_ip,
        advertise_port,
        upnp_bind_multicast,
    )

    hass.data[DOMAIN][name] = server

    return await server.setup()
Example #14
0
    def __init__(
        self,
        host,
        port,
        username,
        password,
        profile_on,
        profile_off,
        device_list,
    ):
        # pylint: disable=import-error
        import fritzconnection as fc
        from fritz_switch_profiles import FritzProfileSwitch

        self.connection = fc.FritzConnection(address=host,
                                             port=port,
                                             user=username,
                                             password=password)

        if device_list != DEFAULT_DEVICES:
            self.profile_switch = FritzProfileSwitch("http://" + host,
                                                     username, password)

        self.fritzstatus = fc.FritzStatus(fc=self.connection)
        self.ha_ip = get_local_ip()
        self.profile_on = profile_on
        self.profile_off = profile_off
        self.profile_last_updated = time.time()
        self.device_list = device_list

        self.username = username
        self.password = password
        self.port = port
        self.host = host
Example #15
0
def setup(hass, config=None):
    """ Sets up the HTTP API and debug interface. """

    if config is None or DOMAIN not in config:
        config = {DOMAIN: {}}

    api_password = util.convert(config[DOMAIN].get(CONF_API_PASSWORD), str)

    no_password_set = api_password is None

    if no_password_set:
        api_password = util.get_random_string()

    # If no server host is given, accept all incoming requests
    server_host = config[DOMAIN].get(CONF_SERVER_HOST, '0.0.0.0')

    server_port = config[DOMAIN].get(CONF_SERVER_PORT, SERVER_PORT)

    development = str(config[DOMAIN].get(CONF_DEVELOPMENT, "")) == "1"

    sessions_enabled = config[DOMAIN].get(CONF_SESSIONS_ENABLED, True)

    server = HomeAssistantHTTPServer(
        (server_host, server_port), RequestHandler, hass, api_password,
        development, no_password_set, sessions_enabled)

    hass.bus.listen_once(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event:
        threading.Thread(target=server.start, daemon=True).start())

    hass.http = server
    hass.config.api = rem.API(util.get_local_ip(), api_password, server_port)

    return True
Example #16
0
def setup(hass, config):
    """Set up Zeroconf and make Home Assistant discoverable."""
    from zeroconf import Zeroconf, ServiceInfo

    zeroconf = Zeroconf()

    zeroconf_name = '{}.{}'.format(uuid_util.get_mac_address(), ZEROCONF_TYPE)

    dev_uuid = uuid_util.get_uuid(hass.config.config_dir)
    params = {
        'version': CUR_VERSION,
        'uuid': dev_uuid
    }

    host_ip = util.get_local_ip()

    try:
        host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
    except socket.error:
        host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip)

    info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, host_ip_pton,
                       hass.http.server_port, 0, 0, params)

    zeroconf.register_service(info)

    def stop_zeroconf(event):
        """Stop Zeroconf."""
        zeroconf.unregister_service(info)
        zeroconf.close()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)

    return True
Example #17
0
def setup(hass, config):
    """Set up Zeroconf and make Home Assistant discoverable."""
    from zeroconf import Zeroconf, ServiceInfo

    zeroconf = Zeroconf()

    zeroconf_name = '{}.{}'.format(hass.config.location_name, ZEROCONF_TYPE)

    requires_api_password = hass.config.api.api_password is not None
    params = {
        'version': __version__,
        'base_url': hass.config.api.base_url,
        'requires_api_password': requires_api_password,
    }

    host_ip = util.get_local_ip()

    try:
        host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
    except socket.error:
        host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip)

    info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, host_ip_pton,
                       hass.http.server_port, 0, 0, params)

    zeroconf.register_service(info)

    def stop_zeroconf(event):
        """Stop Zeroconf."""
        zeroconf.unregister_service(info)
        zeroconf.close()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)

    return True
Example #18
0
def setup(hass, config):
    """Set up Zeroconf and make Home Assistant discoverable."""
    from zeroconf import Zeroconf, ServiceInfo

    zeroconf = Zeroconf()

    zeroconf_name = '{}.{}'.format(hass.config.location_name, ZEROCONF_TYPE)

    requires_api_password = hass.config.api.api_password is not None
    params = {
        'version': __version__,
        'base_url': hass.config.api.base_url,
        'requires_api_password': requires_api_password,
    }

    host_ip = util.get_local_ip()

    try:
        host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
    except socket.error:
        host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip)

    info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, host_ip_pton,
                       hass.http.server_port, 0, 0, params)

    zeroconf.register_service(info)

    def stop_zeroconf(event):
        """Stop Zeroconf."""
        zeroconf.unregister_service(info)
        zeroconf.close()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)

    return True
Example #19
0
def async_setup(hass, config):
    """Set up the HTTP API and debug interface."""
    conf = config.get(DOMAIN)

    if conf is None:
        conf = HTTP_SCHEMA({})

    api_password = conf[CONF_API_PASSWORD]
    server_host = conf[CONF_SERVER_HOST]
    server_port = conf[CONF_SERVER_PORT]
    development = conf[CONF_DEVELOPMENT] == '1'
    ssl_certificate = conf[CONF_SSL_CERTIFICATE]
    ssl_key = conf[CONF_SSL_KEY]
    cors_origins = conf[CONF_CORS_ORIGINS]
    use_x_forwarded_for = conf[CONF_USE_X_FORWARDED_FOR]
    trusted_networks = conf[CONF_TRUSTED_NETWORKS]
    is_ban_enabled = conf[CONF_IP_BAN_ENABLED]
    login_threshold = conf[CONF_LOGIN_ATTEMPTS_THRESHOLD]

    if api_password is not None:
        logging.getLogger('aiohttp.access').addFilter(
            HideSensitiveDataFilter(api_password))

    server = HomeAssistantWSGI(
        hass,
        development=development,
        server_host=server_host,
        server_port=server_port,
        api_password=api_password,
        ssl_certificate=ssl_certificate,
        ssl_key=ssl_key,
        cors_origins=cors_origins,
        use_x_forwarded_for=use_x_forwarded_for,
        trusted_networks=trusted_networks,
        login_threshold=login_threshold,
        is_ban_enabled=is_ban_enabled
    )

    @asyncio.coroutine
    def stop_server(event):
        """Callback to stop the server."""
        yield from server.stop()

    @asyncio.coroutine
    def start_server(event):
        """Callback to start the server."""
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_server)
        yield from server.start()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_server)

    hass.http = server
    hass.config.api = rem.API(server_host if server_host != '0.0.0.0'
                              else get_local_ip(),
                              api_password, server_port,
                              ssl_certificate is not None)

    return True
    def __init__(self, hass, driver, name, entity_id, aid, config):
        """Initialize a Camera accessory object."""
        self._ffmpeg = hass.data[DATA_FFMPEG]
        self._cur_session = None
        self._camera = hass.data[DOMAIN_CAMERA]
        for config_key in CONFIG_DEFAULTS:
            if config_key not in config:
                config[config_key] = CONFIG_DEFAULTS[config_key]

        max_fps = config[CONF_MAX_FPS]
        max_width = config[CONF_MAX_WIDTH]
        max_height = config[CONF_MAX_HEIGHT]
        resolutions = [
            (w, h, fps)
            for w, h, fps in SLOW_RESOLUTIONS
            if w <= max_width and h <= max_height and fps < max_fps
        ] + [
            (w, h, max_fps)
            for w, h in RESOLUTIONS
            if w <= max_width and h <= max_height
        ]

        video_options = {
            "codec": {
                "profiles": [
                    VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["BASELINE"],
                    VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["MAIN"],
                    VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["HIGH"],
                ],
                "levels": [
                    VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE3_1"],
                    VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE3_2"],
                    VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE4_0"],
                ],
            },
            "resolutions": resolutions,
        }
        audio_options = {"codecs": [{"type": "OPUS", "samplerate": 24}]}

        stream_address = config.get(CONF_STREAM_ADDRESS, get_local_ip())

        options = {
            "video": video_options,
            "audio": audio_options,
            "address": stream_address,
            "srtp": True,
        }

        super().__init__(
            hass,
            driver,
            name,
            entity_id,
            aid,
            config,
            category=CATEGORY_CAMERA,
            options=options,
        )
    def local_base_url(self):
        """Define base url of hass in local network."""
        if self._local_base_url is None:
            self._local_base_url = "http://{}".format(util.get_local_ip())

            port = self.hass.config.api.port
            if port is not None:
                self._local_base_url += ':{}'.format(port)
        return self._local_base_url
Example #22
0
    def setup(self):
        """Setup bridge and accessory driver."""
        from .accessories import HomeBridge, HomeDriver

        self._hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.stop)

        path = self._hass.config.path(HOMEKIT_FILE)
        self.bridge = HomeBridge(self._hass)
        self.driver = HomeDriver(self.bridge, self._port, get_local_ip(), path)
Example #23
0
    def local_base_url(self):
        """Define base url of hass in local network."""
        if self._local_base_url is None:
            self._local_base_url = "http://{}".format(util.get_local_ip())

            port = self.hass.config.api.port
            if port is not None:
                self._local_base_url += f":{port}"
        return self._local_base_url
Example #24
0
def _register_hass_zc_service(hass, zeroconf, uuid):
    # Get instance UUID
    valid_location_name = _truncate_location_name_to_valid(
        hass.config.location_name)

    params = {
        "location_name": valid_location_name,
        "uuid": uuid,
        "version": __version__,
        "external_url": "",
        "internal_url": "",
        # Old base URL, for backward compatibility
        "base_url": "",
        # Always needs authentication
        "requires_api_password": True,
    }

    # Get instance URL's
    try:
        params["external_url"] = get_url(hass, allow_internal=False)
    except NoURLAvailableError:
        pass

    try:
        params["internal_url"] = get_url(hass, allow_external=False)
    except NoURLAvailableError:
        pass

    # Set old base URL based on external or internal
    params["base_url"] = params["external_url"] or params["internal_url"]

    host_ip = util.get_local_ip()

    try:
        host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
    except OSError:
        host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip)

    _suppress_invalid_properties(params)

    info = ServiceInfo(
        ZEROCONF_TYPE,
        name=f"{valid_location_name}.{ZEROCONF_TYPE}",
        server=f"{uuid}.local.",
        addresses=[host_ip_pton],
        port=hass.http.server_port,
        properties=params,
    )

    _LOGGER.info("Starting Zeroconf broadcast")
    try:
        zeroconf.register_service(info)
    except NonUniqueNameException:
        _LOGGER.error(
            "Home Assistant instance with identical name present in the local network"
        )
Example #25
0
    def setup(self):
        """Setup bridge and accessory driver."""
        from .accessories import HomeBridge, HomeDriver

        self.hass.bus.async_listen_once(
            EVENT_HOMEASSISTANT_STOP, self.stop)

        path = self.hass.config.path(HOMEKIT_FILE)
        self.bridge = HomeBridge(self.hass)
        self.driver = HomeDriver(self.bridge, self._port, get_local_ip(), path)
Example #26
0
    def setup(self):
        """Set up bridge and accessory driver."""
        from .accessories import HomeBridge, HomeDriver

        self.hass.bus.async_listen_once(
            EVENT_HOMEASSISTANT_STOP, self.stop)

        ip_addr = self._ip_address or get_local_ip()
        path = self.hass.config.path(HOMEKIT_FILE)
        self.driver = HomeDriver(self.hass, address=ip_addr,
                                 port=self._port, persist_file=path)
        self.bridge = HomeBridge(self.hass, self.driver, self._name)
Example #27
0
async def async_setup_platform(hass: HomeAssistantType,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up DLNA DMR platform."""
    if config.get(CONF_URL) is not None:
        url = config[CONF_URL]
        name = config.get(CONF_NAME)
    elif discovery_info is not None:
        url = discovery_info["ssdp_description"]
        name = discovery_info.get("name")

    if DLNA_DMR_DATA not in hass.data:
        hass.data[DLNA_DMR_DATA] = {}

    if "lock" not in hass.data[DLNA_DMR_DATA]:
        hass.data[DLNA_DMR_DATA]["lock"] = asyncio.Lock()

    # build upnp/aiohttp requester
    from async_upnp_client.aiohttp import AiohttpSessionRequester

    session = async_get_clientsession(hass)
    requester = AiohttpSessionRequester(session, True)

    # ensure event handler has been started
    with await hass.data[DLNA_DMR_DATA]["lock"]:
        server_host = config.get(CONF_LISTEN_IP)
        if server_host is None:
            server_host = get_local_ip()
        server_port = config.get(CONF_LISTEN_PORT, DEFAULT_LISTEN_PORT)
        callback_url_override = config.get(CONF_CALLBACK_URL_OVERRIDE)
        event_handler = await async_start_event_handler(
            hass, server_host, server_port, requester, callback_url_override)

    # create upnp device
    from async_upnp_client import UpnpFactory

    factory = UpnpFactory(requester, disable_state_variable_validation=True)
    try:
        upnp_device = await factory.async_create_device(url)
    except (asyncio.TimeoutError, aiohttp.ClientError):
        raise PlatformNotReady()

    # wrap with DmrDevice
    from async_upnp_client.profiles.dlna import DmrDevice

    dlna_device = DmrDevice(upnp_device, event_handler)

    # create our own device
    device = DlnaDmrDevice(dlna_device, name)
    _LOGGER.debug("Adding device: %s", device)
    async_add_entities([device], True)
Example #28
0
    async def async_step_end_progressdone_mezzanine(self, user_input=None):
        _LOGGER.info(f"Step manualtoken, mezz {user_input}")
        autoDiscoveredIP = util.get_local_ip()

        return self.async_show_form(
            step_id="pre_end",
            data_schema=vol.Schema({
                vol.Required("serverhost", default=autoDiscoveredIP):
                str,
                vol.Optional("clearcallbacks", default=True):
                bool,
            }),
        )
Example #29
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    logging.getLogger('aiohttp.access').addFilter(HideSensitiveFilter(hass))

    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, '')) == '1'
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)
    cors_origins = conf.get(CONF_CORS_ORIGINS, [])
    use_x_forwarded_for = conf.get(CONF_USE_X_FORWARDED_FOR, False)
    trusted_networks = [
        ip_network(trusted_network)
        for trusted_network in conf.get(CONF_TRUSTED_NETWORKS, [])]

    server = HomeAssistantWSGI(
        hass,
        development=development,
        server_host=server_host,
        server_port=server_port,
        api_password=api_password,
        ssl_certificate=ssl_certificate,
        ssl_key=ssl_key,
        cors_origins=cors_origins,
        use_x_forwarded_for=use_x_forwarded_for,
        trusted_networks=trusted_networks
    )

    @asyncio.coroutine
    def stop_server(event):
        """Callback to stop the server."""
        yield from server.stop()

    @asyncio.coroutine
    def start_server(event):
        """Callback to start the server."""
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_server)
        yield from server.start()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_server)

    hass.http = server
    hass.config.api = rem.API(server_host if server_host != '0.0.0.0'
                              else util.get_local_ip(),
                              api_password, server_port,
                              ssl_certificate is not None)

    return True
Example #30
0
async def async_setup_platform(hass: HomeAssistant,
                               config,
                               async_add_devices,
                               discovery_info=None):
    """Set up DLNA DMR platform."""
    if config.get(CONF_URL) is not None:
        url = config[CONF_URL]
        name = config.get(CONF_NAME)
    elif discovery_info is not None:
        url = discovery_info['ssdp_description']
        name = discovery_info.get('name')

    if DLNA_DMR_DATA not in hass.data:
        hass.data[DLNA_DMR_DATA] = {}

    if 'lock' not in hass.data[DLNA_DMR_DATA]:
        hass.data[DLNA_DMR_DATA]['lock'] = asyncio.Lock()

    # build upnp/aiohttp requester
    from async_upnp_client.aiohttp import AiohttpSessionRequester
    session = async_get_clientsession(hass)
    requester = AiohttpSessionRequester(session, True)

    # ensure event handler has been started
    with await hass.data[DLNA_DMR_DATA]['lock']:
        server_host = config.get(CONF_LISTEN_IP)
        if server_host is None:
            server_host = get_local_ip()
        server_port = config.get(CONF_LISTEN_PORT, DEFAULT_LISTEN_PORT)
        event_handler = await async_start_event_handler(hass,
                                                        server_host,
                                                        server_port,
                                                        requester)

    # create upnp device
    from async_upnp_client import UpnpFactory
    factory = UpnpFactory(requester, disable_state_variable_validation=True)
    try:
        upnp_device = await factory.async_create_device(url)
    except (asyncio.TimeoutError, aiohttp.ClientError):
        raise PlatformNotReady()

    # wrap with DmrDevice
    from async_upnp_client.dlna import DmrDevice
    dlna_device = DmrDevice(upnp_device, event_handler)

    # create our own device
    device = DlnaDmrDevice(dlna_device, name)
    _LOGGER.debug("Adding device: %s", device)
    async_add_devices([device], True)
Example #31
0
    def __init__(
        self,
        password,
        username = DEFAULT_USERNAME,
        host = DEFAULT_HOST,
        port=DEFAULT_PORT,
        profile_on = DEFAULT_PROFILE_ON,
        profile_off = DEFAULT_PROFILE_OFF,
        device_list = DEFAULT_DEVICES,
        use_port = DEFAULT_USE_PORT,
        use_deflections = DEFAULT_USE_DEFLECTIONS,
        use_wifi = DEFAULT_USE_WIFI,
        use_devices = DEFAULT_USE_DEVICES,
    ):
        # pylint: disable=import-error
        from fritzconnection import FritzConnection
        from fritzconnection.lib.fritzstatus import FritzStatus
        from fritz_switch_profiles import FritzProfileSwitch

        # general timeout for all requests to the router. Some calls need quite some time.
        self.connection = FritzConnection(
            address=host, port=port, user=username, password=password, timeout=30.0
        )

        if device_list != DEFAULT_DEVICES:
            self.profile_switch = FritzProfileSwitch(
                "http://" + host, username, password
            )

        self.fritzstatus = FritzStatus(fc=self.connection)
        self.ha_ip = get_local_ip()
        self.profile_on = profile_on
        self.profile_off = profile_off
        self.profile_last_updated = time.time()
        self.device_list = device_list

        self.username = username
        self.password = password
        self.port = port
        self.host = host

        self.use_wifi = use_wifi
        self.use_port = use_port
        self.use_deflections = use_deflections
        self.use_devices = use_devices

        self._unique_id = self.connection.call_action("DeviceInfo:1", "GetInfo")[
            "NewSerialNumber"
        ]
        self._device_info = self._fetch_device_info()
Example #32
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    logging.getLogger('aiohttp.access').addFilter(HideSensitiveFilter(hass))

    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, '')) == '1'
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)
    cors_origins = conf.get(CONF_CORS_ORIGINS, [])
    use_x_forwarded_for = conf.get(CONF_USE_X_FORWARDED_FOR, False)
    trusted_networks = [
        ip_network(trusted_network)
        for trusted_network in conf.get(CONF_TRUSTED_NETWORKS, [])
    ]

    server = HomeAssistantWSGI(hass,
                               development=development,
                               server_host=server_host,
                               server_port=server_port,
                               api_password=api_password,
                               ssl_certificate=ssl_certificate,
                               ssl_key=ssl_key,
                               cors_origins=cors_origins,
                               use_x_forwarded_for=use_x_forwarded_for,
                               trusted_networks=trusted_networks)

    @asyncio.coroutine
    def stop_server(event):
        """Callback to stop the server."""
        yield from server.stop()

    @asyncio.coroutine
    def start_server(event):
        """Callback to start the server."""
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_server)
        yield from server.start()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_server)

    hass.http = server
    hass.config.api = rem.API(
        server_host if server_host != '0.0.0.0' else util.get_local_ip(),
        api_password, server_port, ssl_certificate is not None)

    return True
Example #33
0
    async def async_add_port_mappings(self, ports, local_ip=None):
        """Add port mappings."""
        # determine local ip, ensure sane IP
        if local_ip is None:
            local_ip = get_local_ip()

        if local_ip == '127.0.0.1':
            _LOGGER.error('Could not create port mapping, our IP is 127.0.0.1')
        local_ip = IPv4Address(local_ip)

        # create port mappings
        for external_port, internal_port in ports.items():
            await self._async_add_port_mapping(external_port, local_ip,
                                               internal_port)
            self._mapped_ports.append(external_port)
Example #34
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    _LOGGER.addFilter(HideSensitiveFilter(hass))

    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, '')) == '1'
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)
    cors_origins = conf.get(CONF_CORS_ORIGINS, [])
    approved_ips = conf.get(CONF_APPROVED_IPS, [])

    server = HomeAssistantWSGI(
        hass,
        development=development,
        server_host=server_host,
        server_port=server_port,
        api_password=api_password,
        ssl_certificate=ssl_certificate,
        ssl_key=ssl_key,
        cors_origins=cors_origins,
        approved_ips=approved_ips
    )

    def start_wsgi_server(event):
        """Start the WSGI server."""
        server.start()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_wsgi_server)

    def stop_wsgi_server(event):
        """Stop the WSGI server."""
        server.stop()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wsgi_server)

    hass.wsgi = server
    hass.config.api = rem.API(server_host if server_host != '0.0.0.0'
                              else util.get_local_ip(),
                              api_password, server_port,
                              ssl_certificate is not None)

    return True
Example #35
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    _LOGGER.addFilter(HideSensitiveFilter(hass))

    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, '')) == '1'
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)
    cors_origins = conf.get(CONF_CORS_ORIGINS, [])
    trusted_networks = [
        ip_network(trusted_network)
        for trusted_network in conf.get(CONF_TRUSTED_NETWORKS, [])
    ]

    server = HomeAssistantWSGI(hass,
                               development=development,
                               server_host=server_host,
                               server_port=server_port,
                               api_password=api_password,
                               ssl_certificate=ssl_certificate,
                               ssl_key=ssl_key,
                               cors_origins=cors_origins,
                               trusted_networks=trusted_networks)

    def start_wsgi_server(event):
        """Start the WSGI server."""
        server.start()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_wsgi_server)

    def stop_wsgi_server(event):
        """Stop the WSGI server."""
        server.stop()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wsgi_server)

    hass.wsgi = server
    hass.config.api = rem.API(
        server_host if server_host != '0.0.0.0' else util.get_local_ip(),
        api_password, server_port, ssl_certificate is not None)

    return True
Example #36
0
    async def async_add_port_mappings(self, ports, local_ip=None):
        """Add port mappings."""
        # determine local ip, ensure sane IP
        if local_ip is None:
            local_ip = get_local_ip()

        if local_ip == '127.0.0.1':
            _LOGGER.error(
                'Could not create port mapping, our IP is 127.0.0.1')
        local_ip = IPv4Address(local_ip)

        # create port mappings
        for external_port, internal_port in ports.items():
            await self._async_add_port_mapping(external_port,
                                               local_ip,
                                               internal_port)
            self._mapped_ports.append(external_port)
Example #37
0
def setup(hass, api_password, server_port=None, server_host=None):
    """ Sets up the HTTP API and debug interface. """
    server_port = server_port or rem.SERVER_PORT

    # If no server host is given, accept all incoming requests
    server_host = server_host or '0.0.0.0'

    server = HomeAssistantHTTPServer((server_host, server_port),
                                     RequestHandler, hass, api_password)

    hass.listen_once_event(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event:
        threading.Thread(target=server.start, daemon=True).start())

    # If no local api set, set one with known information
    if isinstance(hass, rem.HomeAssistant) and hass.local_api is None:
        hass.local_api = rem.API(util.get_local_ip(), api_password, server_port)
Example #38
0
    def start_driver(self, event):
        """Start the accessory driver."""
        from pyhap.accessory_driver import AccessoryDriver
        self._hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.stop_driver)

        import_types()
        _LOGGER.debug("Start adding accessories.")
        for state in self._hass.states.all():
            acc = get_accessory(self._hass, state)
            if acc is not None:
                self.bridge.add_accessory(acc)

        ip_address = get_local_ip()
        path = self._hass.config.path(HOMEKIT_FILE)
        self.driver = AccessoryDriver(self.bridge, self._port, ip_address,
                                      path)
        _LOGGER.debug("Driver started")
        self.driver.start()
Example #39
0
    def setup(self):
        """Set up bridge and accessory driver."""

        self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.stop)

        ip_addr = self._ip_address or get_local_ip()
        path = self.hass.config.path(HOMEKIT_FILE)
        self.driver = HomeDriver(
            self.hass,
            address=ip_addr,
            port=self._port,
            persist_file=path,
            advertised_address=self._advertise_ip,
        )
        self.bridge = HomeBridge(self.hass, self.driver, self._name)
        if self._safe_mode:
            _LOGGER.debug("Safe_mode selected")
            self.driver.safe_mode = True
Example #40
0
    def start_driver(self, event):
        """Start the accessory driver."""
        from pyhap.accessory_driver import AccessoryDriver
        self._hass.bus.listen_once(
            EVENT_HOMEASSISTANT_STOP, self.stop_driver)

        import_types()
        _LOGGER.debug("Start adding accessories.")
        for state in self._hass.states.all():
            acc = get_accessory(self._hass, state)
            if acc is not None:
                self.bridge.add_accessory(acc)

        ip_address = get_local_ip()
        path = self._hass.config.path(HOMEKIT_FILE)
        self.driver = AccessoryDriver(self.bridge, self._port,
                                      ip_address, path)
        _LOGGER.debug("Driver started")
        self.driver.start()
Example #41
0
    def __init__(self, conf):
        """Initialize the instance."""
        self.type = conf.get(CONF_TYPE)
        self.numbers = {}
        self.cached_states = {}

        # Get the IP address that will be passed to the Echo during discovery
        self.host_ip_addr = conf.get(CONF_HOST_IP)
        if self.host_ip_addr is None:
            self.host_ip_addr = util.get_local_ip()
            _LOGGER.warning(
                "Listen IP address not specified, auto-detected address is %s",
                self.host_ip_addr)

        # Get the port that the Hue bridge will listen on
        self.listen_port = conf.get(CONF_LISTEN_PORT)
        if not isinstance(self.listen_port, int):
            self.listen_port = DEFAULT_LISTEN_PORT
            _LOGGER.warning(
                "Listen port not specified, defaulting to %s",
                self.listen_port)

        if self.type == TYPE_GOOGLE and self.listen_port != 80:
            _LOGGER.warning('When targetting Google Home, listening port has '
                            'to be port 80')

        # Get domains that cause both "on" and "off" commands to map to "on"
        # This is primarily useful for things like scenes or scripts, which
        # don't really have a concept of being off
        self.off_maps_to_on_domains = conf.get(CONF_OFF_MAPS_TO_ON_DOMAINS)
        if not isinstance(self.off_maps_to_on_domains, list):
            self.off_maps_to_on_domains = DEFAULT_OFF_MAPS_TO_ON_DOMAINS

        # Get whether or not entities should be exposed by default, or if only
        # explicitly marked ones will be exposed
        self.expose_by_default = conf.get(
            CONF_EXPOSE_BY_DEFAULT, DEFAULT_EXPOSE_BY_DEFAULT)

        # Get domains that are exposed by default when expose_by_default is
        # True
        self.exposed_domains = conf.get(
            CONF_EXPOSED_DOMAINS, DEFAULT_EXPOSED_DOMAINS)
Example #42
0
async def async_setup_entry(hass, config_entry):
    """Set up an emulated roku server from a config entry."""
    config = config_entry.data

    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {}

    name = config[CONF_NAME]
    listen_port = config[CONF_LISTEN_PORT]
    host_ip = config.get(CONF_HOST_IP) or util.get_local_ip()
    advertise_ip = config.get(CONF_ADVERTISE_IP)
    advertise_port = config.get(CONF_ADVERTISE_PORT)
    upnp_bind_multicast = config.get(CONF_UPNP_BIND_MULTICAST)

    server = EmulatedRoku(hass, name, host_ip, listen_port,
                          advertise_ip, advertise_port, upnp_bind_multicast)

    hass.data[DOMAIN][name] = server

    return await server.setup()
Example #43
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the climate platform."""

    platform = entity_platform.current_platform.get()

    platform.async_register_entity_service(
        TURN_ZONE_ON,
        SERVICE_SCHEMA,
        "async_turn_zone_on",
    )

    platform.async_register_entity_service(
        TURN_ZONE_OFF,
        SERVICE_SCHEMA,
        "async_turn_zone_off",
    )

    climate = BonairePyClimate(hass.loop, get_local_ip())
    async_add_entities([BonaireMyClimateClimate(climate, config)])
Example #44
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    _LOGGER.addFilter(HideSensitiveFilter(hass))

    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, "")) == "1"
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)
    cors_origins = conf.get(CONF_CORS_ORIGINS, [])

    server = HomeAssistantWSGI(
        hass,
        development=development,
        server_host=server_host,
        server_port=server_port,
        api_password=api_password,
        ssl_certificate=ssl_certificate,
        ssl_key=ssl_key,
        cors_origins=cors_origins
    )

    hass.bus.listen_once(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event:
        threading.Thread(target=server.start, daemon=True,
                         name='WSGI-server').start())

    hass.wsgi = server
    hass.config.api = rem.API(server_host if server_host != '0.0.0.0'
                              else util.get_local_ip(),
                              api_password, server_port,
                              ssl_certificate is not None)

    return True
Example #45
0
async def async_setup(hass, config):
    """Register a port mapping for Home Assistant via UPnP."""
    config = config[DOMAIN]
    host = config.get(CONF_LOCAL_IP)

    if host is None:
        host = get_local_ip()

    if host == '127.0.0.1':
        _LOGGER.error(
            'Unable to determine local IP. Add it to your configuration.')
        return False

    import pyupnp_async
    from pyupnp_async.error import UpnpSoapError

    service = None
    resp = await pyupnp_async.msearch_first(search_target=IGD_DEVICE)
    if not resp:
        return False

    try:
        device = await resp.get_device()
        hass.data[DATA_UPNP] = device
        for _service in device.services:
            if _service['serviceType'] == PPP_SERVICE:
                service = device.find_first_service(PPP_SERVICE)
            if _service['serviceType'] == IP_SERVICE:
                service = device.find_first_service(IP_SERVICE)
            if _service['serviceType'] == IP_SERVICE2:
                service = device.find_first_service(IP_SERVICE2)
            if _service['serviceType'] == CIC_SERVICE:
                unit = config[CONF_UNITS]
                hass.async_create_task(discovery.async_load_platform(
                    hass, 'sensor', DOMAIN, {'unit': unit}, config))
    except UpnpSoapError as error:
        _LOGGER.error(error)
        return False

    if not service:
        _LOGGER.warning("Could not find any UPnP IGD")
        return False

    port_mapping = config[CONF_ENABLE_PORT_MAPPING]
    if not port_mapping:
        return True

    internal_port = hass.http.server_port

    ports = config.get(CONF_PORTS)
    if ports is None:
        ports = {CONF_HASS: internal_port}

    registered = []
    for internal, external in ports.items():
        if internal == CONF_HASS:
            internal = internal_port
        try:
            await service.add_port_mapping(internal, external, host, 'TCP',
                                           desc='Home Assistant')
            registered.append(external)
            _LOGGER.debug("Mapping external TCP port %s -> %s @ %s",
                          external, internal, host)
        except UpnpSoapError as error:
            _LOGGER.error(error)
            hass.components.persistent_notification.create(
                '<b>ERROR: tcp port {} is already mapped in your router.'
                '</b><br />Please disable port_mapping in the <i>upnp</i> '
                'configuration section.<br />'
                'You will need to restart hass after fixing.'
                ''.format(external),
                title=NOTIFICATION_TITLE,
                notification_id=NOTIFICATION_ID)

    async def deregister_port(event):
        """De-register the UPnP port mapping."""
        tasks = [service.delete_port_mapping(external, 'TCP')
                 for external in registered]
        if tasks:
            await asyncio.wait(tasks)

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, deregister_port)

    return True
Example #46
0
async def async_setup(hass, config):
    """Set up the HTTP API and debug interface."""
    conf = config.get(DOMAIN)

    if conf is None:
        conf = HTTP_SCHEMA({})

    api_password = conf.get(CONF_API_PASSWORD)
    server_host = conf[CONF_SERVER_HOST]
    server_port = conf[CONF_SERVER_PORT]
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_peer_certificate = conf.get(CONF_SSL_PEER_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)
    cors_origins = conf[CONF_CORS_ORIGINS]
    use_x_forwarded_for = conf.get(CONF_USE_X_FORWARDED_FOR, False)
    trusted_proxies = conf.get(CONF_TRUSTED_PROXIES, [])
    is_ban_enabled = conf[CONF_IP_BAN_ENABLED]
    login_threshold = conf[CONF_LOGIN_ATTEMPTS_THRESHOLD]
    ssl_profile = conf[CONF_SSL_PROFILE]

    if api_password is not None:
        logging.getLogger('aiohttp.access').addFilter(
            HideSensitiveDataFilter(api_password))

    server = HomeAssistantHTTP(
        hass,
        server_host=server_host,
        server_port=server_port,
        ssl_certificate=ssl_certificate,
        ssl_peer_certificate=ssl_peer_certificate,
        ssl_key=ssl_key,
        cors_origins=cors_origins,
        use_x_forwarded_for=use_x_forwarded_for,
        trusted_proxies=trusted_proxies,
        login_threshold=login_threshold,
        is_ban_enabled=is_ban_enabled,
        ssl_profile=ssl_profile,
    )

    async def stop_server(event):
        """Stop the server."""
        await server.stop()

    async def start_server(event):
        """Start the server."""
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_server)
        await server.start()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_server)

    hass.http = server

    host = conf.get(CONF_BASE_URL)

    if host:
        port = None
    elif server_host != DEFAULT_SERVER_HOST:
        host = server_host
        port = server_port
    else:
        host = hass_util.get_local_ip()
        port = server_port

    hass.config.api = ApiConfig(host, port, ssl_certificate is not None)

    return True
Example #47
0
def setup(hass, config):
    """Register a port mapping for Home Assistant via UPnP."""
    config = config[DOMAIN]
    host = config.get(CONF_LOCAL_IP)

    if host is not None:
        host = str(host)
    else:
        host = get_local_ip()

    if host == '127.0.0.1':
        _LOGGER.error(
            'Unable to determine local IP. Add it to your configuration.')
        return False

    import miniupnpc

    upnp = miniupnpc.UPnP()
    hass.data[DATA_UPNP] = upnp

    upnp.discoverdelay = 200
    upnp.discover()
    try:
        upnp.selectigd()
    except Exception:
        _LOGGER.exception("Error when attempting to discover an UPnP IGD")
        return False

    unit = config.get(CONF_UNITS)
    discovery.load_platform(hass, 'sensor', DOMAIN, {'unit': unit}, config)

    port_mapping = config.get(CONF_ENABLE_PORT_MAPPING)
    if not port_mapping:
        return True

    internal_port = hass.http.server_port

    ports = config.get(CONF_PORTS)
    if ports is None:
        ports = {CONF_HASS: internal_port}

    registered = []
    for internal, external in ports.items():
        if internal == CONF_HASS:
            internal = internal_port
        try:
            upnp.addportmapping(
                external, 'TCP', host, internal, 'Home Assistant', '')
            registered.append(external)
        except Exception:
            _LOGGER.exception("UPnP failed to configure port mapping for %s",
                              external)
            hass.components.persistent_notification.create(
                '<b>ERROR: tcp port {} is already mapped in your router.'
                '</b><br />Please disable port_mapping in the <i>upnp</i> '
                'configuration section.<br />'
                'You will need to restart hass after fixing.'
                ''.format(external),
                title=NOTIFICATION_TITLE,
                notification_id=NOTIFICATION_ID)

    def deregister_port(event):
        """De-register the UPnP port mapping."""
        for external in registered:
            upnp.deleteportmapping(external, 'TCP')

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, deregister_port)

    return True