python-amazon-echo 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
amazon_echo/const.py ADDED
@@ -0,0 +1,260 @@
1
+ """Protocol constants: app identity, AVS capabilities and GraphQL documents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Final
6
+
7
+ VERSION: Final = "0.1.0"
8
+
9
+ # Identity of the Alexa iOS app, which is what a registration impersonates.
10
+ APP_NAME: Final = "Amazon Echo for Home Assistant"
11
+ APP_VERSION: Final = "2.2.663733.0"
12
+ APP_BUNDLE_ID: Final = "com.amazon.echo"
13
+ APP_DEVICE_TYPE: Final = "A2IVLV5VM2W81"
14
+ APP_OS_VERSION: Final = "18.5"
15
+ APP_SOFTWARE_VERSION: Final = "35602678"
16
+ SDK_VERSION: Final = "6.12.4"
17
+
18
+ USER_AGENT: Final = (
19
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 "
20
+ f"(KHTML, like Gecko) Mobile/15E148 PitanguiBridge/{APP_VERSION}-"
21
+ f"[HARDWARE=iPhone14_7][SOFTWARE={APP_OS_VERSION}][DEVICE=iPhone]"
22
+ )
23
+ APP_USER_AGENT: Final = (
24
+ f"AmazonWebView/AmazonAlexa/{APP_VERSION}/iOS/{APP_OS_VERSION}/iPhone"
25
+ )
26
+
27
+ AUTH_HOST: Final = "api.amazon.com"
28
+ AVS_HOST: Final = "api.amazonalexa.com"
29
+ PUSH_HOST: Final = "bob-dispatch-prod-{region}.amazon.com"
30
+ PUSH_VERSION: Final = "v20160207"
31
+
32
+ # Retail domains whose accounts live outside the EU push region.
33
+ REGION_BY_DOMAIN: Final[dict[str, str]] = {
34
+ "amazon.com": "NA",
35
+ "amazon.ca": "NA",
36
+ "amazon.com.mx": "NA",
37
+ "amazon.com.br": "NA",
38
+ "amazon.co.jp": "FE",
39
+ "amazon.com.au": "FE",
40
+ "amazon.in": "FE",
41
+ "amazon.co.nz": "FE",
42
+ }
43
+
44
+ NOTIFICATION_KINDS: Final[dict[str, str]] = {
45
+ "Alarm": "alarm",
46
+ "Timer": "timer",
47
+ "Reminder": "reminder",
48
+ "MusicAlarm": "music_alarm",
49
+ }
50
+
51
+ LIST_KINDS: Final[dict[str, str]] = {
52
+ "SHOP": "shopping",
53
+ "TODO": "todo",
54
+ "CUSTOM": "custom",
55
+ }
56
+
57
+ MEDIA_COMMANDS: Final[dict[str, str]] = {
58
+ "play": "PlayCommand",
59
+ "pause": "PauseCommand",
60
+ "next": "NextCommand",
61
+ "previous": "PreviousCommand",
62
+ "forward": "ForwardCommand",
63
+ "rewind": "RewindCommand",
64
+ "shuffle": "ShuffleCommand",
65
+ "repeat": "RepeatCommand",
66
+ }
67
+
68
+ # What the Alexa app declares to AVS (PUT /v1/devices/@self/capabilities).
69
+ # Without `Alexa.Mobile.Push` the HTTP/2 channel stays silent.
70
+ _LEGACY_FLAGS: Final[dict[str, Any]] = {
71
+ "SUPPORTS_COMMS": True,
72
+ "SUPPORTS_ARBITRATION": True,
73
+ "SCREEN_WIDTH": 1170,
74
+ "SUPPORTS_SCRUBBING": True,
75
+ "SPEECH_SYNTH_SUPPORTS_TTS_URLS": False,
76
+ "SUPPORTS_HOME_AUTOMATION": True,
77
+ "SUPPORTS_DROPIN_OUTBOUND": True,
78
+ "FRIENDLY_NAME_TEMPLATE": "VOX",
79
+ "SUPPORTS_SIP_OUTBOUND_CALLING": True,
80
+ "VOICE_PROFILE_SWITCHING_DISABLED": True,
81
+ "SUPPORTS_LYRICS_IN_CARD": False,
82
+ "SUPPORTS_DATAMART_NAMESPACE": "Vox",
83
+ "SUPPORTS_VIDEO_CALLING": True,
84
+ "SUPPORTS_PFM_CHANGED": True,
85
+ "SUPPORTS_TARGET_PLATFORM": "TABLET",
86
+ "SUPPORTS_SECURE_LOCKSCREEN": False,
87
+ "AUDIO_PLAYER_SUPPORTS_TTS_URLS": False,
88
+ "SUPPORTS_KEYS_IN_HEADER": False,
89
+ "SUPPORTS_MIXING_BEHAVIOR_FOR_AUDIO_PLAYER": False,
90
+ "AXON_SUPPORT": True,
91
+ "SUPPORTS_TTS_SPEECHMARKS": True,
92
+ }
93
+
94
+ _INTERFACES: Final[list[dict[str, Any]]] = [
95
+ {"interface": "CardRenderer", "version": "0.1"},
96
+ {"interface": "Navigation", "version": "1.1"},
97
+ {"interface": "Alexa.Comms.PhoneCallController", "version": "2.0"},
98
+ {"interface": "ExternalMediaPlayer", "version": "1.1"},
99
+ {
100
+ "interface": "Alerts",
101
+ "version": "1.3",
102
+ "configurations": {"maximumAlerts": {"timers": 2, "overall": 99, "alarms": 2}},
103
+ },
104
+ {
105
+ "interface": "Alexa.Display.Window",
106
+ "version": "1.0",
107
+ "configurations": {
108
+ "templates": [
109
+ {
110
+ "type": "STANDARD",
111
+ "id": "app_window_template",
112
+ "configuration": {
113
+ "sizes": [
114
+ {
115
+ "id": "fullscreen",
116
+ "type": "DISCRETE",
117
+ "value": {
118
+ "value": {"height": 1440, "width": 3200},
119
+ "unit": "PIXEL",
120
+ },
121
+ }
122
+ ],
123
+ "interactionModes": ["mobile_mode", "auto_mode"],
124
+ },
125
+ }
126
+ ]
127
+ },
128
+ },
129
+ {"interface": "AccessoryKit", "version": "0.1"},
130
+ {
131
+ "interface": "Alexa.AudioSignal.ActiveNoiseControl",
132
+ "version": "1.0",
133
+ "configurations": {
134
+ "ambientSoundProcessingModes": [
135
+ {"name": "ACTIVE_NOISE_CONTROL"},
136
+ {"name": "PASSTHROUGH"},
137
+ ]
138
+ },
139
+ },
140
+ {"interface": "PlaybackController", "version": "1.0"},
141
+ {"interface": "Speaker", "version": "1.0"},
142
+ {"interface": "SpeechSynthesizer", "version": "1.0"},
143
+ {"interface": "AudioActivityTracker", "version": "1.0"},
144
+ {"interface": "Alexa.Camera.LiveViewController", "version": "1.0"},
145
+ {"interface": "Alexa.Input.Text", "version": "1.0"},
146
+ {"interface": "Alexa.PlaybackStateReporter", "version": "1.0"},
147
+ {"interface": "Geolocation", "version": "1.1"},
148
+ {"interface": "Alexa.Health.Fitness", "version": "1.0"},
149
+ {"interface": "Settings", "version": "1.0"},
150
+ {
151
+ "interface": "Alexa.InteractionMode",
152
+ "version": "1.1",
153
+ "configurations": {
154
+ "interactionModes": [
155
+ {
156
+ "dialog": "SUPPORTED",
157
+ "interactionDistance": {"value": 18, "unit": "INCHES"},
158
+ "video": "SUPPORTED",
159
+ "keyboard": "SUPPORTED",
160
+ "id": "mobile_mode",
161
+ "uiMode": "MOBILE",
162
+ "touch": "SUPPORTED",
163
+ },
164
+ {
165
+ "video": "UNSUPPORTED",
166
+ "dialog": "SUPPORTED",
167
+ "interactionDistance": {"value": 36, "unit": "INCHES"},
168
+ "uiMode": "AUTO",
169
+ "touch": "SUPPORTED",
170
+ "id": "auto_mode",
171
+ "keyboard": "UNSUPPORTED",
172
+ },
173
+ ]
174
+ },
175
+ },
176
+ {
177
+ "interface": "Alexa.Launcher",
178
+ "version": "0.2",
179
+ "configurations": {
180
+ "catalogs": [
181
+ {
182
+ "type": "IOS_APP_STORE",
183
+ "identifierTypes": ["URI_HTTP_SCHEME", "URI_CUSTOM_SCHEME"],
184
+ }
185
+ ]
186
+ },
187
+ },
188
+ {"interface": "System", "version": "1.4"},
189
+ {"interface": "Alexa.IOComponents", "version": "1.4"},
190
+ {"interface": "Alexa.FavoritesController", "version": "1.0"},
191
+ {
192
+ "interface": "Alexa.Mobile.Push",
193
+ "version": "1.1",
194
+ "configurations": {
195
+ "supportedEventFormats": [{"name": "smarthome-events", "version": "1.0.0"}]
196
+ },
197
+ },
198
+ {"interface": "Alexa.Notifications.Multipart", "version": "1.0"},
199
+ {"interface": "Alexa.Notifications.External", "version": "1.0"},
200
+ {"interface": "InteractionModel", "version": "1.2"},
201
+ {"interface": "Alexa.PlaylistController", "version": "1.0"},
202
+ {"interface": "SpeechRecognizer", "version": "2.1"},
203
+ {"interface": "AudioPlayer", "version": "1.3"},
204
+ {"interface": "Alexa.RTCSessionController", "version": "3.1"},
205
+ {"interface": "VisualActivityTracker", "version": "1.1"},
206
+ {"interface": "Alexa.PlaybackController", "version": "1.0"},
207
+ {"interface": "Alexa.SeekController", "version": "1.0"},
208
+ {"interface": "Alexa.Comms.MessagingController", "version": "1.0"},
209
+ ]
210
+
211
+ DEVICE_CAPABILITIES: Final[dict[str, Any]] = {
212
+ "legacyFlags": _LEGACY_FLAGS,
213
+ "envelopeVersion": "20160207",
214
+ "capabilities": [{"type": "AlexaInterface", **item} for item in _INTERFACES],
215
+ }
216
+
217
+ # `temp:` / `vol:` aliases avoid a field-type conflict between union members.
218
+ # `deviceAccountId` and `firstPartyMetadata` are left out on purpose: they make
219
+ # the server throw for speaker-group endpoints.
220
+ QUERY_ENDPOINTS: Final = """
221
+ query echoEndpoints {
222
+ listEndpoints(listEndpointsInput: {includeHouseholdDevices: true}) {
223
+ endpoints {
224
+ endpointId: id
225
+ friendlyNameObject { value { text } }
226
+ model { value { text } }
227
+ displayCategories { primary { value } }
228
+ dmsIdentifier { deviceType dsn }
229
+ connections { type macAddress }
230
+ settings { doNotDisturb { toggleValue } }
231
+ features {
232
+ name
233
+ instance
234
+ properties {
235
+ name
236
+ type
237
+ __typename
238
+ ... on Battery { batteryValue { levelPercentage } }
239
+ ... on InventoryLevel { inventoryLevelValue { type value unit } }
240
+ ... on TemperatureSensor { temp: value { value scale } timeOfSample }
241
+ ... on ToggleState { toggleStateValue }
242
+ ... on Volume { vol: value { value } }
243
+ ... on Reachability { reachabilityStatusValue }
244
+ }
245
+ }
246
+ }
247
+ }
248
+ }
249
+ """
250
+
251
+ MUTATION_SET_ENDPOINT_FEATURES: Final = """
252
+ mutation setEndpointFeatures($input: SetEndpointFeaturesInput!) {
253
+ setEndpointFeatures(setEndpointFeaturesInput: $input) {
254
+ featureControlResponses {
255
+ endpointId featureName instance featureOperationName code
256
+ }
257
+ errors { endpointId featureName instance featureOperationName code message }
258
+ }
259
+ }
260
+ """
@@ -0,0 +1,37 @@
1
+ """Exceptions raised by python-amazon-echo."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class AmazonEchoError(Exception):
7
+ """Base exception for every error raised by this library."""
8
+
9
+
10
+ class AmazonEchoConnectionError(AmazonEchoError):
11
+ """Amazon could not be reached."""
12
+
13
+
14
+ class AmazonEchoConnectionTimeoutError(AmazonEchoConnectionError):
15
+ """Amazon did not answer in time."""
16
+
17
+
18
+ class AmazonEchoAuthenticationError(AmazonEchoError):
19
+ """The session was rejected and could not be refreshed."""
20
+
21
+
22
+ class AmazonEchoRateLimitError(AmazonEchoError):
23
+ """Amazon kept answering 429/503 after the retries."""
24
+
25
+
26
+ class AmazonEchoResponseError(AmazonEchoError):
27
+ """Amazon answered with an unexpected status or an unparsable body."""
28
+
29
+ def __init__(self, status: int = 0, body: str = "") -> None:
30
+ """Initialize the error with the HTTP status and (truncated) body."""
31
+ super().__init__(f"HTTP {status}: {body[:200]}")
32
+ self.status = status
33
+ self.body = body
34
+
35
+
36
+ class AmazonEchoNotSupportedError(AmazonEchoError):
37
+ """The device or account does not expose the requested resource."""
amazon_echo/local.py ADDED
@@ -0,0 +1,94 @@
1
+ """What an Echo exposes on the LAN: discovery and liveness, never control.
2
+
3
+ An Echo has no local control API. It does answer the Spotify Connect zeroconf
4
+ endpoint without authentication, which gives its name, model, multi-room groups
5
+ and the active Spotify user, and it accepts TCP connections on the whole-home
6
+ audio port, which is enough to tell whether it is powered and on the network.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import contextlib
13
+ from dataclasses import dataclass
14
+
15
+ import aiohttp
16
+
17
+ _SPOTIFY_PORT = 4070
18
+
19
+
20
+ @dataclass(slots=True)
21
+ class LocalInfo:
22
+ """Answer of the Spotify Connect zeroconf endpoint of an Echo."""
23
+
24
+ host: str
25
+ name: str | None = None
26
+ model: str | None = None
27
+ brand: str | None = None
28
+ device_id: str | None = None
29
+ spotify_user: str | None = None
30
+ groups: tuple[str, ...] = ()
31
+ library_version: str | None = None
32
+
33
+
34
+ async def probe_local(
35
+ host: str,
36
+ *,
37
+ session: aiohttp.ClientSession | None = None,
38
+ timeout: float = 4.0, # noqa: ASYNC109 - part of the public contract
39
+ ) -> LocalInfo | None:
40
+ """Return what the Echo at ``host`` says about itself.
41
+
42
+ Returns None when the host is unreachable, does not speak Spotify Connect
43
+ or is not an Amazon device.
44
+ """
45
+ own_session = session is None
46
+ session = session or aiohttp.ClientSession()
47
+ try:
48
+ async with session.get(
49
+ f"http://{host}:{_SPOTIFY_PORT}/spotifyConnect",
50
+ params={"action": "getInfo"},
51
+ timeout=aiohttp.ClientTimeout(total=timeout),
52
+ ) as resp:
53
+ if resp.status != 200:
54
+ return None
55
+ data = await resp.json(content_type=None)
56
+ except TimeoutError, aiohttp.ClientError, ValueError:
57
+ return None
58
+ finally:
59
+ if own_session:
60
+ await session.close()
61
+ if not isinstance(data, dict) or data.get("brandDisplayName") != "Amazon":
62
+ return None
63
+ aliases = [a for a in data.get("aliases") or [] if isinstance(a, dict)]
64
+ own = [a.get("name") for a in aliases if a.get("isGroup") != "true"]
65
+ return LocalInfo(
66
+ host=host,
67
+ name=data.get("remoteName") or next(iter(own), None),
68
+ model=data.get("modelDisplayName") or None,
69
+ brand=data.get("brandDisplayName"),
70
+ device_id=data.get("deviceID") or None,
71
+ spotify_user=data.get("activeUser") or None,
72
+ groups=tuple(
73
+ a["name"] for a in aliases if a.get("isGroup") == "true" and a.get("name")
74
+ ),
75
+ library_version=data.get("libraryVersion") or None,
76
+ )
77
+
78
+
79
+ async def is_reachable(
80
+ host: str,
81
+ *,
82
+ port: int = 55442,
83
+ timeout: float = 2.0, # noqa: ASYNC109 - part of the public contract
84
+ ) -> bool:
85
+ """Return True when ``host`` accepts a TCP connection on ``port``."""
86
+ try:
87
+ async with asyncio.timeout(timeout):
88
+ _, writer = await asyncio.open_connection(host, port)
89
+ except TimeoutError, OSError:
90
+ return False
91
+ writer.close()
92
+ with contextlib.suppress(OSError):
93
+ await writer.wait_closed()
94
+ return True
amazon_echo/models.py ADDED
@@ -0,0 +1,165 @@
1
+ """Data models returned by the client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime, timedelta
7
+ from typing import Any
8
+
9
+
10
+ @dataclass(slots=True, kw_only=True)
11
+ class Account:
12
+ """The Amazon account behind the session."""
13
+
14
+ customer_id: str
15
+ name: str | None = None
16
+ email: str | None = None
17
+ country: str | None = None
18
+ marketplace_id: str | None = None
19
+
20
+
21
+ @dataclass(slots=True, kw_only=True)
22
+ class Device:
23
+ """An Alexa-enabled device, app or speaker group."""
24
+
25
+ serial: str
26
+ device_type: str
27
+ name: str
28
+ family: str
29
+ model: str | None = None
30
+ software_version: str | None = None
31
+ account_id: str | None = None
32
+ online: bool = False
33
+ capabilities: frozenset[str] = frozenset()
34
+ cluster_members: tuple[str, ...] = ()
35
+ parent_clusters: tuple[str, ...] = ()
36
+ mac: str | None = None
37
+ endpoint_id: str | None = None
38
+ battery_level: int | None = None
39
+ charging: bool | None = None
40
+
41
+ @property
42
+ def is_group(self) -> bool:
43
+ """Return True for a multi-room speaker group."""
44
+ return self.family == "WHA"
45
+
46
+ @property
47
+ def is_app(self) -> bool:
48
+ """Return True for an Alexa app instance (phone, browser)."""
49
+ return self.family == "VOX"
50
+
51
+ @property
52
+ def key(self) -> str:
53
+ """Return the stable identifier of the device."""
54
+ return self.serial
55
+
56
+ def supports(self, capability: str) -> bool:
57
+ """Return True when the device advertises ``capability``."""
58
+ return capability in self.capabilities
59
+
60
+
61
+ @dataclass(slots=True, kw_only=True)
62
+ class Notification:
63
+ """An alarm, timer, reminder or music alarm."""
64
+
65
+ id: str
66
+ kind: str
67
+ status: str
68
+ device_serial: str
69
+ device_type: str
70
+ label: str | None = None
71
+ when: datetime | None = None
72
+ remaining: timedelta | None = None
73
+ recurrence: str | None = None
74
+ sound: str | None = None
75
+ raw: dict[str, Any] = field(default_factory=dict)
76
+
77
+ @property
78
+ def is_active(self) -> bool:
79
+ """Return True when the notification is armed."""
80
+ return self.status == "ON"
81
+
82
+
83
+ @dataclass(slots=True, kw_only=True)
84
+ class BluetoothDevice:
85
+ """A Bluetooth device paired with an Echo."""
86
+
87
+ address: str
88
+ name: str | None = None
89
+ connected: bool = False
90
+ profiles: tuple[str, ...] = ()
91
+
92
+
93
+ @dataclass(slots=True, kw_only=True)
94
+ class MediaState:
95
+ """What a device is playing."""
96
+
97
+ state: str = "idle"
98
+ title: str | None = None
99
+ artist: str | None = None
100
+ album: str | None = None
101
+ image_url: str | None = None
102
+ duration: float | None = None
103
+ position: float | None = None
104
+ position_updated_at: datetime | None = None
105
+ provider: str | None = None
106
+ shuffle: bool | None = None
107
+ repeat: bool | None = None
108
+ can_next: bool = False
109
+ can_previous: bool = False
110
+ can_seek: bool = False
111
+ muted: bool = False
112
+ volume: int | None = None
113
+
114
+
115
+ @dataclass(slots=True, kw_only=True)
116
+ class Routine:
117
+ """An Alexa routine (automation)."""
118
+
119
+ id: str
120
+ name: str
121
+ enabled: bool = True
122
+ raw: dict[str, Any] = field(default_factory=dict)
123
+
124
+
125
+ @dataclass(slots=True, kw_only=True)
126
+ class EchoList:
127
+ """A shopping, to-do or custom list."""
128
+
129
+ id: str
130
+ name: str
131
+ kind: str
132
+
133
+
134
+ @dataclass(slots=True, kw_only=True)
135
+ class ListItem:
136
+ """An item of a list."""
137
+
138
+ id: str
139
+ name: str
140
+ completed: bool = False
141
+ version: int = 1
142
+
143
+
144
+ @dataclass(slots=True, kw_only=True)
145
+ class VoiceRecord:
146
+ """One voice interaction from the history."""
147
+
148
+ id: str
149
+ timestamp: datetime
150
+ device_serial: str | None = None
151
+ utterance: str | None = None
152
+ response: str | None = None
153
+ intent: str | None = None
154
+ person: str | None = None
155
+
156
+
157
+ @dataclass(slots=True, kw_only=True)
158
+ class AuxPort:
159
+ """A line in/out port of an Echo."""
160
+
161
+ id: str
162
+ direction: str
163
+ plugged: bool = False
164
+ enabled: bool = False
165
+ active: bool = False