tesla-fleet-api 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1046 @@
1
+ import aiohttp
2
+ from .exceptions import raise_for_status, TeslaFleetError
3
+ from typing import Any
4
+ from enum import StrEnum, IntEnum
5
+ from .const import SERVERS
6
+
7
+
8
+ # Based on https://developer.tesla.com/docs/fleet-api
9
+ class TeslaFleetApi:
10
+ """Class describing the Tesla Fleet API."""
11
+
12
+ server: str
13
+ session: aiohttp.ClientSession
14
+ headers: dict[str, str]
15
+ raise_for_status: bool
16
+
17
+ def __init__(
18
+ self,
19
+ session: aiohttp.ClientSession,
20
+ access_token: str,
21
+ use_command_protocol: bool = False,
22
+ region: str | None = None,
23
+ server: str | None = None,
24
+ raise_for_status: bool = True,
25
+ ):
26
+ """Initialize the Tesla Fleet API."""
27
+
28
+ self.session = session
29
+ self.use_command_protocol = use_command_protocol
30
+
31
+ if region and not server and region not in SERVERS:
32
+ raise ValueError(f"Region must be one of {", ".join(SERVERS.keys())}")
33
+ self.server = server or SERVERS.get(region)
34
+ self.raise_for_status = raise_for_status
35
+
36
+ self.headers = {
37
+ "Authorization": f"Bearer {access_token}",
38
+ "Content-Type": "application/json",
39
+ }
40
+
41
+ self.user = self.User(self)
42
+ self.charging = self.Charging(self)
43
+ self.partner = self.Partner(self)
44
+ self.vehicle = self.Vehicle(self)
45
+
46
+ async def find_server(self) -> None:
47
+ """Find the server URL for the Tesla Fleet API."""
48
+ for server in SERVERS.values():
49
+ self.server = server
50
+ try:
51
+ await self.user.region()
52
+ return
53
+ except TeslaFleetError.Base:
54
+ print(f"not {server}")
55
+ continue
56
+ raise TeslaFleetError.Base("Could not find a valid server.")
57
+
58
+ async def _request(
59
+ self,
60
+ method: str,
61
+ path: str,
62
+ data: dict[str:Any] | None = None,
63
+ json: dict[str:Any] | None = None,
64
+ params: dict[str:Any] | None = None,
65
+ ):
66
+ """Request data to the Tesla Fleet API with URL encoded data."""
67
+
68
+ if not self.server:
69
+ raise ValueError("Server was not set at init. Call find_server() first.")
70
+
71
+ if data:
72
+ data = {k: v for k, v in data.items() if v is not None}
73
+ if json:
74
+ json = {k: v for k, v in json.items() if v is not None}
75
+ if params:
76
+ params = {k: v for k, v in params.items() if v is not None}
77
+
78
+ async with self.session.request(
79
+ method,
80
+ f"{self.server}/{path}",
81
+ headers=self.headers,
82
+ data=data,
83
+ json=json,
84
+ params=params,
85
+ ) as resp:
86
+ if self.raise_for_status:
87
+ await raise_for_status(resp)
88
+ return await resp.json()
89
+
90
+ async def _get(self, path, params: dict[str:Any] | None = None):
91
+ """Get data from the Tesla Fleet API."""
92
+
93
+ if not self.server:
94
+ raise ValueError("Server was not set at init. Call find_server() first.")
95
+
96
+ if params:
97
+ params = {k: v for k, v in params.items() if v is not None}
98
+
99
+ async with self.session.get(
100
+ f"{self.server}/{path}",
101
+ params=params,
102
+ headers=self.headers,
103
+ ) as resp:
104
+ if self.raise_for_status:
105
+ await raise_for_status(resp)
106
+ return await resp.json()
107
+
108
+ async def _post(
109
+ self,
110
+ path,
111
+ data: dict[str:Any] | None = None,
112
+ json: dict[str:Any] | None = None,
113
+ params: dict[str:Any] | None = None,
114
+ ):
115
+ """Post data to the Tesla Fleet API with URL encoded data."""
116
+
117
+ if not self.server:
118
+ raise ValueError("Server was not set at init. Call find_server() first.")
119
+
120
+ if params:
121
+ params = {k: v for k, v in params.items() if v is not None}
122
+
123
+ async with self.session.post(
124
+ f"{self.server}/{path}",
125
+ headers=self.headers,
126
+ data=data,
127
+ json=json,
128
+ params=params,
129
+ ) as resp:
130
+ if self.raise_for_status:
131
+ await raise_for_status(resp)
132
+ return await resp.json()
133
+
134
+ async def _delete(self, path, params: dict[str:Any] | None = None):
135
+ """Delete data from the Tesla Fleet API."""
136
+
137
+ if not self.server:
138
+ raise ValueError("Server was not set at init. Call find_server() first.")
139
+
140
+ if params:
141
+ params = {k: v for k, v in params.items() if v is not None}
142
+
143
+ async with self.session.delete(
144
+ f"{self.server}/{path}",
145
+ headers=self.headers,
146
+ params=params,
147
+ ) as resp:
148
+ if self.raise_for_status:
149
+ await raise_for_status(resp)
150
+ return await resp.json()
151
+
152
+ async def status(self):
153
+ """This endpoint returns the string "ok" if the API is operating normally. No HTTP headers are required."""
154
+ async with self.session.get(f"{self.server}/status") as resp:
155
+ return await resp.text()
156
+
157
+ class Charging:
158
+ """Class describing the Tesla Fleet API charging endpoints."""
159
+
160
+ def __init__(self, parent):
161
+ self._get = parent._get
162
+ self._post = parent._post
163
+
164
+ async def history(
165
+ self,
166
+ vin: str | None = None,
167
+ startTime: str | None = None,
168
+ endTime: str | None = None,
169
+ pageNo: int | None = None,
170
+ pageSize: int | None = None,
171
+ sortBy: str | None = None,
172
+ sortOrder: str | None = None,
173
+ ) -> dict[str, Any]:
174
+ """Returns the paginated charging history."""
175
+ return await self._get(
176
+ "api/1/dx/charging/history",
177
+ {
178
+ vin: vin,
179
+ startTime: startTime,
180
+ endTime: endTime,
181
+ pageNo: pageNo,
182
+ pageSize: pageSize,
183
+ sortBy: sortBy,
184
+ sortOrder: sortOrder,
185
+ },
186
+ )
187
+
188
+ async def sessions(
189
+ self,
190
+ vin: str | None = None,
191
+ date_from: str | None = None,
192
+ date_to: str | None = None,
193
+ limit: int | None = None,
194
+ offset: int | None = None,
195
+ ) -> dict[str, Any]:
196
+ """Returns the charging session information including pricing and energy data. This endpoint is only available for business accounts that own a fleet of vehicles."""
197
+ return await self._get(
198
+ "api/1/dx/charging/sessions",
199
+ {
200
+ vin: vin,
201
+ date_from: date_from,
202
+ date_to: date_to,
203
+ limit: limit,
204
+ offset: offset,
205
+ },
206
+ )
207
+
208
+ class Partner:
209
+ """Class describing the Tesla Fleet API partner endpoints"""
210
+
211
+ def __init__(self, parent):
212
+ self._get = parent._get
213
+ self._post = parent._post
214
+
215
+ async def public_key(self, domain: str | None = None) -> dict[str, Any]:
216
+ """Returns the public key associated with a domain. It can be used to ensure the registration was successful."""
217
+ return await self._get(
218
+ "api/1/partner_accounts/public_key", data={domain: domain}
219
+ )
220
+
221
+ async def register(self, domain: str) -> dict[str, Any]:
222
+ """Registers an existing account before it can be used for general API access. Each application from developer.tesla.com must complete this step."""
223
+ return await self._post("api/1/partner_accounts", data={domain: domain})
224
+
225
+ class User:
226
+ """Class describing the Tesla Fleet API user endpoints"""
227
+
228
+ def __init__(self, parent):
229
+ self._get = parent._get
230
+
231
+ async def backup_key(self) -> dict[str, Any]:
232
+ """Returns the public key associated with the user."""
233
+ return await self._get("api/1/users/backup_key")
234
+
235
+ async def feature_config(self) -> dict[str, Any]:
236
+ """Returns any custom feature flag applied to a user."""
237
+ return await self._get("api/1/users/feature_config")
238
+
239
+ async def me(self) -> dict[str, Any]:
240
+ """Returns a summary of a user's account."""
241
+ return await self._get("api/1/users/me")
242
+
243
+ async def orders(self) -> dict[str, Any]:
244
+ """Returns the active orders for a user."""
245
+ return await self._get("api/1/users/orders")
246
+
247
+ async def region(self) -> dict[str, Any]:
248
+ """Returns a user's region and appropriate fleet-api base URL. Accepts no parameters, response is based on the authentication token subject."""
249
+ return await self._get("api/1/users/region")
250
+
251
+ class Vehicle:
252
+ """Class describing the Tesla Fleet API vehicle endpoints and commands."""
253
+
254
+ def __init__(self, parent):
255
+ self._get = parent._get
256
+ self._post = parent._post
257
+ self._delete = parent._delete
258
+ self.use_command_protocol = parent.use_command_protocol
259
+
260
+ class Trunk(StrEnum):
261
+ """Trunk options"""
262
+
263
+ FRONT: "front"
264
+ REAR: "rear"
265
+
266
+ async def actuate_trunk(
267
+ self, vehicle_tag: str | int, which_trunk: Trunk | str
268
+ ) -> dict[str, Any]:
269
+ """Controls the front or rear trunk."""
270
+ if self.use_command_protocol:
271
+ raise NotImplementedError("Command Protocol not implemented")
272
+ return await self._post(
273
+ f"api/1/vehicles/{vehicle_tag}/command/actuate_trunk",
274
+ json={which_trunk: which_trunk},
275
+ )
276
+
277
+ async def adjust_volume(
278
+ self, vehicle_tag: str | int, volume: float
279
+ ) -> dict[str, Any]:
280
+ """Adjusts vehicle media playback volume."""
281
+ if self.use_command_protocol:
282
+ raise NotImplementedError("Command Protocol not implemented")
283
+ if volume < 0.0 or volume > 11.0:
284
+ raise ValueError("Volume must a number from 0.0 to 11.0")
285
+ return await self._post(
286
+ f"api/1/vehicles/{vehicle_tag}/command/adjust_volume",
287
+ json={volume: volume},
288
+ )
289
+
290
+ async def auto_conditioning_start(
291
+ self, vehicle_tag: str | int
292
+ ) -> dict[str, Any]:
293
+ """Starts climate preconditioning."""
294
+ if self.use_command_protocol:
295
+ raise NotImplementedError("Command Protocol not implemented")
296
+ return await self._post(
297
+ f"api/1/vehicles/{vehicle_tag}/command/auto_conditioning_start"
298
+ )
299
+
300
+ async def auto_conditioning_stop(
301
+ self, vehicle_tag: str | int
302
+ ) -> dict[str, Any]:
303
+ """Stops climate preconditioning."""
304
+ if self.use_command_protocol:
305
+ raise NotImplementedError("Command Protocol not implemented")
306
+ return await self._post(
307
+ f"api/1/vehicles/{vehicle_tag}/command/auto_conditioning_stop"
308
+ )
309
+
310
+ async def cancel_software_update(
311
+ self, vehicle_tag: str | int
312
+ ) -> dict[str, Any]:
313
+ """Cancels the countdown to install the vehicle software update."""
314
+ if self.use_command_protocol:
315
+ raise NotImplementedError("Command Protocol not implemented")
316
+ return await self._post(
317
+ f"api/1/vehicles/{vehicle_tag}/command/cancel_software_update"
318
+ )
319
+
320
+ async def charge_max_range(self, vehicle_tag: str | int) -> dict[str, Any]:
321
+ """Charges in max range mode -- we recommend limiting the use of this mode to long trips."""
322
+ if self.use_command_protocol:
323
+ raise NotImplementedError("Command Protocol not implemented")
324
+ return await self._post(
325
+ f"api/1/vehicles/{vehicle_tag}/command/charge_max_range"
326
+ )
327
+
328
+ async def charge_port_door_close(
329
+ self, vehicle_tag: str | int
330
+ ) -> dict[str, Any]:
331
+ """Closes the charge port door."""
332
+ if self.use_command_protocol:
333
+ raise NotImplementedError("Command Protocol not implemented")
334
+ return await self._post(
335
+ f"api/1/vehicles/{vehicle_tag}/command/charge_port_door_close"
336
+ )
337
+
338
+ async def charge_port_door_open(self, vehicle_tag: str | int) -> dict[str, Any]:
339
+ """Opens the charge port door."""
340
+ if self.use_command_protocol:
341
+ raise NotImplementedError("Command Protocol not implemented")
342
+ return await self._post(
343
+ f"api/1/vehicles/{vehicle_tag}/command/charge_port_door_open"
344
+ )
345
+
346
+ async def charge_standard(self, vehicle_tag: str | int) -> dict[str, Any]:
347
+ """Charges in Standard mode."""
348
+ if self.use_command_protocol:
349
+ raise NotImplementedError("Command Protocol not implemented")
350
+ return await self._post(
351
+ f"api/1/vehicles/{vehicle_tag}/command/charge_standard"
352
+ )
353
+
354
+ async def charge_start(self, vehicle_tag: str | int) -> dict[str, Any]:
355
+ """Starts charging the vehicle."""
356
+ if self.use_command_protocol:
357
+ raise NotImplementedError("Command Protocol not implemented")
358
+ return await self._post(
359
+ f"api/1/vehicles/{vehicle_tag}/command/charge_start"
360
+ )
361
+
362
+ async def charge_stop(self, vehicle_tag: str | int) -> dict[str, Any]:
363
+ """Stops charging the vehicle."""
364
+ if self.use_command_protocol:
365
+ raise NotImplementedError("Command Protocol not implemented")
366
+ return await self._post(f"api/1/vehicles/{vehicle_tag}/command/charge_stop")
367
+
368
+ async def clear_pin_to_drive_admin(self, vehicle_tag: str | int):
369
+ """Deactivates PIN to Drive and resets the associated PIN for vehicles running firmware versions 2023.44+. This command is only accessible to fleet managers or owners."""
370
+ return await self._post(
371
+ f"api/1/vehicles/{vehicle_tag}/command/clear_pin_to_drive_admin"
372
+ )
373
+
374
+ async def door_lock(self, vehicle_tag: str | int) -> dict[str, Any]:
375
+ """Locks the vehicle."""
376
+ if self.use_command_protocol:
377
+ raise NotImplementedError("Command Protocol not implemented")
378
+ return await self._post(f"api/1/vehicles/{vehicle_tag}/command/door_lock")
379
+
380
+ async def door_unlock(self, vehicle_tag: str | int) -> dict[str, Any]:
381
+ """Unlocks the vehicle."""
382
+ if self.use_command_protocol:
383
+ raise NotImplementedError("Command Protocol not implemented")
384
+ return await self._post(f"api/1/vehicles/{vehicle_tag}/command/door_unlock")
385
+
386
+ async def erase_user_data(self, vehicle_tag: str | int) -> dict[str, Any]:
387
+ """Erases user's data from the user interface. Requires the vehicle to be in park."""
388
+ return await self._post(
389
+ f"api/1/vehicles/{vehicle_tag}/command/erase_user_data"
390
+ )
391
+
392
+ async def flash_lights(self, vehicle_tag: str | int) -> dict[str, Any]:
393
+ """Briefly flashes the vehicle headlights. Requires the vehicle to be in park."""
394
+ if self.use_command_protocol:
395
+ raise NotImplementedError("Command Protocol not implemented")
396
+ return await self._post(
397
+ f"api/1/vehicles/{vehicle_tag}/command/flash_lights"
398
+ )
399
+
400
+ async def guest_mode(
401
+ self, vehicle_tag: str | int, enable: bool
402
+ ) -> dict[str, Any]:
403
+ """Restricts certain vehicle UI functionality from guest users"""
404
+ if self.use_command_protocol:
405
+ raise NotImplementedError("Command Protocol not implemented")
406
+ return await self._post(
407
+ f"api/1/vehicles/{vehicle_tag}/command/guest_mode",
408
+ json={enable: enable},
409
+ )
410
+
411
+ async def honk_horn(self, vehicle_tag: str | int) -> dict[str, Any]:
412
+ """Honks the vehicle horn. Requires the vehicle to be in park."""
413
+ if self.use_command_protocol:
414
+ raise NotImplementedError("Command Protocol not implemented")
415
+ return await self._post(f"api/1/vehicles/{vehicle_tag}/command/honk_horn")
416
+
417
+ async def media_next_fav(self, vehicle_tag: str | int) -> dict[str, Any]:
418
+ """Advances media player to next favorite track."""
419
+ return await self._post(
420
+ f"api/1/vehicles/{vehicle_tag}/command/media_next_fav"
421
+ )
422
+
423
+ async def media_next_track(self, vehicle_tag: str | int) -> dict[str, Any]:
424
+ """Advances media player to next track."""
425
+ return await self._post(
426
+ f"api/1/vehicles/{vehicle_tag}/command/media_next_track"
427
+ )
428
+
429
+ async def media_prev_fav(self, vehicle_tag: str | int) -> dict[str, Any]:
430
+ """Advances media player to previous favorite track."""
431
+ return await self._post(
432
+ f"api/1/vehicles/{vehicle_tag}/command/media_prev_fav"
433
+ )
434
+
435
+ async def media_prev_track(self, vehicle_tag: str | int) -> dict[str, Any]:
436
+ """Advances media player to previous track."""
437
+ return await self._post(
438
+ f"api/1/vehicles/{vehicle_tag}/command/media_prev_track"
439
+ )
440
+
441
+ async def media_toggle_playback(self, vehicle_tag: str | int) -> dict[str, Any]:
442
+ """Toggles current play/pause state."""
443
+ return await self._post(
444
+ f"api/1/vehicles/{vehicle_tag}/command/media_toggle_playback"
445
+ )
446
+
447
+ async def media_volume_down(self, vehicle_tag: str | int) -> dict[str, Any]:
448
+ """Turns the volume down by one."""
449
+ return await self._post(
450
+ f"api/1/vehicles/{vehicle_tag}/command/media_volume_down"
451
+ )
452
+
453
+ async def navigation_gps_request(
454
+ self, vehicle_tag: str | int, lat: float, lon: float, order: int
455
+ ) -> dict[str, Any]:
456
+ """Start navigation to given coordinates. Order can be used to specify order of multiple stops."""
457
+ if self.use_command_protocol:
458
+ raise NotImplementedError("Command Protocol not implemented")
459
+ return await self._post(
460
+ f"api/1/vehicles/{vehicle_tag}/command/navigation_gps_request",
461
+ json={lat: lat, lon: lon, order: order},
462
+ )
463
+
464
+ async def navigation_request(
465
+ self, vehicle_tag: str | int, type: str, locale: str, timestamp_ms: str
466
+ ) -> dict[str, Any]:
467
+ """Sends a location to the in-vehicle navigation system."""
468
+ return await self._post(
469
+ f"api/1/vehicles/{vehicle_tag}/command/navigation_request",
470
+ json={type: type, locale: locale, timestamp_ms: timestamp_ms},
471
+ )
472
+
473
+ async def navigation_sc_request(
474
+ self, vehicle_tag: str | int, id: int, order: int
475
+ ) -> dict[str, Any]:
476
+ """Sends a location to the in-vehicle navigation system."""
477
+ return await self._post(
478
+ f"api/1/vehicles/{vehicle_tag}/command/navigation_sc_request",
479
+ json={type: type, id: id, order: order},
480
+ )
481
+
482
+ async def remote_auto_seat_climate_request(
483
+ self, vehicle_tag: str | int, auto_seat_position: int, auto_climate_on: bool
484
+ ) -> dict[str, Any]:
485
+ """Sets automatic seat heating and cooling."""
486
+ if self.use_command_protocol:
487
+ raise NotImplementedError("Command Protocol not implemented")
488
+ return await self._post(
489
+ f"api/1/vehicles/{vehicle_tag}/command/remote_auto_seat_climate_request",
490
+ json={
491
+ auto_seat_position: auto_seat_position,
492
+ auto_climate_on: auto_climate_on,
493
+ },
494
+ )
495
+
496
+ async def remote_auto_steering_wheel_heat_climate_request(
497
+ self, vehicle_tag: str | int, on: bool
498
+ ) -> dict[str, Any]:
499
+ """Sets automatic steering wheel heating on/off."""
500
+ return await self._post(
501
+ f"api/1/vehicles/{vehicle_tag}/command/remote_auto_steering_wheel_heat_climate_request",
502
+ json={on: on},
503
+ )
504
+
505
+ async def remote_boombox(
506
+ self, vehicle_tag: str | int, sound: int
507
+ ) -> dict[str, Any]:
508
+ """Plays a sound through the vehicle external speaker."""
509
+ return await self._post(
510
+ f"api/1/vehicles/{vehicle_tag}/command/remote_boombox",
511
+ json={sound: sound},
512
+ )
513
+
514
+ async def remote_seat_cooler_request(
515
+ self, vehicle_tag: str | int, seat_position: int, seat_cooler_level: int
516
+ ) -> dict[str, Any]:
517
+ """Sets seat cooling."""
518
+ if self.use_command_protocol:
519
+ raise NotImplementedError("Command Protocol not implemented")
520
+ return await self._post(
521
+ f"api/1/vehicles/{vehicle_tag}/command/remote_seat_cooler_request",
522
+ json={
523
+ seat_position: seat_position,
524
+ seat_cooler_level: seat_cooler_level,
525
+ },
526
+ )
527
+
528
+ async def remote_seat_heater_request(
529
+ self, vehicle_tag: str | int
530
+ ) -> dict[str, Any]:
531
+ """Sets seat heating."""
532
+ if self.use_command_protocol:
533
+ raise NotImplementedError("Command Protocol not implemented")
534
+ return await self._post(
535
+ f"api/1/vehicles/{vehicle_tag}/command/remote_seat_heater_request"
536
+ )
537
+
538
+ async def remote_start_drive(self, vehicle_tag: str | int) -> dict[str, Any]:
539
+ """Starts the vehicle remotely. Requires keyless driving to be enabled."""
540
+ if self.use_command_protocol:
541
+ raise NotImplementedError("Command Protocol not implemented")
542
+ return await self._post(
543
+ f"api/1/vehicles/{vehicle_tag}/command/remote_start_drive"
544
+ )
545
+
546
+ async def remote_steering_wheel_heat_level_request(
547
+ self, vehicle_tag: str | int, level: int
548
+ ) -> dict[str, Any]:
549
+ """Sets steering wheel heat level."""
550
+ if self.use_command_protocol:
551
+ raise NotImplementedError("Command Protocol not implemented")
552
+ return await self._post(
553
+ f"api/1/vehicles/{vehicle_tag}/command/remote_steering_wheel_heat_level_request",
554
+ json={level: level},
555
+ )
556
+
557
+ async def remote_steering_wheel_heater_request(
558
+ self, vehicle_tag: str | int, on: bool
559
+ ) -> dict[str, Any]:
560
+ """Sets steering wheel heating on/off. For vehicles that do not support auto steering wheel heat."""
561
+ if self.use_command_protocol:
562
+ raise NotImplementedError("Command Protocol not implemented")
563
+ return await self._post(
564
+ f"api/1/vehicles/{vehicle_tag}/command/remote_steering_wheel_heater_request",
565
+ json={on: on},
566
+ )
567
+
568
+ async def reset_pin_to_drive_pin(
569
+ self, vehicle_tag: str | int
570
+ ) -> dict[str, Any]:
571
+ """Removes PIN to Drive. Requires the car to be in Pin to Drive mode and not in Valet mode. Note that this only works if PIN to Drive is not active. This command also requires the Tesla Vehicle Command Protocol - for more information, please see refer to the documentation here."""
572
+ if self.use_command_protocol:
573
+ raise NotImplementedError("Command Protocol not implemented")
574
+ return await self._post(
575
+ f"api/1/vehicles/{vehicle_tag}/command/reset_pin_to_drive_pin"
576
+ )
577
+
578
+ async def reset_valet_pin(self, vehicle_tag: str | int) -> dict[str, Any]:
579
+ """Removes PIN for Valet Mode."""
580
+ if self.use_command_protocol:
581
+ raise NotImplementedError("Command Protocol not implemented")
582
+ return await self._post(
583
+ f"api/1/vehicles/{vehicle_tag}/command/reset_valet_pin"
584
+ )
585
+
586
+ async def schedule_software_update(
587
+ self, vehicle_tag: str | int, offset_sec: int
588
+ ) -> dict[str, Any]:
589
+ """Schedules a vehicle software update (over the air "OTA") to be installed in the future."""
590
+ if self.use_command_protocol:
591
+ raise NotImplementedError("Command Protocol not implemented")
592
+ return await self._post(
593
+ f"api/1/vehicles/{vehicle_tag}/command/schedule_software_update",
594
+ json={offset_sec: offset_sec},
595
+ )
596
+
597
+ async def set_bioweapon_mode(
598
+ self, vehicle_tag: str | int, on: bool, manual_override: bool
599
+ ) -> dict[str, Any]:
600
+ """Turns Bioweapon Defense Mode on and off."""
601
+ if self.use_command_protocol:
602
+ raise NotImplementedError("Command Protocol not implemented")
603
+ return await self._post(
604
+ f"api/1/vehicles/{vehicle_tag}/command/set_bioweapon_mode",
605
+ json={on: on, manual_override: manual_override},
606
+ )
607
+
608
+ async def set_cabin_overheat_protection(
609
+ self, vehicle_tag: str | int, on: bool, fan_only: bool
610
+ ) -> dict[str, Any]:
611
+ """Sets the vehicle overheat protection."""
612
+ if self.use_command_protocol:
613
+ raise NotImplementedError("Command Protocol not implemented")
614
+ return await self._post(
615
+ f"api/1/vehicles/{vehicle_tag}/command/set_cabin_overheat_protection",
616
+ json={on: on, fan_only: fan_only},
617
+ )
618
+
619
+ async def set_charge_limit(
620
+ self, vehicle_tag: str | int, percent: int
621
+ ) -> dict[str, Any]:
622
+ """Sets the vehicle charge limit."""
623
+ if self.use_command_protocol:
624
+ raise NotImplementedError("Command Protocol not implemented")
625
+ return await self._post(
626
+ f"api/1/vehicles/{vehicle_tag}/command/set_charge_limit",
627
+ json={percent: percent},
628
+ )
629
+
630
+ async def set_charging_amps(
631
+ self, vehicle_tag: str | int, charging_amps: int
632
+ ) -> dict[str, Any]:
633
+ """Sets the vehicle charging amps."""
634
+ if self.use_command_protocol:
635
+ raise NotImplementedError("Command Protocol not implemented")
636
+ return await self._post(
637
+ f"api/1/vehicles/{vehicle_tag}/command/set_charging_amps",
638
+ json={charging_amps: charging_amps},
639
+ )
640
+
641
+ class ClimateKeeperMode(IntEnum):
642
+ """Climate Keeper Mode options"""
643
+
644
+ OFF = 0
645
+ KEEP_MODE = 1
646
+ DOG_MODE = 2
647
+ CAMP_MODE = 3
648
+
649
+ async def set_climate_keeper_mode(
650
+ self, vehicle_tag: str | int, climate_keeper_mode: ClimateKeeperMode | int
651
+ ) -> dict[str, Any]:
652
+ """Enables climate keeper mode."""
653
+ if self.use_command_protocol:
654
+ raise NotImplementedError("Command Protocol not implemented")
655
+ return await self._post(
656
+ f"api/1/vehicles/{vehicle_tag}/command/set_climate_keeper_mode",
657
+ json={climate_keeper_mode: climate_keeper_mode},
658
+ )
659
+
660
+ class CopTemp(IntEnum):
661
+ """COP Temp options"""
662
+
663
+ LOW = 0 # 30C 90F
664
+ MEDIUM = 1 # 35C 95F
665
+ HIGH = 2 # 40C 100F
666
+
667
+ async def set_cop_temp(
668
+ self, vehicle_tag: str | int, cop_temp: CopTemp | int
669
+ ) -> dict[str, Any]:
670
+ """Adjusts the Cabin Overheat Protection temperature (COP)."""
671
+ if self.use_command_protocol:
672
+ raise NotImplementedError("Command Protocol not implemented")
673
+ return await self._post(
674
+ f"api/1/vehicles/{vehicle_tag}/command/set_cop_temp",
675
+ json={cop_temp: cop_temp},
676
+ )
677
+
678
+ async def set_pin_to_drive(
679
+ self, vehicle_tag: str | int, on: bool, password: str | int
680
+ ) -> dict[str, Any]:
681
+ """Sets a four-digit passcode for PIN to Drive. This PIN must then be entered before the vehicle can be driven."""
682
+ if self.use_command_protocol:
683
+ raise NotImplementedError("Command Protocol not implemented")
684
+ return await self._post(
685
+ f"api/1/vehicles/{vehicle_tag}/command/set_pin_to_drive",
686
+ json={on: on, password: str(password)},
687
+ )
688
+
689
+ async def set_preconditioning_max(
690
+ self, vehicle_tag: str | int, on: bool, manual_override: bool
691
+ ) -> dict[str, Any]:
692
+ """Sets an override for preconditioning — it should default to empty if no override is used."""
693
+ if self.use_command_protocol:
694
+ raise NotImplementedError("Command Protocol not implemented")
695
+ return await self._post(
696
+ f"api/1/vehicles/{vehicle_tag}/command/set_preconditioning_max",
697
+ json={on: on, manual_override: manual_override},
698
+ )
699
+
700
+ async def set_scheduled_charging(
701
+ self, vehicle_tag: str | int, enable: bool, time: int
702
+ ) -> dict[str, Any]:
703
+ """Sets a time at which charging should be completed. The time parameter is minutes after midnight (e.g: time=120 schedules charging for 2:00am vehicle local time)."""
704
+ if self.use_command_protocol:
705
+ raise NotImplementedError("Command Protocol not implemented")
706
+ return await self._post(
707
+ f"api/1/vehicles/{vehicle_tag}/command/set_scheduled_charging",
708
+ json={enable: enable, time: time},
709
+ )
710
+
711
+ async def set_scheduled_departure(
712
+ self, vehicle_tag: str | int, enable: bool, time: int
713
+ ) -> dict[str, Any]:
714
+ """Sets a time at which departure should be completed. The time parameter is minutes after midnight (e.g: time=120 schedules departure for 2:00am vehicle local time)."""
715
+ if self.use_command_protocol:
716
+ raise NotImplementedError("Command Protocol not implemented")
717
+ return await self._post(
718
+ f"api/1/vehicles/{vehicle_tag}/command/set_scheduled_departure",
719
+ json={enable: enable, time: time},
720
+ )
721
+
722
+ async def set_sentry_mode(
723
+ self, vehicle_tag: str | int, on: bool
724
+ ) -> dict[str, Any]:
725
+ """Enables and disables Sentry Mode. Sentry Mode allows customers to watch the vehicle cameras live from the mobile app, as well as record sentry events."""
726
+ if self.use_command_protocol:
727
+ raise NotImplementedError("Command Protocol not implemented")
728
+ return await self._post(
729
+ f"api/1/vehicles/{vehicle_tag}/command/set_sentry_mode", json={on: on}
730
+ )
731
+
732
+ async def set_temps(
733
+ self, vehicle_tag: str | int, driver_temp: int, passenger_temp: int
734
+ ) -> dict[str, Any]:
735
+ """Sets the driver and/or passenger-side cabin temperature (and other zones if sync is enabled)."""
736
+ if self.use_command_protocol:
737
+ raise NotImplementedError("Command Protocol not implemented")
738
+ return await self._post(
739
+ f"api/1/vehicles/{vehicle_tag}/command/set_temps",
740
+ json={driver_temp: driver_temp, passenger_temp: passenger_temp},
741
+ )
742
+
743
+ async def set_valet_mode(
744
+ self, vehicle_tag: str | int, on: bool, password: str | int
745
+ ) -> dict[str, Any]:
746
+ """Turns on Valet Mode and sets a four-digit passcode that must then be entered to disable Valet Mode."""
747
+ if self.use_command_protocol:
748
+ raise NotImplementedError("Command Protocol not implemented")
749
+ return await self._post(
750
+ f"api/1/vehicles/{vehicle_tag}/command/set_valet_mode",
751
+ json={on: on, password: str(password)},
752
+ )
753
+
754
+ async def set_vehicle_name(
755
+ self, vehicle_tag: str | int, vehicle_name: str
756
+ ) -> dict[str, Any]:
757
+ """Changes the name of a vehicle. This command also requires the Tesla Vehicle Command Protocol - for more information, please see refer to the documentation here."""
758
+ if self.use_command_protocol:
759
+ raise NotImplementedError("Command Protocol not implemented")
760
+ return await self._post(
761
+ f"api/1/vehicles/{vehicle_tag}/command/set_vehicle_name",
762
+ json={vehicle_name: vehicle_name},
763
+ )
764
+
765
+ async def speed_limit_activate(
766
+ self, vehicle_tag: str | int, pin: str | int
767
+ ) -> dict[str, Any]:
768
+ """Activates Speed Limit Mode with a four-digit PIN."""
769
+ if self.use_command_protocol:
770
+ raise NotImplementedError("Command Protocol not implemented")
771
+ return await self._post(
772
+ f"api/1/vehicles/{vehicle_tag}/command/speed_limit_activate",
773
+ json={pin: str(pin)},
774
+ )
775
+
776
+ async def speed_limit_clear_pin(
777
+ self, vehicle_tag: str | int, pin: str | int
778
+ ) -> dict[str, Any]:
779
+ """Deactivates Speed Limit Mode and resets the associated PIN."""
780
+ if self.use_command_protocol:
781
+ raise NotImplementedError("Command Protocol not implemented")
782
+ return await self._post(
783
+ f"api/1/vehicles/{vehicle_tag}/command/speed_limit_clear_pin",
784
+ json={pin: str(pin)},
785
+ )
786
+
787
+ async def speed_limit_clear_pin_admin(
788
+ self, vehicle_tag: str | int
789
+ ) -> dict[str, Any]:
790
+ """Deactivates Speed Limit Mode and resets the associated PIN for vehicles running firmware versions 2023.38+. This command is only accessible to fleet managers or owners."""
791
+ return await self._post(
792
+ f"api/1/vehicles/{vehicle_tag}/command/speed_limit_clear_pin_admin"
793
+ )
794
+
795
+ async def speed_limit_deactivate(
796
+ self, vehicle_tag: str | int, pin: str | int
797
+ ) -> dict[str, Any]:
798
+ """Deactivates Speed Limit Mode."""
799
+ if self.use_command_protocol:
800
+ raise NotImplementedError("Command Protocol not implemented")
801
+ return await self._post(
802
+ f"api/1/vehicles/{vehicle_tag}/command/speed_limit_deactivate",
803
+ json={pin: str(pin)},
804
+ )
805
+
806
+ async def speed_limit_set_limit(
807
+ self, vehicle_tag: str | int, limit_mph: int
808
+ ) -> dict[str, Any]:
809
+ """Sets the maximum speed allowed when Speed Limit Mode is active."""
810
+ if self.use_command_protocol:
811
+ raise NotImplementedError("Command Protocol not implemented")
812
+ return await self._post(
813
+ f"api/1/vehicles/{vehicle_tag}/command/speed_limit_set_limit",
814
+ json={limit_mph: limit_mph},
815
+ )
816
+
817
+ class SunRoof(StrEnum):
818
+ """Sunroof options"""
819
+
820
+ STOP = "stop"
821
+ CLOSE = "close"
822
+ VENT = "vent"
823
+
824
+ async def sun_roof_control(
825
+ self, vehicle_tag: str | int, state: str | SunRoof
826
+ ) -> dict[str, Any]:
827
+ """Controls the panoramic sunroof on the Model S."""
828
+ return await self._post(
829
+ f"api/1/vehicles/{vehicle_tag}/command/sun_roof_control",
830
+ {state: state},
831
+ )
832
+
833
+ async def take_drivenote(
834
+ self, vehicle_tag: str | int, note: str
835
+ ) -> dict[str, Any]:
836
+ """Records a drive note. The note parameter is truncated to 80 characters in length."""
837
+ return await self._post(
838
+ f"api/1/vehicles/{vehicle_tag}/command/take_drivenote", {note: note}
839
+ )
840
+
841
+ async def trigger_homelink(
842
+ self, vehicle_tag: str | int, lat: float, lon: float, token: str
843
+ ) -> dict[str, Any]:
844
+ """Turns on HomeLink (used to open and close garage doors)."""
845
+ if self.use_command_protocol:
846
+ raise NotImplementedError("Command Protocol not implemented")
847
+ return await self._post(
848
+ f"api/1/vehicles/{vehicle_tag}/command/trigger_homelink",
849
+ {lat: lat, lon: lon, token: token},
850
+ )
851
+
852
+ async def upcoming_calendar_entries(
853
+ self, vehicle_tag: str | int, calendar_data: str
854
+ ) -> dict[str, Any]:
855
+ """Upcoming calendar entries stored on the vehicle."""
856
+ return await self._post(
857
+ f"api/1/vehicles/{vehicle_tag}/command/upcoming_calendar_entries",
858
+ {calendar_data: calendar_data},
859
+ )
860
+
861
+ class WindowControl(StrEnum):
862
+ """Window Control options"""
863
+
864
+ VENT = "vent"
865
+ CLOSE = "close"
866
+
867
+ async def window_control(
868
+ self,
869
+ vehicle_tag: str | int,
870
+ lat: float,
871
+ lon: float,
872
+ command: str | WindowControl,
873
+ ) -> dict[str, Any]:
874
+ """Control the windows of a parked vehicle. Supported commands: vent and close. When closing, specify lat and lon of user to ensure they are within range of vehicle (unless this is an M3 platform vehicle)."""
875
+ return await self._post(
876
+ f"api/1/vehicles/{vehicle_tag}/command/window_control",
877
+ {lat: lat, lon: lon, command: command},
878
+ )
879
+
880
+ async def drivers(self, vehicle_tag: str | int) -> dict[str, Any]:
881
+ """Returns all allowed drivers for a vehicle. This endpoint is only available for the vehicle owner."""
882
+ return await self._get(f"api/1/vehicles/{vehicle_tag}/drivers")
883
+
884
+ async def drivers_remove(
885
+ self, vehicle_tag: str | int, share_user_id: str | int | None = None
886
+ ) -> dict[str, Any]:
887
+ """Removes driver access from a vehicle. Share users can only remove their own access. Owners can remove share access or their own."""
888
+ return await self._delete(
889
+ f"api/1/vehicles/{vehicle_tag}/drivers", {share_user_id: share_user_id}
890
+ )
891
+
892
+ async def list(
893
+ self, page: int | None = None, per_page: int | None = None
894
+ ) -> dict[str, Any]:
895
+ """Returns vehicles belonging to the account."""
896
+ return await self._get("api/1/vehicles", {page: page, per_page: per_page})
897
+
898
+ async def mobile_enabled(self, vehicle_tag: str | int) -> dict[str, Any]:
899
+ """Returns whether or not mobile access is enabled for the vehicle."""
900
+ return await self._get(f"api/1/vehicles/{vehicle_tag}/mobile_enabled")
901
+
902
+ async def nearby_charging_sites(
903
+ self,
904
+ vehicle_tag: str | int,
905
+ count: int | None = None,
906
+ radius: int | None = None,
907
+ detail: bool | None = None,
908
+ ) -> dict[str, Any]:
909
+ """Returns the charging sites near the current location of the vehicle."""
910
+ return await self._get(
911
+ f"api/1/vehicles/{vehicle_tag}/nearby_charging_sites",
912
+ {count: count, radius: radius, detail: detail},
913
+ )
914
+
915
+ async def options(self, vin: str) -> dict[str, Any]:
916
+ """Returns vehicle option details."""
917
+ return await self._get("api/1/dx/vehicles/options", {vin: vin})
918
+
919
+ async def recent_alerts(self, vehicle_tag: str | int) -> dict[str, Any]:
920
+ """List of recent alerts"""
921
+ return await self._get(f"api/1/vehicles/{vehicle_tag}/recent_alerts")
922
+
923
+ async def release_notes(
924
+ self,
925
+ vehicle_tag: str | int,
926
+ staged: bool | None = None,
927
+ language: int | None = None,
928
+ ) -> dict[str, Any]:
929
+ """Returns firmware release notes."""
930
+ return await self._get(
931
+ f"api/1/vehicles/{vehicle_tag}/release_notes",
932
+ {staged: staged, language: language},
933
+ )
934
+
935
+ async def service_data(self, vehicle_tag: str | int) -> dict[str, Any]:
936
+ """Returns service data."""
937
+ return await self._get(f"api/1/vehicles/{vehicle_tag}/service_data")
938
+
939
+ async def share_invites(self, vehicle_tag: str | int) -> dict[str, Any]:
940
+ """Returns the share invites for a vehicle."""
941
+ return await self._get(f"api/1/vehicles/{vehicle_tag}/invitations")
942
+
943
+ async def share_invites_create(self, vehicle_tag: str | int) -> dict[str, Any]:
944
+ """Creates a share invite for a vehicle."""
945
+ return await self._post(f"api/1/vehicles/{vehicle_tag}/invitations")
946
+
947
+ async def share_invites_redeem(self, code: str) -> dict[str, Any]:
948
+ """Redeems a share invite."""
949
+ return await self._post("api/1/invitations/redeem", {code: code})
950
+
951
+ async def share_invites_revoke(
952
+ self, vehicle_tag: str | int, id: str
953
+ ) -> dict[str, Any]:
954
+ """Revokes a share invite."""
955
+ return await self._post(
956
+ f"api/1/vehicles/{vehicle_tag}/invitations/{id}/revoke"
957
+ )
958
+
959
+ async def signed_command(
960
+ self, vehicle_tag: str | int, routable_message: str
961
+ ) -> dict[str, Any]:
962
+ """Signed Commands is a generic endpoint replacing legacy commands."""
963
+ return await self._post(
964
+ f"api/1/vehicles/{vehicle_tag}/signed_command",
965
+ {routable_message: routable_message},
966
+ )
967
+
968
+ async def subscriptions(
969
+ self, device_token: str, device_type: str
970
+ ) -> dict[str, Any]:
971
+ """Returns the list of vehicles for which this mobile device currently subscribes to push notifications."""
972
+ return await self._get(
973
+ "api/1/subscriptions",
974
+ query={device_token: device_token, device_type: device_type},
975
+ )
976
+
977
+ async def subscriptions_set(
978
+ self, device_token: str, device_type: str
979
+ ) -> dict[str, Any]:
980
+ """Allows a mobile device to specify which vehicles to receive push notifications from."""
981
+ return await self._post(
982
+ "api/1/subscriptions",
983
+ query={device_token: device_token, device_type: device_type},
984
+ )
985
+
986
+ async def vehicle(self, vehicle_tag: str | int) -> dict[str, Any]:
987
+ """Returns information about a vehicle."""
988
+ return await self._get(f"api/1/vehicles/{vehicle_tag}")
989
+
990
+ class Endpoints(StrEnum):
991
+ """Endpoints options"""
992
+
993
+ CHARGE_STATE = "charge_state"
994
+ CLIMATE_STATE = "climate_state"
995
+ CLOSURES_STATE = "closures_state"
996
+ DRIVE_STATE = "drive_state"
997
+ GUI_SETTINGS = "gui_settings"
998
+ LOCATION_DATA = "location_data"
999
+ VEHICLE_CONFIG = "vehicle_config"
1000
+ VEHICLE_STATE = "vehicle_state"
1001
+ VEHICLE_DATA_COMBO = "vehicle_data_combo"
1002
+
1003
+ async def vehicle_data(
1004
+ self,
1005
+ vehicle_tag: str | int,
1006
+ endpoints: Endpoints | str | None = None,
1007
+ ) -> dict[str, Any]:
1008
+ """Makes a live call to the vehicle. This may return cached data if the vehicle is offline. For vehicles running firmware versions 2023.38+, location_data is required to fetch vehicle location. This will result in a location sharing icon to show on the vehicle UI."""
1009
+ return await self._get(
1010
+ f"api/1/vehicles/{vehicle_tag}/vehicle_data", {endpoints: endpoints}
1011
+ )
1012
+
1013
+ class DeviceType(StrEnum):
1014
+ """Device Type options"""
1015
+
1016
+ ANDROID = "android"
1017
+ IOS_DEVELOPMENT = "ios-development"
1018
+ IOS_ENTERPRISE = "ios-enterprise"
1019
+ IOS_BETA = "ios-beta"
1020
+ IOS_PRODUCTION = "ios-production"
1021
+
1022
+ async def vehicle_subscriptions(
1023
+ self, device_token: str, device_type: DeviceType | str
1024
+ ) -> dict[str, Any]:
1025
+ """Returns the list of vehicles for which this mobile device currently subscribes to push notifications."""
1026
+ return await self._get(
1027
+ "api/1/vehicle_subscriptions",
1028
+ {device_token: device_token, device_type: device_type},
1029
+ )
1030
+
1031
+ async def vehicle_subscriptions_set(
1032
+ self, device_token: str, device_type: DeviceType | str
1033
+ ) -> dict[str, Any]:
1034
+ """Allows a mobile device to specify which vehicles to receive push notifications from."""
1035
+ return await self._post(
1036
+ "api/1/vehicle_subscriptions",
1037
+ params={device_token: device_token, device_type: device_type},
1038
+ )
1039
+
1040
+ async def wake_up(self, vehicle_tag: str | int) -> dict[str, Any]:
1041
+ """Wakes the vehicle from sleep, which is a state to minimize idle energy consumption."""
1042
+ return await self._post(f"api/1/vehicles/{vehicle_tag}/wake_up")
1043
+
1044
+ async def warranty_details(self, vin: str | None) -> dict[str, Any]:
1045
+ """Returns warranty details."""
1046
+ return await self._get("api/1/dx/warranty/details", {vin: vin})