jasonacox / pypowerwall

Python API for Tesla Powerwall and Solar Power Data
MIT License
134 stars 24 forks source link
battery dashboard inverter-graphs powerwall powerwall-api powerwall-status powerwall-temps python solar solar-panel-data solar-strings tesla tesla-api tesla-powerwall vitals

pyPowerwall

License PyPI version CI simtest Python Version PyPI Downloads

Python module to interface with Tesla Energy Gateways for Powerwall and solar power data. Currently supporting local access to Powerwall, Powerwall 2 and Powerwall+ systems and Tesla Owner cloud API for all systems including Solar Only and Powerwall 3 systems.

Description

This python module can be used to monitor and control Tesla Energy Powerwalls. It uses a single class (Powerwall) and simple functions to fetch energy data and poll API endpoints on the Gateway.

pyPowerwall will cache the authentication headers and API call responses to help reduce the number of calls made to the Gateway (useful if you are polling the Powerwall frequently for trending data).

Setup

You can clone this repo or install the package with pip. Once installed, pyPowerwall can scan your local network to find th IP address of your Tesla Powerwall Gateway.

# Install pyPowerwall
python3 -m pip install pypowerwall

# Option 1 - LOCAL MODE - Scan Network for Powerwalls
python3 -m pypowerwall scan

# Option 2 - FLEETAPI MODE - Setup to use the official Tesla FleetAPI - See notes below.
python3 -m pypowerwal fleetapi

# Option 3 - CLOUD MODE -  Setup to use Tesla Owners cloud API
python3 -m pypowerwall setup

Local Setup - Option 1

The Tesla Powerwall, Powerwall 2 and Powerwall+ have a local LAN based API that you can use to monitor your Powerwall. It requires that you (or your installer) have the IP address (see scan above) and set up Customer Login credentials on your Powerwall Gateway. That is all that is needed to connect. Unfortunately, the Powerwall 3 does not have a local API but you can access it via the cloud (see options 2 and 3).

Extended Device Vitals Metrics: With version v0.10.0+, pypowerwall can be set to access the TEDAPI on the Gateway to pull additional metrics. However, you will need the Gateway Password (often found on the QR sticker on the Powerwall Gateway). Additionally, your computer will need network access to the Gateway IP (192.168.91.1). You can have your computer join the Gateway local WiFi or you can add a route:

# Example - Change 192.168.0.100 to the IP address of Powerwall Gateway on your LAN

# Linux Ubuntu and RPi - Can add to /etc/rc.local for persistence 
sudo ip route add 192.168.91.1 via 192.168.0.100

# MacOS 
sudo route add -host 192.168.91.1 192.168.0.100 # Temporary 
networksetup -setadditionalroutes Wi-Fi 192.168.91.1 255.255.255.255 192.168.0.100 # Persistent

# Windows - Using persistence flag - Administrator Shell
route -p add 192.168.91.1 mask 255.255.255.255 192.168.0.100

FleetAPI Setup - Option 2

FleetAPI is the official Tesla API for accessing your Tesla products. This setup has some additional setup requirements that you will be prompted to do:

Step 1 - Tesla Partner Account - Sign in to Tesla Developer Portal and make an App Access Request: See Tesla App Access Request - During this process, you will need to set up and remember the following account settings:

Step 2 - Run the create_pem_key.py script and place the public key on your website at the URL: https://{DOMAIN}/.well-known/appspecific/com.tesla.3p.public-key.pem

Step 3 - Run python3 -m pypowerwal fleetapi - The credentials and tokens will be stored in the .pypowerwall.fleetapi file.

Cloud Mode - Option 3

The unofficial Tesla Owners API allows FleetAPI access (option 2) without having to set up a website and PEM key. Follow the directions given to you by running python3 -m pypowerwall setup. The credentials and site_id will be stored in .pypowerwall.auth and .pypowerwall.site.

FreeBSD Install

FreeBSD users can install from ports or pkg FreshPorts:

Via pkg:

# pkg install net-mgmt/py-pypowerwall

Via ports:

# cd /usr/ports/net-mgmt/py-pypowerwall/ && make install clean

Note: pyPowerwall installation will attempt to install these required python packages: requests, protobuf and teslapy.

