Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/doorbell initialization #228

Merged
merged 6 commits into from
Oct 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions custom_components/hikvision_next/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import asyncio
from contextlib import suppress
import logging
import traceback

from httpx import TimeoutException

Expand Down Expand Up @@ -59,12 +60,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
device_info = isapi.hass_device_info()
device_registry = dr.async_get(hass)
device_registry.async_get_or_create(config_entry_id=entry.entry_id, **device_info)
except (asyncio.TimeoutError, TimeoutException) as ex:
except (TimeoutError, TimeoutException) as ex:
raise ConfigEntryNotReady(f"Timeout while connecting to {host}. Cannot initialize {DOMAIN}") from ex
except Exception as ex: # pylint: disable=broad-except
raise ConfigEntryNotReady(
f"Unknown error connecting to {host}. Cannot initialize {DOMAIN}. Error is {ex}"
) from ex
msg = f"Cannot initialize {DOMAIN} {host}. Error: {ex}\n"
_LOGGER.error(msg + traceback.format_exc())
raise ConfigEntryNotReady(msg) from ex

coordinators = {}

Expand Down
4 changes: 3 additions & 1 deletion custom_components/hikvision_next/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from homeassistant.config_entries import ConfigEntry, ConfigFlow
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.httpx_client import get_async_client

from .const import DATA_ALARM_SERVER_HOST, DATA_SET_ALARM_SERVER, DOMAIN
from .isapi import ISAPI
Expand Down Expand Up @@ -62,7 +63,8 @@ async def async_step_user(self, user_input: dict[str, Any] | None = None) -> Flo
CONF_HOST: host,
}

isapi = ISAPI(host, username, password)
session = get_async_client(self.hass)
isapi = ISAPI(host, username, password, session)
await isapi.get_device_info()

if self._reauth_entry:
Expand Down
2 changes: 2 additions & 0 deletions custom_components/hikvision_next/isapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,8 @@ def get_event(event_trigger: dict):
supported_events = deep_get(event_notification, "EventTriggerList.EventTrigger", [])
else:
supported_events = deep_get(event_triggers, "EventTriggerList.EventTrigger", [])
if not isinstance(supported_events, list):
supported_events = [supported_events]

for event_trigger in supported_events:
if event := get_event(event_trigger):
Expand Down
24 changes: 16 additions & 8 deletions custom_components/hikvision_next/isapi_client.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import httpx
import logging
from typing import Any, AsyncIterator, List, Union
from urllib.parse import urljoin
import json
import xmltodict
from dataclasses import dataclass

_LOGGER = logging.getLogger(__name__)


def response_parser(response, present="dict"):
"""Parse Hikvision results."""
Expand Down Expand Up @@ -42,16 +45,21 @@ async def _detect_auth_method(self):
if not self.session:
self.session = httpx.AsyncClient(timeout=self.timeout)

url = urljoin(self.host, self.isapi_prefix + "/System/status")
for method in [
httpx.BasicAuth(self.username, self.password),
httpx.DigestAuth(self.username, self.password),
]:
response = await self.session.get(url, auth=method)
if response.status_code == 200:
self._auth_method = method
url = urljoin(self.host, self.isapi_prefix + "/System/deviceInfo")
_LOGGER.debug("--- [WWW-Authenticate detection] %s", self.host)
response = await self.session.get(url)
if response.status_code == 401:
www_authenticate = response.headers.get("WWW-Authenticate", "")
_LOGGER.debug("WWW-Authenticate header: %s", www_authenticate)
if "Basic" in www_authenticate:
self._auth_method = httpx.BasicAuth(self.username, self.password)
elif "Digest" in www_authenticate:
self._auth_method = httpx.DigestAuth(self.username, self.password)

if not self._auth_method:
_LOGGER.error("Authentication method not detected, %s", response.status_code)
if response.headers:
_LOGGER.error("response.headers %s", response.headers)
response.raise_for_status()

def get_url(self, relative_url: str) -> str:
Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def mock_device_endpoints(model):
def mock_isapi():
"""Mock ISAPI instance."""

respx.get(f"{TEST_HOST}/ISAPI/System/status").respond(status_code=200)
respx.get(f"{TEST_HOST}/ISAPI/System/deviceInfo").respond(status_code=200)
isapi = ISAPI(**TEST_CLIENT)
return isapi

Expand Down
Loading