diff --git a/docs/teslemetry.md b/docs/teslemetry.md index bc98774..d747d48 100644 --- a/docs/teslemetry.md +++ b/docs/teslemetry.md @@ -606,15 +606,21 @@ fields in a `networking_status` response have been observed as either raw big-endian uint32 integers or dotted-quad strings; the helper decodes either form and selects an interface for you. Only the `eth` and `wifi` interfaces are considered (never `gsm` - -cellular is not a LAN path): the helper prefers whichever has `active_route` -set and a decodable address, then falls back to the first of the two (in -`eth`, `wifi` order) with any decodable address. A null response body or an +cellular is not a LAN path). Pass the caller's own IPv4 networks to prefer an +address inside one of them; otherwise ethernet is preferred over Wi-Fi. An +address in `192.168.90.0/24` (the Powerwall's own hotspot and inter-Powerwall +network) is used only when there is no other. `active_route` is ignored, +because Tesla has reported it on an unreachable `192.168.90.x` ethernet +address. A null response body or an unrecognized response shape raises `tesla_fleet_api.exceptions.InvalidResponse`, so malformed data is never mistaken for "no address"; a well-formed response where no interface yields a usable address returns `None` instead. ```python +from ipaddress import IPv4Network + + async def main(): async with aiohttp.ClientSession() as session: teslemetry = Teslemetry( @@ -624,7 +630,9 @@ async def main(): energy_site = teslemetry.energySites.create(12345) - address = await energy_site.find_gateway_address() + address = await energy_site.find_gateway_address( + [IPv4Network("192.168.1.0/24")] + ) print(address) # e.g. "192.168.1.138", or None # The untyped response is still available when callers need the exact diff --git a/tesla_fleet_api/teslemetry/energysite.py b/tesla_fleet_api/teslemetry/energysite.py index a6bccd5..433891c 100644 --- a/tesla_fleet_api/teslemetry/energysite.py +++ b/tesla_fleet_api/teslemetry/energysite.py @@ -2,11 +2,12 @@ import asyncio import base64 +import ipaddress import re import socket import struct import warnings -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Iterable from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -233,6 +234,9 @@ def _parse_authorized_clients( # pyright: ignore[reportUnusedFunction] _GATEWAY_INTERFACES = ("eth", "wifi") +# The Powerwall's own hotspot and inter-Powerwall network; the LAN rarely +# routes to it, even when Tesla reports it as the active route. +_POWERWALL_INTERNAL_NETWORK = ipaddress.IPv4Network("192.168.90.0/24") _DOTTED_QUAD_OCTET = r"(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])" _DOTTED_QUAD_RE = re.compile( @@ -306,33 +310,34 @@ def _networking_status_body(payload: Any) -> dict[str, Any]: return body -def _parse_gateway_address(payload: Any) -> str | None: +def _parse_gateway_address( + payload: Any, networks: Iterable[ipaddress.IPv4Network] = () +) -> str | None: """Pick the gateway's LAN IPv4 from a ``networking_status`` response. Considers only ``eth``/``wifi`` (never ``gsm`` - cellular isn't a LAN - path): prefers whichever of those has ``active_route`` set and a - decodable address, then falls back to the first of the two (in - ``eth``, ``wifi`` order) that has any decodable address. Returns - ``None`` when neither yields one - a well-formed response can simply - lack a usable interface. + path), in that order, and picks the first decodable address that is + inside one of ``networks``, else the first outside 192.168.90.0/24, + else the first. ``active_route`` is ignored: Tesla has reported it on + an unreachable 192.168.90.x ``eth``. Returns ``None`` when neither + interface yields an address - a well-formed response can simply lack a + usable interface. """ body = _networking_status_body(payload) - interfaces = [body.get(name) for name in _GATEWAY_INTERFACES] - - for interface in interfaces: - if ( - isinstance(interface, dict) - and cast("dict[str, Any]", interface).get("active_route") - and (address := _interface_address(interface)) is not None - ): - return address + candidates = [ + ipaddress.IPv4Address(address) + for name in _GATEWAY_INTERFACES + if (address := _interface_address(body.get(name))) is not None + ] + local_networks = tuple(networks) - for interface in interfaces: - address = _interface_address(interface) - if address is not None: - return address - - return None + for address in candidates: + if any(address in network for network in local_networks): + return str(address) + for address in candidates: + if address not in _POWERWALL_INTERNAL_NETWORK: + return str(address) + return str(candidates[0]) if candidates else None class TeslemetryEnergySite(EnergySite): @@ -678,7 +683,9 @@ async def get_networking_status(self) -> dict[str, Any]: f"api/1/energy_sites/{self.energy_site_id}/command/networking_status", ) - async def find_gateway_address(self) -> str | None: + async def find_gateway_address( + self, networks: Iterable[ipaddress.IPv4Network] = () + ) -> str | None: """Discover the gateway's LAN IPv4 address, for pre-filling a local control host. @@ -689,10 +696,14 @@ async def find_gateway_address(self) -> str | None: :class:`~tesla_fleet_api.exceptions.InvalidResponse` on a null response body or an unrecognized response shape; returns ``None`` when the response is well-formed but no interface yields an - address. See :func:`_parse_gateway_address` for the exact selection - rule. + address. + + Pass the caller's own IPv4 ``networks`` to prefer an address that is + reachable from them; otherwise ethernet is preferred over Wi-Fi, and + a 192.168.90.x address is used only when there is no other. See + :func:`_parse_gateway_address` for the exact selection rule. """ - return _parse_gateway_address(await self.get_networking_status()) + return _parse_gateway_address(await self.get_networking_status(), networks) async def list_authorized_clients(self) -> dict[str, Any]: """List authorized clients on the energy gateway via the Teslemetry diff --git a/tests/test_teslemetry_gateway_address.py b/tests/test_teslemetry_gateway_address.py index b695929..8b60c78 100644 --- a/tests/test_teslemetry_gateway_address.py +++ b/tests/test_teslemetry_gateway_address.py @@ -2,8 +2,8 @@ over the Teslemetry ``command/networking_status`` endpoint. Only ``eth``/``wifi`` are considered (never ``gsm`` - cellular isn't a LAN -path). An interface with ``active_route`` set wins; otherwise the first of -``eth``, ``wifi`` (in that order) with a decodable address is used. Address +path), in ``eth``, ``wifi`` order: an address inside a caller-supplied +network wins, then one outside 192.168.90.0/24, then any. Address fields on the wire have been observed as both raw big-endian uint32 integers and dotted-quad strings - see ``GatewayAddressRealCaptureTests`` and ``GatewayAddressStringFormatTests`` for the real captured samples this @@ -18,6 +18,7 @@ from __future__ import annotations from contextlib import asynccontextmanager +from ipaddress import IPv4Network from typing import Any from unittest import IsolatedAsyncioTestCase from unittest.mock import AsyncMock, MagicMock @@ -124,7 +125,7 @@ async def test_real_captured_sample_selects_active_route_wifi(self) -> None: class GatewayAddressSelectionTests(IsolatedAsyncioTestCase): - async def test_eth_preferred_when_eth_has_active_route(self) -> None: + async def test_eth_preferred_over_wifi(self) -> None: site = _make_site( { "response": { @@ -144,7 +145,7 @@ async def test_eth_preferred_when_eth_has_active_route(self) -> None: self.assertEqual(result, "192.168.1.1") - async def test_no_active_route_falls_back_to_eth_first(self) -> None: + async def test_powerwall_internal_eth_skipped_for_wifi(self) -> None: site = _make_site( { "response": { @@ -156,9 +157,9 @@ async def test_no_active_route_falls_back_to_eth_first(self) -> None: result = await site.find_gateway_address() - self.assertEqual(result, "192.168.90.2") + self.assertEqual(result, "192.168.1.138") - async def test_no_active_route_falls_back_to_wifi_when_eth_has_no_address( + async def test_falls_back_to_wifi_when_eth_has_no_address( self, ) -> None: site = _make_site( @@ -259,6 +260,129 @@ async def test_bare_body_without_response_envelope(self) -> None: self.assertEqual(result, "192.168.1.138") +class GatewayAddressNetworkPreferenceTests(IsolatedAsyncioTestCase): + """Two Powerwall 3s (leader + follower): Tesla reported the leader's + ``eth`` as 192.168.90.2 with ``active_route`` set and a 192.168.1.254 + gateway, while the home network is 192.168.1.0/24 and only ``wifi`` is + reachable from it. + """ + + TWO_POWERWALL_RESPONSE = { + "response": { + "eth": { + "enabled": True, + "active_route": True, + "ipv4_config": { + "address": "192.168.90.2", + "subnet_mask": "255.255.255.0", + "gateway": "192.168.1.254", + }, + }, + "wifi": { + "enabled": True, + "ipv4_config": { + "address": "192.168.1.252", + "subnet_mask": "255.255.255.0", + "gateway": "192.168.1.254", + }, + }, + } + } + + async def test_two_powerwalls_without_networks_skips_internal_eth( + self, + ) -> None: + site = _make_site(self.TWO_POWERWALL_RESPONSE) + + result = await site.find_gateway_address() + + self.assertEqual(result, "192.168.1.252") + + async def test_two_powerwalls_with_caller_network_picks_wifi(self) -> None: + site = _make_site(self.TWO_POWERWALL_RESPONSE) + + result = await site.find_gateway_address([IPv4Network("192.168.1.0/24")]) + + self.assertEqual(result, "192.168.1.252") + + async def test_caller_network_beats_ethernet_preference(self) -> None: + site = _make_site( + { + "response": { + "eth": {"ipv4_config": {"address": "10.0.0.5"}}, + "wifi": {"ipv4_config": {"address": "192.168.1.252"}}, + } + } + ) + + result = await site.find_gateway_address( + [IPv4Network("172.16.0.0/12"), IPv4Network("192.168.1.0/24")] + ) + + self.assertEqual(result, "192.168.1.252") + + async def test_no_caller_network_match_prefers_ethernet(self) -> None: + site = _make_site( + { + "response": { + "eth": {"ipv4_config": {"address": "10.0.0.5"}}, + "wifi": {"ipv4_config": {"address": "192.168.1.252"}}, + } + } + ) + + result = await site.find_gateway_address([IPv4Network("172.16.0.0/12")]) + + self.assertEqual(result, "10.0.0.5") + + async def test_single_powerwall_on_ethernet(self) -> None: + site = _make_site( + { + "response": { + "eth": {"ipv4_config": {"address": "192.168.1.20"}}, + "wifi": {"enabled": False}, + } + } + ) + + result = await site.find_gateway_address([IPv4Network("192.168.1.0/24")]) + + self.assertEqual(result, "192.168.1.20") + + async def test_wifi_only(self) -> None: + site = _make_site( + {"response": {"wifi": {"ipv4_config": {"address": "192.168.1.138"}}}} + ) + + result = await site.find_gateway_address([IPv4Network("192.168.1.0/24")]) + + self.assertEqual(result, "192.168.1.138") + + async def test_only_internal_address_is_last_resort(self) -> None: + site = _make_site( + {"response": {"eth": {"ipv4_config": {"address": "192.168.90.2"}}}} + ) + + result = await site.find_gateway_address([IPv4Network("192.168.1.0/24")]) + + self.assertEqual(result, "192.168.90.2") + + async def test_no_usable_address_returns_none(self) -> None: + site = _make_site( + { + "response": { + "eth": {"ipv4_config": {"address": "0.0.0.0"}}, + "wifi": {"enabled": True}, + "gsm": {"ipv4_config": {"address": "10.17.123.246"}}, + } + } + ) + + result = await site.find_gateway_address([IPv4Network("10.0.0.0/8")]) + + self.assertIsNone(result) + + class GatewayAddressStringFormatTests(IsolatedAsyncioTestCase): """The API now also serves ipv4 fields as dotted-quad strings directly, alongside the legacy uint32 int form - both must decode to the same