Пример #1
0
def main(arguments):
    """Execute primary loop."""
    logging.basicConfig(format=LOG_FORMAT,
                        datefmt=LOG_DATE_FORMAT,
                        level=LOG_LEVEL)

    # Test the connection to ISY controller.
    try:
        Connection(
            address=ADDRESS,
            port=PORT,
            username=USERNAME,
            password=PASSWORD,
            use_https=USE_HTTPS,
            tls_ver=TLS_VER,
            log=_LOGGER,
            webroot=WEBROOT,
        )
    except ValueError as err:
        _LOGGER.error(
            "Failed to connect to the ISY, "
            "please adjust settings and try again. Error: \n%s",
            err.args[0],
        )
        return

    _LOGGER.info("ISY connected! Connection properties valid, continuing.")

    # Actually connect to the ISY and download full configuration.
    isy = ISY(
        address=ADDRESS,
        port=PORT,
        username=USERNAME,
        password=PASSWORD,
        use_https=USE_HTTPS,
        tls_ver=TLS_VER,
        log=_LOGGER,
        webroot=WEBROOT,
    )

    _LOGGER.info("ISY connected: %s", isy.connected)

    if not isy.connected:
        _LOGGER.error(
            "Failed to connect to the ISY, please adjust settings and try again."
        )
        return
    # Print a representation of all the Nodes
    _LOGGER.debug(repr(isy.nodes))

    # Get the rest of the detailed status information from the ISY
    # not originally reported. This includes statuses for all NodeServer nodes.
    isy.nodes.update()

    # Connect to the Event Stream and print events in the Debug Log.
    isy.auto_update = True

    try:
        while True:
            sleep(10)
    except KeyboardInterrupt:
        _LOGGER.warning("KeyboardInterrupt received. Disconnecting!")
        if isy.connected and isy.auto_update:
            isy.auto_update = False
Пример #2
0
async def async_setup_entry(hass: HomeAssistant,
                            entry: config_entries.ConfigEntry) -> bool:
    """Set up the ISY 994 integration."""
    # As there currently is no way to import options from yaml
    # when setting up a config entry, we fallback to adding
    # the options to the config entry and pull them out here if
    # they are missing from the options
    _async_import_options_from_data_if_missing(hass, entry)

    hass.data[DOMAIN][entry.entry_id] = {}
    hass_isy_data = hass.data[DOMAIN][entry.entry_id]

    hass_isy_data[ISY994_NODES] = {}
    for platform in PLATFORMS:
        hass_isy_data[ISY994_NODES][platform] = []

    hass_isy_data[ISY994_PROGRAMS] = {}
    for platform in PROGRAM_PLATFORMS:
        hass_isy_data[ISY994_PROGRAMS][platform] = []

    hass_isy_data[ISY994_VARIABLES] = []

    isy_config = entry.data
    isy_options = entry.options

    # Required
    user = isy_config[CONF_USERNAME]
    password = isy_config[CONF_PASSWORD]
    host = urlparse(isy_config[CONF_HOST])

    # Optional
    tls_version = isy_config.get(CONF_TLS_VER)
    ignore_identifier = isy_options.get(CONF_IGNORE_STRING,
                                        DEFAULT_IGNORE_STRING)
    sensor_identifier = isy_options.get(CONF_SENSOR_STRING,
                                        DEFAULT_SENSOR_STRING)
    variable_identifier = isy_options.get(CONF_VAR_SENSOR_STRING,
                                          DEFAULT_VAR_SENSOR_STRING)

    if host.scheme == "http":
        https = False
        port = host.port or 80
        session = aiohttp_client.async_create_clientsession(
            hass, verify_ssl=None, cookie_jar=CookieJar(unsafe=True))
    elif host.scheme == "https":
        https = True
        port = host.port or 443
        session = aiohttp_client.async_get_clientsession(hass)
    else:
        _LOGGER.error("The isy994 host value in configuration is invalid")
        return False

    # Connect to ISY controller.
    isy = ISY(
        host.hostname,
        port,
        username=user,
        password=password,
        use_https=https,
        tls_ver=tls_version,
        webroot=host.path,
        websession=session,
        use_websocket=True,
    )

    try:
        async with async_timeout.timeout(60):
            await isy.initialize()
    except asyncio.TimeoutError as err:
        raise ConfigEntryNotReady(
            f"Timed out initializing the ISY; device may be busy, trying again later: {err}"
        ) from err
    except ISYInvalidAuthError as err:
        _LOGGER.error(
            "Invalid credentials for the ISY, please adjust settings and try again: %s",
            err,
        )
        return False
    except ISYConnectionError as err:
        raise ConfigEntryNotReady(
            f"Failed to connect to the ISY, please adjust settings and try again: {err}"
        ) from err
    except ISYResponseParseError as err:
        raise ConfigEntryNotReady(
            f"Invalid XML response from ISY; Ensure the ISY is running the latest firmware: {err}"
        ) from err

    _categorize_nodes(hass_isy_data, isy.nodes, ignore_identifier,
                      sensor_identifier)
    _categorize_programs(hass_isy_data, isy.programs)
    _categorize_variables(hass_isy_data, isy.variables, variable_identifier)

    # Dump ISY Clock Information. Future: Add ISY as sensor to Hass with attrs
    _LOGGER.info(repr(isy.clock))

    hass_isy_data[ISY994_ISY] = isy
    await _async_get_or_create_isy_device_in_registry(hass, entry, isy)

    # Load platforms for the devices in the ISY controller that we support.
    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    @callback
    def _async_stop_auto_update(event) -> None:
        """Stop the isy auto update on Home Assistant Shutdown."""
        _LOGGER.debug("ISY Stopping Event Stream and automatic updates")
        isy.websocket.stop()

    _LOGGER.debug("ISY Starting Event Stream and automatic updates")
    isy.websocket.start()

    entry.async_on_unload(entry.add_update_listener(_async_update_listener))
    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                                   _async_stop_auto_update))

    # Register Integration-wide Services:
    async_setup_services(hass)

    return True
