python-amazon-echo 0.1.1__py3-none-any.whl → 0.2.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/__init__.py CHANGED
@@ -20,6 +20,8 @@ from .models import (
20
20
  BluetoothDevice,
21
21
  Device,
22
22
  EchoList,
23
+ Endpoint,
24
+ Guard,
23
25
  ListItem,
24
26
  MediaState,
25
27
  Notification,
@@ -28,7 +30,7 @@ from .models import (
28
30
  )
29
31
  from .push import PushClient, PushEvent
30
32
 
31
- __version__ = "0.1.1"
33
+ __version__ = "0.2.0"
32
34
 
33
35
  __all__ = [
34
36
  "Account",
@@ -46,6 +48,8 @@ __all__ = [
46
48
  "Credentials",
47
49
  "Device",
48
50
  "EchoList",
51
+ "Endpoint",
52
+ "Guard",
49
53
  "ListItem",
50
54
  "LocalInfo",
51
55
  "MediaState",
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={
@@ -1226,6 +1454,67 @@ class AmazonEchoClient:
1226
1454
  )
1227
1455
  )
1228
1456
 
1457
+ async def send_sequence(
1458
+ self, device: Device, kind: str, payload: dict[str, Any] | None = None
1459
+ ) -> None:
1460
+ """Run any behavior node type (``Alexa.Weather.Play``…) on ``device``."""
1461
+ await self._run(await self._node(device, kind, **(payload or {})))
1462
+
1463
+ async def info_skill(self, device: Device, skill: str) -> None:
1464
+ """Make ``device`` tell something: a key of ``INFO_SKILLS``.
1465
+
1466
+ ``weather``, ``traffic``, ``flash_briefing``, ``good_morning``,
1467
+ ``fun_fact``, ``joke``, ``tell_story``, ``calendar_today``…
1468
+ """
1469
+ if skill not in INFO_SKILLS:
1470
+ raise ValueError(f"Unknown info skill: {skill}")
1471
+ await self.send_sequence(device, INFO_SKILLS[skill])
1472
+
1473
+ async def send_mobile_push(
1474
+ self, message: str, *, title: str | None = None, device: Device | None = None
1475
+ ) -> None:
1476
+ """Send a notification to the Alexa app on the account's phones.
1477
+
1478
+ ``device`` only names the sender in the request; the notification
1479
+ always goes to the app.
1480
+ """
1481
+ customer_id, locale = await self._customer()
1482
+ payload: dict[str, Any] = {
1483
+ "customerId": customer_id,
1484
+ "notificationMessage": message,
1485
+ "alexaUrl": "#v2/behaviors",
1486
+ "title": title or "Home Assistant",
1487
+ "skillId": "amzn1.ask.1p.routines.messaging",
1488
+ }
1489
+ if device is not None:
1490
+ payload = {**self._query(device), "locale": locale, **payload}
1491
+ await self._run(
1492
+ {
1493
+ "@type": f"{_NODE}OpaquePayloadOperationNode",
1494
+ "type": "Alexa.Notifications.SendMobilePush",
1495
+ "operationPayload": payload,
1496
+ }
1497
+ )
1498
+
1499
+ async def send_drop_in_notification(
1500
+ self, message: str, *, title: str | None = None
1501
+ ) -> None:
1502
+ """Send an Alexa app notification that opens the Drop In dialog."""
1503
+ customer_id, _ = await self._customer()
1504
+ await self._run(
1505
+ {
1506
+ "@type": f"{_NODE}OpaquePayloadOperationNode",
1507
+ "type": "Alexa.Notifications.DropIn",
1508
+ "skillId": "amzn1.ask.1p.action.dropin",
1509
+ "operationPayload": {
1510
+ "customerId": customer_id,
1511
+ "notificationMessage": message,
1512
+ "alexaUrl": "#v2/comms/conversation-list?showDropInDialog=true",
1513
+ "title": title or "Home Assistant",
1514
+ },
1515
+ }
1516
+ )
1517
+
1229
1518
  async def run_routine(self, routine: Routine, device: Device | None = None) -> None:
1230
1519
  """Run a routine.
1231
1520
 
@@ -1271,7 +1560,9 @@ class AmazonEchoClient:
1271
1560
  raise AmazonEchoResponseError(200, f"The new {kind} did not show up")
1272
1561
  return max(candidates, key=lambda item: item.raw.get("createdDate") or 0)
1273
1562
 
1274
- async def _alerts(self, method: str, path: str, body: dict[str, Any]) -> Any:
1563
+ async def _alerts(
1564
+ self, method: str, path: str, body: dict[str, Any] | None = None
1565
+ ) -> Any:
1275
1566
  """Call the app's alerts API, which takes the raw access token."""
1276
1567
  url = (await self.get_service_urls()).get("alexaApiUrl")
1277
1568
  if not url:
@@ -1382,6 +1673,44 @@ class AmazonEchoClient:
1382
1673
  await self._alerts("POST", "timers", body)
1383
1674
  return await self._find_new(device, "timer", known)
1384
1675
 
1676
+ @staticmethod
1677
+ def _alarm_index(alarm: Notification) -> str:
1678
+ index = alarm.raw.get("notificationIndex")
1679
+ if alarm.kind not in ("alarm", "music_alarm") or not index:
1680
+ raise AmazonEchoNotSupportedError("Only alarms can be switched")
1681
+ return quote(str(index), safe="")
1682
+
1683
+ async def enable_alarm(self, alarm: Notification) -> None:
1684
+ """Turn an alarm on; it rings at its next occurrence.
1685
+
1686
+ The next ring is computed in the system time zone, which Amazon reads
1687
+ as the Echo's own (see :meth:`create_alarm`).
1688
+
1689
+ Raises:
1690
+ AmazonEchoNotSupportedError: Not an alarm.
1691
+ ValueError: The alarm has no time or an unknown repeat rule.
1692
+
1693
+ """
1694
+ body: dict[str, Any] = {
1695
+ "trigger": {"scheduledTime": _next_ring(alarm.raw, datetime.now())}, # noqa: DTZ005
1696
+ "extensions": [],
1697
+ }
1698
+ if music := alarm.raw.get("musicAlarmId"):
1699
+ body["assets"] = [{"type": "TONE", "assetId": f"MUSIC-{music}"}]
1700
+ elif alarm.sound:
1701
+ body["assets"] = [{"type": "TONE", "assetId": alarm.sound}]
1702
+ await self._alerts("PUT", f"alarms/{self._alarm_index(alarm)}/activate", body)
1703
+
1704
+ async def disable_alarm(self, alarm: Notification) -> None:
1705
+ """Turn an alarm off without deleting it."""
1706
+ await self._alerts("PUT", f"alarms/{self._alarm_index(alarm)}/cancel")
1707
+
1708
+ async def skip_next_alarm(self, alarm: Notification) -> None:
1709
+ """Skip the next occurrence of a repeating alarm."""
1710
+ await self._alerts(
1711
+ "PUT", f"alarms/{self._alarm_index(alarm)}/nextOccurrence/cancel"
1712
+ )
1713
+
1385
1714
  async def delete_notification(self, notification: Notification) -> None:
1386
1715
  """Delete an alarm, timer or reminder."""
1387
1716
  await self._request(
@@ -1578,6 +1907,7 @@ class AmazonEchoClient:
1578
1907
  control["instance"] = instance
1579
1908
  if payload is not None:
1580
1909
  control["payload"] = payload
1910
+ self._endpoints_cache = None # the state is about to change
1581
1911
  data = await self._graphql(
1582
1912
  MUTATION_SET_ENDPOINT_FEATURES,
1583
1913
  {"input": {"featureControlRequests": [control]}},
@@ -1591,6 +1921,98 @@ class AmazonEchoClient:
1591
1921
  if not result.get("featureControlResponses"):
1592
1922
  raise AmazonEchoResponseError(200, "No response to the feature operation")
1593
1923
 
1924
+ # ----------------------------------------------------------- Alexa Guard
1925
+
1926
+ async def get_guard(self) -> Guard | None:
1927
+ """Return the Alexa Guard panel with its state, None without Guard.
1928
+
1929
+ ponytail: the panel is looked up once per client; an account that
1930
+ gets Guard later needs a new client (a reload of the integration).
1931
+ """
1932
+ if not self._guard_known:
1933
+ data = await self._graphql(QUERY_APPLIANCES)
1934
+ self._guard = next(
1935
+ (
1936
+ Guard(
1937
+ entity_id=appliance["entityId"],
1938
+ appliance_id=appliance["applianceId"],
1939
+ )
1940
+ for item in _dig(data, "endpoints", "items") or []
1941
+ if (appliance := item.get("legacyAppliance") or {}).get("modelName")
1942
+ == GUARD_MODEL
1943
+ and appliance.get("entityId")
1944
+ and appliance.get("applianceId")
1945
+ ),
1946
+ None,
1947
+ )
1948
+ self._guard_known = True
1949
+ guard = self._guard
1950
+ if guard is None:
1951
+ return None
1952
+ data = await self._request(
1953
+ "POST",
1954
+ "/api/phoenix/state",
1955
+ json={
1956
+ "stateRequests": [{"entityId": guard.entity_id, "entityType": "ENTITY"}]
1957
+ },
1958
+ )
1959
+ guard.state = None
1960
+ for device_state in (data or {}).get("deviceStates") or []:
1961
+ for raw in device_state.get("capabilityStates") or []:
1962
+ try:
1963
+ capability = jsonlib.loads(raw)
1964
+ except TypeError, ValueError:
1965
+ continue
1966
+ if (
1967
+ capability.get("namespace") == "Alexa.SecurityPanelController"
1968
+ and capability.get("name") == "armState"
1969
+ ):
1970
+ guard.state = capability.get("value")
1971
+ return guard
1972
+
1973
+ async def set_guard(
1974
+ self, guard: Guard, armed: bool, device: Device | None = None
1975
+ ) -> None:
1976
+ """Arm Guard (away mode) or disarm it (home mode).
1977
+
1978
+ Args:
1979
+ guard: The panel from :meth:`get_guard`.
1980
+ armed: True for away, False for home.
1981
+ device: An Echo with Guard (capability ``GUARD_EARCON``) to send
1982
+ the command through, as the Alexa app does. Without one the
1983
+ smart-home state API is used.
1984
+
1985
+ """
1986
+ if device is not None and device.supports(GUARD_CAPABILITY):
1987
+ parts = guard.appliance_id.split("_")
1988
+ await self._run(
1989
+ await self._node(
1990
+ device,
1991
+ "controlGuardState",
1992
+ target=parts[2] if len(parts) > 2 else guard.appliance_id,
1993
+ operationId="controlGuardState",
1994
+ state="AWAY" if armed else "HOME",
1995
+ skillId=GUARD_SKILL_ID,
1996
+ )
1997
+ )
1998
+ return
1999
+ await self._request(
2000
+ "PUT",
2001
+ "/api/phoenix/state",
2002
+ json={
2003
+ "controlRequests": [
2004
+ {
2005
+ "entityId": guard.entity_id,
2006
+ "entityType": "APPLIANCE",
2007
+ "parameters": {
2008
+ "action": "controlSecurityPanel",
2009
+ "armState": "ARMED_AWAY" if armed else "ARMED_STAY",
2010
+ },
2011
+ }
2012
+ ]
2013
+ },
2014
+ )
2015
+
1594
2016
 
1595
2017
  def _parse_voice_record(item: dict[str, Any]) -> VoiceRecord | None:
1596
2018
  """Build a :class:`VoiceRecord` from a privacy-hub history record."""
@@ -1624,4 +2046,5 @@ def _parse_voice_record(item: dict[str, Any]) -> VoiceRecord | None:
1624
2046
  response=" ".join(response) or None,
1625
2047
  intent=item.get("intent") if item.get("intent") != "Unknown" else None,
1626
2048
  person=person.get("personFirstName") if isinstance(person, dict) else None,
2049
+ person_type=person.get("personType") if isinstance(person, dict) else None,
1627
2050
  )
amazon_echo/const.py CHANGED
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  from typing import Any, Final
6
6
 
7
- VERSION: Final = "0.1.1"
7
+ VERSION: Final = "0.2.0"
8
8
 
9
9
  # Identity of the Alexa iOS app, which is what a registration impersonates.
10
10
  APP_NAME: Final = "Amazon Echo for Home Assistant"
@@ -28,6 +28,8 @@ AUTH_HOST: Final = "api.amazon.com"
28
28
  AVS_HOST: Final = "api.amazonalexa.com"
29
29
  PUSH_HOST: Final = "bob-dispatch-prod-{region}.amazon.com"
30
30
  PUSH_VERSION: Final = "v20160207"
31
+ # Communications service; every marketplace has an alias of the same host.
32
+ COMMS_HOST: Final = "alexa-comms-mobile-service.{domain}"
31
33
 
32
34
  # Retail domains whose accounts live outside the EU push region.
33
35
  REGION_BY_DOMAIN: Final[dict[str, str]] = {
@@ -65,6 +67,48 @@ MEDIA_COMMANDS: Final[dict[str, str]] = {
65
67
  "repeat": "RepeatCommand",
66
68
  }
67
69
 
70
+ # "Tell me…" routines actions: name → behavior node type.
71
+ INFO_SKILLS: Final[dict[str, str]] = {
72
+ "calendar_today": "Alexa.Calendar.PlayToday",
73
+ "calendar_tomorrow": "Alexa.Calendar.PlayTomorrow",
74
+ "calendar_next": "Alexa.Calendar.PlayNext",
75
+ "date": "Alexa.Date.Play",
76
+ "time": "Alexa.Time.Play",
77
+ "national_news": "Alexa.News.NationalNews",
78
+ "flash_briefing": "Alexa.FlashBriefing.Play",
79
+ "traffic": "Alexa.Traffic.Play",
80
+ "weather": "Alexa.Weather.Play",
81
+ "clean_up": "Alexa.CleanUp.Play",
82
+ "good_morning": "Alexa.GoodMorning.Play",
83
+ "sing_a_song": "Alexa.SingASong.Play",
84
+ "fun_fact": "Alexa.FunFact.Play",
85
+ "joke": "Alexa.Joke.Play",
86
+ "tell_story": "Alexa.TellStory.Play",
87
+ "im_home": "Alexa.ImHome.Play",
88
+ "good_night": "Alexa.GoodNight.Play",
89
+ }
90
+
91
+ DROP_IN_MODES: Final[dict[str, str]] = {"all": "All", "home": "Home", "off": "Off"}
92
+
93
+ # GraphQL feature instances with a fixed meaning.
94
+ AMBIENT_MODE_INSTANCE: Final = "FTV.AmbientMode"
95
+ REMOTE_BATTERY_INSTANCE: Final = "Remote.Battery"
96
+ # The Amazon Air Quality Monitor reports its readings as numbered ranges.
97
+ AQM_DEVICE_TYPE: Final = "AEZME1X38KDRA"
98
+ AQM_LED_INSTANCE: Final = "11"
99
+ AQM_RANGES: Final[dict[str, str]] = {
100
+ "4": "humidity",
101
+ "5": "voc",
102
+ "6": "pm25",
103
+ "7": "pm10",
104
+ "8": "co",
105
+ "9": "air_quality",
106
+ }
107
+
108
+ GUARD_MODEL: Final = "REDROCK_GUARD_PANEL"
109
+ GUARD_SKILL_ID: Final = "amzn1.ask.skill.f71a9b50-e99a-4669-a226-d50ebb5e0830"
110
+ GUARD_CAPABILITY: Final = "GUARD_EARCON"
111
+
68
112
  # What the Alexa app declares to AVS (PUT /v1/devices/@self/capabilities).
69
113
  # Without `Alexa.Mobile.Push` the HTTP/2 channel stays silent.
70
114
  _LEGACY_FLAGS: Final[dict[str, Any]] = {
@@ -223,6 +267,7 @@ query echoEndpoints {
223
267
  endpoints {
224
268
  endpointId: id
225
269
  friendlyNameObject { value { text } }
270
+ manufacturer { value { text } }
226
271
  model { value { text } }
227
272
  displayCategories { primary { value } }
228
273
  dmsIdentifier { deviceType dsn }
@@ -231,6 +276,7 @@ query echoEndpoints {
231
276
  features {
232
277
  name
233
278
  instance
279
+ operations { name }
234
280
  properties {
235
281
  name
236
282
  type
@@ -241,6 +287,24 @@ query echoEndpoints {
241
287
  ... on ToggleState { toggleStateValue }
242
288
  ... on Volume { vol: value { value } }
243
289
  ... on Reachability { reachabilityStatusValue }
290
+ ... on Illuminance { illuminanceValue { value } }
291
+ ... on DetectionState { detectionStateValue }
292
+ ... on RelativeHumidity { relativeHumidityValue { value } }
293
+ ... on RangeValue { rangeValue { value } }
294
+ ... on Power { powerStateValue }
295
+ ... on Brightness { brightnessStateValue }
296
+ ... on Color { colorStateValue { hue saturation brightness } }
297
+ ... on ColorTemperature { colorTemperatureInKelvinStateValue }
298
+ ... on Lock { lockState }
299
+ ... on Mode { modeValue { value } }
300
+ }
301
+ configuration {
302
+ ... on ModeConfiguration {
303
+ modeOptions {
304
+ value
305
+ modeResources { friendlyName { value { text } } }
306
+ }
307
+ }
244
308
  }
245
309
  }
246
310
  }
@@ -248,6 +312,15 @@ query echoEndpoints {
248
312
  }
249
313
  """
250
314
 
315
+ # The Alexa Guard panel only shows up in the legacy appliance list.
316
+ QUERY_APPLIANCES: Final = """
317
+ query echoAppliances {
318
+ endpoints(endpointsQueryParams: {paginationParams: {disablePagination: true}}) {
319
+ items { legacyAppliance { applianceId modelName entityId } }
320
+ }
321
+ }
322
+ """
323
+
251
324
  MUTATION_SET_ENDPOINT_FEATURES: Final = """
252
325
  mutation setEndpointFeatures($input: SetEndpointFeaturesInput!) {
253
326
  setEndpointFeatures(setEndpointFeaturesInput: $input) {
@@ -0,0 +1,191 @@
1
+ """Parsers for the GraphQL endpoints (Alexa devices and smart-home devices).
2
+
3
+ A GraphQL endpoint lists *features* (``power``, ``temperatureSensor``…), each
4
+ with typed *properties*. They are flattened here into plain values, keyed by
5
+ what the property carries rather than by device model, so any device that
6
+ reports a property gets its value. The same shape arrives over push
7
+ (``EventBus:AlexaMobile::FDAL``), without the query aliases.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Iterator
13
+ import re
14
+ from typing import Any
15
+
16
+ from .const import (
17
+ AMBIENT_MODE_INSTANCE,
18
+ AQM_DEVICE_TYPE,
19
+ AQM_LED_INSTANCE,
20
+ AQM_RANGES,
21
+ REMOTE_BATTERY_INSTANCE,
22
+ )
23
+ from .models import Endpoint
24
+
25
+ # What Amazon reports while a temperature sensor calibrates (after a reboot).
26
+ _CALIBRATING = -280
27
+ _DETECTION = {"motionSensor": "motion", "contactSensor": "contact"}
28
+
29
+
30
+ def format_mac(value: str | None) -> str | None:
31
+ """Return ``aa:bb:cc:dd:ee:ff`` for any 12-hex-digit MAC spelling."""
32
+ digits = re.sub(r"[^0-9a-fA-F]", "", value or "").lower()
33
+ if len(digits) != 12:
34
+ return None
35
+ return ":".join(digits[i : i + 2] for i in range(0, 12, 2))
36
+
37
+
38
+ def dig(data: Any, *path: str) -> Any:
39
+ """Walk nested dicts, returning None as soon as a level is missing."""
40
+ for key in path:
41
+ if not isinstance(data, dict):
42
+ return None
43
+ data = data.get(key)
44
+ return data
45
+
46
+
47
+ def _celsius(reading: Any) -> float | None:
48
+ value = dig(reading, "value")
49
+ if not isinstance(value, (int, float)) or value == _CALIBRATING:
50
+ return None
51
+ if dig(reading, "scale") == "FAHRENHEIT":
52
+ return round((value - 32) / 1.8, 1)
53
+ return value
54
+
55
+
56
+ def _switched(value: Any) -> bool | None:
57
+ return None if value is None else value == "ON"
58
+
59
+
60
+ def _values(
61
+ feature: str, instance: str | None, prop: dict[str, Any], device_type: str | None
62
+ ) -> Iterator[tuple[str, Any]]:
63
+ """Yield the (key, value) pairs one property stands for."""
64
+ name = prop.get("name")
65
+ if name == "temperature":
66
+ # `temp` is the query alias, `value` what a push update carries
67
+ yield "temperature", _celsius(prop.get("temp") or prop.get("value"))
68
+ elif name == "volume":
69
+ yield "volume", dig(prop.get("vol") or prop.get("value"), "value")
70
+ elif "reachabilityStatusValue" in prop:
71
+ status = prop["reachabilityStatusValue"]
72
+ yield "reachable", None if status is None else status == "OK"
73
+ elif "illuminanceValue" in prop:
74
+ yield "illuminance", dig(prop, "illuminanceValue", "value")
75
+ elif "detectionStateValue" in prop and feature in _DETECTION:
76
+ state = prop["detectionStateValue"]
77
+ yield _DETECTION[feature], None if state is None else state == "DETECTED"
78
+ elif "relativeHumidityValue" in prop:
79
+ yield "humidity", dig(prop, "relativeHumidityValue", "value")
80
+ elif "rangeValue" in prop:
81
+ if device_type == AQM_DEVICE_TYPE and instance in AQM_RANGES:
82
+ yield AQM_RANGES[instance], dig(prop, "rangeValue", "value")
83
+ elif "powerStateValue" in prop:
84
+ yield "power", _switched(prop["powerStateValue"])
85
+ elif "brightnessStateValue" in prop:
86
+ yield "brightness", prop["brightnessStateValue"]
87
+ elif "colorStateValue" in prop:
88
+ yield "color", prop["colorStateValue"]
89
+ elif "colorTemperatureInKelvinStateValue" in prop:
90
+ yield "color_temperature", prop["colorTemperatureInKelvinStateValue"]
91
+ elif "lockState" in prop:
92
+ yield "lock", prop["lockState"]
93
+ elif "modeValue" in prop:
94
+ yield "mode", dig(prop, "modeValue", "value")
95
+ elif "toggleStateValue" in prop:
96
+ value = _switched(prop["toggleStateValue"])
97
+ if instance == AMBIENT_MODE_INSTANCE:
98
+ yield "ambient_mode", value
99
+ elif device_type == AQM_DEVICE_TYPE and instance == AQM_LED_INSTANCE:
100
+ yield "aqm_led", value
101
+ elif "batteryValue" in prop:
102
+ yield "battery", dig(prop, "batteryValue", "levelPercentage")
103
+ elif "inventoryLevelValue" in prop:
104
+ level = dig(prop, "inventoryLevelValue", "value")
105
+ if instance == REMOTE_BATTERY_INSTANCE:
106
+ yield "remote_battery", level
107
+ elif "battery" in (instance or "").casefold():
108
+ yield "battery", level
109
+
110
+
111
+ def parse_features(
112
+ features: list[dict[str, Any]] | None, *, device_type: str | None = None
113
+ ) -> dict[str, Any]:
114
+ """Flatten GraphQL features into values.
115
+
116
+ A key is present when the endpoint has the feature; its value is None
117
+ while Amazon cannot read it (device unreachable, sensor calibrating).
118
+
119
+ Keys: ``reachable``, ``temperature`` (°C), ``humidity`` (%),
120
+ ``illuminance`` (lx), ``motion``, ``contact`` (True = open), ``battery``
121
+ (%), ``remote_battery`` (%), ``volume``, ``ambient_mode``, ``power``,
122
+ ``brightness`` (0-100), ``color`` (``hue`` 0-360, ``saturation`` and
123
+ ``brightness`` 0-1), ``color_temperature`` (K), ``lock`` (``LOCKED`` /
124
+ ``UNLOCKED`` / ``JAMMED``), ``mode`` with ``mode_instance`` and
125
+ ``mode_options`` (name → value) and, for the Amazon Air Quality Monitor,
126
+ ``pm25`` / ``pm10`` (µg/m³), ``voc`` (index), ``co`` (ppm),
127
+ ``air_quality`` (index) and ``aqm_led``.
128
+ """
129
+ state: dict[str, Any] = {}
130
+ for feature in features or []:
131
+ name, instance = feature.get("name") or "", feature.get("instance")
132
+ for prop in feature.get("properties") or []:
133
+ for key, value in _values(name, instance, prop or {}, device_type):
134
+ # two features can carry a battery: keep the one that reads
135
+ if value is not None or state.get(key) is None:
136
+ state[key] = value
137
+ options = dig(feature, "configuration", "modeOptions")
138
+ if name == "mode" and options:
139
+ state["mode_instance"] = instance
140
+ state["mode_options"] = {
141
+ dig(option, "modeResources", "friendlyName", "value", "text")
142
+ or option["value"]: option["value"]
143
+ for option in options
144
+ if option.get("value")
145
+ }
146
+ return state
147
+
148
+
149
+ def parse_endpoint(endpoint: dict[str, Any]) -> dict[str, Any]:
150
+ """Flatten one GraphQL endpoint of an Alexa device (see ``parse_features``)."""
151
+ mac = None
152
+ for connection in endpoint.get("connections") or []:
153
+ if connection.get("type") == "TCP_IP" and connection.get("macAddress"):
154
+ mac = format_mac(connection["macAddress"])
155
+ return {
156
+ "endpoint_id": endpoint.get("endpointId"),
157
+ "model": dig(endpoint, "model", "value", "text"),
158
+ "mac": mac,
159
+ "temperature": None,
160
+ "volume": None,
161
+ "reachable": None,
162
+ "remote_battery": None,
163
+ "ambient_mode": None,
164
+ "dnd": dig(endpoint, "settings", "doNotDisturb", "toggleValue"),
165
+ **parse_features(
166
+ endpoint.get("features"),
167
+ device_type=dig(endpoint, "dmsIdentifier", "deviceType"),
168
+ ),
169
+ }
170
+
171
+
172
+ def build_endpoint(endpoint: dict[str, Any]) -> Endpoint:
173
+ """Build an :class:`Endpoint` from one GraphQL endpoint."""
174
+ features = endpoint.get("features") or []
175
+ device_type = dig(endpoint, "dmsIdentifier", "deviceType")
176
+ return Endpoint(
177
+ id=endpoint["endpointId"],
178
+ name=dig(endpoint, "friendlyNameObject", "value", "text")
179
+ or endpoint["endpointId"],
180
+ category=dig(endpoint, "displayCategories", "primary", "value") or "OTHER",
181
+ manufacturer=dig(endpoint, "manufacturer", "value", "text"),
182
+ model=dig(endpoint, "model", "value", "text"),
183
+ serial=dig(endpoint, "dmsIdentifier", "dsn"),
184
+ device_type=device_type,
185
+ operations=frozenset(
186
+ f"{feature.get('name')}.{operation.get('name')}"
187
+ for feature in features
188
+ for operation in feature.get("operations") or []
189
+ ),
190
+ state=parse_features(features, device_type=device_type),
191
+ )
amazon_echo/models.py CHANGED
@@ -152,6 +152,7 @@ class VoiceRecord:
152
152
  response: str | None = None
153
153
  intent: str | None = None
154
154
  person: str | None = None
155
+ person_type: str | None = None
155
156
 
156
157
 
157
158
  @dataclass(slots=True, kw_only=True)
@@ -163,3 +164,45 @@ class AuxPort:
163
164
  plugged: bool = False
164
165
  enabled: bool = False
165
166
  active: bool = False
167
+
168
+
169
+ @dataclass(slots=True, kw_only=True)
170
+ class Endpoint:
171
+ """A smart-home device linked to the account (lamp, plug, sensor, lock…).
172
+
173
+ ``state`` holds the values of ``parse_features``; ``operations`` the
174
+ ``feature.operation`` pairs the endpoint accepts (``power.turnOn``).
175
+ """
176
+
177
+ id: str
178
+ name: str
179
+ category: str
180
+ manufacturer: str | None = None
181
+ model: str | None = None
182
+ serial: str | None = None
183
+ device_type: str | None = None
184
+ operations: frozenset[str] = frozenset()
185
+ state: dict[str, Any] = field(default_factory=dict)
186
+
187
+ @property
188
+ def is_amazon_device(self) -> bool:
189
+ """Return True for Amazon hardware (Echo Glow, Air Quality Monitor)."""
190
+ return self.serial is not None
191
+
192
+ def supports(self, feature: str, operation: str) -> bool:
193
+ """Return True when the endpoint accepts ``operation`` of ``feature``."""
194
+ return f"{feature}.{operation}" in self.operations
195
+
196
+
197
+ @dataclass(slots=True, kw_only=True)
198
+ class Guard:
199
+ """The Alexa Guard panel of the account."""
200
+
201
+ entity_id: str
202
+ appliance_id: str
203
+ state: str | None = None
204
+
205
+ @property
206
+ def armed(self) -> bool:
207
+ """Return True while Guard is in away mode."""
208
+ return self.state == "ARMED_AWAY"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-amazon-echo
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Async Python client for Amazon Echo / Alexa devices: state, settings, media, notifications, lists, HTTP/2 push and LAN discovery
5
5
  Project-URL: Homepage, https://github.com/hudsonbrendon/python-amazon-echo
6
6
  Project-URL: Repository, https://github.com/hudsonbrendon/python-amazon-echo
@@ -52,9 +52,22 @@ on the local network. It is not affiliated with Amazon.
52
52
  volume, default alarm sound, ascending alarm, wake word, AUX direction, whisper
53
53
  mode, adaptive volume and any per-device setting key (speaking rate, time zone,
54
54
  captions, …).
55
- - **Actions.** Volume, stop, speak, announce, text command, sounds, music,
56
- skills, routines, transport commands, Bluetooth, reboot.
57
- - **Alarms, timers and reminders.** List all, create and delete.
55
+ - **Actions.** Volume, stop, speak, announce (spoken, shown or both), text
56
+ command, sounds, music, skills, routines, the "tell me…" info skills (weather,
57
+ traffic, flash briefing, a joke…), any other behavior node type, transport
58
+ commands, Bluetooth, reboot, Echo Show background image.
59
+ - **Notifications to the Alexa app.** A mobile push, or one that opens Drop In.
60
+ - **Communication preferences.** Calls and messages, announcements and Drop In
61
+ per device.
62
+ - **Amazon Kids.** The child profiles of the household, which one a device is
63
+ assigned to, and switching a device into or out of Kids mode.
64
+ - **Alarms, timers and reminders.** List all, create, delete; switch an alarm
65
+ on or off and skip its next ring.
66
+ - **Smart home.** Every device linked to the account (lamps, plugs, sensors,
67
+ locks, Echo Glow, the Air Quality Monitor) with its state and the operations
68
+ it accepts; sensors of the Echos themselves (illuminance, motion, humidity);
69
+ state changes pushed by Amazon decoded into the same values.
70
+ - **Alexa Guard.** Read the panel, arm (away) and disarm (home).
58
71
  - **Lists.** Shopping, to-do and custom lists with full item CRUD.
59
72
  - **Voice history.**
60
73
  - **Push.** One HTTP/2 stream delivers volume, playback, do-not-disturb,
@@ -121,6 +134,26 @@ await push.start() # background task, reconnects with back-off 5·2ⁿ s (≤ 6
121
134
  await push.stop()
122
135
  ```
123
136
 
137
+ Smart home:
138
+
139
+ ```python
140
+ for endpoint in await client.get_smart_home_endpoints():
141
+ print(endpoint.name, endpoint.category, endpoint.state)
142
+
143
+ lamp = next(e for e in await client.get_smart_home_endpoints() if e.category == "LIGHT")
144
+ if lamp.supports("brightness", "setBrightness"):
145
+ await client.call_feature(
146
+ lamp.id, "brightness", "setBrightness", payload={"brightness": 40}
147
+ )
148
+ ```
149
+
150
+ `endpoint.state` uses the keys documented in
151
+ `amazon_echo.endpoints.parse_features` (`power`, `brightness`, `color`,
152
+ `color_temperature`, `temperature`, `humidity`, `battery`, `contact`, `motion`,
153
+ `lock`…); a key is there when the device has the feature, and is None while
154
+ Amazon cannot read it. `get_endpoint_states()` and `get_smart_home_endpoints()`
155
+ share one request when called within 5 seconds.
156
+
124
157
  LAN:
125
158
 
126
159
  ```python
@@ -184,8 +217,9 @@ Credentials are read from `~/.config/amazon-echo/credentials.json`
184
217
 
185
218
  ## Verification
186
219
 
187
- How each part was checked against a real amazon.com.br account on 2026-11-15. Everything is also covered by unit tests with mocked
188
- HTTP.
220
+ How each part was checked against a real amazon.com.br account on 2026-11-15
221
+ (the 0.2.0 additions on 2026-11-16). Everything is also covered by unit tests
222
+ with mocked HTTP.
189
223
 
190
224
  - **live read** — called against Amazon through this library, answer parsed.
191
225
  - **no-op write** — the value just read was written back to one Echo Plus and
@@ -218,6 +252,19 @@ HTTP.
218
252
  | `add_list_item`, `update_list_item`, `delete_list_item` | ported |
219
253
  | `get_voice_history` | live read |
220
254
  | `call_feature` | ported |
255
+ | `get_endpoint_states` with the 0.2.0 query (illuminance, motion, humidity, air quality) | live read: a few hundred endpoints, no GraphQL error. Four devices advertise a light sensor and report no value; no device of the account reports motion, humidity or air quality, so those are unit tested only |
256
+ | `get_smart_home_endpoints` | live read; power, brightness, colour, colour temperature, temperature, battery, contact, motion and lock states and the operation names all parsed |
257
+ | `parse_endpoint_update` (smart-home push) | ported, not replayed live — no push stream on the test session |
258
+ | Smart-home operations through `call_feature` (`turnOn`, `turnOff`, `setBrightness`, `setColor`, `setColorTemperature`, `setMode`, `lock`, `unlock`) | ported, not replayed live — they change a device's visible state. The request shapes of `power`, `brightness`, `lock` and `toggle` are the ones in the Alexa app; the payload of `setColorTemperature` is inferred |
259
+ | `get_communication_preferences` | ported. Called live on five devices: the service answers HTTP 503 for this account whatever the device, while `/accounts` on the same host answers 200 with the same cookies |
260
+ | `set_communications`, `set_announcements`, `set_drop_in` | ported, not replayed live — there was no value to write back (see the line above) |
261
+ | `get_device_preferences`, `get_kids_mode`, `get_children`, `get_kids_profile` | live read |
262
+ | `set_kids_mode` | ported, not replayed live — it changes how a device behaves |
263
+ | `get_guard` | live for an account without Guard (the appliance list is read, no panel is found, None); the state read is ported — the test account has no Guard |
264
+ | `set_guard` | ported, not replayed live — Guard was not touched |
265
+ | `info_skill`, `send_sequence`, `send_mobile_push`, `send_drop_in_notification`, `announce(method=…)` | ported, not replayed live — audible, or visible on a phone |
266
+ | `enable_alarm`, `disable_alarm`, `skip_next_alarm` | ported, not replayed live |
267
+ | `set_background_image` | ported, not replayed live — it changes what an Echo Show displays |
221
268
  | `PushClient` | handshake live (HTTP/2, 200, multipart boundary). the stream is then closed within ~1 s because the test session shares its registration with a running `alexa_media` (one stream per registration, see *Known limitations*); event parsing is unit tested only |
222
269
  | `probe_local`, `is_reachable` | live (two Echo models answer, a smart TV of another brand returns None) |
223
270
 
@@ -250,6 +297,20 @@ HTTP.
250
297
  sends `PUSH_NOTIFICATION_CHANGE`).
251
298
  - `devices-v2` no longer reports MAC addresses or battery levels for most
252
299
  devices; the MAC comes from GraphQL and is missing for apps and groups.
300
+ - **Communication preferences** come from a service that fails for some
301
+ accounts (HTTP 503 on the test account). The call is not retried and raises
302
+ `AmazonEchoRateLimitError`; treat it as "not available for this device".
303
+ - **Guard** is looked up once per client: an account that gets Guard later is
304
+ noticed by a new client. The free version of Guard was retired by Amazon in
305
+ most countries; the code follows `alexapy` and could not be run.
306
+ - **Smart-home state** is what Amazon last heard from the device's own cloud.
307
+ A value Amazon cannot read is None, and `reachable` is False for a device its
308
+ cloud reports offline.
309
+ - **Locks.** Amazon offers `unlock` only for some locks; check
310
+ `endpoint.supports("lock", "unlock")`.
311
+ - **Deleting voice history is not implemented.** The only endpoint the existing
312
+ clients use for it, `/api/activities`, answers 404 since Amazon moved the
313
+ history to the privacy hub.
253
314
  - Amazon can change or remove any of this without notice.
254
315
 
255
316
  ## Development
@@ -0,0 +1,16 @@
1
+ amazon_echo/__init__.py,sha256=0oC9ErIQXFVmdUTl7RYXw1hvl6-gTp3yN2s0qY-8NqM,1437
2
+ amazon_echo/__main__.py,sha256=1Hhd7w2cW5Z9jmwO1OThhcj6gbTLVqAQu5fAMqijJ_0,4325
3
+ amazon_echo/auth.py,sha256=O5SAtY5Wf76-LtFOkHJvrzlNoZdprgJsx5-3crEPUGQ,14417
4
+ amazon_echo/client.py,sha256=k8xzNc6WDSadtZ444HgdCFK71CACFZOYLLN8ODgWvLk,79419
5
+ amazon_echo/const.py,sha256=o8qqiY7JCD1BDELpIn-L17FT2THn_ni_5YejGtWZVM4,11880
6
+ amazon_echo/endpoints.py,sha256=_6vXYWtwGIR_2IjVFJAXWP1vR6jwzIpZ4upkRctwBp8,7925
7
+ amazon_echo/exceptions.py,sha256=7ETH4C2sKbKEJWnJ30ygAO0a_GiD5PWmDHJCSVTedAU,1120
8
+ amazon_echo/local.py,sha256=KHwwgC2-MzFZ0wBaxXRuotyr7-zrrenzfM0P3BEMRvE,3080
9
+ amazon_echo/models.py,sha256=ZKEHuiyG7hqRt5M8nufyf1nyaRZ2-l1WXlOCzG4UH7A,5258
10
+ amazon_echo/push.py,sha256=KMcHeDLgRxEjCQpTybiJUAUNTFTxlDMpTVPDv0ZYAzE,11206
11
+ amazon_echo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ python_amazon_echo-0.2.0.dist-info/METADATA,sha256=Jn6gvMcgmFIkkgObcl4-09A9n07PU0NTChVHwJ7_nGY,16967
13
+ python_amazon_echo-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ python_amazon_echo-0.2.0.dist-info/entry_points.txt,sha256=rbZJ8BI8kkiDTV9cKk6acbHuyAm2xNYfpDBXQNw8Yb8,58
15
+ python_amazon_echo-0.2.0.dist-info/licenses/LICENSE,sha256=4Zgd3fbLJqWSkwKA-hh1rNN6DC9tNQ3rWLX93fingOw,1071
16
+ python_amazon_echo-0.2.0.dist-info/RECORD,,
@@ -1,15 +0,0 @@
1
- amazon_echo/__init__.py,sha256=lHodm3BV0aDFQsWu_TPBD8yaLiHEgwBMT8nEadkF2V0,1383
2
- amazon_echo/__main__.py,sha256=1Hhd7w2cW5Z9jmwO1OThhcj6gbTLVqAQu5fAMqijJ_0,4325
3
- amazon_echo/auth.py,sha256=O5SAtY5Wf76-LtFOkHJvrzlNoZdprgJsx5-3crEPUGQ,14417
4
- amazon_echo/client.py,sha256=zCYu6AytIsa3-qYiNAphJP6C6opEhiwZbxlbkb1jLE8,62495
5
- amazon_echo/const.py,sha256=7T_LijcR0DN8XVAGHDrMT4eOZw5YVNxv2NgU1wsGlyY,9128
6
- amazon_echo/exceptions.py,sha256=7ETH4C2sKbKEJWnJ30ygAO0a_GiD5PWmDHJCSVTedAU,1120
7
- amazon_echo/local.py,sha256=KHwwgC2-MzFZ0wBaxXRuotyr7-zrrenzfM0P3BEMRvE,3080
8
- amazon_echo/models.py,sha256=2RV4rN4G2cNXAbIKDwEWxVgVdJxl98mlHjs6pmHWV6k,3967
9
- amazon_echo/push.py,sha256=KMcHeDLgRxEjCQpTybiJUAUNTFTxlDMpTVPDv0ZYAzE,11206
10
- amazon_echo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
- python_amazon_echo-0.1.1.dist-info/METADATA,sha256=HPqX5Cc0tDe0H0OQ6mA0LmSdC5de2fnfxPCEuhpWvPQ,12236
12
- python_amazon_echo-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
- python_amazon_echo-0.1.1.dist-info/entry_points.txt,sha256=rbZJ8BI8kkiDTV9cKk6acbHuyAm2xNYfpDBXQNw8Yb8,58
14
- python_amazon_echo-0.1.1.dist-info/licenses/LICENSE,sha256=4Zgd3fbLJqWSkwKA-hh1rNN6DC9tNQ3rWLX93fingOw,1071
15
- python_amazon_echo-0.1.1.dist-info/RECORD,,