コード例 #1
0
ファイル: __init__.py プロジェクト: lawtancool/hass-control4
async def refresh_tokens(hass: HomeAssistant, entry: ConfigEntry):
    """Store updated authentication and director tokens in hass.data, and schedule next token refresh."""
    config = entry.data
    verify_ssl_session = aiohttp_client.async_get_clientsession(hass)

    account = C4Account(config[CONF_USERNAME], config[CONF_PASSWORD],
                        verify_ssl_session)
    try:
        await account.getAccountBearerToken()
    except client_exceptions.ClientError as exception:
        raise ConfigEntryNotReady(exception) from exception
    except BadCredentials as exception:
        raise ConfigEntryAuthFailed(exception) from exception

    controller_unique_id = config[CONF_CONTROLLER_UNIQUE_ID]
    director_token_dict = await account.getDirectorBearerToken(
        controller_unique_id)
    no_verify_ssl_session = aiohttp_client.async_get_clientsession(
        hass, verify_ssl=False)

    director = C4Director(config[CONF_HOST], director_token_dict[CONF_TOKEN],
                          no_verify_ssl_session)

    _LOGGER.debug("Saving new account and director tokens in hass data")
    entry_data = hass.data[DOMAIN][entry.entry_id]
    entry_data[CONF_ACCOUNT] = account
    entry_data[CONF_DIRECTOR] = director

    if not (CONF_WEBSOCKET in entry_data
            and isinstance(entry_data[CONF_WEBSOCKET], C4Websocket)):
        _LOGGER.debug("First time setup, creating new C4Websocket object")
        connection_tracker = C4WebsocketConnectionTracker(hass, entry)
        websocket = C4Websocket(
            config[CONF_HOST],
            no_verify_ssl_session,
            connection_tracker.connect_callback,
            connection_tracker.disconnect_callback,
        )
        entry_data[CONF_WEBSOCKET] = websocket

        # Silence C4Websocket related loggers, that would otherwise spam INFO logs with debugging messages
        logging.getLogger("socketio.client").setLevel(logging.WARNING)
        logging.getLogger("engineio.client").setLevel(logging.WARNING)
        logging.getLogger("charset_normalizer").setLevel(logging.ERROR)

    _LOGGER.debug("Starting new WebSocket connection")
    await entry_data[CONF_WEBSOCKET].sio_connect(director.director_bearer_token
                                                 )

    _LOGGER.debug(
        "Registering next token refresh in %s seconds",
        director_token_dict["validSeconds"],
    )
    obj = RefreshTokensObject(hass, entry)
    entry_data[CONF_CANCEL_TOKEN_REFRESH_CALLBACK] = async_call_later(
        hass=hass,
        delay=director_token_dict["validSeconds"],
        action=obj.refresh_tokens,
    )
コード例 #2
0
 async def connect_to_director(self) -> bool:
     """Test if we can connect to the local Control4 Director."""
     try:
         director_session = aiohttp_client.async_get_clientsession(
             self.hass, verify_ssl=False)
         director = C4Director(self.host, self.director_bearer_token,
                               director_session)
         await director.getAllItemInfo()
         return True
     except (Unauthorized, ClientError, asyncioTimeoutError):
         _LOGGER.error("Failed to connect to the Control4 controller")
         return False
コード例 #3
0
async def refresh_tokens(opp: OpenPeerPower, entry: ConfigEntry):
    """Store updated authentication and director tokens in opp.data."""
    config = entry.data
    account_session = aiohttp_client.async_get_clientsession(opp)

    account = C4Account(config[CONF_USERNAME], config[CONF_PASSWORD], account_session)
    await account.getAccountBearerToken()

    controller_unique_id = config[CONF_CONTROLLER_UNIQUE_ID]
    director_token_dict = await account.getDirectorBearerToken(controller_unique_id)
    director_session = aiohttp_client.async_get_clientsession(opp, verify_ssl=False)

    director = C4Director(
        config[CONF_HOST], director_token_dict[CONF_TOKEN], director_session
    )
    director_token_expiry = director_token_dict["token_expiration"]

    _LOGGER.debug("Saving new tokens in opp data")
    entry_data = opp.data[DOMAIN][entry.entry_id]
    entry_data[CONF_ACCOUNT] = account
    entry_data[CONF_DIRECTOR] = director
    entry_data[CONF_DIRECTOR_TOKEN_EXPIRATION] = director_token_expiry
