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

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