Skip to content

Latest commit

 

History

History
340 lines (291 loc) · 16.7 KB

energy_local_control.md

File metadata and controls

340 lines (291 loc) · 16.7 KB

Energy: Local Control (Powerwall LAN + EnergySiteRouter)

The cloud energy-site classes and the tesla_fleet_api.tesla.powerwall sub-package (moved here from aiopowerwall) are designed to be used together to give an energy gateway (Powerwall 2/3) both a local, signed LAN control path and a cloud fallback:

  • The cloud classes hold the keypair lifecycle. Tesla.get_rsa_private_key generates or loads and persists the RSA key, rsa_public_der_pkcs1 derives the public key bytes for registration, and EnergySite.add_authorized_client registers its public half with the gateway over the cloud. tesla_fleet_api.tesla.powerwall deliberately does not implement registration - it only consumes an already-paired key.
  • tesla_fleet_api.tesla.powerwall holds the local, RSA-signed transport. Its PowerwallEnergySite adapter implements the local subset of the EnergySite surface with matching names, signatures, and dict[str, Any] return shapes. It is duck-typed by design (it does not subclass EnergySite), so it drops straight into EnergySiteRouter.

PowerwallClient and PowerwallEnergySite are also exported from tesla_fleet_api.tesla. The aiopowerwall package is not a dependency of this project.

1. Generate or load the RSA private key

get_rsa_private_key(path) (available on Tesla and everything that inherits it - TeslaFleetApi, Teslemetry, Tessie) loads an existing RSA private key or creates a new 4096-bit unencrypted PEM key file. This is the key you will register with the gateway and later hand to PowerwallClient.

Creating a new key uses a plain sys.executable -c subprocess so RSA generation does not block the asyncio event loop. The subprocess runs its own script as __main__ and never imports the caller's entry point, so this works from scripts, REPLs, python -c, and notebooks without an entry-point guard. If the subprocess cannot be used (including in a frozen application), exits unsuccessfully, or returns empty or invalid key data, generation falls back to the current process and logs a warning that the asyncio event loop may be blocked. Loading and validating an existing key runs in a worker thread and does not start a subprocess.

By default, existing keys receive cryptography's full RSA consistency check. For an existing key that your application already trusts, pass skip_rsa_key_validation=True to skip that potentially expensive check. This option does not weaken validation when loading the key's PEM structure. Pass async_rsa_key_creation=False only when subprocess spawning is unavailable or undesired: new-key generation then runs in the current process and blocks the event loop. Both options affect only RSA key handling; their defaults preserve the non-blocking and fully validated behavior described above.

2. Register the key with the gateway, over the cloud

EnergySite.add_authorized_client registers the public half of that key with the gateway. After registration the key sits in PENDING_VERIFICATION state (AuthorizedClientState) during a roughly nine-minute presence-proof window. A physical breaker toggle confirms it (observed in as little as 59 seconds); cloud auto-verification was not observed. If the window expires, the key moves to the terminal PENDING_VERIFICATION_TIMEOUT state. Re-register the same key to reset the window and retry; this does not create a duplicate record.

The gateway can also register an ECC public key when it is encoded as DER SubjectPublicKeyInfo (Tesla.ec_public_der_spki), but ECC cannot authenticate the LAN TEDapi v1r protocol because that protocol has no ECDSA signature variant. Use the RSA/PKCS1 path shown here for local control.

import aiohttp
from tesla_fleet_api import Teslemetry

async def register_key(session: aiohttp.ClientSession, energy_site_id: int):
    api = Teslemetry(access_token="<access_token>", session=session)

    # Creates tedapi_rsa_private.pem (mode 0600) on first run, or loads
    # the existing key on subsequent runs.
    await api.get_rsa_private_key("tedapi_rsa_private.pem")

    energy_site = api.energySites.create(energy_site_id)
    await energy_site.add_authorized_client(
        api.rsa_public_der_pkcs1_b64,
        description="My local control client",
    )
    return api, energy_site

3. Hand the paired key to PowerwallClient

PowerwallClient consumes the same PEM file directly - it does not need anything else from this library at this point. local_energysite then exposes the locally implemented EnergySite-compatible calls (live_status(), operation(), backup(), set_island_mode(), get_backup_events(), and backup-event scheduling) through signed requests directly to the gateway over the LAN:

import aiohttp
from tesla_fleet_api.tesla.powerwall import PowerwallClient, PowerwallEnergySite

async def make_local_energysite(session: aiohttp.ClientSession) -> PowerwallEnergySite:
    with open("tedapi_rsa_private.pem", "rb") as f:
        rsa_private_key_pem = f.read()

    powerwall_client = PowerwallClient(
        host="192.168.91.1",       # the gateway's local IP
        gateway_password="<gateway-password>",  # local gateway password, not your Tesla account password
        rsa_private_key_pem=rsa_private_key_pem,
        session=session,
    )
    return PowerwallEnergySite(powerwall_client)

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 TeslemetryEnergySite.find_gateway_address(), which reads the gateway's networking_status and returns the decoded IPv4 of its active eth/wifi interface (or None when no usable interface is reported) - see Teslemetry.

