-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhomeassistant.py
More file actions
528 lines (449 loc) · 17.5 KB
/
Copy pathhomeassistant.py
File metadata and controls
528 lines (449 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#!/usr/bin/env python3
"""
Home Assistant Integration
API access with caching and fallback for unreliable connections
"""
import requests
import time
import logging
import threading
from typing import Dict, Any, Optional
from config import (
HA_URL,
HA_TOKEN,
HA_TIMEOUT,
HA_POLL_INTERVAL,
HA_SENSORS,
HA_BOOLEANS,
HA_BINARY_SENSORS,
HA_DUMP_LOADS,
HA_WATER_VALVE,
HA_PUMP_SWITCH,
VUE_SENSORS,
ENABLE_DISHWASHER,
ENABLE_WASHER,
ENABLE_DRYER,
ENABLE_WATER,
HA_WASHER_POWER,
HA_DRYER_POWER,
HA_LAUNDRY_OUTLET,
)
logger = logging.getLogger("inverter-control")
# Disable insecure request warnings for local HA instance (http:// is intentional)
# nosec B310
import urllib3 # noqa: E402
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class HomeAssistantClient:
"""
Home Assistant API client with caching and fallback.
Runs polling in background thread.
Uses last known values when HA is unreachable.
"""
# Circuit breaker settings
CIRCUIT_OPEN_THRESHOLD = 5 # Open circuit after N consecutive failures
CIRCUIT_RESET_TIMEOUT = 60 # Try again after N seconds
def __init__(self):
# Use session for connection pooling (reuses TCP connections)
self._session = requests.Session()
self._session.headers.update(
{"Authorization": f"Bearer {HA_TOKEN}", "Content-Type": "application/json"}
)
# Configure connection pool for HA (local network, http or https)
adapter = requests.adapters.HTTPAdapter(
pool_connections=2,
pool_maxsize=5,
max_retries=0, # We handle retries ourselves
)
# http:// mount required for local HA instances (no SSL on local network)
# suppress SonarCloud security-hotspot for intentional http usage
self._session.mount( # sonar:ignore
"http://", adapter
)
self._session.mount("https://", adapter)
# Cached values (persist until HA reconnects)
self._sensors: Dict[str, Any] = {k: 0 for k in HA_SENSORS}
self._vue_sensors: Dict[str, Any] = {k: 0 for k in VUE_SENSORS}
self._booleans: Dict[str, bool] = {k: False for k in HA_BOOLEANS}
self._binary_sensors: Dict[str, bool] = {k: False for k in HA_BINARY_SENSORS}
self._water_valve: bool = False
self._pump_switch: bool = False
self._washer_power: bool = False
self._dryer_power: bool = False
self._laundry_outlet: bool = False
self._home_recliner: bool = False
self._home_garage: bool = False
# Connection status
self._connected = False
self._last_update = 0
self._last_error = ""
self._last_error_log = 0 # Throttle error logging
# Circuit breaker state
self._consecutive_failures = 0
self._circuit_open = False
self._circuit_open_time = 0
# Thread control
self._running = False
self._thread: Optional[threading.Thread] = None
self._lock = threading.Lock()
def start(self):
"""Start background polling thread"""
if self._running:
return
self._running = True
self._start_time = time.time()
self._thread = threading.Thread(target=self._poll_loop, daemon=True)
self._thread.start()
@property
def uptime(self) -> int:
"""Return HA poller uptime in seconds"""
if hasattr(self, "_start_time"):
return int(time.time() - self._start_time)
return 0
def stop(self):
"""Stop background polling and cleanup"""
self._running = False
if self._thread:
self._thread.join(timeout=2)
# Close session to release connections
try:
self._session.close()
except Exception:
pass
def _get_state(self, entity_id: str) -> Optional[str]:
"""Get entity state from HA"""
try:
response = self._session.get(
f"{HA_URL}/api/states/{entity_id}",
timeout=(3, HA_TIMEOUT), # (connect_timeout, read_timeout)
)
if response.status_code == 200:
return response.json().get("state")
except (requests.exceptions.RequestException, ValueError):
pass
return None
def _parse_numeric(self, value: str, default: Any = 0) -> Any:
"""Parse numeric value, handle 'unavailable', 'unknown', etc."""
if value in (None, "unavailable", "unknown", "None", ""):
return default
try:
import re
s = str(value).strip()
m = re.match(r"^([+-]?\d+\.?\d*)", s)
if m:
num = float(m.group(1))
return int(num) if num == int(num) else num
# Fallback: try direct conversion
if "." in s:
return float(s)
return int(s)
except Exception:
return default
def _parse_duration(self, value: str) -> int:
"""Parse duration in HH:MM:SS or MM:SS format to minutes"""
if value in (None, "unavailable", "unknown", "None", ""):
return 0
try:
# Try numeric first
return int(float(value))
except Exception:
pass
try:
# Try HH:MM:SS or MM:SS format
parts = str(value).split(":")
if len(parts) == 3:
hours, mins, secs = int(parts[0]), int(parts[1]), int(parts[2])
return hours * 60 + mins + (1 if secs >= 30 else 0)
elif len(parts) == 2:
mins, secs = int(parts[0]), int(parts[1])
return mins + (1 if secs >= 30 else 0)
except Exception:
pass
return 0
def _poll_loop(self):
"""Background polling loop with circuit breaker"""
while self._running:
now = time.time()
# Circuit breaker: skip polling if circuit is open
if self._circuit_open:
if now - self._circuit_open_time > self.CIRCUIT_RESET_TIMEOUT:
# Try to reset circuit
self._circuit_open = False
logger.info("HA circuit breaker: attempting reset")
else:
time.sleep(HA_POLL_INTERVAL)
continue
try:
self._poll_all()
self._connected = True
self._last_update = now
self._last_error = ""
self._consecutive_failures = 0
except Exception as e:
self._connected = False
self._last_error = str(e)
self._consecutive_failures += 1
# Open circuit breaker after threshold
if self._consecutive_failures >= self.CIRCUIT_OPEN_THRESHOLD:
self._circuit_open = True
self._circuit_open_time = now
logger.warning(
f"HA circuit breaker OPEN after {self._consecutive_failures} failures"
)
# Throttle error logging to once per minute
if now - self._last_error_log > 60:
logger.warning(
f"HA poll failed ({self._consecutive_failures}x): {e}"
)
self._last_error_log = now
time.sleep(HA_POLL_INTERVAL)
def _poll_all(self):
"""Poll all entities from HA"""
# Use template API for batch fetch (much faster)
template = self._build_template()
try:
response = self._session.post(
f"{HA_URL}/api/template",
json={"template": template},
timeout=(3, HA_TIMEOUT), # (connect_timeout, read_timeout)
)
except requests.exceptions.Timeout:
raise Exception("HA timeout")
except requests.exceptions.ConnectionError:
raise Exception("HA connection failed")
if response.status_code != 200:
raise Exception(f"HA API error: {response.status_code}")
data = response.json()
if not isinstance(data, dict):
raise Exception("Invalid response format")
with self._lock:
# Sensors that should be stored as raw strings (duration format HH:MM:SS)
duration_sensors = {"dishwasher_duration", "washer_time", "dryer_time"}
# Parse sensors
for key in HA_SENSORS:
if key in data:
if key in duration_sensors:
self._sensors[key] = data[key] # Store raw for duration parsing
else:
self._sensors[key] = self._parse_numeric(data[key])
# Parse VUE sensors
for key in VUE_SENSORS:
if key in data:
self._vue_sensors[key] = self._parse_numeric(data[key])
# Parse booleans
for key in HA_BOOLEANS:
if key in data:
self._booleans[key] = data[key] == "on"
# Parse binary sensors
for key in HA_BINARY_SENSORS:
if key in data:
self._binary_sensors[key] = data[key] == "on"
# Water valve
if "water_valve" in data:
self._water_valve = data["water_valve"] == "on"
# Pump switch
if "pump_switch" in data:
self._pump_switch = data["pump_switch"] == "on"
# Washer/Dryer power switches
if "washer_power" in data:
self._washer_power = data["washer_power"] == "on"
if "dryer_power" in data:
self._dryer_power = data["dryer_power"] == "on"
if "laundry_outlet" in data:
self._laundry_outlet = data["laundry_outlet"] == "on"
if "home_recliner" in data:
self._home_recliner = data["home_recliner"] == "on"
if "home_garage" in data:
self._home_garage = data["home_garage"] == "on"
def _build_template(self) -> str:
"""Build Jinja2 template for batch fetch"""
# Keys to skip based on disabled features
skip_sensors = set()
skip_binary = set()
if not ENABLE_DISHWASHER:
skip_sensors.add("dishwasher_duration")
skip_binary.add("dishwasher_running")
if not ENABLE_WASHER:
skip_sensors.add("washer_time")
if not ENABLE_DRYER:
skip_sensors.add("dryer_time")
if not ENABLE_WATER:
skip_sensors.add("water_level")
parts = ["{"]
items = []
# Sensors (skip disabled)
for key, entity in HA_SENSORS.items():
if key not in skip_sensors:
items.append(f' "{key}": "{{{{ states("{entity}") }}}}"')
# VUE sensors
for key, entity in VUE_SENSORS.items():
items.append(f' "{key}": "{{{{ states("{entity}") }}}}"')
# Booleans
for key, entity in HA_BOOLEANS.items():
items.append(f' "{key}": "{{{{ states("{entity}") }}}}"')
# Binary sensors (skip disabled)
for key, entity in HA_BINARY_SENSORS.items():
if key not in skip_binary:
items.append(f' "{key}": "{{{{ states("{entity}") }}}}"')
# Water valve and pump (only if water enabled)
if ENABLE_WATER:
items.append(f' "water_valve": "{{{{ states("{HA_WATER_VALVE}") }}}}"')
items.append(f' "pump_switch": "{{{{ states("{HA_PUMP_SWITCH}") }}}}"')
# Washer/Dryer power switches
if ENABLE_WASHER and HA_WASHER_POWER:
items.append(f' "washer_power": "{{{{ states("{HA_WASHER_POWER}") }}}}"')
if ENABLE_DRYER and HA_DRYER_POWER:
items.append(f' "dryer_power": "{{{{ states("{HA_DRYER_POWER}") }}}}"')
# Laundry outlet (shown when washer/dryer not running)
if (ENABLE_WASHER or ENABLE_DRYER) and HA_LAUNDRY_OUTLET:
items.append(
f' "laundry_outlet": "{{{{ states("{HA_LAUNDRY_OUTLET}") }}}}"'
)
# Home switches (always poll if HA enabled)
items.append(' "home_recliner": "{{ states(\'switch.recliner_recliner\') }}"')
items.append(' "home_garage": "{{ states(\'switch.garage_opener_l\') }}"')
parts.append(",\n".join(items))
parts.append("}")
return "\n".join(parts)
# === Public API ===
@property
def connected(self) -> bool:
return self._connected
@property
def last_update(self) -> float:
return self._last_update
@property
def last_error(self) -> str:
return self._last_error
def get_sensor(self, key: str, default: Any = 0) -> Any:
"""Get cached sensor value"""
with self._lock:
return self._sensors.get(key, default)
def get_duration_sensor(self, key: str) -> int:
"""Get cached sensor value and parse as duration (HH:MM:SS) to minutes"""
with self._lock:
raw = self._sensors.get(key)
return self._parse_duration(raw)
def get_vue_sensor(self, key: str, default: Any = 0) -> Any:
"""Get cached VUE sensor value"""
with self._lock:
return self._vue_sensors.get(key, default)
def get_all_vue_sensors(self) -> Dict[str, Any]:
"""Get copy of all VUE sensor values"""
with self._lock:
return dict(self._vue_sensors)
def get_boolean(self, key: str) -> bool:
"""Get cached boolean value"""
with self._lock:
return self._booleans.get(key, False)
def get_binary_sensor(self, key: str) -> bool:
"""Get cached binary sensor value"""
with self._lock:
return self._binary_sensors.get(key, False)
@property
def water_valve_on(self) -> bool:
with self._lock:
return self._water_valve
@property
def pump_switch_on(self) -> bool:
with self._lock:
return self._pump_switch
@property
def washer_power_on(self) -> bool:
with self._lock:
return self._washer_power
@property
def dryer_power_on(self) -> bool:
with self._lock:
return self._dryer_power
@property
def laundry_outlet_on(self) -> bool:
with self._lock:
return self._laundry_outlet
@property
def home_recliner_on(self) -> bool:
with self._lock:
return self._home_recliner
@property
def home_garage_on(self) -> bool:
with self._lock:
return self._home_garage
def get_all_sensors(self) -> Dict[str, Any]:
"""Get copy of all sensor values"""
with self._lock:
return dict(self._sensors)
def get_all_booleans(self) -> Dict[str, bool]:
"""Get copy of all boolean values"""
with self._lock:
return dict(self._booleans)
# === Control Methods ===
def toggle_entity(self, entity_id: str) -> bool:
"""Toggle a switch or input_boolean"""
try:
domain = entity_id.split(".")[0]
response = self._session.post(
f"{HA_URL}/api/services/{domain}/toggle",
json={"entity_id": entity_id},
timeout=(3, HA_TIMEOUT),
)
return response.status_code == 200
except Exception as e:
logger.warning(f"Toggle {entity_id} failed: {e}")
return False
def press_button(self, entity_id: str) -> bool:
"""Press a button entity"""
try:
response = self._session.post(
f"{HA_URL}/api/services/button/press",
json={"entity_id": entity_id},
timeout=(3, HA_TIMEOUT),
)
return response.status_code == 200
except Exception as e:
logger.warning(f"Press {entity_id} failed: {e}")
return False
def turn_on(self, entity_id: str) -> bool:
"""Turn on a switch or light"""
try:
domain = entity_id.split(".")[0]
response = self._session.post(
f"{HA_URL}/api/services/{domain}/turn_on",
json={"entity_id": entity_id},
timeout=(3, HA_TIMEOUT),
)
return response.status_code == 200
except Exception as e:
logger.warning(f"Turn on {entity_id} failed: {e}")
return False
def turn_off(self, entity_id: str) -> bool:
"""Turn off a switch or light"""
try:
domain = entity_id.split(".")[0]
response = self._session.post(
f"{HA_URL}/api/services/{domain}/turn_off",
json={"entity_id": entity_id},
timeout=(3, HA_TIMEOUT),
)
return response.status_code == 200
except Exception as e:
logger.warning(f"Turn off {entity_id} failed: {e}")
return False
def control_dump_loads(self, turn_on: bool) -> int:
"""Control all dump loads for minimize_charging. Returns count of changed."""
changed = 0
for entity in HA_DUMP_LOADS:
if turn_on:
if self.turn_on(entity):
changed += 1
else:
if self.turn_off(entity):
changed += 1
return changed
# Singleton instance
_ha_client: Optional[HomeAssistantClient] = None
def get_ha() -> HomeAssistantClient:
"""Get or create HA client"""
global _ha_client
if _ha_client is None:
_ha_client = HomeAssistantClient()
_ha_client.start()
return _ha_client