Programming with pyPowerwall

After importing pypowerwall, you simply create a handle for your Powerwall device and call function to poll data. Here is an example:

    import pypowerwall

    # Optional: Turn on Debug Mode
    # pypowerwall.set_debug(True)

    # Option 1 - LOCAL MODE - Credentials for your Powerwall - Customer Login
    password="password"
    email="email@example.com"
    host = "10.0.1.123"               # Address of your Powerwall Gateway
    timezone = "America/Los_Angeles"  # Your local timezone

    # Option 2 - FLEETAPI MODE - Requires Setup
    host = password = email = ""
    timezone = "America/Los_Angeles" 

    # Option 3 - CLOUD MODE - Requires Setup
    host = password = ""
    email='email@example.com'
    timezone = "America/Los_Angeles"

    # Connect to Powerwall - auto_select mode (local, fleetapi, cloud)
    pw = pypowerwall.Powerwall(host,password,email,timezone,auto_select=True)

    # Some System Info
    print("Site Name: %s - Firmware: %s - DIN: %s" % (pw.site_name(), pw.version(), pw.din()))
    print("System Uptime: %s\n" % pw.uptime())

    # Pull Sensor Power Data
    grid = pw.grid()
    solar = pw.solar()
    battery = pw.battery()
    home = pw.home()

    # Display Data
    print("Battery power level: %0.0f%%" % pw.level())
    print("Combined power metrics: %r" % pw.power())
    print("")

    # Display Power in kW
    print("Grid Power: %0.2fkW" % (float(grid)/1000.0))
    print("Solar Power: %0.2fkW" % (float(solar)/1000.0))
    print("Battery Power: %0.2fkW" % (float(battery)/1000.0))
    print("Home Power: %0.2fkW" % (float(home)/1000.0))
    print("")

    # Raw JSON Payload Examples
    print("Grid raw: %r\n" % pw.grid(verbose=True))
    print("Solar raw: %r\n" % pw.solar(verbose=True))

    # Display Device Vitals
    print("Vitals: %r\n" % pw.vitals())

    # Display String Data
    print("String Data: %r\n" % pw.strings())

pyPowerwall Module Class and Functions

 set_debug(True, color=True)

 Classes
    Powerwall(host, password, email, timezone, pwcacheexpire, timeout, poolmaxsize, 
               cloudmode, siteid, authpath, authmode, cachefile, fleetapi, auto_select)

 Parameters
    host                      # Hostname or IP of the Tesla gateway
    password                  # Customer password for gateway
    email                     # (required) Customer email for gateway / cloud
    timezone                  # Desired timezone
    pwcacheexpire = 5         # Set API cache timeout in seconds
    timeout = 5               # Timeout for HTTPS calls in seconds
    poolmaxsize = 10          # Pool max size for http connection re-use (persistent
                                connections disabled if zero)
    cloudmode = False         # If True, use Tesla cloud for data (default is False)
    siteid = None             # If cloudmode is True, use this siteid (default is None)
    authpath = ""             # Path to cloud auth and site files (default current directory)
    authmode = "cookie"       # "cookie" (default) or "token" - use cookie or bearer token for auth
    cachefile = ".powerwall"  # Path to cache file (default current directory)
    fleetapi = False          # If True, use Tesla FleetAPI for data (default is False)
    auto_select = False       # If True, select the best available mode to connect (default is False)

 Functions 
    poll(api, json, force)    # Return data from Powerwall api (dict if json=True, bypass cache force=True)
    post(api, payload, json)  # Send payload to Powerwall api (dict if json=True)
    level()                   # Return battery power level percentage
    power()                   # Return power data returned as dictionary
    site(verbose)             # Return site sensor data (W or raw JSON if verbose=True)
    solar(verbose):           # Return solar sensor data (W or raw JSON if verbose=True)
    battery(verbose):         # Return battery sensor data (W or raw JSON if verbose=True)
    load(verbose)             # Return load sensor data (W or raw JSON if verbose=True)
    grid()                    # Alias for site()
    home()                    # Alias for load()
    vitals(json)              # Return Powerwall device vitals (dict or json if True)
    strings(json, verbose)    # Return solar panel string data
    din()                     # Return DIN
    uptime()                  # Return uptime - string hms format
    version()                 # Return system version
    status(param)             # Return status (JSON) or individual param
    site_name()               # Return site name
    temps()                   # Return Powerwall Temperatures
    alerts()                  # Return array of Alerts from devices
    system_status(json)       # Returns the system status
    battery_blocks(json)      # Returns battery specific information merged from system_status() and vitals()
    grid_status(type)         # Return the power grid status, type ="string" (default), "json", or "numeric"
                              #     - "string": "UP", "DOWN", "SYNCING"
                              #     - "numeric": -1 (Syncing), 0 (DOWN), 1 (UP)
    is_connected()            # Returns True if able to connect and login to Powerwall
    get_reserve(scale)        # Get Battery Reserve Percentage
    get_mode()                # Get Current Battery Operation Mode
    set_reserve(level)        # Set Battery Reserve Percentage
    set_mode(mode)            # Set Current Battery Operation Mode
    get_time_remaining()      # Get the backup time remaining on the battery
    set_operation(level, mode, json)  # Set Battery Reserve Percentage and/or Operation Mode
    set_grid_charging(mode)   # Enable or disable grid charging (mode = True or False)
    set_grid_export(mode)     # Set grid export mode (mode = battery_ok, pv_only, never)
    get_grid_charging()       # Get the current grid charging mode
    get_grid_export()         # Get the current grid export mode

