Add support for Tesla Powerwall

Hi Rob,

Sorry to jump on the replies to angusc, but i’ve been trying to get my integration working too and think i’m very close, but not quite there! haha.

I have copied your files above and added my credentials to configuration.yaml, but am getting the below error. Any ideas?

Logger: homeassistant.config_entries
Source: config_entries.py:365
First occurred: 14:58:14 (1 occurrences)
Last logged: 14:58:14

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

Hi @beardboy69

I get this error in my logs as well! :

Logger: homeassistant.config_entries
Source: config_entries.py:365
First occurred: 16:06:13 (1 occurrences)
Last logged: 16:06:13

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

But when I now look in the Developer/template section I now see the required Services and also my automations are working! Have you tried to see if you have the same services there:


image

Im using most of @BruceH5200 Tesla_PowerWall automations from his shared site: bruces_homeassistant_config/packages/systems/tesla_powerwall at master · B-Hartley/bruces_homeassistant_config · GitHub

Thanx @robjones Did you make any changes to those other files since you posted them or are they still the same in your working configuration? Yes I got the User name and password in my dedicated tesla_gateway.yaml file.

@BruceH5200

Hi Bruce, so finally after a very long time of following your set up and now that I have control over the PW2 I would like to ask for your guidance on the following Power Wall variables that your automations require and which I have set up as input fields. What is the normal user interface requirements for filling in these variable and at what time each day/evening do you do that Should the PW max overnight Charge input me an automated value or manual input?

I also added an additional switch to your configuration to allow me to manually switch back to TOU/TBC and 50%, which is what I used this morning at 04:00 to over-ride the automations and put some charge in to the PW before 04:30.

I see that at certain times the PW2 is switched in to Self-Powered mode with a 5% reserve level. This is based your automations;

automation_calculate_max_powerwall_charge_price.yaml
automation_max_powerwall_charge_price_sun_up.yaml
automation_powerwall_set_reserve_and_mode_based_on_time.yaml

Yesterday afternoon my PW switched to Self-Powered @ 5% and remained there right through the night. When I checked at 04:00 this morning it had not charges but then I noticed that the PW max overnight charge was set at 0% so probably the reason for that.
I also notice that the PW max Overnight Charge is automatically reset to 0% every day. So I wondered if the idea is that I need to set this level of charge before I go to bed each night?

image

image

Thanx once again Bruce and everyone else on the forum for sharing and guiding!

Thanks - just checked and i do have the services for the Tesla_Gateway showing in there, so getting closer!

I still have the ‘Failed to set up’ message as posted though, so will look at copying @BruceH5200 automations over to see if that get’s things going.

I see yours is now working - what did you do to get it going in the end?

Thanks!

Hi matey,

ignore the set up error and go to the developer services menu and try to send a command…if its like mine it will work and switch the PW modes!

I still got this error in the integrations and the logs:
image

1 Like

Magic, cheers angus! That does appear to be working.

I’ll see if i can get a nice dashboard knocked up for it now and some automations from Bruce. :smiley:

1 Like

Im just trying to work out the best automation from Bruce that i need.

I just want the PW to charge from 23:45 and switch back Time based consumption at 5am?

