Skip to content

Commit 83a584c

Browse files
authored
feat!: treat energy site ids as int, signal number support via X-Library (#49)
Tesla returns energy site ids as JSON numbers; this library previously forced them to strings throughout. site_id is now int end to end: get_energysite(str | int) normalises via int(...), energysites is keyed by int, and event matching casts the incoming site_id/id to int so it matches whether the api sends a string or a number. The api tells clients apart by the X-Library header: the legacy value "python teslemetry-stream" keeps getting strings, anything with a "/<version>" suffix (read from installed package metadata) opts into numbers. BREAKING CHANGE: TeslemetryStreamEnergySite.site_id is now int, not str. Consumers comparing it against a string will need to update.
1 parent 56da942 commit 83a584c

7 files changed

Lines changed: 78 additions & 16 deletions

File tree

‎AGENTS.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ Project-intrinsic knowledge that should travel with the code: build, test, relea
4343
- `site_info` does **not** carry `tariff_content`/`tariff_content_v2`. The V2 tariff is its own event/listener (`listen_TariffContentV2`), same envelope shape, with a `None` body meaning explicit server-side removal rather than "not received yet".
4444
- All of these share a silence-means-no-change contract: the server sends a connect-time snapshot and then fires only on change. Freshness lives in REST, never in event cadence.
4545
- There is deliberately no helper recombining `site_info` and `tariff_content_v2` - it would only ever cover V2 (legacy V1 `tariff_content` has no SSE topic and stays REST-only). A consumer wanting both tariffs uses the REST site_info endpoint.
46+
- Site ids are `int` throughout, matching Tesla's own JSON-number representation: `get_energysite(site_id: str | int)` normalises via `int(...)` (raising `ValueError` on a non-numeric id), `TeslemetryStream.energysites` is keyed by int, `TeslemetryStreamEnergySite.site_id` is an int, and every site-id/`Key.ID` comparison in `energysite.py` casts the incoming event value with `int(...)` before comparing - so an event carrying either a string or a number matches. The `X-Library` header's `/<version>` suffix (`stream.py`, read from installed package metadata) is the api's signal that this client accepts numeric ids; the bare legacy value means string-only.
4647

4748
## Test map
4849

@@ -58,8 +59,9 @@ Project-intrinsic knowledge that should travel with the code: build, test, relea
5859
| `str` payload coercion against real telemetry | `test_field_type_coercion.py` |
5960
| `topics` URL construction, empty/bare-string handling, tariff listener | `test_sse_topics.py` |
6061
| Native-event regression, source indistinguishability, no-dedup contract | `test_external_ingest.py` |
61-
| Energy event fixtures | `test_energysite_events.py` |
62+
| Energy event fixtures, int/str site-id matching | `test_energysite_events.py` |
6263
| Enum tables vs proto names | `test_enum_tables.py` |
64+
| `X-Library` header version suffix | `test_library_header.py` |
6365

6466
## Maintaining this file
6567

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ Initialize the TeslemetryStream client. `topics` is an optional exact SSE wire e
260260
Create a vehicle object to manage config and create listeners.
261261

262262
### `get_energysite(site_id: str | int) -> TeslemetryStreamEnergySite`
263-
Create an energy site object to create listeners for `live_status` and `site_info`.
263+
Create an energy site object to create listeners for `live_status` and `site_info`. Accepts a str or int; the returned object's `site_id` is always normalized to `int`.
264264

265265
### `connected -> bool`
266266
Return if connected.
@@ -346,7 +346,7 @@ A full list of fields and metadata can be found at [api.teslemetry.com/fields.js
346346

347347
## Public Methods in TeslemetryStreamEnergySite Class
348348

349-
### `__init__(stream: TeslemetryStream, site_id: str)`
349+
### `__init__(stream: TeslemetryStream, site_id: int)`
350350
Initialize the TeslemetryStreamEnergySite instance.
351351

352352
### `listen_LiveStatus(callback: Callable[[dict], None]) -> Callable[[],None]`

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ requires = ["setuptools>=77.0"]
44

55
[project]
66
name = "teslemetry_stream"
7-
version = "0.13.2"
7+
version = "1.0.0"
88
license = "Apache-2.0"
99
description = "Teslemetry Streaming API library for Python"
1010
readme = "README.md"

‎teslemetry_stream/energysite.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ class TeslemetryStreamEnergySite:
2222
here just filter and unwrap the matching topic.
2323
"""
2424

25-
def __init__(self, stream: TeslemetryStream, site_id: str):
25+
def __init__(self, stream: TeslemetryStream, site_id: int):
2626
self.stream = stream
27-
self.site_id = str(site_id)
27+
self.site_id = site_id
2828

2929
def listen_LiveStatus(
3030
self, callback: Callable[[dict[str, Any]], None]
@@ -37,7 +37,7 @@ def listen_LiveStatus(
3737
vehicle state.
3838
"""
3939
def _handler(x: dict[str, Any]) -> None:
40-
if str(x[Key.SITE_ID]) == self.site_id:
40+
if int(x[Key.SITE_ID]) == self.site_id:
4141
callback(x[Key.LIVE_STATUS])
4242

4343
return self.stream.async_add_listener(_handler, {Key.LIVE_STATUS: None})
@@ -56,7 +56,7 @@ def listen_SiteInfo(
5656
snapshot-then-live semantics as vehicle state.
5757
"""
5858
def _handler(x: dict[str, Any]) -> None:
59-
if str(x[Key.SITE_ID]) == self.site_id:
59+
if int(x[Key.SITE_ID]) == self.site_id:
6060
callback(x[Key.SITE_INFO])
6161

6262
return self.stream.async_add_listener(_handler, {Key.SITE_INFO: None})
@@ -72,7 +72,7 @@ def listen_TariffContentV2(
7272
silence means no change, never staleness, matching `listen_SiteInfo`.
7373
"""
7474
def _handler(x: dict[str, Any]) -> None:
75-
if str(x[Key.SITE_ID]) == self.site_id:
75+
if int(x[Key.SITE_ID]) == self.site_id:
7676
callback(x[Key.TARIFF_CONTENT_V2])
7777

7878
return self.stream.async_add_listener(_handler, {Key.TARIFF_CONTENT_V2: None})
@@ -89,7 +89,7 @@ def listen_EnergyTotals(
8989
staleness. This listener only exposes the totals.
9090
"""
9191
def _handler(x: dict[str, Any]) -> None:
92-
if str(x[Key.ID]) == self.site_id:
92+
if int(x[Key.ID]) == self.site_id:
9393
callback(EnergyHistoryTotals.from_dict(x[Key.TOTALS]))
9494

9595
return self.stream.async_add_listener(_handler, {Key.TOTALS: None})

‎teslemetry_stream/stream.py‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import logging
66
from collections.abc import Awaitable, Callable, Iterable
77
from datetime import datetime, timezone
8+
from importlib.metadata import version
89
from typing import Any, cast
910

1011
import aiohttp
@@ -16,6 +17,11 @@
1617

1718
LOGGER = logging.getLogger(__package__)
1819

20+
# The trailing "/<version>" is the api's signal that this client accepts
21+
# numeric energy-site ids; the bare legacy value "python teslemetry-stream"
22+
# (no slash) means string-only.
23+
_LIBRARY_HEADER = f"python teslemetry-stream/{version('teslemetry-stream')}"
24+
1925

2026
class TeslemetryStream:
2127
"""Teslemetry Stream Client"""
@@ -81,7 +87,7 @@ def __init__(
8187
self.manual = manual
8288
self.retries: int = 0
8389
self.vehicles: dict[str, TeslemetryStreamVehicle] = {}
84-
self.energysites: dict[str, TeslemetryStreamEnergySite] = {}
90+
self.energysites: dict[int, TeslemetryStreamEnergySite] = {}
8591
self.fields: dict[str, Any] = {}
8692

8793
if self.vin:
@@ -95,7 +101,7 @@ async def headers(self) -> dict[str, str]:
95101
access_token = self.access_token
96102
return {
97103
"Authorization": f"Bearer {access_token}",
98-
"X-Library": "python teslemetry-stream",
104+
"X-Library": _LIBRARY_HEADER,
99105
}
100106

101107
def get_vehicle(self, vin: str) -> TeslemetryStreamVehicle:
@@ -113,10 +119,12 @@ def get_energysite(self, site_id: str | int) -> TeslemetryStreamEnergySite:
113119
"""
114120
Create an energy site stream.
115121
116-
:param site_id: Numeric energy site ID.
117-
:return: TeslemetryStreamEnergySite instance.
122+
:param site_id: Numeric energy site ID, as a str or int.
123+
:return: TeslemetryStreamEnergySite instance. Its `site_id` is
124+
always an int, regardless of which type was passed in here.
125+
:raises ValueError: If site_id is not numeric.
118126
"""
119-
site_id = str(site_id)
127+
site_id = int(site_id)
120128
if site_id not in self.energysites:
121129
self.energysites[site_id] = TeslemetryStreamEnergySite(self, site_id)
122130
return self.energysites[site_id]

‎tests/test_library_header.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""The api tells string-only clients from numeric-capable ones solely by the
2+
`X-Library` header value: the legacy value `python teslemetry-stream` (no
3+
suffix) means string-only, anything with a `/<version>` suffix means this
4+
client accepts numeric energy-site ids. These tests pin that contract.
5+
"""
6+
from __future__ import annotations
7+
8+
import asyncio
9+
from importlib.metadata import version
10+
11+
from teslemetry_stream.stream import TeslemetryStream
12+
13+
14+
def make_stream() -> TeslemetryStream:
15+
return TeslemetryStream(session=None, access_token="test-token", manual=True) # type: ignore[arg-type]
16+
17+
18+
def check(label: str, ok: bool, detail: str = "") -> bool:
19+
print(f"{label:<64} {'PASS' if ok else 'FAIL'}{' ' + detail if detail else ''}")
20+
return ok
21+
22+
23+
def main() -> None:
24+
results = []
25+
26+
headers = asyncio.run(make_stream().headers())
27+
library_header = headers["X-Library"]
28+
installed_version = version("teslemetry-stream")
29+
30+
results.append(
31+
check(
32+
"X-Library carries the installed package version",
33+
library_header == f"python teslemetry-stream/{installed_version}",
34+
f"got {library_header!r}",
35+
)
36+
)
37+
results.append(
38+
check(
39+
"X-Library is not the bare legacy (string-only) value",
40+
library_header != "python teslemetry-stream",
41+
f"got {library_header!r}",
42+
)
43+
)
44+
45+
print("-" * 72)
46+
print("ALL PASS" if all(results) else "FAILURES PRESENT")
47+
if not all(results):
48+
raise SystemExit(1)
49+
50+
51+
if __name__ == "__main__":
52+
main()

‎uv.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)