Tools

The following are some useful tools based on pypowerwall:

Powerwall Command Line

pyPowerwall has a built in feature to scan your network for available Powerwall gateways and set/get operational and reserve modes.

Usage: PyPowerwall [-h] {setup,scan,set,get,version} ...

PyPowerwall Module v0.8.1

Options:
  -h, --help            Show this help message and exit

Commands (run <command> -h to see usage information):
  {setup,scan,set,get,version}
    setup                 Setup Tesla Login for Cloud Mode access
    scan                  Scan local network for Powerwall gateway
    set                   Set Powerwall Mode and Reserve Level
    get                   Get Powerwall Settings and Power Levels
    version               Print version information

   set options:
      -mode MODE          Powerwall Mode: self_consumption, backup, or autonomous
      -reserve RESERVE    Set Battery Reserve Level [Default=20]
      -current            Set Battery Reserve Level to Current Charge
      -gridcharging MODE  Set Grid Charging (allow) Mode ("on" or "off")
      -gridexport MODE    Set Export to Grid Mode ("battery_ok", "pv_only", or "never")

   get options:
      -format FORMAT      Output format: text, json, csv
      -host HOST          IP address of Powerwall Gateway
      -password PASSWORD  Password for Powerwall Gateway
# Install pyPowerwall if you haven't already
python -m pip install pypowerwall

# Scan Network for Powerwalls
python -m pypowerwall scan

Example Output

pyPowerwall Network Scanner [0.1.2]
Scan local network for Tesla Powerwall Gateways

    Your network appears to be: 10.0.1.0/24

    Enter Network or press enter to use 10.0.1.0/24: 

    Running Scan...
      Host: 10.0.1.16 ... OPEN - Not a Powerwall
      Host: 10.0.1.26 ... OPEN - Not a Powerwall
      Host: 10.0.1.36 ... OPEN - Found Powerwall 1232100-00-E--TG123456789ABG
      Done                           

Discovered 1 Powerwall Gateway
     10.0.1.36 [1232100-00-E--TG123456789ABG]

Get Power Levels, Operation Mode, and Battery Reserve Level

# Setup Connection with Tesla Cloud
python -m pypowerwall setup

# Get Power Levels, Operation Mode, and Battery Reserve Setting
#
# Usage: PyPowerwall get [-h] [-format FORMAT]
#  -h, --help      show this help message and exit
#  -format FORMAT  Output format: text, json, csv
#
python -m pypowerwall get
python -m pypowerwall get -format json
python -m pypowerwall get -format csv

# Set Operation Mode and Battery Reserve Setting
#
# Usage: PyPowerwall set [-h] [-mode MODE] [-reserve RESERVE] [-current]
#  -h, --help        show this help message and exit
#  -mode MODE        Powerwall Mode: self_consumption, backup, or autonomous
#  -reserve RESERVE  Set Battery Reserve Level [Default=20]
#  -current          Set Battery Reserve Level to Current Charge
#
python -m pypowerwall set -mode self_consumption
python -m pypowerwall set -reserve 30
python -m pypowerwall set -current

