tesla-fleet-api 0.9.9__py3-none-any.whl → 1.0.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (49) hide show
  1. tesla_fleet_api/__init__.py +7 -22
  2. tesla_fleet_api/const.py +1 -225
  3. tesla_fleet_api/exceptions.py +117 -0
  4. tesla_fleet_api/tesla/__init__.py +11 -0
  5. tesla_fleet_api/tesla/bluetooth.py +33 -0
  6. tesla_fleet_api/{charging.py → tesla/charging.py} +1 -1
  7. tesla_fleet_api/{energy.py → tesla/energysite.py} +41 -33
  8. tesla_fleet_api/{teslafleetapi.py → tesla/fleet.py} +8 -53
  9. tesla_fleet_api/{teslafleetoauth.py → tesla/oauth.py} +3 -4
  10. tesla_fleet_api/{partner.py → tesla/partner.py} +1 -1
  11. tesla_fleet_api/tesla/tesla.py +52 -0
  12. tesla_fleet_api/{user.py → tesla/user.py} +1 -1
  13. tesla_fleet_api/teslemetry/__init__.py +5 -0
  14. tesla_fleet_api/{teslemetry.py → teslemetry/teslemetry.py} +16 -25
  15. tesla_fleet_api/teslemetry/vehicle.py +73 -0
  16. tesla_fleet_api/tessie/__init__.py +5 -0
  17. tesla_fleet_api/{tessie.py → tessie/tessie.py} +17 -9
  18. tesla_fleet_api/tessie/vehicle.py +41 -0
  19. {tesla_fleet_api-0.9.9.dist-info → tesla_fleet_api-1.0.0.dist-info}/METADATA +3 -2
  20. tesla_fleet_api-1.0.0.dist-info/RECORD +24 -0
  21. tesla_fleet_api/energyspecific.py +0 -125
  22. tesla_fleet_api/pb2/__init__.py +0 -0
  23. tesla_fleet_api/pb2/__init__.pyi +0 -9
  24. tesla_fleet_api/pb2/car_server_pb2.py +0 -175
  25. tesla_fleet_api/pb2/car_server_pb2.pyi +0 -904
  26. tesla_fleet_api/pb2/common_pb2.py +0 -33
  27. tesla_fleet_api/pb2/common_pb2.pyi +0 -130
  28. tesla_fleet_api/pb2/errors_pb2.py +0 -17
  29. tesla_fleet_api/pb2/errors_pb2.pyi +0 -32
  30. tesla_fleet_api/pb2/keys_pb2.py +0 -15
  31. tesla_fleet_api/pb2/keys_pb2.pyi +0 -21
  32. tesla_fleet_api/pb2/managed_charging_pb2.py +0 -15
  33. tesla_fleet_api/pb2/managed_charging_pb2.pyi +0 -17
  34. tesla_fleet_api/pb2/signatures_pb2.py +0 -35
  35. tesla_fleet_api/pb2/signatures_pb2.pyi +0 -152
  36. tesla_fleet_api/pb2/universal_message_pb2.py +0 -30
  37. tesla_fleet_api/pb2/universal_message_pb2.pyi +0 -148
  38. tesla_fleet_api/pb2/vcsec_pb2.py +0 -79
  39. tesla_fleet_api/pb2/vcsec_pb2.pyi +0 -482
  40. tesla_fleet_api/pb2/vehicle_pb2.py +0 -125
  41. tesla_fleet_api/pb2/vehicle_pb2.pyi +0 -1183
  42. tesla_fleet_api/teslafleetopensource.py +0 -61
  43. tesla_fleet_api/vehicle.py +0 -878
  44. tesla_fleet_api/vehiclesigned.py +0 -1127
  45. tesla_fleet_api/vehiclespecific.py +0 -505
  46. tesla_fleet_api-0.9.9.dist-info/RECORD +0 -42
  47. {tesla_fleet_api-0.9.9.dist-info → tesla_fleet_api-1.0.0.dist-info}/LICENSE +0 -0
  48. {tesla_fleet_api-0.9.9.dist-info → tesla_fleet_api-1.0.0.dist-info}/WHEEL +0 -0
  49. {tesla_fleet_api-0.9.9.dist-info → tesla_fleet_api-1.0.0.dist-info}/top_level.txt +0 -0
