pywebasto-ng 3.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pywebasto/__init__.py ADDED
@@ -0,0 +1,1186 @@
1
+ """Module for interfacing with Webasto Connect."""
2
+
3
+ import asyncio
4
+ import json
5
+ import logging
6
+ from collections.abc import Awaitable, Callable
7
+ from dataclasses import dataclass
8
+ from inspect import isawaitable
9
+ from pathlib import Path
10
+ from time import monotonic
11
+ from typing import Self
12
+ from uuid import uuid4
13
+
14
+ import aiohttp
15
+
16
+ from .consts import (
17
+ API_URL,
18
+ APP_API_URL,
19
+ APP_CLIENT_INFO,
20
+ APP_USER_AGENT,
21
+ CMD_AUX1_OFF,
22
+ CMD_AUX1_ON,
23
+ CMD_AUX2_OFF,
24
+ CMD_AUX2_ON,
25
+ CMD_HEATER_OFF,
26
+ CMD_HEATER_ON,
27
+ CMD_VENTILATION_OFF,
28
+ CMD_VENTILATION_ON,
29
+ USER_AGENT,
30
+ )
31
+ from .device import WebastoDevice
32
+ from .enums import Outputs, Request
33
+ from .exceptions import (
34
+ ForbiddenException,
35
+ InvalidRequestException,
36
+ InvalidResponseException,
37
+ TooManyRequestsException,
38
+ UnauthorizedException,
39
+ )
40
+ from .timer import SimpleTimer, SmartTimer, Timer, UnknownTimer, timer_from_api_dict
41
+
42
+ __all__ = [
43
+ "AppCredentials",
44
+ "SimpleTimer",
45
+ "SmartTimer",
46
+ "Timer",
47
+ "UnknownTimer",
48
+ "WebastoConnect",
49
+ ]
50
+
51
+ LOGGER = logging.getLogger(__name__)
52
+ REQUEST_TIMEOUT = aiohttp.ClientTimeout(total=60, connect=10, sock_read=45)
53
+ DEFAULT_REFRESH_INTERVAL = 60
54
+ MAX_READ_RETRIES = 2
55
+ RETRYABLE_STATUS_CODES = {500, 502, 503, 504}
56
+ RETRYABLE_REQUESTS = {
57
+ Request.LOGIN,
58
+ Request.GET_DATA,
59
+ Request.GET_DATA_NOPOLL,
60
+ Request.GET_SETTINGS,
61
+ Request.CHANGE_DEVICE,
62
+ }
63
+ WEBAPI_AJAX_HEADERS = {
64
+ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
65
+ "Origin": "https://my.webastoconnect.com",
66
+ "Referer": "https://my.webastoconnect.com/index.html?lang=en",
67
+ "X-Requested-With": "XMLHttpRequest",
68
+ }
69
+
70
+
71
+ def _webclient_json_number(value: float) -> int | float:
72
+ """Match JavaScript JSON.stringify formatting for numeric form values."""
73
+ numeric_value = float(value)
74
+ return int(numeric_value) if numeric_value.is_integer() else numeric_value
75
+
76
+
77
+ @dataclass(slots=True)
78
+ class AppCredentials:
79
+ """Client credentials used by the Android app backend."""
80
+
81
+ client_id: str
82
+ client_secret: str
83
+
84
+
85
+ class WebastoConnect:
86
+ """Webasto Connect implementation."""
87
+
88
+ def __init__(
89
+ self,
90
+ username: str | None = None,
91
+ password: str | None = None,
92
+ client_id: str | None = None,
93
+ client_secret: str | None = None,
94
+ refresh_interval: float = DEFAULT_REFRESH_INTERVAL,
95
+ credential_store_path: str | None = None,
96
+ client_info: str | None = None,
97
+ credential_load: Callable[
98
+ [], AppCredentials | dict | Awaitable[AppCredentials | dict | None] | None
99
+ ]
100
+ | None = None,
101
+ credential_save: Callable[[AppCredentials], Awaitable[None] | None]
102
+ | None = None,
103
+ ) -> None:
104
+ """Initialize the component."""
105
+ self._usn: str | None = username
106
+ self._pwd: str | None = password
107
+ self._client_id: str | None = client_id
108
+ self._client_secret: str | None = client_secret
109
+ self._credential_store_path = (
110
+ Path(credential_store_path) if credential_store_path is not None else None
111
+ )
112
+ self._client_info = client_info
113
+ self._credential_load = credential_load
114
+ self._credential_save = credential_save
115
+ self._hssess: str | None = None
116
+ self._hssess_webclient: str | None = None
117
+ self._data: dict | None = None
118
+ self._session: aiohttp.ClientSession | None = None
119
+ self._refresh_interval = refresh_interval
120
+ self._last_full_update: float | None = None
121
+ self._last_device_update: dict[str, float] = {}
122
+ self._update_lock = asyncio.Lock()
123
+
124
+ self.devices: dict[str, WebastoDevice] = {}
125
+
126
+ @property
127
+ def client_id(self) -> str | None:
128
+ """Return the app client id."""
129
+ return self._client_id
130
+
131
+ @property
132
+ def client_secret(self) -> str | None:
133
+ """Return the app client secret."""
134
+ return self._client_secret
135
+
136
+ @property
137
+ def uses_app_backend(self) -> bool:
138
+ """Return whether app backend credentials are available."""
139
+ return self._client_id is not None and self._client_secret is not None
140
+
141
+ @property
142
+ def uses_webapi_session(self) -> bool:
143
+ """Return whether a web API session cookie is available."""
144
+ return self._hssess is not None or self._hssess_webclient is not None
145
+
146
+ async def connect(self) -> None:
147
+ """Connect to the API."""
148
+ if (self._usn is None) != (self._pwd is None):
149
+ raise InvalidRequestException("Both username and password must be provided")
150
+
151
+ await self._ensure_app_credentials()
152
+ await self._send_client_info()
153
+ if self._usn is not None and self._pwd is not None:
154
+ await self._ensure_webapi_session()
155
+
156
+ await self.update(force=True)
157
+ if self.uses_webapi_session:
158
+ await self._start_missing_associations_from_webapi()
159
+ await self.update(force=True)
160
+ await self._update_all_webapi_device_settings()
161
+
162
+ def assemble_headers(self) -> dict:
163
+ """Generate headers."""
164
+ _headers: dict = {"User-Agent": USER_AGENT}
165
+
166
+ if (self._hssess is None) and (self._hssess_webclient is None):
167
+ pass
168
+ else:
169
+ if self._hssess_webclient is None:
170
+ _headers.update({"Cookie": f"hssess={self._hssess};"})
171
+ else:
172
+ _headers.update(
173
+ {"Cookie": f"hssess-webclient={self._hssess_webclient};"}
174
+ )
175
+
176
+ return _headers
177
+
178
+ def _handle_cookies(self, response: aiohttp.ClientResponse) -> None:
179
+ """Handle cookies from the response."""
180
+ hssess_cookie = response.cookies.get("hssess")
181
+ if hssess_cookie is not None:
182
+ self._hssess = hssess_cookie.value
183
+
184
+ hssess_webclient_cookie = response.cookies.get("hssess-webclient")
185
+ if hssess_webclient_cookie is not None:
186
+ self._hssess_webclient = hssess_webclient_cookie.value
187
+
188
+ def assemble_app_headers(self, auth: bool = True) -> dict:
189
+ """Generate headers for the Android app backend."""
190
+ headers = {
191
+ "Accept-Encoding": "gzip",
192
+ "User-Agent": APP_USER_AGENT,
193
+ }
194
+ if auth:
195
+ if self._client_secret is None:
196
+ raise UnauthorizedException("App client secret is missing")
197
+ headers["Authorization"] = self._client_secret
198
+ return headers
199
+
200
+ def _credentials_from_dict(self, data: dict | AppCredentials | None) -> None:
201
+ """Set app credentials from a simple object or dictionary."""
202
+ if data is None:
203
+ return
204
+ if isinstance(data, AppCredentials):
205
+ self._client_id = data.client_id
206
+ self._client_secret = data.client_secret
207
+ return
208
+ self._client_id = data.get("client_id")
209
+ self._client_secret = data.get("client_secret")
210
+
211
+ def _load_credentials_from_file(self) -> None:
212
+ """Load app credentials from the configured JSON file."""
213
+ if self._credential_store_path is None:
214
+ return
215
+ if not self._credential_store_path.exists():
216
+ return
217
+ with self._credential_store_path.open(encoding="utf-8") as credential_file:
218
+ self._credentials_from_dict(json.load(credential_file))
219
+
220
+ async def _save_credentials(self) -> None:
221
+ """Save app credentials through the configured store."""
222
+ if self._client_id is None or self._client_secret is None:
223
+ return
224
+
225
+ credentials = AppCredentials(self._client_id, self._client_secret)
226
+ if self._credential_save is not None:
227
+ result = self._credential_save(credentials)
228
+ if isawaitable(result):
229
+ await result
230
+
231
+ if self._credential_store_path is not None:
232
+ with self._credential_store_path.open("w", encoding="utf-8") as file:
233
+ json.dump(
234
+ {
235
+ "client_id": credentials.client_id,
236
+ "client_secret": credentials.client_secret,
237
+ },
238
+ file,
239
+ indent=2,
240
+ )
241
+ file.write("\n")
242
+
243
+ async def _ensure_app_credentials(self) -> None:
244
+ """Ensure app client credentials exist."""
245
+ if self.uses_app_backend:
246
+ return
247
+
248
+ if self._credential_load is not None:
249
+ loaded = self._credential_load()
250
+ if isawaitable(loaded):
251
+ loaded = await loaded
252
+ self._credentials_from_dict(loaded)
253
+ if not self.uses_app_backend:
254
+ self._load_credentials_from_file()
255
+ if self.uses_app_backend:
256
+ return
257
+
258
+ client_id = await self._app_call(
259
+ "GET",
260
+ "/remuc/mobile-api/client_id",
261
+ auth=False,
262
+ )
263
+ if not isinstance(client_id, str) or client_id == "":
264
+ raise InvalidResponseException("Could not get app client id")
265
+
266
+ self._client_id = client_id.strip()
267
+ self._client_secret = uuid4().hex
268
+ payload = json.dumps({"secret": self._client_secret}, separators=(",", ":"))
269
+ await self._app_call(
270
+ "POST",
271
+ f"/remuc/mobile-api/client/{self._client_id}/register",
272
+ payload=payload,
273
+ auth=False,
274
+ extra_headers={"Content-Type": "application/json"},
275
+ )
276
+ await self._save_credentials()
277
+
278
+ async def _send_client_info(self) -> None:
279
+ """Send Android app version/build info for the app client."""
280
+ if self._client_id is None:
281
+ raise UnauthorizedException("App client id is required")
282
+ await self._app_call(
283
+ "POST",
284
+ f"/remote/client/{self._client_id}/info",
285
+ payload=self._get_client_info(),
286
+ )
287
+
288
+ def _get_client_info(self) -> str:
289
+ """Return the client info text shown by the backend."""
290
+ client_info = (
291
+ self._client_info if self._client_info is not None else APP_CLIENT_INFO
292
+ )
293
+ parts = client_info.split()
294
+ if len(parts) != 3:
295
+ raise InvalidRequestException(
296
+ "client_info must contain exactly three parts: name version integer-stamp"
297
+ )
298
+ try:
299
+ int(parts[2])
300
+ except ValueError as err:
301
+ raise InvalidRequestException(
302
+ "client_info stamp must be an integer"
303
+ ) from err
304
+ return " ".join(parts)
305
+
306
+ async def _ensure_webapi_session(self) -> None:
307
+ """Ensure a web API session exists when username/password were provided."""
308
+ if self.uses_webapi_session:
309
+ return
310
+ if self._usn is None or self._pwd is None:
311
+ raise UnauthorizedException("Web API username/password is required")
312
+ await self._call(Request.LOGIN, {"username": self._usn, "password": self._pwd})
313
+ if self._hssess is None and self._hssess_webclient is None:
314
+ raise InvalidResponseException("Login failed, no session cookie received")
315
+
316
+ async def _get_session(self) -> aiohttp.ClientSession:
317
+ """Create or reuse an HTTP session."""
318
+ if self._session is None or self._session.closed:
319
+ self._session = aiohttp.ClientSession(timeout=REQUEST_TIMEOUT)
320
+ return self._session
321
+
322
+ @staticmethod
323
+ def _is_retryable_request(api_type: Request) -> bool:
324
+ """Return whether a request is safe to retry."""
325
+ return api_type in RETRYABLE_REQUESTS
326
+
327
+ @staticmethod
328
+ def _backoff_seconds(attempt: int) -> float:
329
+ """Return exponential backoff delay in seconds."""
330
+ return float(2**attempt)
331
+
332
+ async def close(self) -> None:
333
+ """Close any open HTTP session."""
334
+ if self._session is not None and not self._session.closed:
335
+ await self._session.close()
336
+
337
+ async def __aenter__(self) -> Self:
338
+ """Allow async context manager usage."""
339
+ return self
340
+
341
+ async def __aexit__(self, *_: object) -> None:
342
+ """Close resources when leaving async context."""
343
+ await self.close()
344
+
345
+ async def _call(
346
+ self,
347
+ api_type: Request,
348
+ payload: dict | str | None = None,
349
+ extra_headers: dict | None = None,
350
+ ) -> dict | None:
351
+ """Make an API request."""
352
+
353
+ if payload is None:
354
+ payload = {}
355
+
356
+ headers = self.assemble_headers()
357
+ if isinstance(extra_headers, dict):
358
+ headers.update(extra_headers)
359
+
360
+ max_attempts = (
361
+ MAX_READ_RETRIES + 1 if self._is_retryable_request(api_type) else 1
362
+ )
363
+
364
+ for attempt in range(max_attempts):
365
+ session = await self._get_session()
366
+ try:
367
+ start = monotonic()
368
+ async with session.post(
369
+ f"{API_URL}{api_type.value}",
370
+ headers=headers,
371
+ data=payload,
372
+ ) as response:
373
+ self._handle_cookies(response)
374
+ elapsed = monotonic() - start
375
+ LOGGER.debug(
376
+ "Request %s completed in %.3f seconds with status %s",
377
+ api_type.name,
378
+ elapsed,
379
+ response.status,
380
+ )
381
+
382
+ if response.status != 200:
383
+ if response.status == 401:
384
+ raise UnauthorizedException(
385
+ "Username or password incorrect"
386
+ )
387
+ if response.status == 403:
388
+ raise ForbiddenException(
389
+ "Access to the requested resource is forbidden"
390
+ )
391
+ if response.status == 429:
392
+ raise TooManyRequestsException(
393
+ "Too many requests - you are being rate limited"
394
+ )
395
+ if (
396
+ response.status in RETRYABLE_STATUS_CODES
397
+ and attempt < max_attempts - 1
398
+ ):
399
+ delay = self._backoff_seconds(attempt)
400
+ LOGGER.debug(
401
+ "Retrying %s after HTTP %s in %.1f seconds (attempt %s/%s)",
402
+ api_type.name,
403
+ response.status,
404
+ delay,
405
+ attempt + 1,
406
+ max_attempts,
407
+ )
408
+ await asyncio.sleep(delay)
409
+ continue
410
+
411
+ text = await response.text()
412
+ raise InvalidRequestException(
413
+ f"API reported {response.status}: {text}"
414
+ )
415
+
416
+ if "GET" in api_type.name:
417
+ try:
418
+ return await response.json(content_type=None)
419
+ except (aiohttp.ContentTypeError, json.JSONDecodeError) as err:
420
+ text = await response.text()
421
+ raise InvalidResponseException(
422
+ f"Invalid JSON response for {api_type.name}: {text}"
423
+ ) from err
424
+
425
+ return None
426
+ except (
427
+ TimeoutError,
428
+ aiohttp.ClientConnectionError,
429
+ aiohttp.ClientOSError,
430
+ aiohttp.ServerTimeoutError,
431
+ ) as err:
432
+ if attempt < max_attempts - 1:
433
+ delay = self._backoff_seconds(attempt)
434
+ LOGGER.debug(
435
+ "Retrying %s after network error in %.1f seconds (attempt %s/%s): %s",
436
+ api_type.name,
437
+ delay,
438
+ attempt + 1,
439
+ max_attempts,
440
+ err.__class__.__name__,
441
+ )
442
+ await asyncio.sleep(delay)
443
+ continue
444
+ raise InvalidRequestException(f"API request failed: {err}") from err
445
+
446
+ raise InvalidRequestException("API request failed after retries")
447
+
448
+ async def _app_call(
449
+ self,
450
+ method: str,
451
+ path: str,
452
+ payload: str | None = None,
453
+ auth: bool = True,
454
+ expect_json: bool = False,
455
+ extra_headers: dict | None = None,
456
+ ) -> dict | str | None:
457
+ """Make an app backend request."""
458
+ headers = self.assemble_app_headers(auth=auth)
459
+ if extra_headers is not None:
460
+ headers.update(extra_headers)
461
+ session = await self._get_session()
462
+ data = payload.encode("utf-8") if payload is not None else None
463
+
464
+ try:
465
+ start = monotonic()
466
+ async with session.request(
467
+ method,
468
+ f"{APP_API_URL}{path}",
469
+ headers=headers,
470
+ data=data,
471
+ ) as response:
472
+ elapsed = monotonic() - start
473
+ LOGGER.debug(
474
+ "App request %s %s completed in %.3f seconds with status %s",
475
+ method,
476
+ path,
477
+ elapsed,
478
+ response.status,
479
+ )
480
+
481
+ text = await response.text()
482
+ if response.status != 200:
483
+ if response.status == 401:
484
+ raise UnauthorizedException("App client is unauthorized")
485
+ if response.status == 403:
486
+ raise ForbiddenException(
487
+ "Access to the requested app resource is forbidden"
488
+ )
489
+ if response.status == 429:
490
+ raise TooManyRequestsException(
491
+ "Too many requests - you are being rate limited"
492
+ )
493
+ raise InvalidRequestException(
494
+ f"App API reported {response.status}: {text}"
495
+ )
496
+
497
+ if expect_json:
498
+ try:
499
+ return json.loads(text)
500
+ except json.JSONDecodeError as err:
501
+ raise InvalidResponseException(
502
+ f"Invalid JSON response for app request {path}: {text}"
503
+ ) from err
504
+
505
+ return text
506
+ except (
507
+ TimeoutError,
508
+ aiohttp.ClientConnectionError,
509
+ aiohttp.ClientOSError,
510
+ aiohttp.ServerTimeoutError,
511
+ ) as err:
512
+ raise InvalidRequestException(f"App API request failed: {err}") from err
513
+
514
+ def _is_update_fresh(self, last_update: float | None) -> bool:
515
+ """Return whether cached data is still fresh enough to reuse."""
516
+ if self._refresh_interval <= 0:
517
+ return False
518
+
519
+ if last_update is None:
520
+ return False
521
+
522
+ return monotonic() - last_update < self._refresh_interval
523
+
524
+ async def update(self, device_id: str | None = None, force: bool = False) -> None:
525
+ """Get current data from Webasto API."""
526
+ async with self._update_lock:
527
+ if device_id is None:
528
+ if not force and self._is_update_fresh(self._last_full_update):
529
+ LOGGER.debug("Skipping update because cached account data is fresh")
530
+ return
531
+
532
+ await self._update_all_devices()
533
+ self._last_full_update = monotonic()
534
+ return
535
+
536
+ if not force and self._is_update_fresh(
537
+ self._last_device_update.get(device_id)
538
+ ):
539
+ LOGGER.debug(
540
+ "Skipping update for device %s because cached data is fresh",
541
+ device_id,
542
+ )
543
+ return
544
+
545
+ # A specific device was requested, only update that one
546
+ await self._update_device_data(device_id)
547
+
548
+ async def _update_all_devices(self) -> None:
549
+ """Refresh app account data for all devices."""
550
+ if self._client_id is None:
551
+ raise UnauthorizedException("App client id is missing")
552
+
553
+ self._data = await self._app_call(
554
+ "GET",
555
+ f"/remuc/mobile-api/client/{self._client_id}/all?api_v=8",
556
+ expect_json=True,
557
+ )
558
+ if not isinstance(self._data, dict):
559
+ raise InvalidResponseException("Invalid app data response")
560
+
561
+ for device_data in self._data.get("devices", []):
562
+ device_id = str(device_data["id"])
563
+ device = self.devices.get(device_id)
564
+ if device is None:
565
+ device = WebastoDevice(
566
+ device_id,
567
+ device_data.get("name") or device_data.get("alias") or device_id,
568
+ )
569
+
570
+ device.app_data = device_data
571
+ self.devices[device_id] = device
572
+ self._last_device_update[device_id] = monotonic()
573
+
574
+ async def _update_device_data(
575
+ self, device_id: str, switch_device: bool = True
576
+ ) -> None:
577
+ """Refresh data for one device."""
578
+ await self._update_all_devices()
579
+ self._last_device_update[device_id] = monotonic()
580
+
581
+ async def _update_all_webapi_device_settings(self) -> None:
582
+ """Refresh webapi-only settings for all associated devices."""
583
+ for device_id in self.devices:
584
+ await self._update_webapi_device_settings(device_id)
585
+
586
+ async def _update_webapi_device_settings(
587
+ self, device_id: str, switch_device: bool = True
588
+ ) -> None:
589
+ """Refresh webapi-only settings for one associated device."""
590
+ if not self.uses_webapi_session:
591
+ return
592
+
593
+ device = self.devices.get(device_id)
594
+ if device is None or device.pending_approval:
595
+ return
596
+
597
+ if switch_device:
598
+ await self._change_device(device_id)
599
+
600
+ settings = await self._call(Request.GET_SETTINGS)
601
+ if not isinstance(settings, dict):
602
+ raise InvalidResponseException(
603
+ f"Invalid settings response for device {device_id}"
604
+ )
605
+ device.settings = settings
606
+
607
+ async def _change_device(self, device_id: str) -> None:
608
+ """Change the active device."""
609
+ await self._call(Request.CHANGE_DEVICE, {"device": device_id})
610
+
611
+ def _list_devices(self) -> list[dict]:
612
+ """List all devices associated with the account."""
613
+ device_list = []
614
+ if self._data is None:
615
+ return device_list
616
+
617
+ account_info = self._data.get("account_info", {})
618
+ for device in account_info.get("devices", []):
619
+ if isinstance(device, dict):
620
+ device_list.append(
621
+ {
622
+ "id": str(
623
+ device.get("id")
624
+ or device.get("device_id")
625
+ or device.get("dev_id")
626
+ ),
627
+ "name": device.get("name", ""),
628
+ "check_id": device.get("check_id") or device.get("checkId"),
629
+ }
630
+ )
631
+ else:
632
+ device_list.append(
633
+ {
634
+ "id": str(device[0]),
635
+ "name": device[1],
636
+ "check_id": device[2] if len(device) > 2 else None,
637
+ }
638
+ )
639
+
640
+ return device_list
641
+
642
+ def _list_webapi_association_devices(self) -> list[dict]:
643
+ """List webapi devices with check id when available."""
644
+ devices = []
645
+ if not isinstance(self._data, dict):
646
+ return devices
647
+
648
+ if self._data.get("id") and self._data.get("check_id"):
649
+ devices.append(
650
+ {
651
+ "id": str(self._data["id"]),
652
+ "name": self._data.get("alias", ""),
653
+ "check_id": self._data["check_id"],
654
+ }
655
+ )
656
+
657
+ for device in self._list_devices():
658
+ if any(existing["id"] == device["id"] for existing in devices):
659
+ continue
660
+ devices.append(device)
661
+
662
+ return devices
663
+
664
+ async def _start_missing_associations_from_webapi(self) -> None:
665
+ """Start app association for webapi devices missing from app data."""
666
+ self._data = await self._call(Request.GET_DATA_NOPOLL)
667
+ original_device_id = (
668
+ str(self._data["id"])
669
+ if isinstance(self._data, dict) and self._data.get("id")
670
+ else None
671
+ )
672
+
673
+ devices = self._list_webapi_association_devices()
674
+ did_switch_device = await self._add_missing_webapi_check_ids(devices)
675
+
676
+ for device in devices:
677
+ device_id = str(device["id"])
678
+ check_id = device.get("check_id")
679
+ if device_id in self.devices:
680
+ continue
681
+ if not check_id:
682
+ LOGGER.debug(
683
+ "Skipping auto-association for %s because check id is missing",
684
+ device_id,
685
+ )
686
+ continue
687
+ status = await self.association_status(device_id)
688
+ if status in ("master", "pending"):
689
+ continue
690
+ await self.associate_device(device_id, str(check_id))
691
+
692
+ if did_switch_device and original_device_id is not None:
693
+ await self._change_device(original_device_id)
694
+
695
+ async def _add_missing_webapi_check_ids(self, devices: list[dict]) -> bool:
696
+ """Switch webapi device context to read missing check ids."""
697
+ did_switch_device = False
698
+ for device in devices:
699
+ if device.get("check_id"):
700
+ continue
701
+ device_id = str(device["id"])
702
+ await self._change_device(device_id)
703
+ did_switch_device = True
704
+ data = await self._call(Request.GET_DATA_NOPOLL)
705
+ if not isinstance(data, dict):
706
+ continue
707
+ if str(data.get("id")) != device_id:
708
+ continue
709
+ check_id = data.get("check_id")
710
+ if check_id:
711
+ device["check_id"] = check_id
712
+ if not device.get("name"):
713
+ device["name"] = data.get("alias", "")
714
+
715
+ return did_switch_device
716
+
717
+ @staticmethod
718
+ def _extract_raw_timers_from_data(data: dict | None, line: str) -> list[dict]:
719
+ """Extract raw timer dicts for a specific output line from API data."""
720
+ if not isinstance(data, dict):
721
+ return []
722
+
723
+ timers: list[dict] = []
724
+ for section in ("outputs", "disabled_outputs"):
725
+ outputs = data.get(section)
726
+ if not isinstance(outputs, list):
727
+ continue
728
+
729
+ for output in outputs:
730
+ if not isinstance(output, dict):
731
+ continue
732
+ if output.get("line") != line:
733
+ continue
734
+
735
+ output_timers = output.get("timers")
736
+ if not isinstance(output_timers, list):
737
+ continue
738
+
739
+ timers.extend(
740
+ timer_data
741
+ for timer_data in output_timers
742
+ if isinstance(timer_data, dict)
743
+ )
744
+
745
+ return timers
746
+
747
+ @staticmethod
748
+ def _extract_simple_timers_from_data(
749
+ data: dict | None, line: str
750
+ ) -> list[SimpleTimer]:
751
+ """Extract simple timers for a specific output line from API data."""
752
+ timers: list[SimpleTimer] = []
753
+ for timer_data in WebastoConnect._extract_raw_timers_from_data(data, line):
754
+ if timer_data.get("type") != "simple":
755
+ continue
756
+
757
+ try:
758
+ timers.append(SimpleTimer.from_api_dict(timer_data))
759
+ except (KeyError, TypeError, ValueError) as err:
760
+ raise InvalidRequestException(
761
+ f"Invalid simple timer data in response: {err}"
762
+ ) from err
763
+
764
+ return timers
765
+
766
+ @staticmethod
767
+ def _extract_all_timers_from_data(data: dict | None, line: str) -> list[Timer]:
768
+ """Extract timers of every type for a specific output line from API data."""
769
+ timers: list[Timer] = []
770
+ for timer_data in WebastoConnect._extract_raw_timers_from_data(data, line):
771
+ try:
772
+ timers.append(timer_from_api_dict(timer_data))
773
+ except (KeyError, TypeError, ValueError) as err:
774
+ raise InvalidRequestException(
775
+ f"Invalid {timer_data.get('type')} timer data in response: {err}"
776
+ ) from err
777
+
778
+ return timers
779
+
780
+ @staticmethod
781
+ def _merge_simple_timers(
782
+ raw_timers: list[dict], timers: list[SimpleTimer]
783
+ ) -> list[dict]:
784
+ """Replace the simple timers in a raw list, keeping other types in place.
785
+
786
+ Simple timers are matched by position: the n-th simple timer in
787
+ `raw_timers` becomes the n-th entry of `timers`. Extra entries are
788
+ appended; missing entries remove the remaining simple timers.
789
+ """
790
+ simple_timers = iter(timers)
791
+ merged: list[dict] = []
792
+ for timer_data in raw_timers:
793
+ if timer_data.get("type") != "simple":
794
+ try:
795
+ merged.append(timer_from_api_dict(timer_data).to_api_dict())
796
+ except (KeyError, TypeError, ValueError):
797
+ # Never drop a timer we cannot parse; send it back as-is.
798
+ merged.append(dict(timer_data))
799
+ continue
800
+ replacement = next(simple_timers, None)
801
+ if replacement is not None:
802
+ merged.append(replacement.to_api_dict())
803
+ merged.extend(timer.to_api_dict() for timer in simple_timers)
804
+ return merged
805
+
806
+ def _device_path(self, device_id: str, endpoint: str) -> str:
807
+ """Build an app remote device path."""
808
+ if self._client_id is None:
809
+ raise UnauthorizedException("App client id is missing")
810
+ return f"/remote/client/{self._client_id}/device/{device_id}/{endpoint}"
811
+
812
+ @staticmethod
813
+ def _raise_if_pending(device: WebastoDevice) -> None:
814
+ """Reject operations for devices waiting for approval."""
815
+ if device.pending_approval:
816
+ raise InvalidRequestException("Device is waiting for association approval")
817
+
818
+ async def _send_device_command(self, device: WebastoDevice, command: str) -> None:
819
+ """Send a raw app command to a device."""
820
+ await self._app_call(
821
+ "POST",
822
+ self._device_path(device.device_id, "cmd"),
823
+ payload=command,
824
+ )
825
+
826
+ async def get_timers(
827
+ self, device: WebastoDevice, line: Outputs = Outputs.HEATER
828
+ ) -> list[SimpleTimer]:
829
+ """Get simple timers for an output line from the latest API data."""
830
+ if device.pending_approval:
831
+ return []
832
+ await self.update(device_id=device.device_id, force=True)
833
+ data = self.devices[device.device_id].last_data
834
+ return self._extract_simple_timers_from_data(data, line.value)
835
+
836
+ async def save_timers(
837
+ self,
838
+ device: WebastoDevice,
839
+ timers: list[SimpleTimer],
840
+ line: Outputs = Outputs.HEATER,
841
+ ) -> None:
842
+ """Save the simple-timer list for an output line.
843
+
844
+ Timers of other types (for example `smart` timers) on the same line are
845
+ kept unchanged, based on the latest data read from the API. Call
846
+ `get_timers()` first so that data is current.
847
+ """
848
+ self._raise_if_pending(device)
849
+
850
+ known_device = self.devices.get(device.device_id)
851
+ raw_timers = self._extract_raw_timers_from_data(
852
+ known_device.last_data if known_device is not None else None,
853
+ line.value,
854
+ )
855
+ await self._post_timers(
856
+ device, line, self._merge_simple_timers(raw_timers, timers)
857
+ )
858
+
859
+ async def get_all_timers(
860
+ self, device: WebastoDevice, line: Outputs = Outputs.HEATER
861
+ ) -> list[Timer]:
862
+ """Get timers of every type for an output line from the latest API data."""
863
+ if device.pending_approval:
864
+ return []
865
+ await self.update(device_id=device.device_id, force=True)
866
+ data = self.devices[device.device_id].last_data
867
+ return self._extract_all_timers_from_data(data, line.value)
868
+
869
+ async def save_all_timers(
870
+ self,
871
+ device: WebastoDevice,
872
+ timers: list[Timer],
873
+ line: Outputs = Outputs.HEATER,
874
+ ) -> None:
875
+ """Replace the full timer list, of every type, for an output line."""
876
+ self._raise_if_pending(device)
877
+ await self._post_timers(device, line, [timer.to_api_dict() for timer in timers])
878
+
879
+ async def _post_timers(
880
+ self, device: WebastoDevice, line: Outputs, timers: list[dict]
881
+ ) -> None:
882
+ """Send a full timer list using the app `timers2` contract."""
883
+ payload = {
884
+ "output": line.value[-1],
885
+ "timers": timers,
886
+ }
887
+ await self._app_call(
888
+ "POST",
889
+ self._device_path(device.device_id, "timers2"),
890
+ payload=json.dumps(payload, separators=(",", ":")),
891
+ )
892
+ await self.update(device_id=device.device_id, force=True)
893
+
894
+ async def get_simple_timers(
895
+ self, device: WebastoDevice, line: Outputs = Outputs.HEATER
896
+ ) -> list[SimpleTimer]:
897
+ """Backward-compatible alias for `get_timers`."""
898
+ return await self.get_timers(device=device, line=line)
899
+
900
+ async def save_simple_timers(
901
+ self,
902
+ device: WebastoDevice,
903
+ timers: list[SimpleTimer],
904
+ line: Outputs = Outputs.HEATER,
905
+ ) -> None:
906
+ """Backward-compatible alias for `save_timers`."""
907
+ await self.save_timers(device=device, timers=timers, line=line)
908
+
909
+ async def set_output_main(self, device: WebastoDevice, state: bool) -> None:
910
+ """Turn on or off the heater or ventilation."""
911
+ self._raise_if_pending(device)
912
+
913
+ if state:
914
+ if device.is_ventilation:
915
+ await self._send_device_command(device, CMD_VENTILATION_ON)
916
+ else:
917
+ await self._send_device_command(device, CMD_HEATER_ON)
918
+ else:
919
+ if device.is_ventilation:
920
+ await self._send_device_command(device, CMD_VENTILATION_OFF)
921
+ else:
922
+ await self._send_device_command(device, CMD_HEATER_OFF)
923
+ await self.update(device_id=device.device_id, force=True)
924
+
925
+ async def set_output_aux1(self, device: WebastoDevice, state: bool) -> None:
926
+ """Turn on or off the aux1 output."""
927
+ self._raise_if_pending(device)
928
+
929
+ if state:
930
+ await self._send_device_command(device, CMD_AUX1_ON)
931
+ else:
932
+ await self._send_device_command(device, CMD_AUX1_OFF)
933
+ await self.update(device_id=device.device_id, force=True)
934
+
935
+ async def set_output_aux2(self, device: WebastoDevice, state: bool) -> None:
936
+ """Turn on or off the aux2 output."""
937
+ self._raise_if_pending(device)
938
+
939
+ if state:
940
+ await self._send_device_command(device, CMD_AUX2_ON)
941
+ else:
942
+ await self._send_device_command(device, CMD_AUX2_OFF)
943
+ await self.update(device_id=device.device_id, force=True)
944
+
945
+ async def ventilation_mode(self, device: WebastoDevice, state: bool) -> None:
946
+ """Turn ventilation mode on or off."""
947
+ self._raise_if_pending(device)
948
+ app_data = device.app_data or {}
949
+ active_output = next(
950
+ (
951
+ output
952
+ for output in app_data.get("outputs", [])
953
+ if output.get("line") in ("OUTH", "OUTV")
954
+ ),
955
+ {},
956
+ )
957
+ LOGGER.debug(
958
+ "Changing heater mode to %s (association status: %s, "
959
+ "ventilation available: %s)",
960
+ "ventilation" if state else "heating",
961
+ app_data.get("assocStatus"),
962
+ active_output.get("ventilation_mode_available"),
963
+ )
964
+ payload = {"dev_id": device.device_id, "mode": 1 if state else 0}
965
+ await self._app_call(
966
+ "POST",
967
+ f"/remuc/mobile-api/client/{self._client_id}/heatermode",
968
+ payload=json.dumps(payload, separators=(",", ":")),
969
+ extra_headers={"Content-Type": "application/json"},
970
+ )
971
+ await self.update(device_id=device.device_id, force=True)
972
+
973
+ async def associate_device(
974
+ self,
975
+ device_id: str,
976
+ check_id: str,
977
+ message: str = "Association request",
978
+ ) -> str:
979
+ """Start association for a device and return the current status."""
980
+ payload = {"checkId": check_id, "msg": message}
981
+ result = await self._app_call(
982
+ "POST",
983
+ self._device_path(device_id, "assoc3"),
984
+ payload=json.dumps(payload, separators=(",", ":")),
985
+ )
986
+ return "" if result is None else str(result).strip()
987
+
988
+ async def association_status(self, device_id: str) -> str:
989
+ """Get the app association status for a device."""
990
+ result = await self._app_call(
991
+ "GET",
992
+ self._device_path(device_id, "assocstatus2"),
993
+ )
994
+ return "" if result is None else str(result).strip()
995
+
996
+ async def disassociate_device(self, device: WebastoDevice | str) -> None:
997
+ """Remove a device association from this app client."""
998
+ device_id = device.device_id if isinstance(device, WebastoDevice) else device
999
+ if self._client_id is None:
1000
+ raise UnauthorizedException("App client id is missing")
1001
+ await self._app_call(
1002
+ "POST",
1003
+ self._device_path(device_id, "setassoc"),
1004
+ payload=f"{self._client_id} none",
1005
+ )
1006
+ self.devices.pop(device_id, None)
1007
+
1008
+ async def set_location_services(self, device: WebastoDevice, state: bool) -> None:
1009
+ """Enable or disable app location services for a device."""
1010
+ payload = {"dev_id": device.device_id, "state": "ON" if state else "OFF"}
1011
+ await self._app_call(
1012
+ "POST",
1013
+ f"/remuc/mobile-api/client/{self._client_id}/location-services",
1014
+ payload=json.dumps(payload, separators=(",", ":")),
1015
+ )
1016
+ await self.update(device_id=device.device_id, force=True)
1017
+
1018
+ async def get_location_text(self, device: WebastoDevice) -> str:
1019
+ """Read the raw app location2 text for a device."""
1020
+ result = await self._app_call(
1021
+ "GET",
1022
+ self._device_path(device.device_id, "location2"),
1023
+ )
1024
+ return "" if result is None else str(result)
1025
+
1026
+ async def set_main_timeout(
1027
+ self,
1028
+ device: WebastoDevice,
1029
+ heater: int | None = None,
1030
+ ventilation: int | None = None,
1031
+ ) -> None:
1032
+ """Sets timeout of main output port in seconds."""
1033
+ await self._ensure_webapi_session()
1034
+ if heater is not None:
1035
+ device.timeout_heat = heater
1036
+
1037
+ if ventilation is not None:
1038
+ device.timeout_vent = ventilation
1039
+
1040
+ await self._change_device(device_id=device.device_id)
1041
+
1042
+ vent_sec = device.timeout_vent % (24 * 3600)
1043
+ vent_h = vent_sec // 3600
1044
+ vent_sec = vent_sec % 3600
1045
+ vent_m = vent_sec // 60
1046
+
1047
+ heat_sec = device.timeout_heat % (24 * 3600)
1048
+ heat_h = heat_sec // 3600
1049
+ heat_sec = heat_sec % 3600
1050
+ heat_m = heat_sec // 60
1051
+
1052
+ payload = {
1053
+ "device_settings": {
1054
+ "webasto_emul_mode": self._current_emulation_mode(device),
1055
+ "OUTV_timeout_on": True,
1056
+ "OUTV_timeout_h": vent_h,
1057
+ "OUTV_timeout_min": vent_m,
1058
+ "OUTH_timeout_on": True,
1059
+ "OUTH_timeout_h": heat_h,
1060
+ "OUTH_timeout_min": heat_m,
1061
+ },
1062
+ "service_settings": {},
1063
+ "location_events": None,
1064
+ "air_heater": {},
1065
+ }
1066
+ await self._call(
1067
+ Request.POST_SETTING,
1068
+ json.dumps(payload),
1069
+ extra_headers=WEBAPI_AJAX_HEADERS,
1070
+ )
1071
+ await self.update(device_id=device.device_id, force=True)
1072
+
1073
+ @staticmethod
1074
+ def _current_emulation_mode(device: WebastoDevice) -> str:
1075
+ """Return the device's current emulation mode from webapi settings.
1076
+
1077
+ `/post_settings` for the main timeout sends `webasto_emul_mode`. Sending
1078
+ a fixed value would overwrite a different mode, so the current value is
1079
+ reused. `thermoconnect` is only used when the settings do not say.
1080
+ """
1081
+ settings = device.settings
1082
+ groups = settings.get("settings_tab") if isinstance(settings, dict) else None
1083
+ for group in groups if isinstance(groups, list) else []:
1084
+ if not isinstance(group, dict) or group.get("group") != "webasto":
1085
+ continue
1086
+ for option in group.get("options", []):
1087
+ if (
1088
+ isinstance(option, dict)
1089
+ and option.get("key") == "webasto_emul_mode"
1090
+ and isinstance(option.get("value"), str)
1091
+ ):
1092
+ return option["value"]
1093
+
1094
+ LOGGER.debug(
1095
+ "Emulation mode unknown for %s, sending 'thermoconnect'", device.device_id
1096
+ )
1097
+ return "thermoconnect"
1098
+
1099
+ async def set_aux_timeout(
1100
+ self,
1101
+ device: WebastoDevice,
1102
+ timeout: int,
1103
+ aux: Outputs = Outputs.AUX1,
1104
+ ) -> None:
1105
+ """Sets timeout of an AUX port in seconds."""
1106
+ await self._ensure_webapi_session()
1107
+ await self._change_device(device_id=device.device_id)
1108
+
1109
+ if aux == Outputs.AUX1:
1110
+ device.timeout_aux1 = timeout
1111
+ elif aux == Outputs.AUX2:
1112
+ device.timeout_aux2 = timeout
1113
+
1114
+ heat_sec = timeout % (24 * 3600)
1115
+ heat_h = heat_sec // 3600
1116
+ heat_sec = heat_sec % 3600
1117
+ heat_m = heat_sec // 60
1118
+
1119
+ data = {
1120
+ "device_settings": {
1121
+ f"{aux.value}_function": "enabled",
1122
+ f"{aux.value}_timeout_on": True,
1123
+ f"{aux.value}_timeout_h": heat_h,
1124
+ f"{aux.value}_timeout_min": heat_m,
1125
+ },
1126
+ "service_settings": {
1127
+ f"{aux.value}_on": True,
1128
+ f"{aux.value}_name": (
1129
+ device.output_aux1_name
1130
+ if aux == Outputs.AUX1
1131
+ else device.output_aux2_name
1132
+ ),
1133
+ f"{aux.value}_icon": (
1134
+ device.icon_aux1 if aux == Outputs.AUX1 else device.icon_aux2
1135
+ ),
1136
+ },
1137
+ "location_events": None,
1138
+ "air_heater": {},
1139
+ }
1140
+
1141
+ await self._call(
1142
+ Request.POST_SETTING,
1143
+ json.dumps(data),
1144
+ extra_headers=WEBAPI_AJAX_HEADERS,
1145
+ )
1146
+ await self._update_device_data(device.device_id, switch_device=False)
1147
+
1148
+ async def set_low_voltage_cutoff(self, device: WebastoDevice, value: float) -> None:
1149
+ """Set the low voltage cutoff value."""
1150
+ await self._ensure_webapi_session()
1151
+ await self._change_device(device_id=device.device_id)
1152
+
1153
+ payload = {
1154
+ "device_settings": {"low_voltage_cutoff": _webclient_json_number(value)},
1155
+ "service_settings": {},
1156
+ "location_events": None,
1157
+ "air_heater": {},
1158
+ }
1159
+ await self._call(
1160
+ Request.POST_SETTING,
1161
+ json.dumps(payload),
1162
+ extra_headers=WEBAPI_AJAX_HEADERS,
1163
+ )
1164
+ await self._update_device_data(device.device_id, switch_device=False)
1165
+ await self._update_webapi_device_settings(device.device_id, switch_device=False)
1166
+
1167
+ async def set_temperature_compensation(
1168
+ self, device: WebastoDevice, value: float
1169
+ ) -> None:
1170
+ """Set the temperature compensation value."""
1171
+ await self._ensure_webapi_session()
1172
+ await self._change_device(device_id=device.device_id)
1173
+
1174
+ payload = {
1175
+ "device_settings": {"ext_temp_comp": _webclient_json_number(value)},
1176
+ "service_settings": {},
1177
+ "location_events": None,
1178
+ "air_heater": {},
1179
+ }
1180
+ await self._call(
1181
+ Request.POST_SETTING,
1182
+ json.dumps(payload),
1183
+ extra_headers=WEBAPI_AJAX_HEADERS,
1184
+ )
1185
+ await self._update_device_data(device.device_id, switch_device=False)
1186
+ await self._update_webapi_device_settings(device.device_id, switch_device=False)