Add support for Tesla Powerwall

I tried setting this up from scratch on a brand new HA setup.

I first had the issue where the integration would not load, now i get an error saying it could not be set up.

I had to manually add username and password in config.yaml

now i get this below:

i have not been able to run the script to create a cache.json as my hacs runs on a virtual machine with its own ha os.

any help greatly appreciated

Logger: homeassistant.config_entries
Source: config_entries.py:335
First occurred: 00:05:18 (1 occurrences)
Last logged: 00:05:18

Error setting up entry Tesla Gateway for tesla_gateway
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 335, in async_setup
    result = await component.async_setup_entry(hass, self)
AttributeError: module 'custom_components.tesla_gateway' has no attribute 'async_setup_entry'

@estebanp you seem to have a good idea on how to get this custom component functional, albeit with the hack to get the cache.json in the right location.

That said, I am still struggling to get this working for me.

Could I ask you to post your current init.py and any other changes you have made to get things functional and I would then be happy to load a PR/ fork in github to get something back to functional.

Thanks.

does this still work? iā€™m trying to set up something similar (i donā€™t necessarily care about having HA control it as much as just making sure iā€™m in self-consumption vs TBC at the times i want to be)ā€¦i have teslaPy working on its own, but obviously the cron doesnā€™t work because i donā€™t have a separate authorization for it. how often do you have to reset the auth?

I am looking to do this on my Powerwall but canā€™t work out what works or how to do it. Does anyone have a write up on this? Iā€™d like to be able to call something from HA but Iā€™m happy to just get anything that changes the Backup percentage.

This guy has shared his configuration in got hub, he has a power wall section under his packages/ folder which might be worth looking atā€¦

Iā€™ve spent the morning reading this post and looking and trying his code. Still no go. Does anyone know if tesla-gateway-ha-component still works? @BruceH5200

Iā€™m still using the coop Tesla gateway.
I think I had to use teslapy to manually create a cache file for the login keys.

I have gotten this working and have done a bit of a writeup here.

I also had to fork the custom component to get it to load, My changes are some instructions are here:

I recommend getting the teslapy library working first from the command line, you need to get cache.json anyway and changing your PW settings from the command line first and they getting the HA custom component working.

1 Like

Did you/can you run TeslaPy on Home Assistant or on another box?

Yes teslapy works on your homeassistant box, you either need to login at the command line or use the ssh add-on. Or you can run teslapy on another box and then copy the cache.json file over to your homeassistant box custom_components/tesla-gateway folder.

1 Like

So I have copied over the files to custom_components/teslapy and have run the command pip install -r requirements which resulted in it installing a lot of the files but it looks like it fails installing selenium. Any ideas? Iā€™m sorry for the questions but Iā€™m not a programmer but a dabbler. I have also just tried on a seperate Ubuntu box which gets me to a log on prompt but after I type in my email address it just hangs.
Iā€™m getting fed up with waking up in the morning with no cheap electricity because Tesla has got the forecast wrong!

Iā€™m not promising anything, as I donā€™t have a huge amount of time for it, but I started to work on updating the carboncoop integration at the weekend. If I get round to finishing it, the aim will be to have as much as possible taken care of in the UI config flow. If thatā€™s not possible, as a first step, Iā€™ll at least try and make it accept the refresh token through the UI so it can be set up without needing to edit any files manually. Iā€™ll post back here if I make any progress.

5 Likes

That would be fantastic. If i can help in anyway, please let me know, I would be more than happy to test, etc. Thank you. Any assistance would be greatly appreciated.

@markpurcell @craigrouse @BruceH5200 - Iā€™ve managed to get teslapy working. Well I have a cache.json file :smiley:

How do I change the backup reserve from the command line to test it?

I canā€™t seem to work that out. Can you give me an example that I can refer to or do I need some sort or script?

Iā€™m not sure what to do with the cache.json file.

Create an automation, which you can then run manually to test. Under that Actions part set the following.

action type set to ā€˜Call serviceā€™

service set to ā€˜Tesla Gateway: set_operationā€™

service data set to something like this;

service: tesla_gateway.set_operation
data: null
real_mode: self_consumption
backup_reserve_percent: 15

You can set the real_mode to either ā€˜self_consumptionā€™ (Self-Powered), ā€˜autonomousā€™ (Time-Based Control) or ā€˜backupā€™ (Backup).

Backup mode no longer exists in the Tesla app which means that if you set it to backup mode, then go in to the app, it will reset it back to Self-Powered mode. The only way to check that it goes to Backup Mode is to look at power consumption via a different app. I have MyEnergi devices so can check charging of the battery via the MyEnergi app. This issue will catch you out if you check your Tesla app halfway through the night!