4. Wait for the key to be paired

The gateway takes registration (step 2) and physical confirmation as two separate events, and there is a window between them where the key exists but is not yet usable. The typed Teslemetry helper below uses the gateway's authorized-client state as its primary signal. Where local network access is available, a successful signed read through PowerwallEnergySite can additionally confirm that the key is usable; the gateway would reject that read before verification.

get_system_info()/get_status()-style reads are the natural choice for this, but PowerwallEnergySite does not implement them locally yet (they raise NotImplementedError and would tell you nothing about the key - see the EnergySiteRouter note in step 5). Use live_status() instead: it is already implemented locally and, under the hood, issues a signed v1r request, so it fails exactly the way an unverified key would fail.

TeslemetryEnergySite.wait_until_paired() implements this combined check as a library helper: it polls find_authorized_clients() for the registered key's state, returning as soon as it is VERIFIED, and raises tesla_fleet_api.exceptions.AuthorizedClientPairingTimedOut immediately if the gateway reports the terminal PENDING_VERIFICATION_TIMEOUT state rather than continuing to poll a dead registration - re-register the same key to retry. Its own bounded overall wait (default 600s) raises tesla_fleet_api.exceptions.AuthorizedClientWaitExpired instead if the window is simply still open. Pass an async verify_by_use callable (e.g. local_energysite.live_status) to additionally require a successful signed local read before returning:

client = await teslemetry_energysite.wait_until_paired(
    api.rsa_public_der_pkcs1_b64,
    verify_by_use=local_energysite.live_status,
)

The manual polling loop below predates this helper and remains as a reference for building a custom confirmation flow (e.g. against the base Fleet API, which has no typed find_authorized_clients()).

