tesla-fleet-api 0.7.8__py3-none-any.whl → 0.8.1__py3-none-any.whl

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