python-amazon-echo 0.1.1__py3-none-any.whl → 0.3.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.
amazon_echo/client.py CHANGED
@@ -23,13 +23,27 @@ from .auth import (
23
23
  )
24
24
  from .const import (
25
25
  APP_USER_AGENT,
26
+ COMMS_HOST,
27
+ DROP_IN_MODES,
28
+ GUARD_CAPABILITY,
29
+ GUARD_MODEL,
30
+ GUARD_SKILL_ID,
31
+ INFO_SKILLS,
26
32
  LIST_KINDS,
27
33
  MEDIA_COMMANDS,
28
34
  MUTATION_SET_ENDPOINT_FEATURES,
29
35
  NOTIFICATION_KINDS,
36
+ QUERY_APPLIANCES,
30
37
  QUERY_ENDPOINTS,
31
38
  USER_AGENT,
32
39
  )
40
+ from .endpoints import (
41
+ build_endpoint,
42
+ dig as _dig,
43
+ format_mac,
44
+ parse_endpoint,
45
+ parse_features,
46
+ )
33
47
  from .exceptions import (
34
48
  AmazonEchoAuthenticationError,
35
49
  AmazonEchoConnectionError,
@@ -45,6 +59,8 @@ from .models import (
45
59
  BluetoothDevice,
46
60
  Device,
47
61
  EchoList,
62
+ Endpoint,
63
+ Guard,
48
64
  ListItem,
49
65
  MediaState,
50
66
  Notification,
@@ -60,6 +76,11 @@ _REAUTH_COOLDOWN = 60.0 # a 401/403 this soon after a cookie exchange is final
60
76
  _TOKEN_MARGIN = 60.0
61
77
  _HISTORY_CSRF_TTL = 12 * 3600
62
78
  _HISTORY_PAGES = 5
79
+ # One GraphQL answer serves the Alexa devices and the smart-home endpoints.
80
+ _ENDPOINTS_TTL = 5.0
81
+ _BACKGROUND_IMAGE_ID = "JqIFZhtBTx25wLGTJGdNGQ" # the app's "personal photo" slot
82
+ # The Amazon Kids parent dashboard is parents.<domain>, except where translated.
83
+ _PARENTS_SUBDOMAINS = {"amazon.de": "eltern"}
63
84
  _CSRF_META = re.compile(
64
85
  r'<meta[^>]*name="csrf-token"[^>]*content="([^"]+)"', re.IGNORECASE
65
86
  )
@@ -69,6 +90,13 @@ _SKIPPED_UTTERANCES = frozenset(
69
90
  )
70
91
  _LIST_NAMES = {"SHOP": "Shopping", "TODO": "To-do"} # the built-in lists are unnamed
71
92
  _WEEKDAYS = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")
93
+ # `recurringPattern` of an alarm → ISO weekdays (empty = every day).
94
+ _PATTERN_DAYS: dict[str, tuple[int, ...]] = {
95
+ "P1D": (),
96
+ "XXXX-WD": (1, 2, 3, 4, 5),
97
+ "XXXX-WE": (6, 7),
98
+ **{f"XXXX-WXX-{day}": (day,) for day in range(1, 8)},
99
+ }
72
100
  _RECURRENCE_PRESETS: dict[str, list[str]] = {
73
101
  "DAILY": [],
74
102
  "EVERYDAY": [],
@@ -77,14 +105,6 @@ _RECURRENCE_PRESETS: dict[str, list[str]] = {
77
105
  }
78
106
 
79
107
 
80
- def format_mac(value: str | None) -> str | None:
81
- """Return ``aa:bb:cc:dd:ee:ff`` for any 12-hex-digit MAC spelling."""
82
- digits = re.sub(r"[^0-9a-fA-F]", "", value or "").lower()
83
- if len(digits) != 12:
84
- return None
85
- return ":".join(digits[i : i + 2] for i in range(0, 12, 2))
86
-
87
-
88
108
  def _from_ms(value: Any) -> datetime | None:
89
109
  """Return an aware datetime for an epoch in milliseconds (0/None → None)."""
90
110
  try:
@@ -104,15 +124,6 @@ def _local(when: datetime) -> datetime:
104
124
  return when.astimezone().replace(tzinfo=None) if when.tzinfo else when
105
125
 
106
126
 
107
- def _dig(data: Any, *path: str) -> Any:
108
- """Walk nested dicts, returning None as soon as a level is missing."""
109
- for key in path:
110
- if not isinstance(data, dict):
111
- return None
112
- data = data.get(key)
113
- return data
114
-
115
-
116
127
  def parse_notification(item: dict[str, Any]) -> Notification:
117
128
  """Build a :class:`Notification` from an ``/api/notifications`` item."""
118
129
  kind = NOTIFICATION_KINDS.get(item.get("type") or "", "")
@@ -176,46 +187,6 @@ def _parse_media(info: dict[str, Any]) -> MediaState:
176
187
  )
177
188
 
178
189
 
179
- def _parse_endpoint(endpoint: dict[str, Any]) -> dict[str, Any]:
180
- """Flatten one GraphQL endpoint into the values the integration needs."""
181
- state: dict[str, Any] = {
182
- "endpoint_id": endpoint.get("endpointId"),
183
- "model": _dig(endpoint, "model", "value", "text"),
184
- "mac": None,
185
- "temperature": None,
186
- "volume": None,
187
- "reachable": None,
188
- "remote_battery": None,
189
- "ambient_mode": None,
190
- "dnd": _dig(endpoint, "settings", "doNotDisturb", "toggleValue"),
191
- }
192
- for connection in endpoint.get("connections") or []:
193
- if connection.get("type") == "TCP_IP" and connection.get("macAddress"):
194
- state["mac"] = format_mac(connection["macAddress"])
195
- for feature in endpoint.get("features") or []:
196
- for prop in feature.get("properties") or []:
197
- kind = prop.get("__typename")
198
- if kind == "TemperatureSensor" and prop.get("temp"):
199
- value, scale = prop["temp"].get("value"), prop["temp"].get("scale")
200
- if value is not None and scale == "FAHRENHEIT":
201
- value = round((value - 32) / 1.8, 1)
202
- state["temperature"] = value
203
- elif kind == "Volume" and prop.get("vol"):
204
- state["volume"] = prop["vol"].get("value")
205
- elif kind == "Reachability" and prop.get("reachabilityStatusValue"):
206
- state["reachable"] = prop["reachabilityStatusValue"] == "OK"
207
- elif kind == "InventoryLevel" and feature.get("instance") == (
208
- "Remote.Battery"
209
- ):
210
- state["remote_battery"] = _dig(prop, "inventoryLevelValue", "value")
211
- elif kind == "ToggleState" and feature.get("instance") == (
212
- "FTV.AmbientMode"
213
- ):
214
- value = prop.get("toggleStateValue")
215
- state["ambient_mode"] = None if value is None else value == "ON"
216
- return state
217
-
218
-
219
190
  def _replace_placeholders(node: Any, values: dict[str, str]) -> Any:
220
191
  """Return a copy of a routine node with the ``ALEXA_CURRENT_*`` markers set."""
221
192
  if isinstance(node, dict):
@@ -247,6 +218,36 @@ def _recurrence_rule(recurrence: str, when: datetime) -> dict[str, Any]:
247
218
  return {"freq": "WEEKLY", "byDay": days, "interval": 1}
248
219
 
249
220
 
221
+ def _next_ring(alarm: dict[str, Any], now: datetime) -> str:
222
+ """Return the next ring of an alarm as local ``YYYY-MM-DDTHH:MM:SS``.
223
+
224
+ Raises:
225
+ ValueError: The alarm has no time, or an unknown repeat rule.
226
+
227
+ """
228
+ try:
229
+ hour, minute, second = (
230
+ int(part) for part in alarm["originalTime"][:8].split(":")
231
+ )
232
+ except (KeyError, TypeError, ValueError) as err:
233
+ raise ValueError("The alarm has no time") from err
234
+ # recurringPattern only names the first day when an alarm repeats on a few
235
+ days: tuple[int, ...] = tuple(
236
+ _WEEKDAYS.index(day) + 1
237
+ for day in _dig(alarm, "rRuleData", "byWeekDays") or ()
238
+ if day in _WEEKDAYS
239
+ )
240
+ pattern = alarm.get("recurringPattern")
241
+ if not days and pattern:
242
+ if pattern not in _PATTERN_DAYS:
243
+ raise ValueError(f"Unsupported repeat rule: {pattern!r}")
244
+ days = _PATTERN_DAYS[pattern]
245
+ when = now.replace(hour=hour, minute=minute, second=second, microsecond=0)
246
+ while when <= now or (days and when.isoweekday() not in days):
247
+ when += timedelta(days=1)
248
+ return when.isoformat(timespec="seconds")
249
+
250
+
250
251
  class AmazonEchoClient:
251
252
  """Client for the Alexa cloud API of one Amazon account.
252
253
 
@@ -280,6 +281,11 @@ class AmazonEchoClient:
280
281
  self._devices: dict[str, Device] = {}
281
282
  self._service_urls: dict[str, str] | None = None
282
283
  self._history_csrf: tuple[str, float] | None = None
284
+ self._endpoints_lock = asyncio.Lock()
285
+ self._endpoints_cache: tuple[float, list[dict[str, Any]]] | None = None
286
+ self._endpoint_types: dict[str, str | None] = {}
287
+ self._guard: Guard | None = None
288
+ self._guard_known = False
283
289
 
284
290
  # ------------------------------------------------------------------ core
285
291
 
@@ -429,13 +435,14 @@ class AmazonEchoClient:
429
435
  headers: dict[str, str] | None = None,
430
436
  app: bool = False,
431
437
  text: bool = False,
438
+ retry: bool = True,
432
439
  ) -> Any:
433
440
  url = (
434
441
  path
435
442
  if path.startswith("https://")
436
443
  else f"https://{host or self.host}{path}"
437
444
  )
438
- delays = list(_RETRY_DELAYS)
445
+ delays = list(_RETRY_DELAYS) if retry else []
439
446
  reauthorized = False
440
447
  while True:
441
448
  seen = self._generation
@@ -558,15 +565,37 @@ class AmazonEchoClient:
558
565
  assert self.credentials.customer_id is not None # noqa: S101
559
566
  return self.credentials.customer_id, self._locale or "en-US"
560
567
 
568
+ async def _raw_endpoints(self) -> list[dict[str, Any]]:
569
+ """Return every GraphQL endpoint of the account.
570
+
571
+ ponytail: the (large) answer is kept for 5 s so that the device states
572
+ and the smart-home endpoints of one poll share a request; a feature
573
+ call drops it.
574
+ """
575
+ async with self._endpoints_lock:
576
+ cached = self._endpoints_cache
577
+ if cached is not None and cached[0] > time.monotonic():
578
+ return cached[1]
579
+ data = await self._graphql(QUERY_ENDPOINTS)
580
+ endpoints = [
581
+ endpoint
582
+ for endpoint in _dig(data, "listEndpoints", "endpoints") or []
583
+ if endpoint.get("endpointId")
584
+ ]
585
+ self._endpoint_types = {
586
+ endpoint["endpointId"]: _dig(endpoint, "dmsIdentifier", "deviceType")
587
+ for endpoint in endpoints
588
+ }
589
+ self._endpoints_cache = (time.monotonic() + _ENDPOINTS_TTL, endpoints)
590
+ return endpoints
591
+
561
592
  async def _endpoints(self) -> dict[str, dict[str, Any]]:
562
593
  """Return the GraphQL state of every Alexa-enabled endpoint by serial."""
563
- data = await self._graphql(QUERY_ENDPOINTS)
564
- result: dict[str, dict[str, Any]] = {}
565
- for endpoint in _dig(data, "listEndpoints", "endpoints") or []:
566
- serial = _dig(endpoint, "dmsIdentifier", "dsn")
567
- if serial:
568
- result[serial] = _parse_endpoint(endpoint)
569
- return result
594
+ return {
595
+ serial: parse_endpoint(endpoint)
596
+ for endpoint in await self._raw_endpoints()
597
+ if (serial := _dig(endpoint, "dmsIdentifier", "dsn"))
598
+ }
570
599
 
571
600
  async def get_devices(self) -> list[Device]:
572
601
  """Return every Alexa device, app and speaker group of the account.
@@ -743,10 +772,43 @@ class AmazonEchoClient:
743
772
 
744
773
  Each value has ``temperature`` (°C), ``volume``, ``reachable``,
745
774
  ``remote_battery``, ``ambient_mode``, ``mac``, ``dnd``, ``model`` and
746
- ``endpoint_id``; values the device does not report are None.
775
+ ``endpoint_id``; values the device does not report are None. A device
776
+ with more sensors also has ``illuminance``, ``motion``, ``humidity``
777
+ and the air-quality keys of :func:`amazon_echo.endpoints.parse_features`.
747
778
  """
748
779
  return await self._endpoints()
749
780
 
781
+ async def get_smart_home_endpoints(self) -> list[Endpoint]:
782
+ """Return the smart-home devices linked to the account.
783
+
784
+ That is every endpoint that is not an Alexa voice device: lamps,
785
+ plugs, sensors and locks of other brands, plus Amazon hardware without
786
+ a microphone (Echo Glow, Air Quality Monitor). Shares its request with
787
+ :meth:`get_endpoint_states` when both are called within 5 s.
788
+ """
789
+ return [
790
+ build_endpoint(endpoint)
791
+ for endpoint in await self._raw_endpoints()
792
+ if _dig(endpoint, "displayCategories", "primary", "value")
793
+ != "ALEXA_VOICE_ENABLED"
794
+ ]
795
+
796
+ def parse_endpoint_update(
797
+ self, payload: dict[str, Any]
798
+ ) -> tuple[str, dict[str, Any]] | None:
799
+ """Decode a smart-home push event into (endpoint id, changed values).
800
+
801
+ ``payload`` is the one of a ``PushEvent`` whose command is
802
+ ``EventBus:AlexaMobile::FDAL``; None when it is something else.
803
+ """
804
+ endpoint_id = _dig(payload, "entity", "id")
805
+ features = _dig(payload, "data", "features")
806
+ if not isinstance(endpoint_id, str) or not isinstance(features, list):
807
+ return None
808
+ return endpoint_id, parse_features(
809
+ features, device_type=self._endpoint_types.get(endpoint_id)
810
+ )
811
+
750
812
  # ------------------------------------------------- per-device settings
751
813
 
752
814
  async def get_wifi(self, device: Device) -> tuple[str | None, str | None]:
@@ -863,8 +925,91 @@ class AmazonEchoClient:
863
925
  sound: str | None = _dig(data, "defaultNotificationSound", "id")
864
926
  return sound
865
927
 
928
+ def _comms_path(self, device: Device) -> str:
929
+ # "devicesTypes" is Amazon's spelling
930
+ return (
931
+ f"/devicesTypes/{device.device_type}/deviceId/{device.serial}/preferences"
932
+ )
933
+
934
+ async def get_communication_preferences(self, device: Device) -> dict[str, Any]:
935
+ """Return the communication preferences of ``device``.
936
+
937
+ Keys, each only when Amazon allows the preference on the device:
938
+ ``communications`` (bool), ``announcements`` (bool) and ``drop_in``
939
+ (``all``, ``home`` or ``off``). One call per device, not retried.
940
+ """
941
+ data = await self._request(
942
+ "GET",
943
+ self._comms_path(device)
944
+ + "?devicePreferences=communications&devicePreferences=dropin"
945
+ "&devicePreferences=announcements",
946
+ host=COMMS_HOST.format(domain=self.credentials.domain),
947
+ app=True,
948
+ retry=False,
949
+ )
950
+ result: dict[str, Any] = {}
951
+ for item in (data or {}).get("devicePermissionsPreferences") or []:
952
+ name, state = item.get("devicePreference"), item.get("state")
953
+ if item.get("allowed") is not True or not isinstance(state, str):
954
+ continue
955
+ if name == "dropin":
956
+ result["drop_in"] = state.lower()
957
+ elif name in ("communications", "announcements"):
958
+ result[name] = state == "ON"
959
+ return result
960
+
961
+ async def get_kids_mode(self, device: Device) -> bool:
962
+ """Return whether ``device`` is in Amazon Kids mode."""
963
+ data = await self._request(
964
+ "GET", "/api/device/op-mode", params=self._query(device)
965
+ )
966
+ return bool((data or {}).get("isChildDirectedDevice"))
967
+
968
+ @property
969
+ def _parents_host(self) -> str:
970
+ """Host of the Amazon Kids parent dashboard of the marketplace."""
971
+ domain = self.credentials.domain
972
+ return f"{_PARENTS_SUBDOMAINS.get(domain, 'parents')}.{domain}"
973
+
974
+ async def get_kids_profile(self, device: Device) -> str | None:
975
+ """Return the id of the child ``device`` is assigned to, if any."""
976
+ data = await self._request(
977
+ "GET",
978
+ "/ajax/get-oobe-device-data",
979
+ host=self._parents_host,
980
+ params={"deviceId": device.serial, "deviceTypeId": device.device_type},
981
+ )
982
+ child: str | None = (data or {}).get("childDirectedId") or None
983
+ return child
984
+
866
985
  # ------------------------------------------------- account preferences
867
986
 
987
+ async def get_children(self) -> dict[str, str]:
988
+ """Return the child profiles of the household as id → first name."""
989
+ data = await self._request(
990
+ "GET", "/ajax/get-household-with-age", host=self._parents_host
991
+ )
992
+ return {
993
+ member["directedId"]: member.get("firstName") or member["directedId"]
994
+ for member in (data or {}).get("members") or []
995
+ if member.get("role") == "CHILD" and member.get("directedId")
996
+ }
997
+
998
+ async def get_device_preferences(self) -> dict[str, dict[str, Any]]:
999
+ """Return ``locale``, ``time_zone`` and ``temperature_scale`` by serial."""
1000
+ data = await self._request(
1001
+ "GET", "/api/device-preferences", params={"cached": "true"}
1002
+ )
1003
+ return {
1004
+ item["deviceSerialNumber"]: {
1005
+ "locale": item.get("locale"),
1006
+ "time_zone": item.get("timeZoneId"),
1007
+ "temperature_scale": item.get("temperatureScale"),
1008
+ }
1009
+ for item in (data or {}).get("devicePreferences") or []
1010
+ if item.get("deviceSerialNumber")
1011
+ }
1012
+
868
1013
  async def get_whisper_mode(self) -> bool:
869
1014
  """Return whether Alexa whispers back when whispered to."""
870
1015
  data = await self._request("GET", "/api/response-modulation-preferences")
@@ -1030,6 +1175,73 @@ class AmazonEchoClient:
1030
1175
  f"/api/bluetooth/disconnect-sink/{device.device_type}/{device.serial}",
1031
1176
  )
1032
1177
 
1178
+ async def _set_comms(self, device: Device, preference: str, state: str) -> None:
1179
+ await self._request(
1180
+ "PATCH",
1181
+ f"{self._comms_path(device)}/{preference}",
1182
+ host=COMMS_HOST.format(domain=self.credentials.domain),
1183
+ json={"state": state},
1184
+ app=True,
1185
+ )
1186
+
1187
+ async def set_communications(self, device: Device, enabled: bool) -> None:
1188
+ """Allow or block calls and messages on ``device``."""
1189
+ await self._set_comms(device, "communications", "ON" if enabled else "OFF")
1190
+
1191
+ async def set_announcements(self, device: Device, enabled: bool) -> None:
1192
+ """Allow or block announcements on ``device``."""
1193
+ await self._set_comms(device, "announcements", "ON" if enabled else "OFF")
1194
+
1195
+ async def set_drop_in(self, device: Device, mode: str) -> None:
1196
+ """Set who may drop in on ``device``: ``all``, ``home`` or ``off``."""
1197
+ if mode not in DROP_IN_MODES:
1198
+ raise ValueError("mode must be all, home or off")
1199
+ await self._set_comms(device, "dropin", DROP_IN_MODES[mode])
1200
+
1201
+ async def set_kids_mode(self, device: Device, child_id: str | None) -> None:
1202
+ """Put ``device`` in Amazon Kids mode for a child, or take it out (None).
1203
+
1204
+ ``child_id`` is a key of :meth:`get_children`.
1205
+ """
1206
+ if child_id is None:
1207
+ await self._request(
1208
+ "POST",
1209
+ f"/api/unassign-device-from-child/{device.serial}/{device.device_type}",
1210
+ )
1211
+ return
1212
+ host = self._parents_host
1213
+ start = f"/oobe/brownie/start/{device.device_type}/{device.serial}"
1214
+ # The dashboard has a CSRF token of its own, set by its setup page.
1215
+ await self._request("GET", start, host=host, text=True)
1216
+ await self._request(
1217
+ "POST",
1218
+ "/ajax/assign-device-to-child",
1219
+ host=host,
1220
+ json={
1221
+ "deviceId": device.serial,
1222
+ "deviceTypeId": device.device_type,
1223
+ "childDirectedId": child_id,
1224
+ },
1225
+ headers={
1226
+ "Referer": f"https://{host}{start}",
1227
+ "Origin": f"https://{host}",
1228
+ "x-amzn-csrf": self.credentials.cookies.get("ft-panda-csrf-token", ""),
1229
+ },
1230
+ )
1231
+
1232
+ async def set_background_image(self, device: Device, url: str) -> None:
1233
+ """Show the image at ``url`` (https) as the background of an Echo Show."""
1234
+ await self._request(
1235
+ "POST",
1236
+ "/api/background-image",
1237
+ json={
1238
+ **self._query(device),
1239
+ "backgroundImageID": _BACKGROUND_IMAGE_ID,
1240
+ "backgroundImageType": "PERSONAL_PHOTOS",
1241
+ "backgroundImageURL": url,
1242
+ },
1243
+ )
1244
+
1033
1245
  async def reboot(self, device: Device) -> None:
1034
1246
  """Restart ``device``."""
1035
1247
  await self._request(
@@ -1145,9 +1357,20 @@ class AmazonEchoClient:
1145
1357
  return list(result.values())
1146
1358
 
1147
1359
  async def announce(
1148
- self, devices: list[Device], text: str, *, title: str | None = None
1360
+ self,
1361
+ devices: list[Device],
1362
+ text: str,
1363
+ *,
1364
+ title: str | None = None,
1365
+ method: str = "all",
1149
1366
  ) -> None:
1150
- """Announce ``text`` (chime + speech + on-screen card) on ``devices``."""
1367
+ """Announce ``text`` (chime + speech + on-screen card) on ``devices``.
1368
+
1369
+ ``method`` is ``all``, ``speak`` (nothing on screen) or ``show``
1370
+ (nothing spoken).
1371
+ """
1372
+ if method not in ("all", "speak", "show"):
1373
+ raise ValueError("method must be all, speak or show")
1151
1374
  targets = await self._members(devices)
1152
1375
  if not targets:
1153
1376
  raise ValueError("No device to announce on")
@@ -1160,8 +1383,13 @@ class AmazonEchoClient:
1160
1383
  content=[
1161
1384
  {
1162
1385
  "locale": locale,
1163
- "display": {"title": title or "Home Assistant", "body": text},
1164
- "speak": {"type": "text", "value": text},
1386
+ "display": {"title": "", "body": ""}
1387
+ if method == "speak"
1388
+ else {"title": title or "Home Assistant", "body": text},
1389
+ "speak": {
1390
+ "type": "text",
1391
+ "value": "" if method == "show" else text,
1392
+ },
1165
1393
  }
1166
1394
  ],
1167
1395
  target={
@@ -1197,16 +1425,32 @@ class AmazonEchoClient:
1197
1425
  )
1198
1426
  )
1199
1427
 
1200
- async def play_music(self, device: Device, provider_id: str, phrase: str) -> None:
1201
- """Play ``phrase`` from a music provider (see :meth:`get_music_providers`)."""
1428
+ async def play_music(
1429
+ self,
1430
+ device: Device,
1431
+ provider_id: str,
1432
+ phrase: str,
1433
+ *,
1434
+ timer: int | None = None,
1435
+ ) -> None:
1436
+ """Play ``phrase`` from a music provider (see :meth:`get_music_providers`).
1437
+
1438
+ Args:
1439
+ device: The device that plays.
1440
+ provider_id: A key of :meth:`get_music_providers`.
1441
+ phrase: What to search for.
1442
+ timer: Stop after this many seconds (a sleep timer).
1443
+
1444
+ """
1445
+ payload: dict[str, Any] = {
1446
+ "searchPhrase": phrase,
1447
+ "sanitizedSearchPhrase": phrase,
1448
+ "musicProviderId": provider_id,
1449
+ }
1450
+ if timer:
1451
+ payload["waitTimeInSeconds"] = timer
1202
1452
  await self._run(
1203
- await self._node(
1204
- device,
1205
- "Alexa.Music.PlaySearchPhrase",
1206
- searchPhrase=phrase,
1207
- sanitizedSearchPhrase=phrase,
1208
- musicProviderId=provider_id,
1209
- )
1453
+ await self._node(device, "Alexa.Music.PlaySearchPhrase", **payload)
1210
1454
  )
1211
1455
 
1212
1456
  async def launch_skill(self, device: Device, skill_id: str) -> None:
@@ -1226,6 +1470,67 @@ class AmazonEchoClient:
1226
1470
  )
1227
1471
  )
1228
1472
 
1473
+ async def send_sequence(
1474
+ self, device: Device, kind: str, payload: dict[str, Any] | None = None
1475
+ ) -> None:
1476
+ """Run any behavior node type (``Alexa.Weather.Play``…) on ``device``."""
1477
+ await self._run(await self._node(device, kind, **(payload or {})))
1478
+
1479
+ async def info_skill(self, device: Device, skill: str) -> None:
1480
+ """Make ``device`` tell something: a key of ``INFO_SKILLS``.
1481
+
1482
+ ``weather``, ``traffic``, ``flash_briefing``, ``good_morning``,
1483
+ ``fun_fact``, ``joke``, ``tell_story``, ``calendar_today``…
1484
+ """
1485
+ if skill not in INFO_SKILLS:
1486
+ raise ValueError(f"Unknown info skill: {skill}")
1487
+ await self.send_sequence(device, INFO_SKILLS[skill])
1488
+
1489
+ async def send_mobile_push(
1490
+ self, message: str, *, title: str | None = None, device: Device | None = None
1491
+ ) -> None:
1492
+ """Send a notification to the Alexa app on the account's phones.
1493
+
1494
+ ``device`` only names the sender in the request; the notification
1495
+ always goes to the app.
1496
+ """
1497
+ customer_id, locale = await self._customer()
1498
+ payload: dict[str, Any] = {
1499
+ "customerId": customer_id,
1500
+ "notificationMessage": message,
1501
+ "alexaUrl": "#v2/behaviors",
1502
+ "title": title or "Home Assistant",
1503
+ "skillId": "amzn1.ask.1p.routines.messaging",
1504
+ }
1505
+ if device is not None:
1506
+ payload = {**self._query(device), "locale": locale, **payload}
1507
+ await self._run(
1508
+ {
1509
+ "@type": f"{_NODE}OpaquePayloadOperationNode",
1510
+ "type": "Alexa.Notifications.SendMobilePush",
1511
+ "operationPayload": payload,
1512
+ }
1513
+ )
1514
+
1515
+ async def send_drop_in_notification(
1516
+ self, message: str, *, title: str | None = None
1517
+ ) -> None:
1518
+ """Send an Alexa app notification that opens the Drop In dialog."""
1519
+ customer_id, _ = await self._customer()
1520
+ await self._run(
1521
+ {
1522
+ "@type": f"{_NODE}OpaquePayloadOperationNode",
1523
+ "type": "Alexa.Notifications.DropIn",
1524
+ "skillId": "amzn1.ask.1p.action.dropin",
1525
+ "operationPayload": {
1526
+ "customerId": customer_id,
1527
+ "notificationMessage": message,
1528
+ "alexaUrl": "#v2/comms/conversation-list?showDropInDialog=true",
1529
+ "title": title or "Home Assistant",
1530
+ },
1531
+ }
1532
+ )
1533
+
1229
1534
  async def run_routine(self, routine: Routine, device: Device | None = None) -> None:
1230
1535
  """Run a routine.
1231
1536
 
@@ -1271,7 +1576,9 @@ class AmazonEchoClient:
1271
1576
  raise AmazonEchoResponseError(200, f"The new {kind} did not show up")
1272
1577
  return max(candidates, key=lambda item: item.raw.get("createdDate") or 0)
1273
1578
 
1274
- async def _alerts(self, method: str, path: str, body: dict[str, Any]) -> Any:
1579
+ async def _alerts(
1580
+ self, method: str, path: str, body: dict[str, Any] | None = None
1581
+ ) -> Any:
1275
1582
  """Call the app's alerts API, which takes the raw access token."""
1276
1583
  url = (await self.get_service_urls()).get("alexaApiUrl")
1277
1584
  if not url:
@@ -1291,6 +1598,7 @@ class AmazonEchoClient:
1291
1598
  *,
1292
1599
  label: str | None = None,
1293
1600
  recurrence: str | None = None,
1601
+ music: Notification | None = None,
1294
1602
  ) -> Notification:
1295
1603
  """Create an alarm.
1296
1604
 
@@ -1301,6 +1609,14 @@ class AmazonEchoClient:
1301
1609
  label: Not supported by Amazon for alarms; accepted and ignored.
1302
1610
  recurrence: ``DAILY``, ``WEEKDAYS``, ``WEEKENDS``, ``WEEKLY`` or a
1303
1611
  day list such as ``MO,WE,FR``.
1612
+ music: An existing music alarm of the account; the new alarm
1613
+ wakes with the same station. Amazon has no public way to
1614
+ search for a station, so one that was picked in the Alexa app
1615
+ is reused (the ``MUSIC-<id>`` tone :meth:`enable_alarm` sends;
1616
+ this request has not been replayed against Amazon).
1617
+
1618
+ Raises:
1619
+ AmazonEchoNotSupportedError: ``music`` is not a music alarm.
1304
1620
 
1305
1621
  """
1306
1622
  del label
@@ -1308,17 +1624,20 @@ class AmazonEchoClient:
1308
1624
  trigger: dict[str, Any] = {"scheduledTime": local.isoformat(timespec="seconds")}
1309
1625
  if recurrence:
1310
1626
  trigger["recurrence"] = _recurrence_rule(recurrence, local)
1627
+ body: dict[str, Any] = {
1628
+ "trigger": trigger,
1629
+ "extensions": [],
1630
+ "endpointId": f"{device.serial}@{device.device_type}",
1631
+ }
1632
+ if music is not None:
1633
+ if not (music_id := music.raw.get("musicAlarmId")):
1634
+ raise AmazonEchoNotSupportedError("Not a music alarm")
1635
+ body["assets"] = [{"type": "TONE", "assetId": f"MUSIC-{music_id}"}]
1311
1636
  known = {item.id for item in await self.get_notifications()}
1312
- await self._alerts(
1313
- "POST",
1314
- "alarms",
1315
- {
1316
- "trigger": trigger,
1317
- "extensions": [],
1318
- "endpointId": f"{device.serial}@{device.device_type}",
1319
- },
1637
+ await self._alerts("POST", "alarms", body)
1638
+ return await self._find_new(
1639
+ device, "alarm" if music is None else "music_alarm", known
1320
1640
  )
1321
- return await self._find_new(device, "alarm", known)
1322
1641
 
1323
1642
  async def create_reminder(
1324
1643
  self, device: Device, when: datetime, label: str
@@ -1382,6 +1701,44 @@ class AmazonEchoClient:
1382
1701
  await self._alerts("POST", "timers", body)
1383
1702
  return await self._find_new(device, "timer", known)
1384
1703
 
1704
+ @staticmethod
1705
+ def _alarm_index(alarm: Notification) -> str:
1706
+ index = alarm.raw.get("notificationIndex")
1707
+ if alarm.kind not in ("alarm", "music_alarm") or not index:
1708
+ raise AmazonEchoNotSupportedError("Only alarms can be switched")
1709
+ return quote(str(index), safe="")
1710
+
1711
+ async def enable_alarm(self, alarm: Notification) -> None:
1712
+ """Turn an alarm on; it rings at its next occurrence.
1713
+
1714
+ The next ring is computed in the system time zone, which Amazon reads
1715
+ as the Echo's own (see :meth:`create_alarm`).
1716
+
1717
+ Raises:
1718
+ AmazonEchoNotSupportedError: Not an alarm.
1719
+ ValueError: The alarm has no time or an unknown repeat rule.
1720
+
1721
+ """
1722
+ body: dict[str, Any] = {
1723
+ "trigger": {"scheduledTime": _next_ring(alarm.raw, datetime.now())}, # noqa: DTZ005
1724
+ "extensions": [],
1725
+ }
1726
+ if music := alarm.raw.get("musicAlarmId"):
1727
+ body["assets"] = [{"type": "TONE", "assetId": f"MUSIC-{music}"}]
1728
+ elif alarm.sound:
1729
+ body["assets"] = [{"type": "TONE", "assetId": alarm.sound}]
1730
+ await self._alerts("PUT", f"alarms/{self._alarm_index(alarm)}/activate", body)
1731
+
1732
+ async def disable_alarm(self, alarm: Notification) -> None:
1733
+ """Turn an alarm off without deleting it."""
1734
+ await self._alerts("PUT", f"alarms/{self._alarm_index(alarm)}/cancel")
1735
+
1736
+ async def skip_next_alarm(self, alarm: Notification) -> None:
1737
+ """Skip the next occurrence of a repeating alarm."""
1738
+ await self._alerts(
1739
+ "PUT", f"alarms/{self._alarm_index(alarm)}/nextOccurrence/cancel"
1740
+ )
1741
+
1385
1742
  async def delete_notification(self, notification: Notification) -> None:
1386
1743
  """Delete an alarm, timer or reminder."""
1387
1744
  await self._request(
@@ -1578,6 +1935,7 @@ class AmazonEchoClient:
1578
1935
  control["instance"] = instance
1579
1936
  if payload is not None:
1580
1937
  control["payload"] = payload
1938
+ self._endpoints_cache = None # the state is about to change
1581
1939
  data = await self._graphql(
1582
1940
  MUTATION_SET_ENDPOINT_FEATURES,
1583
1941
  {"input": {"featureControlRequests": [control]}},
@@ -1591,6 +1949,98 @@ class AmazonEchoClient:
1591
1949
  if not result.get("featureControlResponses"):
1592
1950
  raise AmazonEchoResponseError(200, "No response to the feature operation")
1593
1951
 
1952
+ # ----------------------------------------------------------- Alexa Guard
1953
+
1954
+ async def get_guard(self) -> Guard | None:
1955
+ """Return the Alexa Guard panel with its state, None without Guard.
1956
+
1957
+ ponytail: the panel is looked up once per client; an account that
1958
+ gets Guard later needs a new client (a reload of the integration).
1959
+ """
1960
+ if not self._guard_known:
1961
+ data = await self._graphql(QUERY_APPLIANCES)
1962
+ self._guard = next(
1963
+ (
1964
+ Guard(
1965
+ entity_id=appliance["entityId"],
1966
+ appliance_id=appliance["applianceId"],
1967
+ )
1968
+ for item in _dig(data, "endpoints", "items") or []
1969
+ if (appliance := item.get("legacyAppliance") or {}).get("modelName")
1970
+ == GUARD_MODEL
1971
+ and appliance.get("entityId")
1972
+ and appliance.get("applianceId")
1973
+ ),
1974
+ None,
1975
+ )
1976
+ self._guard_known = True
1977
+ guard = self._guard
1978
+ if guard is None:
1979
+ return None
1980
+ data = await self._request(
1981
+ "POST",
1982
+ "/api/phoenix/state",
1983
+ json={
1984
+ "stateRequests": [{"entityId": guard.entity_id, "entityType": "ENTITY"}]
1985
+ },
1986
+ )
1987
+ guard.state = None
1988
+ for device_state in (data or {}).get("deviceStates") or []:
1989
+ for raw in device_state.get("capabilityStates") or []:
1990
+ try:
1991
+ capability = jsonlib.loads(raw)
1992
+ except TypeError, ValueError:
1993
+ continue
1994
+ if (
1995
+ capability.get("namespace") == "Alexa.SecurityPanelController"
1996
+ and capability.get("name") == "armState"
1997
+ ):
1998
+ guard.state = capability.get("value")
1999
+ return guard
2000
+
2001
+ async def set_guard(
2002
+ self, guard: Guard, armed: bool, device: Device | None = None
2003
+ ) -> None:
2004
+ """Arm Guard (away mode) or disarm it (home mode).
2005
+
2006
+ Args:
2007
+ guard: The panel from :meth:`get_guard`.
2008
+ armed: True for away, False for home.
2009
+ device: An Echo with Guard (capability ``GUARD_EARCON``) to send
2010
+ the command through, as the Alexa app does. Without one the
2011
+ smart-home state API is used.
2012
+
2013
+ """
2014
+ if device is not None and device.supports(GUARD_CAPABILITY):
2015
+ parts = guard.appliance_id.split("_")
2016
+ await self._run(
2017
+ await self._node(
2018
+ device,
2019
+ "controlGuardState",
2020
+ target=parts[2] if len(parts) > 2 else guard.appliance_id,
2021
+ operationId="controlGuardState",
2022
+ state="AWAY" if armed else "HOME",
2023
+ skillId=GUARD_SKILL_ID,
2024
+ )
2025
+ )
2026
+ return
2027
+ await self._request(
2028
+ "PUT",
2029
+ "/api/phoenix/state",
2030
+ json={
2031
+ "controlRequests": [
2032
+ {
2033
+ "entityId": guard.entity_id,
2034
+ "entityType": "APPLIANCE",
2035
+ "parameters": {
2036
+ "action": "controlSecurityPanel",
2037
+ "armState": "ARMED_AWAY" if armed else "ARMED_STAY",
2038
+ },
2039
+ }
2040
+ ]
2041
+ },
2042
+ )
2043
+
1594
2044
 
1595
2045
  def _parse_voice_record(item: dict[str, Any]) -> VoiceRecord | None:
1596
2046
  """Build a :class:`VoiceRecord` from a privacy-hub history record."""
@@ -1624,4 +2074,5 @@ def _parse_voice_record(item: dict[str, Any]) -> VoiceRecord | None:
1624
2074
  response=" ".join(response) or None,
1625
2075
  intent=item.get("intent") if item.get("intent") != "Unknown" else None,
1626
2076
  person=person.get("personFirstName") if isinstance(person, dict) else None,
2077
+ person_type=person.get("personType") if isinstance(person, dict) else None,
1627
2078
  )