aiopytedapi 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.
- aiopytedapi/__init__.py +71 -0
- aiopytedapi/_proto/__init__.py +1 -0
- aiopytedapi/_proto/tedapi.proto +641 -0
- aiopytedapi/_proto/tedapi_pb2.py +186 -0
- aiopytedapi/_proto/tedapi_pb2.pyi +857 -0
- aiopytedapi/_version.py +24 -0
- aiopytedapi/client.py +364 -0
- aiopytedapi/exceptions.py +76 -0
- aiopytedapi/keys.py +142 -0
- aiopytedapi/models.py +404 -0
- aiopytedapi/py.typed +0 -0
- aiopytedapi/transport.py +351 -0
- aiopytedapi-0.1.0.dist-info/METADATA +139 -0
- aiopytedapi-0.1.0.dist-info/RECORD +17 -0
- aiopytedapi-0.1.0.dist-info/WHEEL +4 -0
- aiopytedapi-0.1.0.dist-info/licenses/LICENSE +21 -0
- aiopytedapi-0.1.0.dist-info/licenses/NOTICE +32 -0
aiopytedapi/transport.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
"""Transports: how a request envelope reaches the gateway.
|
|
2
|
+
|
|
3
|
+
* :class:`SignedTransport` (``/tedapi/v1r``) wraps each envelope in a
|
|
4
|
+
RoutableMessage signed with the client's registered RSA key. It works on the
|
|
5
|
+
gateway's home-network address and on its Wi-Fi address (192.168.91.1), and
|
|
6
|
+
is the only transport that can send commands that change settings.
|
|
7
|
+
* :class:`WifiTransport` (``/tedapi/v1``) uses the Gateway Wi-Fi password
|
|
8
|
+
over HTTP Basic auth. It works only on the gateway's own Wi-Fi network and
|
|
9
|
+
can only read.
|
|
10
|
+
|
|
11
|
+
Both take an :class:`aiohttp.ClientSession` from the caller and never close
|
|
12
|
+
it. Each transport sends one request at a time: the gateway copes badly with
|
|
13
|
+
several at once.
|
|
14
|
+
|
|
15
|
+
The gateway's HTTPS certificate is self-signed, so it is not verified. That is
|
|
16
|
+
only done for the gateway's address, never for another host.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import asyncio
|
|
22
|
+
import base64
|
|
23
|
+
import gzip
|
|
24
|
+
import json
|
|
25
|
+
import logging
|
|
26
|
+
import math
|
|
27
|
+
import struct
|
|
28
|
+
import time
|
|
29
|
+
import uuid
|
|
30
|
+
from abc import ABC, abstractmethod
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
import aiohttp
|
|
34
|
+
from google.protobuf.message import DecodeError
|
|
35
|
+
|
|
36
|
+
from ._proto import tedapi_pb2 as pb
|
|
37
|
+
from .exceptions import (
|
|
38
|
+
GatewayAuthError,
|
|
39
|
+
GatewayBusyError,
|
|
40
|
+
GatewayConnectionError,
|
|
41
|
+
KeyNotAuthorizedError,
|
|
42
|
+
KeyPendingVerificationError,
|
|
43
|
+
MessageFaultError,
|
|
44
|
+
UnexpectedResponseError,
|
|
45
|
+
)
|
|
46
|
+
from .keys import RsaKey
|
|
47
|
+
|
|
48
|
+
_LOGGER = logging.getLogger(__name__)
|
|
49
|
+
|
|
50
|
+
DEFAULT_TIMEOUT = 10.0
|
|
51
|
+
WIFI_HOST = "192.168.91.1"
|
|
52
|
+
# How long a signature stays valid after signing (seconds).
|
|
53
|
+
SIGNATURE_LIFETIME = 12
|
|
54
|
+
_BUSY = (429, 503)
|
|
55
|
+
_DENIED = (401, 403)
|
|
56
|
+
_KEY_FAULTS = (pb.MESSAGEFAULT_ERROR_UNKNOWN_KEY_ID, pb.MESSAGEFAULT_ERROR_INACTIVE_KEY)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def decompress(content: bytes) -> bytes:
|
|
60
|
+
"""Gunzip a response when it is gzip compressed (firmware 25.42.2 and
|
|
61
|
+
later compress some answers); anything else is returned unchanged."""
|
|
62
|
+
if content[:2] == b"\x1f\x8b":
|
|
63
|
+
try:
|
|
64
|
+
return gzip.decompress(content)
|
|
65
|
+
except (OSError, EOFError):
|
|
66
|
+
return content
|
|
67
|
+
return content
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def signature_payload(din: str, expires_at: int, message: bytes) -> bytes:
|
|
71
|
+
"""The bytes the RSA signature covers: a tag-length-value header
|
|
72
|
+
(signature type RSA, domain ENERGY_DEVICE, the DIN, the expiry), the end
|
|
73
|
+
tag, then the signed message."""
|
|
74
|
+
|
|
75
|
+
def tlv(tag: int, value: bytes) -> bytes:
|
|
76
|
+
return bytes([tag, len(value)]) + value
|
|
77
|
+
|
|
78
|
+
return b"".join(
|
|
79
|
+
[
|
|
80
|
+
tlv(pb.TAG_SIGNATURE_TYPE, bytes([pb.SIGNATURE_TYPE_RSA])),
|
|
81
|
+
tlv(pb.TAG_DOMAIN, bytes([pb.DOMAIN_ENERGY_DEVICE])),
|
|
82
|
+
tlv(pb.TAG_PERSONALIZATION, din.encode()),
|
|
83
|
+
tlv(pb.TAG_EXPIRES_AT, struct.pack(">I", expires_at)),
|
|
84
|
+
bytes([pb.TAG_END]),
|
|
85
|
+
message,
|
|
86
|
+
]
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Transport(ABC):
|
|
91
|
+
"""Sends a request :class:`MessageEnvelope` and returns the gateway's
|
|
92
|
+
answer envelope."""
|
|
93
|
+
|
|
94
|
+
#: True when the transport can send signed commands (settings changes).
|
|
95
|
+
signed: bool = False
|
|
96
|
+
|
|
97
|
+
def __init__(self, session: aiohttp.ClientSession, host: str, timeout: float) -> None:
|
|
98
|
+
self._session = session
|
|
99
|
+
self.host = host
|
|
100
|
+
self._timeout = aiohttp.ClientTimeout(total=timeout)
|
|
101
|
+
self._lock = asyncio.Lock()
|
|
102
|
+
self._cookies: dict[str, str] = {}
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def public_key_der(self) -> bytes | None:
|
|
106
|
+
"""PKCS#1 DER of the key this transport signs with, if it signs."""
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
@abstractmethod
|
|
110
|
+
async def get_din(self) -> str:
|
|
111
|
+
"""The gateway's DIN (Device Identification Number)."""
|
|
112
|
+
|
|
113
|
+
@abstractmethod
|
|
114
|
+
async def send(self, envelope: pb.MessageEnvelope, din: str) -> pb.MessageEnvelope:
|
|
115
|
+
"""Send ``envelope`` to the gateway ``din`` and return its answer."""
|
|
116
|
+
|
|
117
|
+
async def _request(self, method: str, path: str, **kwargs: Any) -> tuple[int, bytes]:
|
|
118
|
+
"""One HTTPS request to the gateway: (status, body). Connection
|
|
119
|
+
errors and timeouts become GatewayConnectionError; rate limiting
|
|
120
|
+
becomes GatewayBusyError. Cookies the gateway sets are kept on the
|
|
121
|
+
transport and sent back (a shared session's cookie jar ignores cookies
|
|
122
|
+
from an IP address)."""
|
|
123
|
+
url = f"https://{self.host}{path}"
|
|
124
|
+
if self._cookies:
|
|
125
|
+
headers = dict(kwargs.pop("headers", None) or {})
|
|
126
|
+
headers["Cookie"] = "; ".join(f"{k}={v}" for k, v in self._cookies.items())
|
|
127
|
+
kwargs["headers"] = headers
|
|
128
|
+
try:
|
|
129
|
+
async with self._session.request(method, url, ssl=False, timeout=self._timeout, **kwargs) as resp:
|
|
130
|
+
body = await resp.read()
|
|
131
|
+
status = resp.status
|
|
132
|
+
for name, morsel in resp.cookies.items():
|
|
133
|
+
self._cookies[name] = morsel.value
|
|
134
|
+
except asyncio.TimeoutError as err:
|
|
135
|
+
raise GatewayConnectionError(f"no answer from the gateway within {self._timeout.total} s") from err
|
|
136
|
+
except aiohttp.ClientError as err:
|
|
137
|
+
raise GatewayConnectionError(f"could not reach the gateway: {type(err).__name__}") from err
|
|
138
|
+
if status in _BUSY:
|
|
139
|
+
raise GatewayBusyError(f"the gateway is rate limiting requests (HTTP {status})")
|
|
140
|
+
return status, body
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class SignedTransport(Transport):
|
|
144
|
+
"""The signed connection: RSA-signed requests to ``/tedapi/v1r``.
|
|
145
|
+
|
|
146
|
+
``password`` is the customer login password, used to log in for the DIN
|
|
147
|
+
and when the gateway asks for a fresh session (HTTP 401/403). Pass
|
|
148
|
+
``din`` to skip the DIN lookup.
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
signed = True
|
|
152
|
+
|
|
153
|
+
def __init__(
|
|
154
|
+
self,
|
|
155
|
+
session: aiohttp.ClientSession,
|
|
156
|
+
host: str,
|
|
157
|
+
key: RsaKey,
|
|
158
|
+
*,
|
|
159
|
+
password: str | None = None,
|
|
160
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
161
|
+
) -> None:
|
|
162
|
+
super().__init__(session, host, timeout)
|
|
163
|
+
self.key = key
|
|
164
|
+
self._password = password
|
|
165
|
+
self._token: str | None = None
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def public_key_der(self) -> bytes:
|
|
169
|
+
return self.key.public_key_der
|
|
170
|
+
|
|
171
|
+
async def _login(self) -> None:
|
|
172
|
+
"""Customer login (``/api/login/Basic``) for a session token."""
|
|
173
|
+
if not self._password:
|
|
174
|
+
raise GatewayAuthError("the gateway asked for a login and no password was given")
|
|
175
|
+
status, body = await self._request(
|
|
176
|
+
"POST",
|
|
177
|
+
"/api/login/Basic",
|
|
178
|
+
json={
|
|
179
|
+
"username": "customer",
|
|
180
|
+
"password": self._password,
|
|
181
|
+
"email": "customer@customer.domain",
|
|
182
|
+
"clientInfo": {"timezone": "UTC"},
|
|
183
|
+
},
|
|
184
|
+
)
|
|
185
|
+
if status in _DENIED:
|
|
186
|
+
raise GatewayAuthError("the gateway refused the password")
|
|
187
|
+
if status != 200:
|
|
188
|
+
raise UnexpectedResponseError(f"login failed (HTTP {status})")
|
|
189
|
+
try:
|
|
190
|
+
token = json.loads(body).get("token")
|
|
191
|
+
except (ValueError, AttributeError) as err:
|
|
192
|
+
raise UnexpectedResponseError("the login answer could not be decoded") from err
|
|
193
|
+
if not isinstance(token, str) or not token:
|
|
194
|
+
raise UnexpectedResponseError("the login answer has no token")
|
|
195
|
+
self._token = token
|
|
196
|
+
|
|
197
|
+
def _auth_headers(self) -> dict[str, str]:
|
|
198
|
+
return {"Authorization": f"Bearer {self._token}"} if self._token else {}
|
|
199
|
+
|
|
200
|
+
async def get_din(self) -> str:
|
|
201
|
+
async with self._lock:
|
|
202
|
+
if self._token is None and self._password:
|
|
203
|
+
await self._login()
|
|
204
|
+
status, body = await self._request("GET", "/tedapi/din", headers=self._auth_headers())
|
|
205
|
+
if status in _DENIED and self._password:
|
|
206
|
+
await self._login()
|
|
207
|
+
status, body = await self._request("GET", "/tedapi/din", headers=self._auth_headers())
|
|
208
|
+
if status in _DENIED:
|
|
209
|
+
raise GatewayAuthError("the gateway refused the DIN request")
|
|
210
|
+
if status != 200:
|
|
211
|
+
raise UnexpectedResponseError(f"DIN request failed (HTTP {status})")
|
|
212
|
+
try:
|
|
213
|
+
din = decompress(body).decode().strip()
|
|
214
|
+
except UnicodeDecodeError as err:
|
|
215
|
+
raise UnexpectedResponseError("the DIN could not be decoded") from err
|
|
216
|
+
if not din:
|
|
217
|
+
raise UnexpectedResponseError("the gateway returned an empty DIN")
|
|
218
|
+
return din
|
|
219
|
+
|
|
220
|
+
def _signed_request(self, envelope_bytes: bytes, din: str) -> bytes:
|
|
221
|
+
"""The RoutableMessage for ``envelope_bytes``: a fresh uuid and a
|
|
222
|
+
signature that expires SIGNATURE_LIFETIME seconds from now."""
|
|
223
|
+
routable = pb.RoutableMessage()
|
|
224
|
+
routable.to_destination.domain = pb.DOMAIN_ENERGY_DEVICE
|
|
225
|
+
routable.protobuf_message_as_bytes = envelope_bytes
|
|
226
|
+
routable.uuid = str(uuid.uuid4()).encode()
|
|
227
|
+
expires_at = math.ceil(time.time()) + SIGNATURE_LIFETIME
|
|
228
|
+
signature = self.key.sign(signature_payload(din, expires_at, envelope_bytes))
|
|
229
|
+
routable.signature_data.signer_identity.public_key = self.key.public_key_der
|
|
230
|
+
routable.signature_data.rsa_data.expires_at = expires_at
|
|
231
|
+
routable.signature_data.rsa_data.signature = signature
|
|
232
|
+
return routable.SerializeToString()
|
|
233
|
+
|
|
234
|
+
async def _post(self, envelope_bytes: bytes, din: str) -> tuple[int, bytes]:
|
|
235
|
+
return await self._request(
|
|
236
|
+
"POST",
|
|
237
|
+
"/tedapi/v1r",
|
|
238
|
+
data=self._signed_request(envelope_bytes, din),
|
|
239
|
+
headers={"Content-Type": "application/octet-stream"},
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
async def send(self, envelope: pb.MessageEnvelope, din: str) -> pb.MessageEnvelope:
|
|
243
|
+
envelope_bytes = envelope.SerializeToString()
|
|
244
|
+
async with self._lock:
|
|
245
|
+
status, body = await self._post(envelope_bytes, din)
|
|
246
|
+
if status in _DENIED and self._password:
|
|
247
|
+
# The session expired: log in again and re-sign (the first
|
|
248
|
+
# signature may have expired meanwhile).
|
|
249
|
+
await self._login()
|
|
250
|
+
status, body = await self._post(envelope_bytes, din)
|
|
251
|
+
if status in _DENIED:
|
|
252
|
+
raise GatewayAuthError(f"the gateway refused the signed request (HTTP {status})")
|
|
253
|
+
if status != 200:
|
|
254
|
+
raise UnexpectedResponseError(f"signed request failed (HTTP {status})")
|
|
255
|
+
return self._parse(body)
|
|
256
|
+
|
|
257
|
+
def _parse(self, body: bytes) -> pb.MessageEnvelope:
|
|
258
|
+
routable = pb.RoutableMessage()
|
|
259
|
+
try:
|
|
260
|
+
routable.ParseFromString(body)
|
|
261
|
+
except DecodeError as err:
|
|
262
|
+
raise UnexpectedResponseError("the signed answer could not be decoded") from err
|
|
263
|
+
fault = routable.signed_message_status.message_fault
|
|
264
|
+
if fault in _KEY_FAULTS:
|
|
265
|
+
raise KeyNotAuthorizedError(
|
|
266
|
+
f"the gateway does not accept this key ({pb.MessageFault_E.Name(fault)})", self.key.fingerprint
|
|
267
|
+
)
|
|
268
|
+
if fault != pb.MESSAGEFAULT_ERROR_NONE:
|
|
269
|
+
try:
|
|
270
|
+
name = pb.MessageFault_E.Name(fault)
|
|
271
|
+
except ValueError:
|
|
272
|
+
name = f"UNKNOWN ({fault})"
|
|
273
|
+
raise MessageFaultError(name)
|
|
274
|
+
inner = routable.protobuf_message_as_bytes
|
|
275
|
+
if b"authorization not verified" in body.lower():
|
|
276
|
+
raise KeyPendingVerificationError(
|
|
277
|
+
"the key is registered but not verified yet: toggle the Powerwall's On/Off switch", self.key.fingerprint
|
|
278
|
+
)
|
|
279
|
+
if not inner:
|
|
280
|
+
raise KeyNotAuthorizedError("the gateway answered with no data (key not accepted?)", self.key.fingerprint)
|
|
281
|
+
envelope = pb.MessageEnvelope()
|
|
282
|
+
try:
|
|
283
|
+
envelope.ParseFromString(inner)
|
|
284
|
+
except DecodeError as err:
|
|
285
|
+
raise UnexpectedResponseError("the gateway's answer could not be decoded") from err
|
|
286
|
+
return envelope
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
class WifiTransport(Transport):
|
|
290
|
+
"""The Gateway Wi-Fi connection: ``/tedapi/v1`` with the Wi-Fi password
|
|
291
|
+
(HTTP Basic auth), reachable only on the gateway's own Wi-Fi network.
|
|
292
|
+
Read-only: it can't send signed commands."""
|
|
293
|
+
|
|
294
|
+
def __init__(
|
|
295
|
+
self, session: aiohttp.ClientSession, password: str, *, host: str = WIFI_HOST, timeout: float = DEFAULT_TIMEOUT
|
|
296
|
+
) -> None:
|
|
297
|
+
super().__init__(session, host, timeout)
|
|
298
|
+
if not password:
|
|
299
|
+
raise ValueError("the Wi-Fi connection needs the gateway Wi-Fi password")
|
|
300
|
+
credentials = base64.b64encode(f"Tesla_Energy_Device:{password}".encode()).decode()
|
|
301
|
+
self._auth_header = {"Authorization": f"Basic {credentials}"}
|
|
302
|
+
|
|
303
|
+
async def get_din(self) -> str:
|
|
304
|
+
async with self._lock:
|
|
305
|
+
status, body = await self._request("GET", "/tedapi/din", headers=dict(self._auth_header))
|
|
306
|
+
if status in _DENIED:
|
|
307
|
+
raise GatewayAuthError("the gateway refused the Wi-Fi password")
|
|
308
|
+
if status != 200:
|
|
309
|
+
raise UnexpectedResponseError(f"DIN request failed (HTTP {status})")
|
|
310
|
+
try:
|
|
311
|
+
din = decompress(body).decode().strip()
|
|
312
|
+
except UnicodeDecodeError as err:
|
|
313
|
+
raise UnexpectedResponseError("the DIN could not be decoded") from err
|
|
314
|
+
if not din:
|
|
315
|
+
raise UnexpectedResponseError("the gateway returned an empty DIN")
|
|
316
|
+
return din
|
|
317
|
+
|
|
318
|
+
async def send(self, envelope: pb.MessageEnvelope, din: str) -> pb.MessageEnvelope:
|
|
319
|
+
message = pb.Message()
|
|
320
|
+
message.message.CopyFrom(envelope)
|
|
321
|
+
message.tail.value = 1
|
|
322
|
+
async with self._lock:
|
|
323
|
+
status, body = await self._request(
|
|
324
|
+
"POST",
|
|
325
|
+
"/tedapi/v1",
|
|
326
|
+
data=message.SerializeToString(),
|
|
327
|
+
headers={"Content-Type": "application/octet-stream", **self._auth_header},
|
|
328
|
+
)
|
|
329
|
+
if status in _DENIED:
|
|
330
|
+
raise GatewayAuthError("the gateway refused the Wi-Fi password")
|
|
331
|
+
if status != 200:
|
|
332
|
+
raise UnexpectedResponseError(f"request failed (HTTP {status})")
|
|
333
|
+
answer = pb.Message()
|
|
334
|
+
try:
|
|
335
|
+
answer.ParseFromString(decompress(body))
|
|
336
|
+
except DecodeError as err:
|
|
337
|
+
raise UnexpectedResponseError("the gateway's answer could not be decoded") from err
|
|
338
|
+
if not answer.HasField("message"):
|
|
339
|
+
raise UnexpectedResponseError("the gateway's answer has no message")
|
|
340
|
+
return answer.message
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
__all__ = [
|
|
344
|
+
"DEFAULT_TIMEOUT",
|
|
345
|
+
"WIFI_HOST",
|
|
346
|
+
"SignedTransport",
|
|
347
|
+
"Transport",
|
|
348
|
+
"WifiTransport",
|
|
349
|
+
"decompress",
|
|
350
|
+
"signature_payload",
|
|
351
|
+
]
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: aiopytedapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async client for the Tesla Powerwall gateway's local TEDAPI
|
|
5
|
+
Project-URL: Homepage, https://github.com/cnapagoda/aiopytedapi
|
|
6
|
+
Project-URL: Issues, https://github.com/cnapagoda/aiopytedapi/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/cnapagoda/aiopytedapi/blob/main/CHANGELOG.md
|
|
8
|
+
Author-email: Chandana Napagoda <cnapagoda@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: NOTICE
|
|
12
|
+
Keywords: asyncio,home-assistant,powerwall,tedapi,tesla
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Topic :: Home Automation
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Requires-Python: >=3.9
|
|
28
|
+
Requires-Dist: aiohttp>=3.9
|
|
29
|
+
Requires-Dist: cryptography>=42
|
|
30
|
+
Requires-Dist: protobuf>=4.25.1
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# aiopytedapi
|
|
34
|
+
|
|
35
|
+
An async Python client for the Tesla Powerwall gateway's local TEDAPI.
|
|
36
|
+
|
|
37
|
+
- **Async only**, built on [aiohttp](https://docs.aiohttp.org/). You pass in the `ClientSession`, so it fits Home Assistant and other asyncio apps.
|
|
38
|
+
- **Typed** (`py.typed`, checked with `mypy --strict`).
|
|
39
|
+
- **Local**: talks to the gateway on your network. Nothing goes to Tesla's servers.
|
|
40
|
+
- **Errors are exceptions**, never `None`: every one derives from `TedapiError`.
|
|
41
|
+
|
|
42
|
+
> **Status: alpha (0.x).** The API may change between minor versions. Pin `aiopytedapi>=0.1,<0.2`.
|
|
43
|
+
|
|
44
|
+
## Connections
|
|
45
|
+
|
|
46
|
+
| Connection | Endpoint | Authenticates with | Can change settings |
|
|
47
|
+
|---|---|---|---|
|
|
48
|
+
| **Signed** | `/tedapi/v1r` on the gateway's home-network address or its Wi-Fi address (192.168.91.1) | An RSA key registered with the gateway | Yes |
|
|
49
|
+
| **Gateway Wi-Fi** | `/tedapi/v1` on 192.168.91.1 | The Wi-Fi password printed on the gateway | No (read-only) |
|
|
50
|
+
|
|
51
|
+
Registering a key needs Tesla's cloud once (for example `python -m pypowerwall register`). This library doesn't do that step.
|
|
52
|
+
|
|
53
|
+
## Features
|
|
54
|
+
|
|
55
|
+
| Feature | Methods | Signed | Gateway Wi-Fi |
|
|
56
|
+
|---|---|---|---|
|
|
57
|
+
| Network status (Wi-Fi, Ethernet, cellular) | `get_network_status()` | ✅ Powerwall 3 | ✅ Powerwall 3 and 2 |
|
|
58
|
+
| Site import/export limits | `get_site_limits()`, `set_import_limit()`, `set_export_limit()` | ✅ read and write | ✅ read |
|
|
59
|
+
| Battery calibration delay | `get_battery_calibration_delay_status()`, `delay_battery_calibration()` | ✅ | — |
|
|
60
|
+
| Registered keys | `get_authorized_clients()`, `add_authorized_client()`, `remove_authorized_client()` | ✅ list, add, remove | ✅ list |
|
|
61
|
+
| Gateway configuration | `get_config()` | ✅ | ✅ |
|
|
62
|
+
|
|
63
|
+
What has been seen on hardware so far:
|
|
64
|
+
|
|
65
|
+
- **Network status:** Powerwall 3 (firmware 26.34.3) on both connections; Powerwall 2 (26.42.0) on Gateway Wi-Fi only. Over the signed connection a Powerwall 2 answers `MessageFaultError` (`MESSAGEFAULT_ERROR_TIMEOUT`).
|
|
66
|
+
- **Registered keys:** listing, adding and removing on a Powerwall 3 (26.34.3).
|
|
67
|
+
- **Site limits:** reading on a Powerwall 3 (26.34.3). Writing has not been tried on hardware.
|
|
68
|
+
- **Calibration delay:** a Powerwall 3 on 26.34.3 answers `NotSupportedError` (the firmware doesn't implement it). The delay command has not been sent to hardware.
|
|
69
|
+
|
|
70
|
+
## Example
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import asyncio
|
|
74
|
+
from pathlib import Path
|
|
75
|
+
|
|
76
|
+
import aiohttp
|
|
77
|
+
|
|
78
|
+
from aiopytedapi import RsaKey, TedapiClient
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def main() -> None:
|
|
82
|
+
key = RsaKey.from_pem(Path("tedapi_rsa_private.pem").read_bytes())
|
|
83
|
+
async with aiohttp.ClientSession() as session:
|
|
84
|
+
client = TedapiClient.signed(session, "192.168.1.50", key, password="ABCDE")
|
|
85
|
+
await client.connect()
|
|
86
|
+
|
|
87
|
+
status = await client.get_network_status()
|
|
88
|
+
print(status.active, status.to_dict())
|
|
89
|
+
|
|
90
|
+
limits = await client.get_site_limits()
|
|
91
|
+
print(limits.import_limit_kw, limits.export_limit_kw)
|
|
92
|
+
|
|
93
|
+
for c in (await client.get_authorized_clients()).clients:
|
|
94
|
+
print(c.fingerprint[:16], c.type, c.state)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
asyncio.run(main())
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`password` is the customer login password (the last 5 characters of the Gateway Wi-Fi password on most gateways). It's used to fetch the DIN. Pass `din=` instead if you already know it.
|
|
101
|
+
|
|
102
|
+
For the Gateway Wi-Fi connection:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
client = TedapiClient.wifi(session, "WIFI_PASSWORD")
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Safety
|
|
109
|
+
|
|
110
|
+
Some commands change how your Powerwall and your site behave.
|
|
111
|
+
|
|
112
|
+
- **Site limits:** an installer may have set the import or export limit to meet your grid connection agreement (for example a network export limit). Don't raise or remove one unless you're allowed to.
|
|
113
|
+
- **Calibration delay:** the gateway allows a limited number of delays, and each may use one.
|
|
114
|
+
- **Removing a key** stops that client sending commands. Removing the key you sign with is refused unless you pass `allow_current_key=True`.
|
|
115
|
+
|
|
116
|
+
Every command that changes something logs a WARNING. You use these commands at your own risk; check your warranty and your grid connection agreement first.
|
|
117
|
+
|
|
118
|
+
## Privacy
|
|
119
|
+
|
|
120
|
+
Models keep values that identify a home or a person (Wi-Fi SSID, MAC and IP addresses, key descriptions) out of `repr`, and `to_dict()` only includes them with `details=True`. The gateway's Wi-Fi password is never parsed. `get_config()` returns the gateway's full configuration, which includes identifiers: don't log or publish it.
|
|
121
|
+
|
|
122
|
+
## Credits
|
|
123
|
+
|
|
124
|
+
The wire schema and the request formats come from [pypowerwall](https://github.com/jasonacox/pypowerwall) (MIT), which in turn credits Matthew1471's Tesla-API, Nexarian's TEDAPI work and [Teslemetry/tesla-protocol](https://github.com/Teslemetry/tesla-protocol). See [NOTICE](NOTICE).
|
|
125
|
+
|
|
126
|
+
This project is not affiliated with or endorsed by Tesla.
|
|
127
|
+
|
|
128
|
+
## Development
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
pip install -e . pytest pytest-asyncio pytest-cov mypy ruff types-protobuf
|
|
132
|
+
ruff check . && mypy && pytest --cov
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
The protobuf bindings are generated: change `src/aiopytedapi/_proto/tedapi.proto`, then run `bash tools/gen_proto.sh`. Never edit `tedapi_pb2.py` by hand.
|
|
136
|
+
|
|
137
|
+
## Licence
|
|
138
|
+
|
|
139
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
aiopytedapi/__init__.py,sha256=h8J57KzeUgaz5ey5eS6HKC9--Q2kg0y62_eTp5xFwIQ,1846
|
|
2
|
+
aiopytedapi/_version.py,sha256=n_5vdJsPNu7wZ57LGuRL585uvll-hiuvZUBWzdG0RQU,520
|
|
3
|
+
aiopytedapi/client.py,sha256=lpuF8v-DQoZUeXuO1zfWgtRMR7qSy4a7NrCNmEcCalA,17003
|
|
4
|
+
aiopytedapi/exceptions.py,sha256=k_WJUUtGKZmcWUdQCmUNwIhGaeL-ffH0KCU09vmyzQM,2632
|
|
5
|
+
aiopytedapi/keys.py,sha256=AMysuEJmE2GXVP6sF4T8_slBhtSDRzdrmHOZ7D28IZM,5605
|
|
6
|
+
aiopytedapi/models.py,sha256=nitaA0_XWJEY6a5YRZw1dveiH8-gU4R3nIrgBlX5anE,17044
|
|
7
|
+
aiopytedapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
aiopytedapi/transport.py,sha256=1F3QRqjPN28caouLU50K3CkKl9zenp5MPzXEEXMtjn0,14238
|
|
9
|
+
aiopytedapi/_proto/__init__.py,sha256=n10EoJN-NqDw5CGsfFJal7zSntphCRUuDZU_F61H91o,60
|
|
10
|
+
aiopytedapi/_proto/tedapi.proto,sha256=_eNJVoqEMJptQcDPbT86oLWXnOtDrEB_fwYhQOQ9wUA,21394
|
|
11
|
+
aiopytedapi/_proto/tedapi_pb2.py,sha256=_uT90WKjbkYt4Am-Y3ZVDjGJRiD-B_NYFZ6x1aEZkus,31656
|
|
12
|
+
aiopytedapi/_proto/tedapi_pb2.pyi,sha256=EP2HxRSE5r6hsQ-SX4rJOmjnFrjOZTUPqPIbnuyZMTk,47167
|
|
13
|
+
aiopytedapi-0.1.0.dist-info/METADATA,sha256=MAgtLgSfigs3LnioS2ARW7lbpcPQnc2pO0P0lUOWoYA,6353
|
|
14
|
+
aiopytedapi-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
15
|
+
aiopytedapi-0.1.0.dist-info/licenses/LICENSE,sha256=Blm-gflY-97GZxKj3sbMKc_xug7z9SlBOKgZvdJI4z4,1074
|
|
16
|
+
aiopytedapi-0.1.0.dist-info/licenses/NOTICE,sha256=0JWw0KrqzVkKqndlsXldigPynieJcYR4SgybgFLx5vA,1691
|
|
17
|
+
aiopytedapi-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chandana Napagoda
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
aiopytedapi includes material derived from pypowerwall
|
|
2
|
+
(https://github.com/jasonacox/pypowerwall), used under the MIT License:
|
|
3
|
+
|
|
4
|
+
MIT License
|
|
5
|
+
|
|
6
|
+
Copyright (c) 2021 Jason Cox
|
|
7
|
+
|
|
8
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
9
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
10
|
+
in the Software without restriction, including without limitation the rights
|
|
11
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
12
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
13
|
+
furnished to do so, subject to the following conditions:
|
|
14
|
+
|
|
15
|
+
The above copyright notice and this permission notice shall be included in all
|
|
16
|
+
copies or substantial portions of the Software.
|
|
17
|
+
|
|
18
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
19
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
20
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
21
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
22
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
23
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
24
|
+
SOFTWARE.
|
|
25
|
+
|
|
26
|
+
Derived material:
|
|
27
|
+
- src/aiopytedapi/_proto/tedapi.proto: the TEDAPI wire schema, from
|
|
28
|
+
pypowerwall's tedapi_combined.proto, which credits Matthew1471's Tesla-API
|
|
29
|
+
(signing protocol), Nexarian's TEDAPI protocol work and
|
|
30
|
+
Teslemetry/tesla-protocol (energy device schema).
|
|
31
|
+
- The signed (v1r) request format, and the network status, authorized clients,
|
|
32
|
+
battery calibration delay and site limit models, ported from pypowerwall.
|