I cant appear to find a simple solution? - My automations dont appear to be working either (which is just seting the battery reserve to 90% at 23:45 and back to 10% at 5:30 (if i set it via the dev menu, this works)

Hi Rob,

Im sure there is a million ways to skin this cat :slight_smile: Bruce’s automations are quite complex and using lots of other sensors and binary_sensors.

A simple way to do what you want would be to create a toggle helper switch, I called mine “pw2_tou” to allow me to manually put the PW in to manual charge over ride.

Then create this automation in the UI:

alias: Powerwall: Turn ON TOU and 90% Back-up mode
description: ""
trigger:
  - platform: state
    entity_id:
      - input_boolean.pw2_tou
    from: "off"
    to: "on"
  - platform: time
    at: "23:45:00"
condition: []
action:
  - service: tesla_gateway.set_operation
    data:
      real_mode: autonomous
      backup_reserve_percent: 90
  - service: input_boolean.turn_on
    data: {}
    target:
      entity_id: input_boolean.pw2_tou
mode: single

And this second automation to turn it off and back in to back_up mode:

alias: Powerwall: Turn OFF  TOU and switch to Back-up 10% Reserve
description: ""
trigger:
  - platform: state
    entity_id:
      - input_boolean.pw2_tou
    from: "on"
    to: "off"
  - platform: time
    at: "05:30:00"
condition: []
action:
  - service: tesla_gateway.set_operation
    data:
      real_mode: backup
      backup_reserve_percent: 10
  - service: input_boolean.turn_off
    data: {}
    target:
      entity_id: input_boolean.pw2_tou
mode: single
1 Like

Really helpful :slight_smile: thanks mate - the bit i was missing was the mode to change it back to Time based control - didnt reallise it was “autonomous” i tried all sorts haha

Congratulations everyone! yours is working and mine is not (yet). I’ve just trawled through 290 posts and am struggling to get a definitive set of “instructions”. Given that we now appear to have a working solution, might someone be good enough to share a complete set up? I’d really appreciate it and I am sure there are others like me!

OK I will try to make it as easy as I can remember:

  1. Install or you must already have installed the built-in Terminal editor available from the Integrations page. /config/integrations. Setting up terminal can be a challenge and you will need to search for how to do that if you are struggling with the public/private key set-up.

1a) install teslapy following these instructions:

  1. Follow these instruction to install teslpy in to your HA machine using the Terminal commands listed below (after the “filename.py” example below). Create this filename.py file that you will run in the terminal to create the cache.json file (dont forget to enter your Tesla account email on the second line):

filename.py:

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()

Continue with the Terminal window to now execute the filename.py using these instructions: create the cache.json file that requires the token from the Tesla Token app. Add support for Tesla Powerwall - #271 by robjones

  1. Install “tesla_gateway” from the HACs store restart HA.

  2. Install tesla_gateway in the integrations of HA, Restart HA.

  3. using the Editor function navigate the the “custom_components/tesla_gateway” folder and replace these files with the below from Robjones init.py, manifest.json, services.yaml OR you can simply open each file and replace its contents with the below:

init.py:

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

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

services.yaml:

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

Ensure that the cace.json file that you created in step 2 above is present in the /config root directory of HA. As good measure copy it to the /config/custom_components_tesla_gateway" folder. I think it only needs to be in the /config ROOT folder to work unless you added the redirection line in to the init.py file above.

  1. Restart HA. Check in the Integrations and you will probably see that the error for “tesla_gateway” failed to start.
    image

  2. Go to the Developers section in HA. then to Services and type in the search “set” scroll down and you should have two entries there for “tesla_gateway” being like below (if they are there then you have done it and running the commands from services should yield in the PW2 App changing states of TBC and Self-Consumption.

1 Like

I do feel your pain, this method is overly complex, error prone and doesn’t give much feedback if it is actually working, but is currently necessary as this integration hasn’t been completely setup for authentication, hence the workaround.

I do however have some good news, there is a completely rewritten HA integration that provides fully integrated control and monitoring of powerwall and other Tesla energy products which is about to be released for development testing, so please stay on this chat and I’ll ensure details are released when it is ready.

4 Likes

Following :slight_smile: - let me know if i can help do any of the testing - more than happy to help out and fully test it - looking forward to seeing this.

1 Like

Will need a lot of testing with different configurations so your offer of assistance will be important.

3 Likes

thanks for your response Mark, that is indeed good news and I look forward to seeing it evolve. I too will be more than happy to be a beta tester as appropriate!
Mike

1 Like

Happy to be a tester to, as getting nowhere fast at present with controlling the Powerwall 2

Did you follow the guide that I posted above?

I did, but its failing in Teslapy with a web service call, but the detail is obscured at the moment as to what is actually happening. Just double checking everything and trying to setup remote debugging.

You are only following this post and not any earlier, right? Looking at the file you posted it is an earlier version and not the one that I posted in my guide…