0
# Energy Product Management
1
2
Management functionality for Tesla energy products including Powerwall batteries and solar panel installations with status monitoring, configuration, and control capabilities.
3
4
## Capabilities
5
6
### Base Product Operations
7
8
Core functionality shared by all Tesla energy products including site data retrieval and historical data access.
9
10
```python { .api }
11
class Product(JsonDict):
12
def api(self, name, **kwargs):
13
"""
14
Endpoint request with site_id path variable.
15
16
Parameters:
17
- name (str): Endpoint name
18
- **kwargs: Endpoint parameters
19
20
Returns:
21
dict: API response
22
"""
23
24
def get_site_info(self):
25
"""
26
Retrieve current site/battery information.
27
28
Returns:
29
Product: Updated Product object
30
"""
31
32
def get_site_data(self):
33
"""
34
Retrieve current site/battery live status.
35
36
Returns:
37
Product: Updated Product object
38
"""
39
40
def command(self, name, **kwargs):
41
"""
42
Wrapper method for product command response error handling.
43
44
Parameters:
45
- name (str): Command name
46
- **kwargs: Command parameters
47
48
Returns:
49
str: Success message
50
51
Raises:
52
ProductError: If command fails
53
"""
54
```
55
56
### Historical Data Retrieval
57
58
Methods for retrieving historical energy data with various time periods and data types.
59
60
```python { .api }
61
def get_history_data(self, kind='energy', period='day', start_date=None,
62
end_date=None, installation_timezone=None, timezone=None):
63
"""
64
Retrieve historical status data for the energy product.
65
66
Parameters:
67
- kind (str): Telemetry type - 'backup', 'energy', 'power', 'self_consumption',
68
'time_of_use_energy', 'time_of_use_self_consumption' (default: 'energy')
69
- period (str): Time period - 'day', 'month', 'year', 'lifetime' (default: 'day')
70
- start_date (str): Start date in JSON format 'YYYY-MM-DDTHH:MM:SS.sssZ' (optional)
71
- end_date (str): End date in JSON format 'YYYY-MM-DDTHH:MM:SS.sssZ' (optional)
72
- installation_timezone (str): Timezone of installation location (optional)
73
- timezone (str): Timezone in JSON format e.g. 'Europe/Brussels' (optional)
74
75
Returns:
76
dict: Historical data response
77
"""
78
79
def get_calendar_history_data(self, kind='energy', period='day', start_date=None,
80
end_date=None, installation_timezone=None,
81
timezone=None, tariff=None):
82
"""
83
Retrieve calendar-based historical status data for the energy product.
84
85
Parameters:
86
- kind (str): Telemetry type - 'backup', 'energy', 'power', 'self_consumption',
87
'time_of_use_energy', 'time_of_use_self_consumption', 'savings', 'soe' (default: 'energy')
88
- period (str): Time period - 'day', 'month', 'year', 'lifetime' (default: 'day')
89
- start_date (str): Start date in JSON format 'YYYY-MM-DDTHH:MM:SS.sssZ' (optional)
90
- end_date (str): End date in JSON format 'YYYY-MM-DDTHH:MM:SS.sssZ' (optional)
91
- installation_timezone (str): Timezone of installation location for 'savings' (optional)
92
- timezone (str): Timezone in JSON format e.g. 'Europe/Brussels' (optional)
93
- tariff: Tariff format for 'savings' data type (optional)
94
95
Returns:
96
dict: Calendar historical data response
97
"""
98
```
99
100
### Powerwall Battery Management
101
102
Comprehensive Powerwall battery control including operation modes, backup settings, grid import/export configuration, and time-of-use tariff management.
103
104
```python { .api }
105
class Battery(Product):
106
def set_operation(self, mode):
107
"""
108
Set battery operation mode.
109
110
Parameters:
111
- mode (str): Operation mode - 'self_consumption', 'backup', or 'autonomous'
112
113
Returns:
114
str: Success message
115
"""
116
117
def set_backup_reserve_percent(self, percent):
118
"""
119
Set the minimum backup reserve percent for the battery.
120
121
Parameters:
122
- percent (int): Backup reserve percentage (0-100)
123
124
Returns:
125
str: Success message
126
"""
127
128
def set_import_export(self, allow_grid_charging=None, allow_battery_export=None):
129
"""
130
Set the battery grid import and export settings.
131
132
Parameters:
133
- allow_grid_charging (bool): Whether charging from the grid is allowed (optional)
134
- allow_battery_export (bool): Whether export to the grid is allowed (optional)
135
136
Note:
137
This endpoint returns an empty response instead of a result code.
138
"""
139
```
140
141
### Tariff Management
142
143
Powerwall time-of-use tariff configuration for optimizing energy costs and grid interaction.
144
145
```python { .api }
146
def get_tariff(self):
147
"""
148
Get the current tariff rate data.
149
150
Returns:
151
dict: Tariff configuration data
152
"""
153
154
def set_tariff(self, tariff_data):
155
"""
156
Set the tariff rate data.
157
158
Parameters:
159
- tariff_data (dict): Tariff configuration data (can be created with create_tariff)
160
161
Returns:
162
str: Success message
163
"""
164
165
@staticmethod
166
def create_tariff(default_price, periods, provider, plan):
167
"""
168
Create a correctly formatted dictionary of tariff data.
169
170
Parameters:
171
- default_price (BatteryTariffPeriodCost): Price of the background time period
172
- periods (list[BatteryTariffPeriod]): List of time periods with higher prices
173
- provider (str): Name of the energy provider
174
- plan (str): Name of the energy plan
175
176
Returns:
177
JsonDict or None: Formatted tariff data dictionary, or None if periods overlap incorrectly
178
"""
179
```
180
181
### Solar Panel Management
182
183
Solar panel installation monitoring and data retrieval functionality.
184
185
```python { .api }
186
class SolarPanel(Product):
187
"""
188
Solar panel class - inherits all methods from Product base class.
189
190
Provides access to solar panel installations with get_site_data() for current
191
generation data and get_history_data() for historical solar production data.
192
"""
193
```
194
195
## Tariff Data Types
196
197
Specialized data types for managing Powerwall time-of-use tariff configurations.
198
199
```python { .api }
200
class BatteryTariffPeriodCost:
201
"""
202
Represents the costs of a tariff period.
203
204
Attributes:
205
- buy (float): Import price per kWh
206
- sell (float): Export price per kWh
207
- name (str): Period name - 'ON_PEAK', 'PARTIAL_PEAK', 'OFF_PEAK', or 'SUPER_OFF_PEAK'
208
"""
209
210
class BatteryTariffPeriod:
211
"""
212
Represents a time period of a tariff.
213
214
Attributes:
215
- cost (BatteryTariffPeriodCost): Cost object for this time period
216
- start (datetime.time): Start time of the period
217
- end (datetime.time): End time of the period
218
"""
219
```
220
221
## Usage Examples
222
223
### Basic Powerwall Control
224
225
```python
226
import teslapy
227
228
with teslapy.Tesla('elon@tesla.com') as tesla:
229
batteries = tesla.battery_list()
230
if batteries:
231
battery = batteries[0]
232
233
# Get current battery status
234
battery.get_site_data()
235
print(f"Battery level: {battery['percentage_charged']}%")
236
print(f"Power: {battery['battery_power']} W")
237
print(f"Grid status: {battery['grid_status']}")
238
239
# Set operation mode to self-consumption
240
battery.set_operation('self_consumption')
241
242
# Set backup reserve to 20%
243
battery.set_backup_reserve_percent(20)
244
```
245
246
### Grid Import/Export Configuration
247
248
```python
249
# Allow grid charging but disable battery export
250
battery.set_import_export(allow_grid_charging=True, allow_battery_export=False)
251
252
# Disable grid charging, allow battery export
253
battery.set_import_export(allow_grid_charging=False, allow_battery_export=True)
254
255
# Allow both grid charging and battery export
256
battery.set_import_export(allow_grid_charging=True, allow_battery_export=True)
257
```
258
259
### Time-of-Use Tariff Configuration
260
261
```python
262
import teslapy
263
import datetime
264
265
# Create tariff period costs
266
off_peak_cost = teslapy.BatteryTariffPeriodCost(buy=0.10, sell=0.05, name='OFF_PEAK')
267
on_peak_cost = teslapy.BatteryTariffPeriodCost(buy=0.25, sell=0.15, name='ON_PEAK')
268
269
# Define time periods
270
morning_peak = teslapy.BatteryTariffPeriod(
271
cost=on_peak_cost,
272
start=datetime.time(hour=7),
273
end=datetime.time(hour=10)
274
)
275
276
evening_peak = teslapy.BatteryTariffPeriod(
277
cost=on_peak_cost,
278
start=datetime.time(hour=17),
279
end=datetime.time(hour=21)
280
)
281
282
# Create and set tariff
283
tariff_data = teslapy.Battery.create_tariff(
284
default_price=off_peak_cost,
285
periods=[morning_peak, evening_peak],
286
provider="Local Utility",
287
plan="Time of Use"
288
)
289
290
if tariff_data:
291
battery.set_tariff(tariff_data)
292
print("Tariff configured successfully")
293
else:
294
print("Failed to create tariff - check time period overlaps")
295
```
296
297
### Historical Energy Data
298
299
```python
300
import time
301
302
# Get today's energy data
303
today = time.strftime('%Y-%m-%dT%H:%M:%S.000Z')
304
yesterday = time.strftime('%Y-%m-%dT%H:%M:%S.000Z',
305
time.gmtime(time.time() - 86400))
306
307
# Get daily energy history
308
energy_data = battery.get_history_data(
309
kind='energy',
310
period='day',
311
start_date=yesterday,
312
end_date=today,
313
timezone='America/Los_Angeles'
314
)
315
316
print(f"Energy consumption: {energy_data}")
317
318
# Get power data with calendar history
319
power_data = battery.get_calendar_history_data(
320
kind='power',
321
period='day',
322
timezone='America/Los_Angeles'
323
)
324
325
print(f"Power usage: {power_data}")
326
```
327
328
### Solar Panel Monitoring
329
330
```python
331
with teslapy.Tesla('elon@tesla.com') as tesla:
332
solar_panels = tesla.solar_list()
333
if solar_panels:
334
solar = solar_panels[0]
335
336
# Get current solar generation
337
solar.get_site_data()
338
print(f"Current solar power: {solar['solar_power']} W")
339
print(f"Grid power: {solar['grid_power']} W")
340
341
# Get solar energy history
342
solar_history = solar.get_history_data(
343
kind='energy',
344
period='month',
345
timezone='America/Los_Angeles'
346
)
347
print(f"Monthly solar generation: {solar_history}")
348
```
349
350
### Combined Energy System Monitoring
351
352
```python
353
with teslapy.Tesla('elon@tesla.com') as tesla:
354
batteries = tesla.battery_list()
355
solar_panels = tesla.solar_list()
356
357
if batteries and solar_panels:
358
battery = batteries[0]
359
solar = solar_panels[0]
360
361
# Get current status of both systems
362
battery.get_site_data()
363
solar.get_site_data()
364
365
# Calculate net energy flow
366
battery_power = battery['battery_power']
367
solar_power = solar['solar_power']
368
grid_power = battery.get('grid_power', 0)
369
370
print(f"Solar generation: {solar_power} W")
371
print(f"Battery power: {battery_power} W")
372
print(f"Grid power: {grid_power} W")
373
374
if grid_power < 0:
375
print(f"Exporting {abs(grid_power)} W to grid")
376
elif grid_power > 0:
377
print(f"Importing {grid_power} W from grid")
378
else:
379
print("No grid interaction")
380
```
381
382
### Error Handling
383
384
```python
385
try:
386
battery.set_operation('invalid_mode')
387
except teslapy.ProductError as e:
388
print(f"Product command failed: {e}")
389
except teslapy.HTTPError as e:
390
print(f"API error: {e}")
391
392
# Check if battery is available before commands
393
try:
394
battery.get_site_info()
395
battery.set_backup_reserve_percent(25)
396
except teslapy.HTTPError as e:
397
if "offline" in str(e).lower():
398
print("Battery system is offline")
399
else:
400
print(f"Unexpected error: {e}")
401
```
402
403
### Batch Operations
404
405
```python
406
# Configure multiple batteries
407
with teslapy.Tesla('elon@tesla.com') as tesla:
408
batteries = tesla.battery_list()
409
410
for i, battery in enumerate(batteries):
411
print(f"Configuring battery {i+1}...")
412
413
# Set consistent operation mode
414
battery.set_operation('self_consumption')
415
416
# Set backup reserve based on battery index
417
reserve_percent = 20 + (i * 5) # 20%, 25%, 30%, etc.
418
battery.set_backup_reserve_percent(reserve_percent)
419
420
# Get current status
421
battery.get_site_data()
422
print(f"Battery {i+1}: {battery['percentage_charged']}% charged, "
423
f"{reserve_percent}% reserve")
424
```