Example API Calls

The following APIs are a result of help from other projects as well as my own investigation.

Powerwall Reference

Firmware Version History

Firmware version of the Powerwall can be seen with pw.version(). An estimate of Firmware versions in the wild can be seen here: https://www.netzeroapp.io/firmware_versions

Powerwall Firmware Date Seen Features pyPowerwall Tesla App
20.49.0 Unknown Unknown N/A
21.13.2 May-2021 Improved Powerwall behavior during power outage. Push notification when charge level is low during outage. N/A
21.31.2 Sep-2021 Unknown N/A
21.39.1 7759c368 Nov-2021 Unknown v0.1.0
21.44 223a5cd Unknown Issue with this firmware is that when the Neurio meter (1.6.1-Tesla) loses connection with gateway (happens frequently) it stops solar generation. v0.1.0
21.44.1 c58c2df3 1-Jan-2022 Neurio converted to RGM only so that when it disconnects it no longer stop solar power generation v0.2.0
22.1 92118b67 21-Jan-2022 Upgrades Neurio Revenue Grade Meter (RGM) to 1.7.1-Tesla addressing Neurio instability and missing RGM data v0.3.0
22.1.1 22-Feb-2022 Unknown v0.3.0
22.1.2 34013a3f N/A Unknown N/A
22.9 1-Apr-2022 More options for ‘Advanced Settings’ in the Tesla app to control grid charging and export behavior Improved Powerwall performance when charge level is below backup reserve and Powerwall is importing from the grid Capability to configure the charge rate of Powerwall below backup reserve Improved metering accuracy when loads are not balanced across phases v0.4.0 4.8.0
22.9.1 12-Apr-2022 Unknown v0.4.0 4.8.0
22.9.1.1 75c90bda 2-May-2022 Unknown v0.4.0 4.8.0-1025
22.9.2 a54352e6 2-May-2022 Unknown v0.4.0 Proxy t11 4.8.0-1025
22.18.3 21c0ad81 28-Jun-2022 Two new alerts did show up in device vitals: HighCPU and SystemConnectedToGrid * The HighCPU was particularly interesting. If you updated your customer password on the gateway, it seems to have reverted during the firmware upgrade. Any monitoring tools using the new password were getting errors. The gateway was presenting "API rate limit" errors (even for installer mode). Reverting the password to the older one fixes the issue but revealed the HighCPU alert. v0.4.0 Proxy t15 4.9.2-1087
22.18.6 7884188e 27-Sep-2022 STSTSM HighCPU Alert appeared after upgrade. The firmwareVersion now shows "2022-08-01-g8b6399632f". Alerts during upgrade: "PINV_a010_can_gtwMIA", "PINV_a039_can_thcMIA". v0.4.0 Proxy t15 4.13.1-1312
22.26.1-foxtrot 4d562eaf 13-Oct-2022 This release seems to have introduced a Powerwall charging slowdown mode. After 95% full, the charging will slow dramatically with excess solar production getting pushed to the grid even if the battery is less than 100% (see discussion). This upgrade also upgrades the Neurio Revenue Grade Meter (RGM) to 1.7.2-Tesla with STSTSM firmware showing 2022-09-28-g7cb0d69c2b. Tesla Release Notes: Time-Based Control mode updates, Improved off-grid retry, improved commissioning, improved metering accuracy on Neurio Smart CTs v0.6.0 Proxy t19 4.13.1-1334
22.26.2 8cd8cac4 26-Oct-2022 STSTSM firmware showing 2022-10-24-g64e8c689f9 - This version seems to have fixed a slow charging issue with the Powerwall. With version 22.26.1, it started trickle charging at around 85-90% and would never get above 95%. With this new version it charges up to 98% and then starts trickle charging to the final 100%. v0.6.0 Proxy t19 4.14.1-1395
22.26.4 fc00d5dd 22-Nov-2022 STSTSM firmware showing 2022-10-26-g9b8e445626 - No noticeable changes so far. v0.6.0 Proxy t22 4.14.4-1455
22.36.6 cf1839cb 11-Mar-2023 STSTSM firmware showing 2023-03-04-gd9f19c06f2 - Improved detection of open circuit breakers on Powerwall systems (see Tesla release notes). Change was reverted and rolled back to 22.26.4 v0.6.0 Proxy t24 4.18.0-1607
22.36.7 08d06dad 21-Mar-2023 STSTSM firmware showing 2023-03-04-gd9f19c06f2 - No noticeable changes so far. v0.6.1 Proxy t24 4.18.0-1607
22.36.9 c55384d2 11-Apr-2023 STSTSM firmware showing 2023-03-29-g66549e6ca7 v0.6.2 Proxy t25 4.19.5-1665
23.4.2-1 fe55682a 3-May-2023 STSTSM firmware showing localbuild v0.6.2 Proxy t25 4.20.69-1691
23.12.10 30f95d0b 1-Jul-2023 STSTSM firmware showing 2023-07-11-geb56bf57ab v0.6.2 Proxy t26 4.23.6-1844
23.12.11 452c76cb 4-Aug-2023 STSTSM firmware showing 2023-07-20-ga38210a892 v0.6.2 Proxy t26 4.23.6-1844
23.28.1 fa0c1ad0 11-Sep-2023 STSTSM firmware showing 2023-08-22-g807640ca4a v0.6.2 Proxy t26 4.24.5-1931
23.28.2 27626f98 13-Oct-2023 STSTSM firmware showing 2023-09-12-gafa2393b50 v0.6.2 Proxy t26 4.25.6-1976
23.36.3 aa269d353 22-Dec-2023 STSTSM firmware showing 2023-11-30-g6e07d12eea .. ..
23.36.4 4064fc6a 17-Jan-2024 STSTSM firmware showing 2023-11-30-g6e07d12eea .. ..
23.44.0 eb113390 25-Jan-2024 STSTSM firmware showing Unknown - No vitals available .. ..
23.44.3-msa 7-Feb-2024 No vitals available .. ..
24.4.0 0fe780c9 15-Mar-2024 No vitals available .. ..
24.12.3 1feaff3a May-2024 No vitals available .. ..