@@ -1,1127 +0,0 @@
1
- from __future__ import annotations
2
- import base64
3
- from random import randbytes
4
- from typing import Any, TYPE_CHECKING
5
- import time
6
- import struct
7
- import hmac
8
- import hashlib
9
- from cryptography.hazmat.primitives.asymmetric import ec
10
- from cryptography.hazmat.primitives.serialization import PublicFormat, Encoding
11
- from asyncio import Lock, sleep
12
-
13
- from tesla_fleet_api.pb2.errors_pb2 import GenericError_E
14
-
15
- from .exceptions import MESSAGE_FAULTS, SIGNED_MESSAGE_INFORMATION_FAULTS, TeslaFleetMessageFaultIncorrectEpoch, TeslaFleetMessageFaultInvalidTokenOrCounter
16
-
17
- from .const import (
18
- LOGGER,
19
- Trunk,
20
- ClimateKeeperMode,
21
- CabinOverheatProtectionTemp,
22
- SunRoofCommand,
23
- WindowCommand,
24
- )
25
- from .vehiclespecific import VehicleSpecific
26
-
27
- from .pb2.universal_message_pb2 import (
28
- OPERATIONSTATUS_WAIT,
29
- OPERATIONSTATUS_ERROR,
30
- DOMAIN_VEHICLE_SECURITY,
31
- DOMAIN_INFOTAINMENT,
32
- Domain,
33
- RoutableMessage,
34
- )
35
- from .pb2.car_server_pb2 import (
36
- Response,
37
- Action,
38
- MediaPlayAction,
39
- VehicleAction,
40
- VehicleControlFlashLightsAction,
41
- ChargingStartStopAction,
42
- ChargingSetLimitAction,
43
- EraseUserDataAction,
44
- DrivingClearSpeedLimitPinAction,
45
- DrivingSetSpeedLimitAction,
46
- DrivingSpeedLimitAction,
47
- HvacAutoAction,
48
- HvacSeatHeaterActions,
49
- HvacSeatCoolerActions,
50
- HvacSetPreconditioningMaxAction,
51
- HvacSteeringWheelHeaterAction,
52
- HvacTemperatureAdjustmentAction,
53
- GetNearbyChargingSites,
54
- # NearbyChargingSites,
55
- # Superchargers,
56
- VehicleControlCancelSoftwareUpdateAction,
57
- VehicleControlHonkHornAction,
58
- VehicleControlResetValetPinAction,
59
- VehicleControlScheduleSoftwareUpdateAction,
60
- VehicleControlSetSentryModeAction,
61
- VehicleControlSetValetModeAction,
62
- VehicleControlSunroofOpenCloseAction,
63
- VehicleControlTriggerHomelinkAction,
64
- VehicleControlWindowAction,
65
- HvacBioweaponModeAction,
66
- AutoSeatClimateAction,
67
- # Ping,
68
- ScheduledChargingAction,
69
- ScheduledDepartureAction,
70
- HvacClimateKeeperAction,
71
- SetChargingAmpsAction,
72
- SetCabinOverheatProtectionAction,
73
- SetVehicleNameAction,
74
- SetCopTempAction,
75
- VehicleControlSetPinToDriveAction,
76
- VehicleControlResetPinToDriveAction,
77
- MediaNextTrack,
78
- MediaNextFavorite,
79
- MediaUpdateVolume,
80
- MediaPreviousTrack,
81
- MediaPreviousFavorite,
82
- )
83
- from .pb2.vehicle_pb2 import VehicleState
84
- from .pb2.vcsec_pb2 import (
85
- # SignedMessage_information_E,
86
- OPERATIONSTATUS_OK,
87
- FromVCSECMessage,
88
- UnsignedMessage,
89
- RKEAction_E,
90
- ClosureMoveRequest,
91
- ClosureMoveType_E,
92
- )
93
- from .pb2.signatures_pb2 import (
94
- SIGNATURE_TYPE_HMAC_PERSONALIZED,
95
- TAG_DOMAIN,
96
- TAG_SIGNATURE_TYPE,
97
- SessionInfo,
98
- HMAC_Personalized_Signature_Data,
99
- TAG_PERSONALIZATION,
100
- TAG_EPOCH,
101
- TAG_EXPIRES_AT,
102
- TAG_COUNTER,
103
- TAG_END,
104
- )
105
- from .pb2.common_pb2 import (
106
- Void,
107
- PreconditioningTimes,
108
- OffPeakChargingTimes,
109
- # ChargeSchedule,
110
- # PreconditionSchedule,
111
- )
112
-
113
- if TYPE_CHECKING:
114
- from .vehicle import Vehicle
115
-
116
-
117
- class Session:
118
- """A connect to a domain"""
119
-
120
- key: bytes
121
- counter: int
122
- epoch: bytes
123
- delta: int
124
- hmac: bytes
125
- publicKey: bytes
126
- lock: Lock
127
-
128
- def __init__(self):
129
- self.lock = Lock()
130
-
131
- def update(self, sessionInfo: SessionInfo, privateKey: ec.EllipticCurvePrivateKey):
132
- """Update the session with new information"""
133
- self.counter = sessionInfo.counter
134
- self.epoch = sessionInfo.epoch
135
- self.delta = int(time.time()) - sessionInfo.clock_time
136
- self.publicKey = sessionInfo.publicKey
137
- self.key = hashlib.sha1(
138
- privateKey.exchange(
139
- ec.ECDH(),
140
- ec.EllipticCurvePublicKey.from_encoded_point(
141
- ec.SECP256R1(), self.publicKey
142
- ),
143
- )
144
- ).digest()[:16]
145
- self.hmac = hmac.new(
146
- self.key, "authenticated command".encode(), hashlib.sha256
147
- ).digest()
148
-
149
- def get(self) -> HMAC_Personalized_Signature_Data:
150
- """Sign a command and return session metadata"""
151
- self.counter = self.counter+1
152
- return HMAC_Personalized_Signature_Data(
153
- epoch=self.epoch,
154
- counter=self.counter,
155
- expires_at=int(time.time()) - self.delta + 10,
156
- )
157
-
158
-
159
- class VehicleSigned(VehicleSpecific):
160
- """Class describing the Tesla Fleet API vehicle endpoints and commands for a specific vehicle with command signing."""
161
-
162
- private_key: ec.EllipticCurvePrivateKey
163
- _public_key: bytes
164
- _from_destination: bytes
165
- _sessions: dict[int, Session]
166
-
167
- def __init__(
168
- self, parent: Vehicle, vin: str, key: ec.EllipticCurvePrivateKey | None = None
169
- ):
170
- super().__init__(parent, vin)
171
- if key:
172
- self.private_key = key
173
- elif parent._parent.private_key:
174
- self.private_key = parent._parent.private_key
175
- else:
176
- raise ValueError("No private key.")
177
-
178
- self._public_key = self.private_key.public_key().public_bytes(
179
- encoding=Encoding.X962, format=PublicFormat.UncompressedPoint
180
- )
181
- self._from_destination = randbytes(16)
182
- self._sessions = {}
183
-
184
- async def _send(self, msg: RoutableMessage) -> RoutableMessage:
185
- """Serialize a message and send to the signed command endpoint."""
186
-
187
- async with self._sessions[msg.to_destination.domain].lock:
188
- resp = await self.signed_command(
189
- base64.b64encode(msg.SerializeToString()).decode()
190
- )
191
-
192
- resp_msg = RoutableMessage.FromString(base64.b64decode(resp["response"]))
193
-
194
- # Check UUID?
195
- # Check RoutingAdress?
196
-
197
- if resp_msg.session_info:
198
- self._sessions[resp_msg.from_destination.domain].update(
199
- SessionInfo.FromString(resp_msg.session_info), self.private_key
200
- )
201
-
202
- if resp_msg.signedMessageStatus.signed_message_fault:
203
- raise MESSAGE_FAULTS[resp_msg.signedMessageStatus.signed_message_fault]
204
-
205
- return resp_msg
206
-
207
- async def _handshake(self, domain: Domain) -> Session:
208
- """Perform a handshake with the vehicle."""
209
- if session := self._sessions.get(domain):
210
- return session
211
- self._sessions[domain] = Session()
212
-
213
- LOGGER.debug(f"Handshake with domain {Domain.Name(domain)}")
214
- msg = RoutableMessage()
215
- msg.to_destination.domain = domain
216
- msg.from_destination.routing_address = self._from_destination
217
- msg.session_info_request.public_key = self._public_key
218
- msg.uuid = randbytes(16)
219
-
220
- # Send handshake message
221
- await self._send(msg)
222
-
223
- return self._sessions[domain]
224
-
225
- async def _sendVehicleSecurity(self, command: UnsignedMessage) -> dict[str, Any]:
226
- """Sign and send a message to Infotainment computer."""
227
- return await self._sign(DOMAIN_VEHICLE_SECURITY, command.SerializeToString())
228
-
229
- async def _sendInfotainment(self, command: Action) -> dict[str, Any]:
230
- """Sign and send a message to Infotainment computer."""
231
- return await self._sign(DOMAIN_INFOTAINMENT, command.SerializeToString())
232
-
233
- async def _sign(
234
- self, domain: Domain, command: bytes, attempt: int = 1
235
- ) -> dict[str, Any]:
236
- """Send a signed message to the vehicle."""
237
- LOGGER.debug(f"Sending to domain {Domain.Name(domain)}")
238
-
239
- session = await self._handshake(domain)
240
- hmac_personalized = session.get()
241
-
242
- msg = RoutableMessage()
243
- msg.to_destination.domain = domain
244
- msg.from_destination.routing_address = self._from_destination
245
- msg.protobuf_message_as_bytes = command
246
- msg.uuid = randbytes(16)
247
-
248
- metadata = bytes([
249
- TAG_SIGNATURE_TYPE,
250
- 1,
251
- SIGNATURE_TYPE_HMAC_PERSONALIZED,
252
- TAG_DOMAIN,
253
- 1,
254
- domain,
255
- TAG_PERSONALIZATION,
256
- 17,
257
- *self.vin.encode(),
258
- TAG_EPOCH,
259
- len(hmac_personalized.epoch),
260
- *hmac_personalized.epoch,
261
- TAG_EXPIRES_AT,
262
- 4,
263
- *struct.pack(">I", hmac_personalized.expires_at),
264
- TAG_COUNTER,
265
- 4,
266
- *struct.pack(">I", hmac_personalized.counter),
267
- TAG_END,
268
- ])
269
-
270
- hmac_personalized.tag = hmac.new(
271
- session.hmac, metadata + command, hashlib.sha256
272
- ).digest()
273
-
274
- # I think this whole section could be improved
275
- msg.signature_data.HMAC_Personalized_data.CopyFrom(hmac_personalized)
276
- msg.signature_data.signer_identity.public_key = self._public_key
277
-
278
- try:
279
- resp = await self._send(msg)
280
- except (
281
- TeslaFleetMessageFaultIncorrectEpoch,
282
- TeslaFleetMessageFaultInvalidTokenOrCounter,
283
- ) as e:
284
- attempt += 1
285
- if attempt > 3:
286
- # We tried 3 times, give up, raise the error
287
- raise e
288
- return await self._sign(domain, command, attempt)
289
-
290
- if resp.signedMessageStatus.operation_status == OPERATIONSTATUS_WAIT:
291
- attempt += 1
292
- if attempt > 3:
293
- # We tried 3 times, give up, raise the error
294
- return {"response": {"result": False, "reason": "Too many retries"}}
295
- async with session.lock:
296
- await sleep(2)
297
- return await self._sign(domain, command, attempt)
298
-
299
- if resp.HasField("protobuf_message_as_bytes"):
300
- if(resp.from_destination.domain == DOMAIN_VEHICLE_SECURITY):
301
- vcsec = FromVCSECMessage.FromString(resp.protobuf_message_as_bytes)
302
- LOGGER.debug("VCSEC Response: %s", vcsec)
303
- if vcsec.HasField("nominalError"):
304
- LOGGER.error("Command failed with reason: %s", vcsec.nominalError.genericError)
305
- return {
306
- "response": {
307
- "result": False,
308
- "reason": GenericError_E.Name(vcsec.nominalError.genericError)
309
- }
310
- }
311
- elif vcsec.commandStatus.operationStatus == OPERATIONSTATUS_OK:
312
- return {"response": {"result": True, "reason": ""}}
313
- elif vcsec.commandStatus.operationStatus == OPERATIONSTATUS_WAIT:
314
- attempt += 1
315
- if attempt > 3:
316
- # We tried 3 times, give up, raise the error
317
- return {"response": {"result": False, "reason": "Too many retries"}}
318
- async with session.lock:
319
- await sleep(2)
320
- return await self._sign(domain, command, attempt)
321
- elif vcsec.commandStatus.operationStatus == OPERATIONSTATUS_ERROR:
322
- if(resp.HasField("signedMessageStatus")):
323
- raise SIGNED_MESSAGE_INFORMATION_FAULTS[vcsec.commandStatus.signedMessageStatus.signedMessageInformation]
324
-
325
- elif(resp.from_destination.domain == DOMAIN_INFOTAINMENT):
326
- response = Response.FromString(resp.protobuf_message_as_bytes)
327
- LOGGER.debug("Infotainment Response: %s", response)
328
- if (response.HasField("ping")):
329
- print(response.ping)
330
- return {
331
- "response": {
332
- "result": True,
333
- "reason": response.ping.local_timestamp
334
- }
335
- }
336
- if response.HasField("actionStatus"):
337
- return {
338
- "response": {
339
- "result": response.actionStatus.result == OPERATIONSTATUS_OK,
340
- "reason": response.actionStatus.result_reason.plain_text or ""
341
- }
342
- }
343
-
344
- return {"response": {"result": True, "reason": ""}}
345
-
346
- async def actuate_trunk(self, which_trunk: Trunk | str) -> dict[str, Any]:
347
- """Controls the front or rear trunk."""
348
- if which_trunk == Trunk.FRONT:
349
- return await self._sendVehicleSecurity(
350
- UnsignedMessage(
351
- closureMoveRequest=ClosureMoveRequest(
352
- frontTrunk=ClosureMoveType_E.CLOSURE_MOVE_TYPE_MOVE
353
- )
354
- )
355
- )
356
- if which_trunk == Trunk.REAR:
357
- return await self._sendVehicleSecurity(
358
- UnsignedMessage(
359
- closureMoveRequest=ClosureMoveRequest(
360
- rearTrunk=ClosureMoveType_E.CLOSURE_MOVE_TYPE_MOVE
361
- )
362
- )
363
- )
364
-
365
- async def adjust_volume(self, volume: float) -> dict[str, Any]:
366
- """Adjusts vehicle media playback volume."""
367
- return await self._sendInfotainment(
368
- Action(
369
- vehicleAction=VehicleAction(
370
- mediaUpdateVolume=MediaUpdateVolume(volume_absolute_float=volume)
371
- )
372
- )
373
- )
374
-
375
- async def auto_conditioning_start(self) -> dict[str, Any]:
376
- """Starts climate preconditioning."""
377
- return await self._sendInfotainment(
378
- Action(
379
- vehicleAction=VehicleAction(
380
- hvacAutoAction=HvacAutoAction(power_on=True)
381
- )
382
- )
383
- )
384
-
385
- async def auto_conditioning_stop(self) -> dict[str, Any]:
386
- """Stops climate preconditioning."""
387
- return await self._sendInfotainment(
388
- Action(
389
- vehicleAction=VehicleAction(
390
- hvacAutoAction=HvacAutoAction(power_on=False)
391
- )
392
- )
393
- )
394
-
395
- async def cancel_software_update(self) -> dict[str, Any]:
396
- """Cancels the countdown to install the vehicle software update."""
397
- return await self._sendInfotainment(
398
- Action(
399
- vehicleAction=VehicleAction(
400
- vehicleControlCancelSoftwareUpdateAction=VehicleControlCancelSoftwareUpdateAction()
401
- )
402
- )
403
- )
404
-
405
- async def charge_max_range(self) -> dict[str, Any]:
406
- """Charges in max range mode -- we recommend limiting the use of this mode to long trips."""
407
- return await self._sendInfotainment(
408
- Action(
409
- vehicleAction=VehicleAction(
410
- chargingStartStopAction=ChargingStartStopAction(
411
- start_max_range=Void()
412
- )
413
- )
414
- )
415
- )
416
-
417
- async def charge_port_door_close(self) -> dict[str, Any]:
418
- """Closes the charge port door."""
419
- return await self._sendVehicleSecurity(
420
- UnsignedMessage(
421
- closureMoveRequest=ClosureMoveRequest(
422
- chargePort=ClosureMoveType_E.CLOSURE_MOVE_TYPE_CLOSE
423
- )
424
- )
425
- )
426
-
427
- async def charge_port_door_open(self) -> dict[str, Any]:
428
- """Opens the charge port door."""
429
- return await self._sendVehicleSecurity(
430
- UnsignedMessage(
431
- closureMoveRequest=ClosureMoveRequest(
432
- chargePort=ClosureMoveType_E.CLOSURE_MOVE_TYPE_OPEN
433
- )
434
- )
435
- )
436
-
437
- async def charge_standard(self) -> dict[str, Any]:
438
- """Charges in Standard mode."""
439
- return await self._sendInfotainment(
440
- Action(
441
- vehicleAction=VehicleAction(
442
- chargingStartStopAction=ChargingStartStopAction(
443
- start_standard=Void()
444
- )
445
- )
446
- )
447
- )
448
-
449
- async def charge_start(self) -> dict[str, Any]:
450
- """Starts charging the vehicle."""
451
- return await self._sendInfotainment(
452
- Action(
453
- vehicleAction=VehicleAction(
454
- chargingStartStopAction=ChargingStartStopAction(start=Void())
455
- )
456
- )
457
- )
458
-
459
- async def charge_stop(self) -> dict[str, Any]:
460
- """Stops charging the vehicle."""
461
- return await self._sendInfotainment(
462
- Action(
463
- vehicleAction=VehicleAction(
464
- chargingStartStopAction=ChargingStartStopAction(stop=Void())
465
- )
466
- )
467
- )
468
-
469
- async def clear_pin_to_drive_admin(self, pin: str):
470
- """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."""
471
- return await self._sendInfotainment(
472
- Action(
473
- vehicleAction=VehicleAction(
474
- drivingClearSpeedLimitPinAction=DrivingClearSpeedLimitPinAction(
475
- pin=pin
476
- )
477
- )
478
- )
479
- )
480
-
481
- async def door_lock(self) -> dict[str, Any]:
482
- """Locks the vehicle."""
483
- return await self._sendVehicleSecurity(
484
- UnsignedMessage(RKEAction=RKEAction_E.RKE_ACTION_LOCK)
485
- )
486
-
487
- async def door_unlock(self) -> dict[str, Any]:
488
- """Unlocks the vehicle."""
489
- return await self._sendVehicleSecurity(
490
- UnsignedMessage(RKEAction=RKEAction_E.RKE_ACTION_UNLOCK)
491
- )
492
-
493
- async def erase_user_data(self) -> dict[str, Any]:
494
- """Erases user's data from the user interface. Requires the vehicle to be in park."""
495
- return await self._sendInfotainment(
496
- Action(
497
- vehicleAction=VehicleAction(eraseUserDataAction=EraseUserDataAction())
498
- )
499
- )
500
-
501
- async def flash_lights(self) -> dict[str, Any]:
502
- """Briefly flashes the vehicle headlights. Requires the vehicle to be in park."""
503
- return await self._sendInfotainment(
504
- Action(
505
- vehicleAction=VehicleAction(
506
- vehicleControlFlashLightsAction=VehicleControlFlashLightsAction()
507
- )
508
- )
509
- )
510
-
511
- async def guest_mode(self, enable: bool) -> dict[str, Any]:
512
- """Restricts certain vehicle UI functionality from guest users"""
513
- return await self._sendInfotainment(
514
- Action(
515
- vehicleAction=VehicleAction(
516
- guestModeAction=VehicleState.GuestMode(GuestModeActive=enable)
517
- )
518
- )
519
- )
520
-
521
- async def honk_horn(self) -> dict[str, Any]:
522
- """Honks the vehicle horn. Requires the vehicle to be in park."""
523
- return await self._sendInfotainment(
524
- Action(
525
- vehicleAction=VehicleAction(
526
- vehicleControlHonkHornAction=VehicleControlHonkHornAction()
527
- )
528
- )
529
- )
530
-
531
- async def media_next_fav(self) -> dict[str, Any]:
532
- """Advances media player to next favorite track."""
533
- return await self._sendInfotainment(
534
- Action(vehicleAction=VehicleAction(mediaNextFavorite=MediaNextFavorite()))
535
- )
536
-
537
- async def media_next_track(self) -> dict[str, Any]:
538
- """Advances media player to next track."""
539
- return await self._sendInfotainment(
540
- Action(vehicleAction=VehicleAction(mediaNextTrack=MediaNextTrack()))
541
- )
542
-
543
- async def media_prev_fav(self) -> dict[str, Any]:
544
- """Advances media player to previous favorite track."""
545
- return await self._sendInfotainment(
546
- Action(
547
- vehicleAction=VehicleAction(
548
- mediaPreviousFavorite=MediaPreviousFavorite()
549
- )
550
- )
551
- )
552
-
553
- async def media_prev_track(self) -> dict[str, Any]:
554
- """Advances media player to previous track."""
555
- return await self._sendInfotainment(
556
- Action(vehicleAction=VehicleAction(mediaPreviousTrack=MediaPreviousTrack()))
557
- )
558
-
559
- async def media_toggle_playback(self) -> dict[str, Any]:
560
- """Toggles current play/pause state."""
561
- return await self._sendInfotainment(
562
- Action(vehicleAction=VehicleAction(mediaPlayAction=MediaPlayAction()))
563
- )
564
-
565
- async def media_volume_down(self) -> dict[str, Any]:
566
- """Turns the volume down by one."""
567
- return await self._sendInfotainment(
568
- Action(
569
- vehicleAction=VehicleAction(
570
- mediaUpdateVolume=MediaUpdateVolume(volume_delta=-1)
571
- )
572
- )
573
- )
574
-
575
- # This one is new
576
- async def media_volume_up(self) -> dict[str, Any]:
577
- """Turns the volume up by one."""
578
- return await self._sendInfotainment(
579
- Action(
580
- vehicleAction=VehicleAction(
581
- mediaUpdateVolume=MediaUpdateVolume(volume_delta=1)
582
- )
583
- )
584
- )
585
-
586
- # navigation_gps_request doesnt require signing
587
- # navigation_request doesnt require signing
588
- # navigation_sc_request doesnt require signing
589
-
590
- async def remote_auto_seat_climate_request(
591
- self, auto_seat_position: int, auto_climate_on: bool
592
- ) -> dict[str, Any]:
593
- """Sets automatic seat heating and cooling."""
594
- # AutoSeatPosition_FrontLeft = 1;
595
- # AutoSeatPosition_FrontRight = 2;
596
- return await self._sendInfotainment(
597
- Action(
598
- vehicleAction=VehicleAction(
599
- autoSeatClimateAction=AutoSeatClimateAction(
600
- carseat=[
601
- AutoSeatClimateAction.CarSeat(
602
- on=auto_climate_on, seat_position=auto_seat_position
603
- )
604
- ]
605
- )
606
- )
607
- )
608
- )
609
-
610
- # remote_auto_steering_wheel_heat_climate_request has no protobuf
611
-
612
- # remote_boombox not implemented
613
-
614
- async def remote_seat_cooler_request(
615
- self, seat_position: int, seat_cooler_level: int
616
- ) -> dict[str, Any]:
617
- """Sets seat cooling."""
618
- # HvacSeatCoolerLevel_Unknown = 0;
619
- # HvacSeatCoolerLevel_Off = 1;
620
- # HvacSeatCoolerLevel_Low = 2;
621
- # HvacSeatCoolerLevel_Med = 3;
622
- # HvacSeatCoolerLevel_High = 4;
623
- # HvacSeatCoolerPosition_Unknown = 0;
624
- # HvacSeatCoolerPosition_FrontLeft = 1;
625
- # HvacSeatCoolerPosition_FrontRight = 2;
626
- return await self._sendInfotainment(
627
- Action(
628
- vehicleAction=VehicleAction(
629
- hvacSeatCoolerActions=HvacSeatCoolerActions(
630
- hvacSeatCoolerAction=[
631
- HvacSeatCoolerActions.HvacSeatCoolerAction(
632
- seat_cooler_level=seat_cooler_level + 1,
633
- seat_position=seat_position,
634
- )
635
- ]
636
- )
637
- )
638
- )
639
- )
640
-
641
- async def remote_seat_heater_request(
642
- self, seat_position: int, seat_heater_level: int
643
- ) -> dict[str, Any]:
644
- """Sets seat heating."""
645
- # HvacSeatCoolerLevel_Unknown = 0;
646
- # HvacSeatCoolerLevel_Off = 1;
647
- # HvacSeatCoolerLevel_Low = 2;
648
- # HvacSeatCoolerLevel_Med = 3;
649
- # HvacSeatCoolerLevel_High = 4;
650
- # Void CAR_SEAT_UNKNOWN = 6;
651
- # Void CAR_SEAT_FRONT_LEFT = 7;
652
- # Void CAR_SEAT_FRONT_RIGHT = 8;
653
- # Void CAR_SEAT_REAR_LEFT = 9;
654
- # Void CAR_SEAT_REAR_LEFT_BACK = 10;
655
- # Void CAR_SEAT_REAR_CENTER = 11;
656
- # Void CAR_SEAT_REAR_RIGHT = 12;
657
- # Void CAR_SEAT_REAR_RIGHT_BACK = 13;
658
- # Void CAR_SEAT_THIRD_ROW_LEFT = 14;
659
- # Void CAR_SEAT_THIRD_ROW_RIGHT = 15;
660
-
661
- heater_action_dict = {}
662
- match seat_position:
663
- case 0:
664
- heater_action_dict["CAR_SEAT_FRONT_LEFT"] = Void()
665
- case 1:
666
- heater_action_dict["CAR_SEAT_FRONT_RIGHT"] = Void()
667
- case 2:
668
- heater_action_dict["CAR_SEAT_REAR_LEFT"] = Void()
669
- case 3:
670
- heater_action_dict["CAR_SEAT_REAR_LEFT_BACK"] = Void()
671
- case 4:
672
- heater_action_dict["CAR_SEAT_REAR_CENTER"] = Void()
673
- case 5:
674
- heater_action_dict["CAR_SEAT_REAR_RIGHT"] = Void()
675
- case 6:
676
- heater_action_dict["CAR_SEAT_REAR_RIGHT_BACK"] = Void()
677
- case 7:
678
- heater_action_dict["CAR_SEAT_THIRD_ROW_LEFT"] = Void()
679
- case 8:
680
- heater_action_dict["CAR_SEAT_THIRD_ROW_RIGHT"] = Void()
681
- case _:
682
- raise ValueError(f"Invalid seat position: {seat_position}")
683
- match seat_heater_level:
684
- case 0:
685
- heater_action_dict["SEAT_HEATER_OFF"] = Void()
686
- case 1:
687
- heater_action_dict["SEAT_HEATER_LOW"] = Void()
688
- case 2:
689
- heater_action_dict["SEAT_HEATER_MEDIUM"] = Void()
690
- case 3:
691
- heater_action_dict["SEAT_HEATER_HIGH"] = Void()
692
- case _:
693
- raise ValueError(f"Invalid seat heater level: {seat_heater_level}")
694
-
695
- heater_action = HvacSeatHeaterActions.HvacSeatHeaterAction(**heater_action_dict)
696
- return await self._sendInfotainment(
697
- Action(
698
- vehicleAction=VehicleAction(
699
- hvacSeatHeaterActions=HvacSeatHeaterActions(
700
- hvacSeatHeaterAction=[heater_action]
701
- )
702
- )
703
- )
704
- )
705
-
706
- async def remote_start_drive(self) -> dict[str, Any]:
707
- """Starts the vehicle remotely. Requires keyless driving to be enabled."""
708
- return await self._sendVehicleSecurity(
709
- UnsignedMessage(RKEAction=RKEAction_E.RKE_ACTION_REMOTE_DRIVE)
710
- )
711
-
712
- async def remote_steering_wheel_heat_level_request(
713
- self, level: int
714
- ) -> dict[str, Any]:
715
- """Sets steering wheel heat level."""
716
- raise NotImplementedError()
717
-
718
- async def remote_steering_wheel_heater_request(self, on: bool) -> dict[str, Any]:
719
- """Sets steering wheel heating on/off. For vehicles that do not support auto steering wheel heat."""
720
- return await self._sendInfotainment(
721
- Action(
722
- vehicleAction=VehicleAction(
723
- hvacSteeringWheelHeaterAction=HvacSteeringWheelHeaterAction(
724
- power_on=on
725
- )
726
- )
727
- )
728
- )
729
-
730
- async def reset_pin_to_drive_pin(self) -> dict[str, Any]:
731
- """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."""
732
- return await self._sendInfotainment(
733
- Action(
734
- vehicleAction=VehicleAction(
735
- vehicleControlResetPinToDriveAction=VehicleControlResetPinToDriveAction()
736
- )
737
- )
738
- )
739
-
740
- async def reset_valet_pin(self) -> dict[str, Any]:
741
- """Removes PIN for Valet Mode."""
742
- return await self._sendInfotainment(
743
- Action(
744
- vehicleAction=VehicleAction(
745
- vehicleControlResetValetPinAction=VehicleControlResetValetPinAction()
746
- )
747
- )
748
- )
749
-
750
- async def schedule_software_update(self, offset_sec: int) -> dict[str, Any]:
751
- """Schedules a vehicle software update (over the air "OTA") to be installed in the future."""
752
- return await self._sendInfotainment(
753
- Action(
754
- vehicleAction=VehicleAction(
755
- vehicleControlScheduleSoftwareUpdateAction=VehicleControlScheduleSoftwareUpdateAction(
756
- offset_sec=offset_sec
757
- )
758
- )
759
- )
760
- )
761
-
762
- async def set_bioweapon_mode(
763
- self, on: bool, manual_override: bool
764
- ) -> dict[str, Any]:
765
- """Turns Bioweapon Defense Mode on and off."""
766
- return await self._sendInfotainment(
767
- Action(
768
- vehicleAction=VehicleAction(
769
- hvacBioweaponModeAction=HvacBioweaponModeAction(
770
- on=on, manual_override=manual_override
771
- )
772
- )
773
- )
774
- )
775
-
776
- async def set_cabin_overheat_protection(
777
- self, on: bool, fan_only: bool
778
- ) -> dict[str, Any]:
779
- """Sets the vehicle overheat protection."""
780
- return await self._sendInfotainment(
781
- Action(
782
- vehicleAction=VehicleAction(
783
- setCabinOverheatProtectionAction=SetCabinOverheatProtectionAction(
784
- on=on, fan_only=fan_only
785
- )
786
- )
787
- )
788
- )
789
-
790
- async def set_charge_limit(self, percent: int) -> dict[str, Any]:
791
- """Sets the vehicle charge limit."""
792
- return await self._sendInfotainment(
793
- Action(
794
- vehicleAction=VehicleAction(
795
- chargingSetLimitAction=ChargingSetLimitAction(percent=percent)
796
- )
797
- )
798
- )
799
-
800
- async def set_charging_amps(self, charging_amps: int) -> dict[str, Any]:
801
- """Sets the vehicle charging amps."""
802
- return await self._sendInfotainment(
803
- Action(
804
- vehicleAction=VehicleAction(
805
- setChargingAmpsAction=SetChargingAmpsAction(
806
- charging_amps=charging_amps
807
- )
808
- )
809
- )
810
- )
811
-
812
- async def set_climate_keeper_mode(
813
- self, climate_keeper_mode: ClimateKeeperMode | int
814
- ) -> dict[str, Any]:
815
- """Enables climate keeper mode."""
816
- if isinstance(climate_keeper_mode, ClimateKeeperMode):
817
- climate_keeper_mode = climate_keeper_mode.value
818
- return await self._sendInfotainment(
819
- Action(
820
- vehicleAction=VehicleAction(
821
- hvacClimateKeeperAction=HvacClimateKeeperAction(
822
- ClimateKeeperAction=climate_keeper_mode,
823
- # manual_override
824
- )
825
- )
826
- )
827
- )
828
-
829
- async def set_cop_temp(
830
- self, cop_temp: CabinOverheatProtectionTemp | int
831
- ) -> dict[str, Any]:
832
- """Adjusts the Cabin Overheat Protection temperature (COP)."""
833
- if isinstance(cop_temp, CabinOverheatProtectionTemp):
834
- cop_temp = cop_temp.value
835
- return await self._sendInfotainment(
836
- Action(
837
- vehicleAction=VehicleAction(
838
- setCopTempAction=SetCopTempAction(copActivationTemp=cop_temp + 1)
839
- )
840
- )
841
- )
842
-
843
- async def set_pin_to_drive(self, on: bool, password: str | int) -> dict[str, Any]:
844
- """Sets a four-digit passcode for PIN to Drive. This PIN must then be entered before the vehicle can be driven."""
845
- return await self._sendInfotainment(
846
- Action(
847
- vehicleAction=VehicleAction(
848
- vehicleControlSetPinToDriveAction=VehicleControlSetPinToDriveAction(
849
- on=on, password=str(password)
850
- )
851
- )
852
- )
853
- )
854
-
855
- async def set_preconditioning_max(
856
- self, on: bool, manual_override: bool
857
- ) -> dict[str, Any]:
858
- """Sets an override for preconditioning — it should default to empty if no override is used."""
859
- return await self._sendInfotainment(
860
- Action(
861
- vehicleAction=VehicleAction(
862
- hvacSetPreconditioningMaxAction=HvacSetPreconditioningMaxAction(
863
- on=on,
864
- manual_override=manual_override,
865
- # manual_override_mode
866
- )
867
- )
868
- )
869
- )
870
-
871
- async def set_scheduled_charging(self, enable: bool, time: int) -> dict[str, Any]:
872
- """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)."""
873
- return await self._sendInfotainment(
874
- Action(
875
- vehicleAction=VehicleAction(
876
- scheduledChargingAction=ScheduledChargingAction(
877
- enable=enable, charging_time=time
878
- )
879
- )
880
- )
881
- )
882
-
883
- async def set_scheduled_departure(
884
- self,
885
- enable: bool = True,
886
- preconditioning_enabled: bool = False,
887
- preconditioning_weekdays_only: bool = False,
888
- departure_time: int = 0,
889
- off_peak_charging_enabled: bool = False,
890
- off_peak_charging_weekdays_only: bool = False,
891
- end_off_peak_time: int = 0,
892
- ) -> dict[str, Any]:
893
- """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)."""
894
-
895
- if preconditioning_weekdays_only:
896
- preconditioning_times = PreconditioningTimes(weekdays=Void)
897
- else:
898
- preconditioning_times = PreconditioningTimes(all_week=Void)
899
-
900
- if off_peak_charging_weekdays_only:
901
- off_peak_charging_times = OffPeakChargingTimes(weekdays=Void)
902
- else:
903
- off_peak_charging_times = OffPeakChargingTimes(all_week=Void)
904
-
905
- return await self._sendInfotainment(
906
- Action(
907
- vehicleAction=VehicleAction(
908
- scheduledDepartureAction=ScheduledDepartureAction(
909
- enabled=enable,
910
- departure_time=departure_time,
911
- preconditioning_times=preconditioning_times,
912
- off_peak_charging_times=off_peak_charging_times,
913
- off_peak_hours_end_time=end_off_peak_time,
914
- )
915
- )
916
- )
917
- )
918
-
919
- async def set_sentry_mode(self, on: bool) -> dict[str, Any]:
920
- """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."""
921
- return await self._sendInfotainment(
922
- Action(
923
- vehicleAction=VehicleAction(
924
- vehicleControlSetSentryModeAction=VehicleControlSetSentryModeAction(
925
- on=on
926
- )
927
- )
928
- )
929
- )
930
-
931
- async def set_temps(
932
- self, driver_temp: float, passenger_temp: float
933
- ) -> dict[str, Any]:
934
- """Sets the driver and/or passenger-side cabin temperature (and other zones if sync is enabled)."""
935
- return await self._sendInfotainment(
936
- Action(
937
- vehicleAction=VehicleAction(
938
- hvacTemperatureAdjustmentAction=HvacTemperatureAdjustmentAction(
939
- driver_temp_celsius=driver_temp,
940
- passenger_temp_celsius=passenger_temp,
941
- )
942
- )
943
- )
944
- )
945
-
946
- async def set_valet_mode(self, on: bool, password: str | int) -> dict[str, Any]:
947
- """Turns on Valet Mode and sets a four-digit passcode that must then be entered to disable Valet Mode."""
948
- return await self._sendInfotainment(
949
- Action(
950
- vehicleAction=VehicleAction(
951
- vehicleControlSetValetModeAction=VehicleControlSetValetModeAction(
952
- on=on, password=str(password)
953
- )
954
- )
955
- )
956
- )
957
-
958
- async def set_vehicle_name(self, vehicle_name: str) -> dict[str, Any]:
959
- """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."""
960
- return await self._sendInfotainment(
961
- Action(
962
- vehicleAction=VehicleAction(
963
- setVehicleNameAction=SetVehicleNameAction(vehicle_name=vehicle_name)
964
- )
965
- )
966
- )
967
-
968
- async def speed_limit_activate(self, pin: str | int) -> dict[str, Any]:
969
- """Activates Speed Limit Mode with a four-digit PIN."""
970
- return await self._sendInfotainment(
971
- Action(
972
- vehicleAction=VehicleAction(
973
- drivingSpeedLimitAction=DrivingSpeedLimitAction(
974
- activate=True, pin=str(pin)
975
- )
976
- )
977
- )
978
- )
979
-
980
- async def speed_limit_clear_pin(self, pin: str | int) -> dict[str, Any]:
981
- """Deactivates Speed Limit Mode and resets the associated PIN."""
982
- return await self._sendInfotainment(
983
- Action(
984
- vehicleAction=VehicleAction(
985
- drivingClearSpeedLimitPinAction=DrivingClearSpeedLimitPinAction(
986
- pin=str(pin)
987
- )
988
- )
989
- )
990
- )
991
-
992
- # speed_limit_clear_pin_admin doesnt require signing
993
-
994
- async def speed_limit_deactivate(self, pin: str | int) -> dict[str, Any]:
995
- """Deactivates Speed Limit Mode."""
996
- return await self._sendInfotainment(
997
- Action(
998
- vehicleAction=VehicleAction(
999
- drivingSpeedLimitAction=DrivingSpeedLimitAction(
1000
- activate=False, pin=str(pin)
1001
- )
1002
- )
1003
- )
1004
- )
1005
-
1006
- async def speed_limit_set_limit(self, limit_mph: int) -> dict[str, Any]:
1007
- """Sets the maximum speed allowed when Speed Limit Mode is active."""
1008
- return await self._sendInfotainment(
1009
- Action(
1010
- vehicleAction=VehicleAction(
1011
- drivingSetSpeedLimitAction=DrivingSetSpeedLimitAction(
1012
- limit_mph=limit_mph
1013
- )
1014
- )
1015
- )
1016
- )
1017
-
1018
- async def sun_roof_control(self, state: str | SunRoofCommand) -> dict[str, Any]:
1019
- """Controls the panoramic sunroof on the Model S."""
1020
- if isinstance(state, SunRoofCommand):
1021
- state = state.value
1022
- action = VehicleControlSunroofOpenCloseAction()
1023
- match state:
1024
- case "vent":
1025
- action = VehicleControlSunroofOpenCloseAction(vent=Void())
1026
- case "open":
1027
- action = VehicleControlSunroofOpenCloseAction(open=Void())
1028
- case "close":
1029
- action = VehicleControlSunroofOpenCloseAction(close=Void())
1030
-
1031
- return await self._sendInfotainment(
1032
- Action(
1033
- vehicleAction=VehicleAction(
1034
- vehicleControlSunroofOpenCloseAction=action
1035
- )
1036
- )
1037
- )
1038
-
1039
- # take_drivenote doesnt require signing
1040
-
1041
- async def trigger_homelink(
1042
- self,
1043
- token: str | None = None,
1044
- lat: float | None = None,
1045
- lon: float | None = None,
1046
- ) -> dict[str, Any]:
1047
- """Turns on HomeLink (used to open and close garage doors)."""
1048
- action = VehicleControlTriggerHomelinkAction()
1049
- if lat is not None and lon is not None:
1050
- action.location.latitude = lat
1051
- action.location.longitude = lon
1052
- if token is not None:
1053
- action.token = token
1054
-
1055
- return await self._sendInfotainment(
1056
- Action(
1057
- vehicleAction=VehicleAction(vehicleControlTriggerHomelinkAction=action)
1058
- )
1059
- )
1060
-
1061
- # upcoming_calendar_entries doesnt require signing
1062
-
1063
- async def window_control(
1064
- self,
1065
- command: str | WindowCommand,
1066
- lat: float | None = None,
1067
- lon: float | None = None,
1068
- ) -> dict[str, Any]:
1069
- """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)."""
1070
- if isinstance(command, WindowCommand):
1071
- command = command.value
1072
-
1073
- if command == "vent":
1074
- action = VehicleControlWindowAction(vent=Void())
1075
- elif command == "close":
1076
- action = VehicleControlWindowAction(close=Void())
1077
-
1078
- return await self._sendInfotainment(
1079
- Action(vehicleAction=VehicleAction(vehicleControlWindowAction=action))
1080
- )
1081
-
1082
- # drivers doesnt require signing
1083
- # drivers_remove doesnt require signing
1084
- # mobile_enabled
1085
-
1086
- async def nearby_charging_sites(
1087
- self,
1088
- count: int | None = None,
1089
- radius: int | None = None,
1090
- detail: bool | None = None,
1091
- ) -> dict[str, Any]:
1092
- """Returns the charging sites near the current location of the vehicle."""
1093
- action = GetNearbyChargingSites()
1094
- if count is not None:
1095
- action.count = count
1096
- if radius is not None:
1097
- action.radius = radius
1098
- if detail is not None:
1099
- action.include_meta_data = detail
1100
-
1101
- return await self._sendInfotainment(
1102
- Action(vehicleAction=VehicleAction(getNearbyChargingSites=action))
1103
- )
1104
-
1105
- # options doesnt require signing
1106
- # recent_alerts doesnt require signing
1107
- # release_notes doesnt require signing
1108
- # service_data doesnt require signing
1109
- # share_invites doesnt require signing
1110
- # share_invites_create doesnt require signing
1111
- # share_invites_redeem doesnt require signing
1112
- # share_invites_revoke doesnt require signing
1113
- # signed command doesnt require signing
1114
- # vehicle doesnt require signing
1115
- # vehicle_data doesnt require signing
1116
- # wake_up doesnt require signing
1117
- # warranty_details doesnt require signing
1118
- # fleet_status doesnt require signing
1119
-
1120
- async def fleet_telemetry_config_create(
1121
- self, config: dict[str, Any]
1122
- ) -> dict[str, Any]:
1123
- """Configures fleet telemetry."""
1124
- raise NotImplementedError
1125
-
1126
- # fleet_telemetry_config_get doesnt require signing
1127
- # fleet_telemetry_config_delete doesnt require signing