Before verification, every signed request rejects with tesla_fleet_api.tesla.powerwall.PowerwallAuthenticationError (the gateway's "unknown key id" or "authorization not verified" fault) - that failure is expected and not a bug; treat it as "not yet, keep retrying" and back off between attempts:

import asyncio
from tesla_fleet_api.tesla.powerwall import (
    PowerwallAuthenticationError,
    PowerwallEnergySite,
)

async def wait_until_verified(
    local_energysite: PowerwallEnergySite,
    attempts: int = 10,
    initial_delay: float = 5.0,
    max_delay: float = 60.0,
) -> None:
    delay = initial_delay
    for attempt in range(attempts):
        try:
            await local_energysite.live_status()
            return  # a successful signed read proves the key is VERIFIED
        except PowerwallAuthenticationError:
            if attempt == attempts - 1:
                raise
            await asyncio.sleep(delay)
            delay = min(delay * 2, max_delay)

The base Fleet API has no typed equivalent of wait_until_paired(). Its callers can poll list_authorized_clients() and combine that with the manual signed-read loop above. Tesla's cloud endpoint is undocumented, and Teslemetry's list_authorized_clients in particular has been observed returning a bare JSON null with a 200 status rather than an envelope; that behavior may recur. Treat an unavailable or malformed cloud response as no signal, and never let it override a successful signed local read. TeslemetryEnergySite.find_authorized_clients() parses the recognized shapes (list vs. dict envelope, state typing) into a typed AuthorizedClients, but raises tesla_fleet_api.exceptions.InvalidResponse on a null body or any other unrecognized response shape so that malformed data is distinguishable from a genuinely empty client list. Catch InvalidResponse (or TeslaFleetError) around this call and treat it as "no signal" - note that TeslaFleetError subclasses BaseException, so a bare except Exception will not catch it. Either way, a null response here tells you nothing about whether the key actually works.

Any 502 response, including one from a gateway-relay command endpoint, raises tesla_fleet_api.exceptions.BadGateway regardless of whether the response carries a JSON body. Teslemetry's energy_gateway_unreachable error code raises the EnergyGatewayUnreachable subclass, so catch that to tell an unreachable gateway apart from any other 502.

To revoke a key, call remove_authorized_client(public_key) with its DER bytes or the base64 string returned by list_authorized_clients(). Removal does not require physical presence proof: any paired key can revoke every other key, including the owner's. The base Fleet API command route is inferred and has not been hardware-verified; only removal over the local v1r transport has been verified.

5. Compose local + cloud with EnergySiteRouter

import asyncio
import aiohttp
from tesla_fleet_api.router import EnergySiteRouter

async def main():
    async with aiohttp.ClientSession() as session:
        api, teslemetry_energysite = await register_key(session, energy_site_id=12345)
        local_energysite = await make_local_energysite(session)
        await wait_until_verified(local_energysite)

        router = EnergySiteRouter(local_energysite, teslemetry_energysite)

        status = await router.live_status()  # tries local first, cloud on failure
        print(status)

asyncio.run(main())

Locally implemented commands go over the LAN when the gateway is reachable, including set_export_limit(), set_import_limit(), set_on_grid_solar_curtailment() and set_config_json(), which take the cloud EnergySite's arguments and limits and answer its applied readback, and fail over to the Teslemetry cloud otherwise - the same local-primary/cloud-fallback pattern VehicleRouter uses for vehicles. Calls that PowerwallEnergySite does not implement locally yet, including get_system_info() and most energy-device gRPC commands, raise NotImplementedError from the local adapter and then fall through to the cloud backend. A local error fails over to the cloud only if is_failover_safe() accepts it: an OSError, aiohttp.ClientConnectionError, NotImplementedError, or an exception class with failover_safe = True. The Powerwall exception classes subclass Exception directly, not TeslaFleetError; PowerwallConnectionError, PowerwallRateLimitError and PowerwallAuthenticationError set failover_safe = True, so they fail over. A command the gateway answered and rejected is not sent to the cloud, because the cloud sends it to the same gateway. See the README's Routing and Failover section for the general Router semantics (per-command failover, the double-execution caveat, and the health check).

Warning: island mode / off-grid actuation is not guaranteed, and the unsigned cloud path cannot do it at all.

Gateways have been observed accepting the unsigned cloud grpc_command for set_island_mode() / go_off_grid() / reconnect_grid() without physically operating the grid contactor. So a Fleet API EnergySite built without a signing key raises tesla_fleet_api.exceptions.SignedCommandRequired for these three methods instead of returning a false success. Built with private_key and din (see Client-signed device commands), it signs them and sends them through the cloud device_command endpoint. A TeslemetryEnergySite without a key calls Teslemetry's route, which signs with Teslemetry's key.

Routing through EnergySiteRouter with a PowerwallEnergySite local primary sends a signed request over the LAN first. If the local primary fails and Router fails over to the cloud secondary, a keyed cloud site sends the signed command. A Fleet API site without a key raises SignedCommandRequired, and a Teslemetry site without a key calls Teslemetry's signed route. A command that failed mid-flight on the LAN may already have run, so the cloud retry can run it twice; island mode is absolute, so a second run sets the same mode. The local PowerwallClient.set_island_mode also has an unresolved, firmware-dependent caveat - some gateways acknowledge it without acting on it, and trigger_islanding() (the explicit black-start command) may be needed as a fallback.

Even on the signed local path, a success-shaped response does not prove the contactor moved. Always confirm the actual outcome with a signed local status read (for example live_status()'s grid/island fields) before trusting the response for anything actuation-critical.

Merge contract

EnergySiteRouter's per-command dispatch is not a merge - calling router.live_status() returns one whole source's response (local, or cloud on failover), not a blend of both. PowerwallEnergySite.live_status() reports all of the cloud response's keys but fills in None for the ones it cannot serve locally, so a consumer that wants "local readings where available, cloud otherwise" needs to merge the two responses itself, field by field.

tesla_fleet_api.router.energysite provides that merge via two entry points, one per response shape:

from tesla_fleet_api.router.energysite import merge_live_status, merge_site_info

cloud_status = await teslemetry_energysite.live_status()
local_status = await local_energysite.live_status()
merged = merge_live_status(cloud_status, local_status)
  • merge_live_status overlays the live_status() fields the local gateway can actually serve; merge_site_info does the same for site_info() (backup_reserve_percent, default_real_mode, the grid limits min_site_meter_power_ac/max_site_meter_power_ac in kW, and on_grid_solar_curtailment_enabled, which local_config() reports as False when the gateway has dropped the key).
  • Only keys the wrapper owns and present in local are overlaid onto a copy of cloud; every other key keeps its cloud value.
  • If the local read failed entirely (local is None, e.g. the LAN call raised), the result is just cloud - the same fallback-to-cloud behavior Router gives non-merged commands.

Both wrappers call the underlying primitive, merge_local_into_cloud(cloud, local, owned_keys), which is still public for a caller with its own key set (LOCAL_LIVE_STATUS_KEYS/LOCAL_SITE_INFO_KEYS are also exported).

See also

  • Fleet API for Energy Sites - the cloud EnergySite command surface (get_rsa_private_key, the gRPC "Device Commands" section) on its own, without a local backend.
  • Routing and Failover - the general Router/EnergySiteRouter dispatch and failover semantics.
  • The aiopowerwall README (the project tesla_fleet_api.tesla.powerwall came from) for local-only concerns: gateway pairing (breaker toggle / auto-verify), backup-reserve and SoC scaling, and multi-Powerwall leader/follower behavior.