Devices and Alerts

Devices and Alerts will show up in the device vitals API (e.g. /api/device/vitals). Below are a list of the devices and alerts that I have seen. I'm looking for information on what these mean. Please submit an Issue or PR if you have more alerts or definitions we can add. The device details below are mostly educated guesses.

    import pypowerwall

    # Connect to Powerwall
    pw = pypowerwall.Powerwall(host,password,email,timezone)

    # Display Device Vitals
    print("Device Vitals:\n %s\n" % pw.vitals(True))

Example Output: here

Devices

Device ECU Type Description
STSTSM 207 Tesla Energy System
TETHC 224 Tesla Energy Total Home Controller - Energy Storage System (ESS)
TEPOD 226 Tesla Energy Powerwall
TEPINV 253 Tesla Energy Powerwall Inverter
TESYNC 259 Tesla Energy Synchronizer
TEMSA 300 Tesla Backup Switch
PVAC 296 Photovoltaic AC - Solar Inverter
PVS 297 Photovoltaic Strings
TESLA x Internal Device Attributes
NERUIO x Wireless Revenue Grade Solar Meter

STSTSM - Tesla Energy System

TETHC - Tesla Energy Total Home Controller

TEPOD - Tesla Energy Powerwall

TEPINV - Tesla Energy Powerwall Inverter

TESYNC - Tesla Energy Synchronizer

TEMSA - Tesla Backup Switch

PVAC - Photovoltaic AC - Solar Inverter

PVS - Photovoltaic Strings

NEURIO - Wireless Revenue Grade Solar Meter

TESLA - Internal Device Attributes

Glossary

This is an unofficial list of terms that are seen in Powerwall responses and message.

Credits and References

Other Tools and Similar Projects

Citation

If you wish to cite this project, please use:

@software{pyPowerwall,
  author = {Cox, Jason A.},
  title = {pyPowerwall: Python API for Tesla Powerwall and Solar Energy Data.},
  year = {2023},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/jasonacox/pypowerwall}},
}