Also if you set the real_mode to backup then it doesnā€™t matter what backup_reserve_percent is set to as it will always put it to 100.

Why would you use all these variations? Self-Powered only charges the powerwall at 1.7kW. Autonomous charges the battery at 5kW. Backup charges the battery at 3.3kW. If you are on a tariff like Octopus Go then you only have 4 hours of off-peak electric. 1.7kW x 4 hours = 6.8kW total recharge, a half full (or empty!) battery.

Backup mode charges at a sensible charge of 3.3kW but over 4 hours will only charge 13.2kW, so can sometime charge just short of 100% dependant on how much you have depleted the battery the previous day. However if you set the real_mode to backup then it doesnā€™t matter what backup_reserver_percent is set to in the configuration, it will always set to 100.

For both self_consumption and autonomous the backup_reserve_percent can be set to the desired amount.

Autonomous mode charges up at 5kW (dependant on the Tesla forecast). I use autonomous mode if I am trying to charge to a percentage between 50 and 100, as up to 50% and 100% I can use either other mode to charge accurately to these levels. Autonomous is the fastest so will charge more than self_consumption but if i set the reservce to 75%, the Powerwall ā€œforecastingā€ may decide that I need 90%, so although I have the reserve set to 75% in this example the battery will charge to 90%. Also fastest might not be best for the batteries long term health!

If you want to take this further then you can intergrate this with a solar forcast, and then automate your battery charge level over night dependant on the solar forecast. I stress the solar forecasts are only forecasts and can occationally be wildly in accurate. I find in the occasion that they do under or over estimate power generation, that I can change my usage. The benefit of integrating solar forecasting is that I am not changing the charge level every day in Home Assistant.

Hope this helps. Tesla have made this much harder than necessary, but at least it is still possible thanks to the dev that started this! I wish they just added this functionality to the app in the first place!

1 Like

I havenā€™t got that far yet - That to me is the easy part. All I have running is teslapy on another Ubuntu machine with a cache.json file.

Do I need teslapy on home assistant? The tesla gateway code seems to refer to it (import teslapy).

Is the tesla gateway code correct on the coop github (itā€™s 15 months old I think) and there appears to be multiple edits of it on this thread.

In HACS I canā€™t find reference to Tesla gateway anywhere.

So far I have done:

  1. Installed a fresh copy of Ubuntu on a bare machine.
  2. Installed teslapy (pip -install teslapy)
  3. Use the cli.py script (included with teslapy) to get the cache.json file and view the details of the powerwall (pyhton3 cli.py -e email@address -b

Have a look at this python code you can run from the command line with teslapy:

tesla_77pct.py:

#!/usr/bin/env python3
import teslapy
with teslapy.Tesla("[email protected]") as tesla:
        tesla.fetch_token()
        battery = tesla.battery_list()[0]
        battery.set_backup_reserve_percent(77)
        print(battery) # should print battery status once successfully authenticated
        print(battery.get_battery_data())

Then run from the command line:
$ python3 ./tesla_77pcy.pt

:laughing: Thanks Mark.

I have just managed to work out exactly that!

My code is nearly identical - even down to the filename format (backup75.py).

I think for now Iā€™m just going to stick this in a crontab until thereā€™s a cleaner way of doing this within HA.

Thanks to everyone for their help.

1 Like

As I couldnā€™t get it to work on Home Assistant I have managed to put it on a spare Raspberry Pi (an old model B) and it works fine with Crontab.

Iā€™ll wait until tesla_gateway integrates better with HA before messing with my HA server too much.

Looking at my setup on Home Assistant I have the following.

  1. Create the folder structure under config directory as follows. Config\custom_components\tesla_gateway

  2. Create the following files in the tesla_gateway directory and add the following config

__init__.py
manifest.json
services.yaml

__init__.py with the following code in it

"""
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

manifest.json with the following code in it

{
    "domain": "tesla_gateway",
    "name": "Tesla Gateway",
    "documentation": "",
    "dependencies": [],
    "codeowners": [],
    "requirements": ["teslapy==2.3.0"],
    "version": "0.1.0"
}

services.yaml with the following code in it

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
  1. Add the following code in to the configuration.yaml with your Tesla username and password in
#Tesla Powerwall 2
tesla_gateway:
  username: "Tesla email address here"
  password: "Tesla password here"
  1. Create cache.json file by following estebanp post from step 3 Add support for Tesla Powerwall - #205 by estebanp. Make sure this file is saved in the config root directory.

  2. Create automations that call service. Follow my previous post Add support for Tesla Powerwall - #238 by pnut

2 Likes