Simplify and caption

This commit is contained in:
Andras Schmelczer 2026-04-26 15:49:14 +01:00
commit 2c8d78b397

View file

@ -1,10 +1,8 @@
#!/usr/bin/env python3
import json
import time
from urllib.error import URLError
from urllib.request import Request, urlopen
from urllib.request import Request
RETRY_DELAYS = (3, 10)
from net import urlopen_with_retry
class HomeAssistantClient:
@ -12,26 +10,14 @@ class HomeAssistantClient:
self.base_url = base_url.rstrip("/")
self.token = token
def get_state(self, entity_id: str) -> dict:
url = f"{self.base_url}/api/states/{entity_id}"
req = Request(url, headers={
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json",
})
last_err: Exception | None = None
for attempt in range(len(RETRY_DELAYS) + 1):
try:
with urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
except (URLError, TimeoutError) as e:
last_err = e
if attempt < len(RETRY_DELAYS):
time.sleep(RETRY_DELAYS[attempt])
raise last_err
def is_person_home(self, entity_id: str) -> bool:
req = Request(
f"{self.base_url}/api/states/{entity_id}",
headers={"Authorization": f"Bearer {self.token}"},
)
try:
return self.get_state(entity_id).get("state") == "home"
with urlopen_with_retry(req, timeout=30) as resp:
return json.loads(resp.read().decode()).get("state") == "home"
except Exception as e:
print(f"Failed to check {entity_id}: {e}")
return False