Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/energy_local_control.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,14 @@ async def make_local_energysite(session: aiohttp.ClientSession) -> PowerwallEner
return PowerwallEnergySite(powerwall_client)
```

An early Tesla Backup Gateway 1 (Powerwall 2) rejects the last-5-characters
login `PowerwallClient` sends and needs the full gateway password. Build its
client with `PowerwallClient.legacy_gateway(...)`, which takes the same
arguments. `is_legacy_gateway(site_info)` tells you which one a site needs: pass
it the body of the cloud `site_info()` response (`response`), and it returns
True when a listed gateway, or the site DIN when none is listed, has the
Gateway 1 part number `1118431-`.

The example uses `192.168.91.1`, the gateway's own WiFi access point. When
your client connects over your own LAN instead, you can discover the
gateway's LAN IP over the cloud with
Expand Down
2 changes: 2 additions & 0 deletions tesla_fleet_api/tesla/powerwall/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
current_power,
islander_frequency,
islander_voltage,
is_legacy_gateway,
raw_to_scaled_reserve,
raw_to_scaled_soc,
scaled_to_raw_reserve,
Expand Down Expand Up @@ -150,6 +151,7 @@
"current_power",
"islander_frequency",
"islander_voltage",
"is_legacy_gateway",
"pv_power",
"pv_string_current",
"pv_string_state",
Expand Down
42 changes: 41 additions & 1 deletion tesla_fleet_api/tesla/powerwall/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
transport_pb2,
)

from ...exceptions import InvalidResponse
from ..island import island_mode_rejection
from . import queries
from .exceptions import (
Expand Down Expand Up @@ -132,6 +133,10 @@
_TEG_FIELD_SET_ISLAND_MODE_REQUEST: Final = 3
_TEG_FIELD_TRIGGER_ISLANDING_REQUEST: Final = 5

# Backup Gateway 1 part number prefix, as in a gateway's ``part_number`` and
# at the start of its DIN.
_GATEWAY_1_PART_NUMBER: Final = "1118431-"

def _lookup(data: Any, *keys: str) -> Any:
"""Walk a nested mapping; return None if any key is missing."""
for key in keys:
Expand Down Expand Up @@ -226,7 +231,9 @@ def legacy_gateway(

These units reject the last-5-characters login that the default
constructor sends, and need the full ``gateway_password`` instead.
Everything else is the same as the default constructor.
Everything else is the same as the default constructor. Use
:func:`is_legacy_gateway` on the site's cloud ``site_info`` to tell
which constructor a site needs.
"""
return cls(
host=host,
Expand Down Expand Up @@ -1758,6 +1765,38 @@ def text(key: str) -> str | None:
)


def is_legacy_gateway(site_info: Any) -> bool:
"""Return True when a site's gateway is a Backup Gateway 1.

``site_info`` is the body of the cloud ``site_info`` response (the
``"response"`` object). A Gateway 1 has part number ``1118431-``; it is
read from ``components.gateways[].part_number``, or from the site ``id``
(the gateway DIN, which starts with the part number) when no listed
gateway has a part number. A True result means the site needs
:meth:`PowerwallClient.legacy_gateway`, which logs in with the full
gateway password. Raises :class:`InvalidResponse` when ``site_info`` is
not a mapping or carries neither a gateway part number nor an ``id``.
"""
if not isinstance(site_info, Mapping):
raise InvalidResponse(repr(site_info))
body = cast(Mapping[str, Any], site_info)
gateways = _lookup(body, "components", "gateways")
part_numbers: list[str] = []
if isinstance(gateways, list):
for gateway in cast(list[Any], gateways):
part_number = _lookup(gateway, "part_number")
if isinstance(part_number, str):
part_numbers.append(part_number)
if not part_numbers:
site_id = body.get("id")
if not isinstance(site_id, str):
raise InvalidResponse("site_info has no gateway part number and no id")
part_numbers = [site_id]
return any(
part_number.startswith(_GATEWAY_1_PART_NUMBER) for part_number in part_numbers
)


def backup_time_remaining(status: StatusPayload) -> float | None:
"""Estimated backup runtime in hours at current load, or None if unknown."""
remaining = _lookup(
Expand All @@ -1783,6 +1822,7 @@ def backup_time_remaining(status: StatusPayload) -> float | None:
"current_power",
"islander_frequency",
"islander_voltage",
"is_legacy_gateway",
"raw_to_scaled_reserve",
"raw_to_scaled_soc",
"scaled_to_raw_reserve",
Expand Down
87 changes: 87 additions & 0 deletions tests/powerwall/test_legacy_gateway.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""Tests for is_legacy_gateway over the cloud site_info body."""

from __future__ import annotations

from typing import Any

import pytest

from tesla_fleet_api.exceptions import InvalidResponse
from tesla_fleet_api.tesla.powerwall import is_legacy_gateway

GATEWAY_1_DIN = "1118431-01-F--TG000000000000"
GATEWAY_2_DIN = "1232100-00-E--TG000000000000"


def _gateway(part_number: str) -> dict[str, Any]:
return {
"device_id": "device",
"din": f"{part_number}--TG000000000000",
"serial_number": "TG000000000000",
"part_number": part_number,
"is_active": True,
}


@pytest.mark.parametrize(
("site_info", "expected"),
[
pytest.param(
{
"id": GATEWAY_2_DIN,
"components": {"gateways": [_gateway("1118431-01-F")]},
},
True,
id="gateway_1_part_number",
),
pytest.param(
{
"id": GATEWAY_2_DIN,
"components": {"gateways": [_gateway("1232100-00-E")]},
},
False,
id="gateway_2_part_number",
),
pytest.param(
{
"id": GATEWAY_1_DIN,
"components": {"gateways": [_gateway("1232100-00-E")]},
},
False,
id="listed_gateway_wins_over_id",
),
pytest.param(
{"id": GATEWAY_1_DIN, "components": {"gateways": []}},
True,
id="gateway_1_site_din",
),
pytest.param(
{"id": GATEWAY_1_DIN, "components": {}}, True, id="no_gateways_key"
),
pytest.param({"id": GATEWAY_2_DIN}, False, id="gateway_2_site_din"),
pytest.param(
{"id": GATEWAY_1_DIN, "components": {"gateways": [{"part_number": None}]}},
True,
id="gateway_without_part_number_falls_back_to_id",
),
],
)
def test_is_legacy_gateway(site_info: dict[str, Any], expected: bool) -> None:
assert is_legacy_gateway(site_info) is expected


@pytest.mark.parametrize(
"site_info",
[
pytest.param(None, id="null_body"),
pytest.param({}, id="empty_body"),
pytest.param({"components": {"gateways": []}}, id="no_gateways_no_id"),
pytest.param(
{"components": {"gateways": [{"din": GATEWAY_1_DIN}]}},
id="no_part_number_no_id",
),
],
)
def test_is_legacy_gateway_unknown_shape(site_info: Any) -> None:
with pytest.raises(InvalidResponse):
is_legacy_gateway(site_info)
Loading