コード例 #4
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Control4 from a config entry."""
    hass.data.setdefault(DOMAIN, {})
    entry_data = hass.data[DOMAIN].setdefault(entry.entry_id, {})
    account_session = aiohttp_client.async_get_clientsession(hass)

    config = entry.data
    account = C4Account(config[CONF_USERNAME], config[CONF_PASSWORD],
                        account_session)
    try:
        await account.getAccountBearerToken()
    except client_exceptions.ClientError as exception:
        _LOGGER.error("Error connecting to Control4 account API: %s",
                      exception)
        raise ConfigEntryNotReady from exception
    except BadCredentials as exception:
        _LOGGER.error(
            "Error authenticating with Control4 account API, incorrect username or password: %s",
            exception,
        )
        return False
    entry_data[CONF_ACCOUNT] = account

    controller_unique_id = config[CONF_CONTROLLER_UNIQUE_ID]
    entry_data[CONF_CONTROLLER_UNIQUE_ID] = controller_unique_id

    director_token_dict = await account.getDirectorBearerToken(
        controller_unique_id)
    director_session = aiohttp_client.async_get_clientsession(hass,
                                                              verify_ssl=False)

    director = C4Director(config[CONF_HOST], director_token_dict[CONF_TOKEN],
                          director_session)
    entry_data[CONF_DIRECTOR] = director
    entry_data[CONF_DIRECTOR_TOKEN_EXPIRATION] = director_token_dict[
        "token_expiration"]

    # Add Control4 controller to device registry
    controller_href = (await account.getAccountControllers())["href"]
    entry_data[
        CONF_DIRECTOR_SW_VERSION] = await account.getControllerOSVersion(
            controller_href)

    _, model, mac_address = controller_unique_id.split("_", 3)
    entry_data[CONF_DIRECTOR_MODEL] = model.upper()

    device_registry = await dr.async_get_registry(hass)
    device_registry.async_get_or_create(
        config_entry_id=entry.entry_id,
        identifiers={(DOMAIN, controller_unique_id)},
        connections={(dr.CONNECTION_NETWORK_MAC, mac_address)},
        manufacturer="Control4",
        name=controller_unique_id,
        model=entry_data[CONF_DIRECTOR_MODEL],
        sw_version=entry_data[CONF_DIRECTOR_SW_VERSION],
    )

    # Store all items found on controller for platforms to use
    director_all_items = await director.getAllItemInfo()
    director_all_items = json.loads(director_all_items)
    entry_data[CONF_DIRECTOR_ALL_ITEMS] = director_all_items

    # Load options from config entry
    entry_data[CONF_SCAN_INTERVAL] = entry.options.get(CONF_SCAN_INTERVAL,
                                                       DEFAULT_SCAN_INTERVAL)

    entry_data[CONF_CONFIG_LISTENER] = entry.add_update_listener(
        update_listener)

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
コード例 #5
0

# session = asyncio.run(returnClientSession())

account = C4Account(username, password)
asyncio.run(account.getAccountBearerToken())
data = asyncio.run(account.getAccountControllers())
# print(asyncio.run(account.getAccountControllers()))
# print(data["controllerCommonName"])
# print(data["href"])
# print(asyncio.run(account.getControllerOSVersion(data["href"])))

director_bearer_token = asyncio.run(
    account.getDirectorBearerToken(data["controllerCommonName"]))
# print(director_bearer_token)
director = C4Director(ip, director_bearer_token["token"])

alarm = C4SecurityPanel(director, 460)
print(asyncio.run(alarm.getEmergencyTypes()))

print(asyncio.run(director.getItemSetup(471)))

# sensor = C4ContactSensor(director, 471)
# print(asyncio.run(sensor.getContactState()))

# f = open("allitems.txt", "x")

# f.write(asyncio.run(director.getAllItemInfo()))
# f.close()

# print(asyncio.run(director.getAllItemVariableValue("LIGHT_LEVEL")))