-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathclient.py
More file actions
executable file
·1722 lines (1448 loc) · 54.6 KB
/
Copy pathclient.py
File metadata and controls
executable file
·1722 lines (1448 loc) · 54.6 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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env -S uv run
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "aiohttp>=3.7.4,<4.0.0",
# "cryptography>=42.0.0",
# "pyatmo==9.4.0",
# ]
# ///
"""Minimal VELUX ACTIVE CLI backed by upstream pyatmo."""
# ruff: noqa: E402
from __future__ import annotations
import argparse
import asyncio
import base64
import json
import os
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent
VELUX_ACTIVE_SRC = ROOT / "custom_components" / "velux_active"
if str(VELUX_ACTIVE_SRC) not in sys.path:
sys.path.insert(0, str(VELUX_ACTIVE_SRC))
import aiohttp
import pyatmo
from connectivity import gateway_reachable
from pairing import SigningKey, retrieve_signing_key
from pyatmo.const import (
AUTH_REQ_ENDPOINT,
DEFAULT_BASE_URL,
GETHOMESDATA_ENDPOINT,
GETHOMESTATUS_ENDPOINT,
HOME,
SETSTATE_ENDPOINT,
)
from pyatmo.enums import ScheduleType
from pyatmo.exceptions import NoDeviceError
from pyatmo.helpers import extract_raw_data
from pyatmo.modules.device_types import DeviceType
from realtime import async_iter_events
from signing import (
allocate_nonces,
build_signed_modules,
resolve_bridge_id,
retrieve_key_error,
)
# Work around pyatmo 9.4.0 until https://github.com/jabesq-org/pyatmo/pull/564 is released.
ScheduleType._value2member_map_.setdefault("algo", ScheduleType.AUTO)
DEFAULT_CLIENT_ID = "5931426da127d981e76bdd3f"
DEFAULT_CLIENT_SECRET = "6ae2d89d15e767ae5c56b456b452d319"
DEFAULT_APP_VERSION = "791302006"
DEFAULT_USER_PREFIX = "velux"
DEFAULT_SCOPE = "velux_scopes"
DEFAULT_TIMEOUT = 10.0
DEFAULT_SYNC_BASE_URL = "https://app.velux-active.com"
DEFAULT_APP_TYPE = "app_velux"
DEFAULT_TIMEZONE = "UTC"
BATTERY_MODULE_TYPES = frozenset({"NXS", "NXD"})
CONTROLLED_OPENERS_OPTIONS = ("windows", "external_covers")
ROOM_MEASUREMENT_KEYS = (
"temperature",
"co2",
"humidity",
"lux",
"air_quality",
"algo_status",
"auto_close_ts",
"min_comfort_temperature",
"max_comfort_temperature",
"min_comfort_humidity",
"max_comfort_humidity",
"max_comfort_co2",
)
MODULE_STATUS_KEYS = (
"type",
"battery_level",
"battery_percent",
"battery_state",
"reachable",
"last_seen",
"rf_state",
"rf_strength",
"firmware_revision",
)
class VeluxAuthError(RuntimeError):
"""Raised when VELUX authentication fails."""
@dataclass(slots=True)
class OAuthTokens:
"""Container for OAuth token data."""
access_token: str
refresh_token: str | None
expires_in: int | None
expires_at: int | None
issued_at: int
scope: list[str]
token_type: str | None
raw: dict[str, Any]
def as_dict(self) -> dict[str, Any]:
"""Serialize tokens for CLI output."""
return {
"access_token": self.access_token,
"refresh_token": self.refresh_token,
"expires_in": self.expires_in,
"expires_at": self.expires_at,
"scope": self.scope,
"token_type": self.token_type,
"issued_at": self.issued_at,
"raw": self.raw,
}
class VeluxAsyncAuth(pyatmo.AbstractAsyncAuth):
"""pyatmo auth adapter for the VELUX ACTIVE password grant."""
def __init__(
self,
websession: aiohttp.ClientSession,
*,
base_url: str,
client_id: str,
client_secret: str,
app_version: str,
user_prefix: str,
scope: str,
timeout: float,
username: str | None = None,
password: str | None = None,
access_token: str | None = None,
refresh_token: str | None = None,
expires_at: int | None = None,
) -> None:
"""Initialize auth state."""
super().__init__(websession, base_url=normalize_base_url(base_url))
self.client_id = client_id
self.client_secret = client_secret
self.app_version = app_version
self.user_prefix = user_prefix
self.scope = scope
self.timeout = timeout
self.username = username
self.password = password
self._tokens: OAuthTokens | None = None
if access_token is not None:
issued_at = int(time.time())
self._tokens = OAuthTokens(
access_token=access_token,
refresh_token=refresh_token,
expires_in=(expires_at - issued_at) if expires_at is not None else None,
expires_at=expires_at,
issued_at=issued_at,
scope=(scope.split() if scope else []),
token_type=None,
raw={},
)
elif refresh_token is not None:
issued_at = int(time.time())
self._tokens = OAuthTokens(
access_token="",
refresh_token=refresh_token,
expires_in=None,
expires_at=expires_at,
issued_at=issued_at,
scope=(scope.split() if scope else []),
token_type=None,
raw={},
)
async def async_get_access_token(self) -> str:
"""Return a valid access token for pyatmo requests."""
if self._tokens is None:
await self.login()
elif self._tokens.access_token and not self._token_expired(self._tokens):
return self._tokens.access_token
elif self._tokens.refresh_token:
try:
await self.refresh()
except VeluxAuthError:
if self.username and self.password:
await self.login()
else:
raise
else:
await self.login()
if self._tokens is None or not self._tokens.access_token:
raise VeluxAuthError("No access token available")
return self._tokens.access_token
async def login(self) -> OAuthTokens:
"""Authenticate with username and password."""
if not self.username or not self.password:
raise VeluxAuthError("Email and password are required for login")
return await self._request_tokens(
{
"grant_type": "password",
"username": self.username,
"password": self.password,
},
)
async def refresh(self) -> OAuthTokens:
"""Refresh the access token."""
refresh_token = self._tokens.refresh_token if self._tokens else None
if not refresh_token:
raise VeluxAuthError("Refresh token is not available")
return await self._request_tokens(
{
"grant_type": "refresh_token",
"refresh_token": refresh_token,
},
)
async def _request_tokens(self, payload: dict[str, str]) -> OAuthTokens:
"""Request tokens from the OAuth endpoint."""
url = self.base_url + AUTH_REQ_ENDPOINT
data = {
"client_id": self.client_id,
"client_secret": self.client_secret,
"app_version": self.app_version,
**payload,
}
if payload.get("grant_type") == "password":
data["user_prefix"] = self.user_prefix
data["scope"] = self.scope
timeout = aiohttp.ClientTimeout(total=self.timeout)
async with self.websession.post(url, data=data, timeout=timeout) as resp:
try:
raw: Any = await resp.json(content_type=None)
except (aiohttp.ContentTypeError, json.JSONDecodeError):
raw = {"raw": await resp.text()}
if not resp.ok:
raise VeluxAuthError(format_auth_error(resp.status, raw))
if not isinstance(raw, dict) or "access_token" not in raw:
raise VeluxAuthError(f"Unexpected token response from {url}")
tokens = parse_tokens(raw)
self._tokens = tokens
return tokens
async def process_response(
self,
response: aiohttp.ClientResponse,
url: str,
params: dict[str, Any] | None = None,
) -> aiohttp.ClientResponse:
"""Process API responses and fail on product-level setstate errors."""
# pyatmo 9.9 passes params to overrides, while 9.4-9.8 do not accept it.
response = await super().process_response(response, url)
if not url.endswith(SETSTATE_ENDPOINT):
return response
try:
raw: Any = await response.json(content_type=None)
except (aiohttp.ContentTypeError, json.JSONDecodeError):
return response
body = raw.get("body") if isinstance(raw, dict) else None
errors = body.get("errors") if isinstance(body, dict) else None
if errors:
raise RuntimeError(f"setstate returned API errors: {errors}")
return response
@staticmethod
def _token_expired(tokens: OAuthTokens) -> bool:
"""Return whether the token is expired or close to expiry."""
return tokens.expires_at is not None and int(time.time()) >= max(
tokens.expires_at - 60, tokens.issued_at
)
def normalize_base_url(value: str) -> str:
"""Normalize the base URL to include a trailing slash."""
return value if value.endswith("/") else f"{value}/"
def parse_tokens(raw: dict[str, Any]) -> OAuthTokens:
"""Parse a token response."""
issued_at = int(time.time())
expires_in_raw = raw.get("expires_in", raw.get("expire_in"))
expires_in = int(expires_in_raw) if expires_in_raw is not None else None
expires_at = issued_at + expires_in if expires_in is not None else None
scope_raw = raw.get("scope", [])
if isinstance(scope_raw, str):
scope = [part for part in scope_raw.split() if part]
elif isinstance(scope_raw, list):
scope = [str(part) for part in scope_raw]
else:
scope = []
refresh_token = raw.get("refresh_token")
if refresh_token is not None:
refresh_token = str(refresh_token)
return OAuthTokens(
access_token=str(raw["access_token"]),
refresh_token=refresh_token,
expires_in=expires_in,
expires_at=expires_at,
issued_at=issued_at,
scope=scope,
token_type=raw.get("token_type"),
raw=raw,
)
def format_auth_error(status: int, raw: Any) -> str:
"""Format an auth error payload."""
if isinstance(raw, dict):
error = raw.get("error")
description = raw.get("error_description")
if isinstance(error, dict):
message = error.get("message") or json.dumps(error, sort_keys=True)
elif error is not None:
message = str(error)
else:
message = json.dumps(raw, sort_keys=True)
if description:
return f"{status} - {message}: {description}"
return f"{status} - {message}"
return f"{status} - {raw}"
def add_connection_arguments(parser: argparse.ArgumentParser) -> None:
"""Add connection arguments."""
parser.add_argument(
"--base-url",
default=os.getenv("VELUX_BASE_URL", DEFAULT_BASE_URL),
help=f"API base URL (default: {DEFAULT_BASE_URL})",
)
parser.add_argument(
"--sync-base-url",
default=os.getenv("VELUX_SYNC_BASE_URL", DEFAULT_SYNC_BASE_URL),
help=f"VELUX app sync API base URL (default: {DEFAULT_SYNC_BASE_URL})",
)
parser.add_argument(
"--client-id",
default=os.getenv("VELUX_CLIENT_ID", DEFAULT_CLIENT_ID),
help="OAuth client ID",
)
parser.add_argument(
"--client-secret",
default=os.getenv("VELUX_CLIENT_SECRET", DEFAULT_CLIENT_SECRET),
help="OAuth client secret",
)
parser.add_argument(
"--app-version",
default=os.getenv("VELUX_APP_VERSION", DEFAULT_APP_VERSION),
help="VELUX app version value",
)
parser.add_argument(
"--user-prefix",
default=os.getenv("VELUX_USER_PREFIX", DEFAULT_USER_PREFIX),
help="VELUX user prefix",
)
parser.add_argument(
"--scope",
default=os.getenv("VELUX_SCOPE", DEFAULT_SCOPE),
help="OAuth scope",
)
parser.add_argument(
"--timeout",
type=float,
default=float(os.getenv("VELUX_TIMEOUT", DEFAULT_TIMEOUT)),
help=f"Request timeout in seconds (default: {DEFAULT_TIMEOUT})",
)
parser.add_argument(
"--timezone",
default=os.getenv("VELUX_TIMEZONE", DEFAULT_TIMEZONE),
help=f"Home timezone for sync setstate payloads (default: {DEFAULT_TIMEZONE})",
)
def add_auth_arguments(parser: argparse.ArgumentParser) -> None:
"""Add credential arguments."""
parser.add_argument(
"--email",
default=os.getenv("VELUX_EMAIL"),
help="VELUX account email",
)
parser.add_argument(
"--password",
default=os.getenv("VELUX_PASSWORD"),
help="VELUX account password",
)
parser.add_argument(
"--access-token",
default=os.getenv("VELUX_ACCESS_TOKEN"),
help="Existing access token",
)
parser.add_argument(
"--refresh-token",
default=os.getenv("VELUX_REFRESH_TOKEN"),
help="Existing refresh token",
)
parser.add_argument(
"--expires-at",
type=int,
default=parse_optional_int(os.getenv("VELUX_EXPIRES_AT")),
help="Unix timestamp for access token expiry",
)
def add_signing_arguments(parser: argparse.ArgumentParser) -> None:
"""Add signing key arguments for roof-window commands."""
parser.add_argument(
"--hash-sign-key",
default=os.getenv("VELUX_HASH_SIGN_KEY"),
help="Hash Sign Key returned by retrieve-key",
)
parser.add_argument(
"--sign-key-id",
default=os.getenv("VELUX_SIGN_KEY_ID"),
help="Sign Key ID returned by retrieve-key",
)
parser.add_argument(
"--sign-key-gateway",
default=os.getenv("VELUX_SIGN_KEY_GATEWAY_ID"),
help="Gateway ID the signing key was paired with",
)
def parse_optional_int(value: str | None) -> int | None:
"""Parse an optional integer value."""
return int(value) if value else None
def build_parser() -> argparse.ArgumentParser:
"""Build the command line parser."""
parser = argparse.ArgumentParser(description=__doc__)
connection_parent = argparse.ArgumentParser(add_help=False)
add_connection_arguments(connection_parent)
auth_parent = argparse.ArgumentParser(add_help=False, parents=[connection_parent])
add_auth_arguments(auth_parent)
subparsers = parser.add_subparsers(dest="command", required=True)
login_parser = subparsers.add_parser(
"login",
parents=[connection_parent],
help="Authenticate and print tokens",
)
login_parser.add_argument("login_email", nargs="?", help="VELUX account email")
login_parser.add_argument(
"login_password",
nargs="?",
help="VELUX account password",
)
subparsers.add_parser(
"list-devices",
parents=[auth_parent],
help="List homes and devices",
)
subparsers.add_parser(
"raw-homesdata",
parents=[auth_parent],
help="Print raw /homesdata response",
)
subparsers.add_parser(
"watch-events",
parents=[auth_parent],
help="Stream realtime VELUX events as JSON lines",
)
raw_status_parser = subparsers.add_parser(
"raw-homestatus",
parents=[auth_parent],
help="Print raw /homestatus response",
)
raw_status_parser.add_argument(
"home",
nargs="?",
help="Home ID or exact name; omitted only when the account has one home",
)
get_configs_parser = subparsers.add_parser(
"get-configs",
parents=[auth_parent],
help="Print raw /syncapi/v1/getconfigs response",
)
get_configs_parser.add_argument(
"home",
nargs="?",
help="Home ID or exact name; omitted only when the account has one home",
)
set_controlled_openers_parser = subparsers.add_parser(
"set-controlled-openers",
parents=[auth_parent],
help="Set which products an indoor climate sensor controls",
)
set_controlled_openers_parser.add_argument(
"module",
help="NXS module ID or exact name",
)
set_controlled_openers_parser.add_argument(
"controlled_openers",
choices=CONTROLLED_OPENERS_OPTIONS,
help="Products controlled by the indoor climate sensor",
)
set_position_parser = subparsers.add_parser(
"set-cover-position",
parents=[auth_parent],
help="Set a cover target position (0-100)",
)
set_position_parser.add_argument("cover", help="Cover ID or exact name")
set_position_parser.add_argument("position", type=int, help="Target position")
set_position_parser.add_argument(
"--signed",
action="store_true",
help="Use the signed VELUX app command path required by roof windows",
)
set_position_parser.add_argument(
"--gateway",
help="Gateway ID or exact name to use for the signed command",
)
add_signing_arguments(set_position_parser)
stop_cover_parser = subparsers.add_parser(
"stop-cover",
parents=[auth_parent],
help="Stop one cover through the regular cloud command path",
)
stop_cover_parser.add_argument("cover", help="Cover ID or exact name")
stop_gateway_parser = subparsers.add_parser(
"stop-gateway",
parents=[auth_parent],
help="Stop all movements on a VELUX gateway",
)
stop_gateway_parser.add_argument(
"--gateway",
help="Gateway ID or exact name when multiple NXG gateways exist",
)
mode_parser = subparsers.add_parser(
"set-window-mode",
parents=[auth_parent],
help="Set a roof window auto-ventilation mode",
)
mode_parser.add_argument("window", help="Window ID or exact name")
mode_parser.add_argument(
"mode",
choices=["on", "off", "algo_available", "manual"],
help="Use on/algo_available to enable, off/manual to disable",
)
mode_parser.add_argument(
"--gateway",
help="Gateway ID or exact name when the window bridge cannot be resolved",
)
retrieve_key_parser = subparsers.add_parser(
"retrieve-key",
parents=[auth_parent],
help="Trigger gateway authentication and retrieve a local Netcom key",
)
retrieve_key_parser.add_argument("host", help="Gateway IP address or hostname")
retrieve_key_parser.add_argument(
"--gateway",
help="Gateway ID or exact name when multiple NXG gateways exist",
)
retrieve_key_parser.add_argument(
"--no-prompt",
action="store_true",
help="Do not pause for the physical gateway button step",
)
return parser
async def command_login(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the login command."""
email = args.login_email or os.getenv("VELUX_EMAIL")
password = args.login_password or os.getenv("VELUX_PASSWORD")
if not email or not password:
raise VeluxAuthError("Email and password are required")
async with aiohttp.ClientSession() as websession:
auth = VeluxAsyncAuth(
websession,
base_url=args.base_url,
client_id=args.client_id,
client_secret=args.client_secret,
app_version=args.app_version,
user_prefix=args.user_prefix,
scope=args.scope,
timeout=args.timeout,
username=email,
password=password,
)
tokens = await auth.login()
return tokens.as_dict()
async def command_list_devices(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the list-devices command."""
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
account, raw_status_by_home_id = await load_account_with_raw_status(auth)
return serialize_account(account, raw_status_by_home_id)
async def command_raw_homesdata(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the raw-homesdata command."""
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
return await post_api_json(auth, GETHOMESDATA_ENDPOINT)
async def command_watch_events(args: argparse.Namespace) -> None:
"""Stream realtime WebSocket events until interrupted."""
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
async for event in async_iter_events(
websession,
auth.async_get_access_token,
args.app_version,
):
print_json_line(event)
async def command_raw_homestatus(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the raw-homestatus command."""
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
homesdata = await post_api_json(auth, GETHOMESDATA_ENDPOINT)
home_id = resolve_home_id(homesdata, args.home)
return await post_api_json(
auth,
GETHOMESTATUS_ENDPOINT,
params={"home_id": home_id},
)
async def command_get_configs(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the get-configs command."""
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
homesdata = await post_api_json(auth, GETHOMESDATA_ENDPOINT)
home_id = resolve_home_id(homesdata, args.home)
return await get_sync_configs(auth, args, home_id=home_id)
async def command_set_controlled_openers(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the set-controlled-openers command."""
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
homesdata = await post_api_json(auth, GETHOMESDATA_ENDPOINT)
home_id, module_id, bridge_id = resolve_controlled_openers_target(
homesdata, args.module
)
return await set_sync_controlled_openers(
auth,
args,
home_id=home_id,
module_id=module_id,
bridge_id=bridge_id,
controlled_openers=args.controlled_openers,
)
async def command_set_cover_position(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the set-cover-position command."""
if not 0 <= args.position <= 100:
raise ValueError("Position must be between 0 and 100")
if args.signed:
require_signing_args(args)
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
account = await load_account(auth)
home, module = find_cover(account, args.cover)
if args.signed:
bridge_id = resolve_module_bridge_id(account, home, module, args.gateway)
if args.sign_key_gateway and bridge_id != args.sign_key_gateway:
raise ValueError(
f"Cover is on gateway {bridge_id}, but signing key was paired "
f"with gateway {args.sign_key_gateway}"
)
response = await send_signed_position_command(
auth,
args,
home_id=home.entity_id,
module_id=module.entity_id,
bridge_id=bridge_id,
position=args.position,
)
accepted = True
else:
accepted = await module.async_set_target_position(args.position)
response = None
await account.async_update_status(home.entity_id)
updated_home = account.homes[home.entity_id]
updated_module = updated_home.modules[module.entity_id]
result: dict[str, Any] = {
"accepted": accepted,
"requested_position": args.position,
"home": {"id": updated_home.entity_id, "name": updated_home.name},
"device": serialize_module(updated_home, updated_module),
}
if response is not None:
result["setstate_response"] = response
return result
async def command_stop_cover(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the stop-cover command."""
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
account = await load_account(auth)
home, module = find_cover(account, args.cover)
accepted = await module.async_stop()
await account.async_update_status(home.entity_id)
updated_home = account.homes[home.entity_id]
updated_module = updated_home.modules[module.entity_id]
return {
"accepted": accepted,
"home": {"id": updated_home.entity_id, "name": updated_home.name},
"device": serialize_module(updated_home, updated_module),
}
async def command_stop_gateway(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the stop-gateway command."""
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
account = await load_account(auth)
home, gateway = find_gateway(account, args.gateway)
response = await send_sync_setstate(
auth,
args,
home_id=home.entity_id,
modules=[{"id": gateway.entity_id, "stop_movements": "all"}],
)
await account.async_update_status(home.entity_id)
updated_home = account.homes[home.entity_id]
updated_gateway = updated_home.modules[gateway.entity_id]
return {
"accepted": True,
"home": {"id": updated_home.entity_id, "name": updated_home.name},
"gateway": serialize_module(updated_home, updated_gateway),
"setstate_response": response,
}
async def command_set_window_mode(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the set-window-mode command."""
mode = {"on": "algo_available", "off": "manual"}.get(args.mode, args.mode)
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
account = await load_account(auth)
home, module = find_cover(account, args.window)
bridge_id = resolve_module_bridge_id(account, home, module, args.gateway)
response = await send_sync_setstate(
auth,
args,
home_id=home.entity_id,
modules=[{"id": module.entity_id, "bridge": bridge_id, "mode": mode}],
)
await account.async_update_status(home.entity_id)
updated_home = account.homes[home.entity_id]
updated_module = updated_home.modules[module.entity_id]
return {
"accepted": True,
"requested_mode": mode,
"home": {"id": updated_home.entity_id, "name": updated_home.name},
"device": serialize_module(updated_home, updated_module),
"setstate_response": response,
}
async def command_retrieve_key(args: argparse.Namespace) -> dict[str, Any]:
"""Handle the retrieve-key command."""
require_interactive_gateway_prompt(args.no_prompt)
async with aiohttp.ClientSession() as websession:
auth = build_auth(args, websession)
account = await load_account(auth)
home, gateway = find_gateway(account, args.gateway)
trigger_response = await trigger_gateway_key_retrieval(auth, home, gateway)
await prompt_for_gateway_button(args.no_prompt, home, gateway)
key = await asyncio.to_thread(
retrieve_signing_key,
host=args.host,
timeout=int(args.timeout),
socket_timeout=args.timeout,
)
return {
"cloud_triggered": True,
"home": {"id": home.entity_id, "name": home.name},
"gateway": serialize_module(home, gateway),
"trigger_response": trigger_response,
"netcom": {
"host": args.host,
"port": 25050,
"verified": True,
"key": serialize_signing_key(key, gateway.entity_id),
},
}
def build_auth(
args: argparse.Namespace,
websession: aiohttp.ClientSession,
) -> VeluxAsyncAuth:
"""Build an auth instance from CLI arguments."""
if not args.email and not args.access_token and not args.refresh_token:
raise VeluxAuthError(
"Provide --email/--password or an access token / refresh token",
)
return VeluxAsyncAuth(
websession,
base_url=args.base_url,
client_id=args.client_id,
client_secret=args.client_secret,
app_version=args.app_version,
user_prefix=args.user_prefix,
scope=args.scope,
timeout=args.timeout,
username=args.email,
password=args.password,
access_token=args.access_token,
refresh_token=args.refresh_token,
expires_at=args.expires_at,
)
async def load_account(auth: VeluxAsyncAuth) -> pyatmo.AsyncAccount:
"""Load homes and device status."""
account, _raw_status_by_home_id = await load_account_with_raw_status(auth)
return account
async def load_account_with_raw_status(
auth: VeluxAsyncAuth,
) -> tuple[pyatmo.AsyncAccount, dict[str, dict[str, Any]]]:
"""Load homes, update status, and keep raw status for debug serialization."""
account = pyatmo.AsyncAccount(auth)
raw_status_by_home_id: dict[str, dict[str, Any]] = {}
await account.async_update_topology()
for home_id in sorted(account.homes):
try:
raw_status = await post_api_json(
auth,
GETHOMESTATUS_ENDPOINT,
params={"home_id": home_id},
)
raw_data = extract_raw_data(raw_status, HOME)
await account.homes[home_id].update(
raw_data, do_raise_for_reachability_error=True
)
raw_status_by_home_id[home_id] = raw_status
except NoDeviceError:
pass
return account, raw_status_by_home_id
async def post_api_json(
auth: VeluxAsyncAuth,
endpoint: str,
*,
params: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""POST to a regular Netatmo API endpoint and return JSON."""
response = await auth.async_post_api_request(endpoint=endpoint, params=params)
try:
raw = await response.json(content_type=None)
except (aiohttp.ContentTypeError, ValueError) as err:
raise RuntimeError(f"Unexpected non-JSON response from {endpoint}") from err
if not isinstance(raw, dict):
raise RuntimeError(f"Unexpected JSON response from {endpoint}: {raw!r}")
return raw
async def get_sync_configs(
auth: VeluxAsyncAuth,
args: argparse.Namespace,
*,
home_id: str,
) -> dict[str, Any]:
"""GET the raw VELUX app sync configuration for one home."""
return await request_sync_json(
auth,
args,
method="GET",
endpoint="getconfigs",
params={"home_id": home_id},
)
async def set_sync_controlled_openers(
auth: VeluxAsyncAuth,
args: argparse.Namespace,
*,
home_id: str,
module_id: str,
bridge_id: str,
controlled_openers: str,
) -> dict[str, Any]:
"""POST one indoor climate sensor control target to setconfigs."""
if controlled_openers not in CONTROLLED_OPENERS_OPTIONS:
raise ValueError(f"Unsupported controlled_openers: {controlled_openers}")
return await request_sync_json(
auth,
args,
method="POST",
endpoint="setconfigs",
json_payload={
"home_id": home_id,
"home": {
"modules": [
{
"id": module_id,
"bridge": bridge_id,
"controlled_openers": controlled_openers,
}
]
},
},
)
async def request_sync_json(
auth: VeluxAsyncAuth,
args: argparse.Namespace,