Add support for Tesla Powerwall

Ive just given that another go - shows as successfull - but again when i check the logs - i get the same error “Battery object is None”

I just cant seem to get to the bottom of it.

Did you want to drop your init.py manifest.json and services.yaml config in here and I can check against mine to see if there are any differences?

Sure

'''"""
Monitors and controls the Tesla gateway.
"""
import logging

import asyncio
import voluptuous as vol
import teslapy

from homeassistant.const import (
    CONF_USERNAME,
    CONF_PASSWORD
    )
import homeassistant.helpers.config_validation as cv

DOMAIN = 'tesla_gateway'

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Required(CONF_USERNAME): cv.string,
        vol.Required(CONF_PASSWORD): cv.string
    }),
}, extra=vol.ALLOW_EXTRA)

@asyncio.coroutine
def async_setup(hass, config):

    domain_config = config[DOMAIN]
    conf_user = domain_config[CONF_USERNAME]
    conf_password = domain_config[CONF_PASSWORD]
    
    tesla = teslapy.Tesla(domain_config[CONF_USERNAME])

    def get_battery():
        batteries = tesla.battery_list()
        if len(batteries) > 0:
            return batteries[0]
        else:
            return None

    @asyncio.coroutine
    async def set_operation(service):
        
        battery = await hass.async_add_executor_job(get_battery)
        if not battery:
            _LOGGER.warning('Battery object is None')
            return None

        await hass.async_add_executor_job(battery.set_operation, service.data['real_mode'])
        if 'backup_reserve_percent' in service.data:
            await hass.async_add_executor_job(battery.set_backup_reserve_percent, service.data['backup_reserve_percent'])

    hass.services.async_register(DOMAIN, 'set_operation', set_operation)

    @asyncio.coroutine
    async def set_reserve(service):
        
        battery = await hass.async_add_executor_job(get_battery)
        if not battery:
            _LOGGER.warning('Battery object is None')
            return None
            
        if 'backup_reserve_percent' in service.data:
            await hass.async_add_executor_job(battery.set_backup_reserve_percent, service.data['backup_reserve_percent'])

    hass.services.async_register(DOMAIN, 'set_reserve', set_reserve)

    return True
{
    "domain": "tesla_gateway",
    "name": "Tesla Gateway",
    "documentation": "",
    "dependencies": [],
    "codeowners": [],
    "requirements": ["teslapy==2.6.0"],
    "version": "0.1.0"
}
set_operation:
  description: >
    Changes operation mode
  fields:
    real_mode:
      description: Mode to set to the Tesla gateway.
      example: 'self_consumption, backup'
    backup_reserve_percent:
      description: Percentage of battery reserved for outages
      example: 40
set_reserve:
  description: >
    Changes battery reserve percent in self_consumption mode
  fields:
    backup_reserve_percent:
      description: Percentage of battery reserved for outages
      example: 70

hi @robjones

Please could you help me to know how you were able to generate the JSON file. I tried in my Supervisor HA Terminal but i cant seem to run the required commands.

I posted some screen shots of my errors in a post just up from here…

This may sound like a daft question - are you an iphone user? (i may have a simpler way to generate the json for you?)

hehehe no Im an Android user. I been trying to find out how to generate the cache.json but Im stuck at the HA Supervised terminal, it doesnt recognise the sudo commands.

image

ok there just type

pip install teslapy

youll then need to create the python script

so browse to your config directory and use

nano filename.py

and copy the python script you need.

you may then need to run

chmod +x filename.py

then you need to run it

python ./filename.py
1 Like

@robjones your config looks good. Only difference is that I created mine a while back with Teslapy 2.3.0, but dont think that would make any difference. Only other thing that I can think of is the automation. Below is my full automation configuration to set 50% reserve. You might want to bin the condition section which is my integrated solar forecast.

alias: Set 50% Powerwall Reserve
description: Set Powerwall to 50% reserve for power outages
trigger:
  - platform: time
    at: "00:30:00"
  - platform: time
    at: "01:30:00"
  - platform: time
    at: "02:30:00"
  - platform: time
    at: "03:30:00"
  - platform: time
    at: "04:30:00"
condition:
  - type: is_energy
    condition: device
    device_id: 96cc592a005e30f4fc4ab429ff501f68
    entity_id: sensor.energy_production_today
    domain: sensor
    above: 16.001
    below: 19
action:
  - service: tesla_gateway.set_operation
    data:
      service: tesla_gateway.set_operation
      data: null
      real_mode: self_consumption
      backup_reserve_percent: 50
mode: single

fell at the first hurdle:

image

Try

Apt get pip

image

I’ll have a look when I’m back in front of my computer but try

Apt install pip

Are you connecting directly onto HA through the console?

If so, this is prob where your going wrong, install terminal from addins

I have Feenck version of terminal installed. Maybe I will uninstall and revert back to the original version and try… I tried to get Putty to connect but it won’t accept the keys and refuses the connection. But I managed to get WinCP to shh in and connect with the private key and I can access the system files.

I will tackle again tomorrow and try uninstalling the current version of terminal:



Hi @robjones

OK I got the SSH config working and now installed tesla.py
now working out the script to run…

This is my script (I think its correct?) should I have added the Tesla web address and any refresh token in to this script before running it?

import webview
import teslapy

def custom_auth(url):
    result = ['']
    window = webview.create_window('Login', url)
    def on_loaded():
        result[0] = window.get_current_url()
        if 'void/callback' in result[0].split('?')[0]:
            window.destroy()
    window.loaded += on_loaded
    webview.start()
    return result[0]

with teslapy.Tesla('[email protected]', authenticator=custom_auth) as tesla:
    tesla.fetch_token()

But when I run the filename.py it does not open any Telsa Login web page? I see this in the Terminal window:

Is there any error in the script that I used?

Was this the correct place to install teslapy?:

Try this one

import teslapy
tesla = teslapy.Tesla('<insert email address here>')
if not tesla.authorized:
    print('Use browser to login. Page Not Found will be shown at success.')
    print('Open this URL: ' + tesla.authorization_url())
    tesla.fetch_token(authorization_response=input('Enter URL after authentication: '))
vehicles = tesla.vehicle_list()
print(vehicles[0])
tesla.close()
1 Like

Thanx Rob,

OK some progress, now I have generated the cache.JSON file and it was created in the /config folder. I then re installed the Tesla_custom integration and then restarted HA. Went to the /config/integrations and added the Tesla_Custom integration in to the UI. Entered my account e-mail and the token generated from Tesla Tokens and the integration said success.

I uninstalled everything and started again…it was there that I realise i had been installing “tesla_custom” rather than ‘tesla_gateway’… LOL
So after deleting all and restarting HA I installed tesla_gateway. Then followed the instructions again but still cant get t to log in on start up. I get this error in the logs:

Error during setup of component tesla_gateway
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/setup.py", line 235, in _async_setup_component
    result = await task
  File "/usr/local/lib/python3.10/asyncio/coroutines.py", line 124, in coro
    res = func(*args, **kw)
  File "/config/custom_components/tesla_gateway/__init__.py", line 66, in async_setup
    domain_config = config[DOMAIN]
KeyError: 'tesla_gateway'

Someone else earlier in this topic had the same issue and used a modified init.py which I tried but still the same error.
does anyone have any suggestions?

I actually have mine working now (Tesla have added my powerwall to the wrong account (my car which is in my company email etc) howver its working :slight_smile:

I would recommend you copying the __init__py and other files i posted earlier.

Dont forget you need the username and password in the configuration.yaml as well

tesla_gateway:
  username:
  password:
1 Like