Python Dependencies for Tesla Powerwall2

Tesla Powerwall2

Since the Dec 2020 update OAUTH2 is mandatory for accessing the PW2 API even from the home network. This is part of Tesla move of all the APIs to cloud. 

https://pypi.org/project/tesla-powerwall/



Install

sudo apt update sudo apt upgrade python --version sudo apt install python-virtualenv apt install python3-virtualenv apt autoremove sudo apt update sudo apt upgrade cd pw .pw/bin/activate pip install Flask sudo apt update curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python get-pip.py pip install tesla_powerwall cat app.py chmod a+x app.py


Try Service

sudo systemctl daemon-reload
sudo systemctl start pw.service
sudo systemctl status pw.service
journalctl -e -u pw


Files


/etc/systemd/system/pw.service

[Unit]
Description=PW2 web API
After=network.target [Service]
User=root
WorkingDirectory=/root/pw
# ExecStart=/root/pw/app.py # Orginal worked on Armbian
# New Ubuntu LTS needed an explicit call to Python3.8 and the app.py
ExecStart=/root/pw/bin/python3.8 app.py
Restart=always [Install]
WantedBy=multi-user.target

/root/pw/app.py

#!flask/bin/python from flask import Flask, jsonify from tesla_powerwall import Powerwall from tesla_powerwall import User app = Flask(__name__) @app.route('/pw2-api/get_pw_stat', methods=['GET']) def get_pw_stats(): powerwall = Powerwall("192.168.0.209") powerwall.login("secret", "agentx@foo.bar") meters = powerwall.get_meters() pw_stats = { 'SoC' : int(powerwall.get_charge()), 'SolarActive' : meters.solar.is_drawing_from(), 'BatteryPoweringHouse' : meters.battery.is_drawing_from(), 'GridInUse' : meters.site.is_drawing_from(), 'SolarPowerFlowkW' : meters.solar.get_power(), 'BatteryPowerFlowkW' : meters.battery.get_power(), 'GridPowerFlowkW' : meters.site.get_power(), 'HousePowerUsekW' : meters.load.get_power() } return jsonify({'pw_stats': pw_stats}) if __name__ == '__main__': app.run(host="0.0.0.0", port=5100, debug=True)