Пример #3
0
def main(arguments):
    """Execute primary loop."""
    fmt = "%(asctime)s %(levelname)s [%(name)s] %(message)s"
    datefmt = "%Y-%m-%d %H:%M:%S"
    logging.basicConfig(format=fmt, datefmt=datefmt, level=logging.DEBUG)

    # Test the connection to ISY controller.
    try:
        Connection(
            address=ADDRESS,
            port=PORT,
            username=USERNAME,
            password=PASSWORD,
            use_https=USE_HTTPS,
            tls_ver=TLS_VER,
            log=_LOGGER,
            webroot=WEBROOT,
        )
    except ValueError as err:
        _LOGGER.error(
            "Failed to connect to the ISY, "
            "please adjust settings and try again. Error: \n%s",
            err.args[0],
        )
        return

    _LOGGER.info("ISY connected! Connection properties valid, continuing.")

    # Actually connect to the ISY and download full configuration.
    isy = ISY(
        address=ADDRESS,
        port=PORT,
        username=USERNAME,
        password=PASSWORD,
        use_https=USE_HTTPS,
        tls_ver=TLS_VER,
        log=_LOGGER,
        webroot=WEBROOT,
    )

    _LOGGER.info("ISY connected: %s", isy.connected)

    # Print a representation of all the Nodes
    _LOGGER.debug(repr(isy.nodes))

    if isy.connected:
        # Connect to the Event Stream and print events in the Debug Log.
        isy.auto_update = True
    else:
        _LOGGER.error(
            "Failed to connect to the ISY, please adjust settings and try again."
        )
        return

    try:
        while True:
            sleep(10)
    except KeyboardInterrupt:
        _LOGGER.warning("KeyboardInterrupt received. Disconnecting!")
        if isy.connected and isy.auto_update:
            isy.auto_update = False
async def main(url, username, password, tls_ver):
    """Execute connection to ISY and load all system info."""
    t0 = time.time()
    host = urlparse(url)
    if host.scheme == "http":
        https = False
        port = host.port or 80
    elif host.scheme == "https":
        https = True
        port = host.port or 443
    else:
        _LOGGER.error("host value in configuration is invalid.")
        return False

    # Use the helper function to get a new aiohttp.ClientSession.
    websession = get_new_client_session(https, tls_ver)

    # Connect to ISY controller.
    isy = ISY(
        host.hostname,
        port,
        username=username,
        password=password,
        use_https=https,
        tls_ver=tls_ver,
        webroot=host.path,
        websession=websession,
        use_websocket=True,
    )

    listeners = []
    try:
        await isy.initialize()
        # nodes = {}
        for node_tuple in isy.nodes:
            node = node_tuple[1]
            if await is_light_device(node):
                listeners.append(LightListener(node))
            elif await is_fan_device(node):
                listener = FanListener(node)
                listeners.append(listener)
                listener.update_db_device_status()
            # if is_supported_device(node):
            #     nodes.update({node.address: node})
    except (ISYInvalidAuthError, ISYConnectionError):
        _LOGGER.error(
            "Failed to connect to the ISY, please adjust settings and try again."
        )
        for listener in listeners:
            await listener.unsubscribe()
        await isy.shutdown()
        return
    except Exception as err:
        _LOGGER.error("Unknown error occurred: %s", err.args[0])
        for listener in listeners:
            await listener.unsubscribe()
        await isy.shutdown()
        raise

    # Print a representation of all the Nodes
    # _LOGGER.debug(repr(isy.nodes))
    _LOGGER.info("Total Loading time: %.2fs", time.time() - t0)

    try:
        isy.websocket.start()
        while True:
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        pass
    finally:
        for listener in listeners:
            await listener.unsubscribe()
        await isy.shutdown()