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.
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.
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
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!
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:
- Installed a fresh copy of Ubuntu on a bare machine.
- Installed teslapy (pip -install teslapy)
- 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
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.
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.
-
Create the folder structure under config directory as follows. Config\custom_components\tesla_gateway
-
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
- 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"
-
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.
-
Create automations that call service. Follow my previous post Add support for Tesla Powerwall - #238 by pnut
@pnut - Thank you - I followed your instructions and all is working on HA now. Many thanks to everyone for their help.
Incidentally, I have just attempted to buy a second Powerwall and there is now a 12 month waiting list and the price of them has gone up by £1000.
In the tesla_login.py file I had to change:
window.loaded += on_loaded
to
window.events.loaded += on_loaded
Due to a deprecation in pwebview. Maybe I’m using too recent of versions.
[pywebview] loaded event is deprecated and will be removed in 4.0. Use events.loaded instead.
It works!!! Finally setting my mode dynamically. Thanks for all your work here!
Does anyone know if when StormWatch mode is enabled, what we set reserve and Operations mode wise doesn’t matter? That it will ignore our settings unless we turn off StormWatch mode. My worry was that StormWatch mode engages, and then when I dynamically set the mode and charge in an auotmation, it would interfere with StormWatch. But from memory I think it doesn’t matter what the other settings are for Op mode or charge level. It will ignore it if a StormWatch is engaged (which is what I want). Other way around this would be in the automation detect if StormWatch is active (if it is do nothing), but I see no way to detect StormWatch mode.
Thanks to all who’ve posted info on getting this working so far!
I’m very new to HA, but working my way through gradually.
I think i’ve got the integration setup, i’ve put the json file in the config root and all appears to be correct, however, i’m getting the below after rebooting HA.
2022-07-25 11:40:04 WARNING (SyncWorker_2) [homeassistant.loader] We found a custom integration tesla_gateway which has not been tested by Home Assistant. This component might cause stability problems, be sure to disable it if you experience issues with Home Assistant
2022-07-25 11:40:09 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry Tesla Gateway for tesla_gateway
AttributeError: module ‘custom_components.tesla_gateway’ has no attribute ‘async_setup_entry’
Does anyone have any ideas on this please?
Thanks you for that I got mine working like a dream.
If some one could help.
I want to set an automation at 10 pm each night to set the reserve value to what ever is left in the battery. So I can use it later the next morning.
Basically the action is what I can’t work out
action:
Set
Tesla Gateway: set_reserve
backup_reserve_percent:
to equal
Get Value of
sensor.powerwall_charge
( be nice to set the value (sensor.powerwall_charge - 5))
I do something similar.
alias: Battery SOC Forecast
description: ""
trigger:
- platform: state
entity_id:
- sensor.soc_batt_forecast
condition: []
action:
- service: tesla_gateway.set_reserve
data:
backup_reserve_percent: "{{states('sensor.soc_batt_forecast')|int(0)-5}}"
mode: single
Thank you works a charm.
I am going to save every last cent I can of my power bill.
Have a look at EMHASS add-on: An energy management optimization add-on for Home Assistant OS and supervised, it is a bit complex to setup but it takes power optimisation to the next level, including solar, battery and variable buy/sell prices.
Would anyone be willing and able to create this file for me? I’m not a Linux user and find that a bit daunting to be honest, plus I don’ t have a machine to do it on and don’t fancy messing with my RPi 4 as its running my HA server.
From what I understand about the process you would only need my e-mail address for the Tesla Account?
But I would be eternally grateful if anyone can assist, please DM me for details.
P.S. I finally got my PW installed this week after waiting for 12 months for delivery, I have the automations from @BruceH5200 so I’m just short of this file to get the integration to work. Currently after installing the tesla_custom integration and using the SS Token the integration fails to set up. Which I’m hoping is just because of these changes that are required and the file generated in step 4) above…