-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
1428 lines (1284 loc) · 58.5 KB
/
Copy pathapi.py
File metadata and controls
1428 lines (1284 loc) · 58.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Smart vehicle cloud API client."""
from __future__ import annotations
import json
import logging
from datetime import datetime
from typing import Any
from urllib.parse import urlparse
import aiohttp
from .auth import AuthenticationError, build_signed_headers, build_vc_signed_headers
from .const import (
API_CHARGING_RESERVATION_PATH,
API_CLIMATE_SCHEDULE_PATH,
API_CODE_SUCCESS,
API_CODE_TOKEN_EXPIRED,
API_CODE_VEHICLE_NOT_LINKED,
API_TELEMATICS_COMMAND_PATH,
API_VC_ABILITY_PATH,
EU_API_BASE_URL,
OTA_BASE_URL,
URL_ALLOWLIST,
VC_EU_BASE_URL,
VC_INTL_BASE_URL,
)
from .models import (
Account,
AuthState,
ChargingReservation,
ChargingState,
ClimateSchedule,
CommandResult,
DiagnosticEntry,
EnergyRanking,
FOTANotification,
FragranceDetails,
FridgeStatus,
GeofenceInfo,
LockerSecret,
LockerStatus,
OTAInfo,
Region,
TelematicsStatus,
TripJournal,
Vehicle,
VehicleAbility,
VehicleCapabilities,
VehicleData,
VehicleRunningState,
VehicleStatus,
VtmSettings,
charging_state_from_api,
power_mode_from_api,
)
_LOGGER = logging.getLogger(__name__)
class SmartAPIError(Exception):
"""Base exception for Smart API errors."""
class TokenExpiredError(SmartAPIError):
"""Raised when the API reports token expiry (code 1402 or HTTP 401)."""
class VehicleNotLinkedError(SmartAPIError):
"""Raised when the API reports vehicle not linked (code 8006)."""
class RateLimitedError(SmartAPIError):
"""Raised when the API returns HTTP 429."""
def __init__(self, retry_after: int = 60) -> None:
super().__init__(f"Rate limited, retry after {retry_after}s")
self.retry_after = retry_after
class SmartAPI:
"""Client for the Smart vehicle cloud API."""
def __init__(self, session: aiohttp.ClientSession) -> None:
self._session = session
def _validate_url(self, url: str) -> None:
"""Validate URL against the allowlist (FR-015) and enforce HTTPS (FR-016)."""
parsed = urlparse(url)
if parsed.scheme != "https":
raise SmartAPIError(f"HTTPS required, got {parsed.scheme}")
if parsed.hostname not in URL_ALLOWLIST:
raise SmartAPIError(f"URL host not in allowlist: {parsed.hostname}")
async def _signed_request(
self,
method: str,
url: str,
account: Account,
*,
json_body: dict | None = None,
) -> dict:
"""Execute a signed API request and handle standard error codes."""
self._validate_url(url)
body_str: str | None = None
if json_body is not None:
body_str = json.dumps(json_body)
headers = build_signed_headers(method, url, body_str, account)
kwargs: dict = {"headers": headers}
if body_str is not None:
kwargs["data"] = body_str
async with self._session.request(method, url, **kwargs) as resp:
if resp.status == 401:
raise TokenExpiredError("HTTP 401 Unauthorized")
if resp.status == 429:
retry_after = int(resp.headers.get("Retry-After", "60"))
raise RateLimitedError(retry_after)
resp.raise_for_status()
data = await resp.json()
code = data.get("code")
try:
code = int(code) if code is not None else None
except (ValueError, TypeError):
pass
if code == API_CODE_TOKEN_EXPIRED:
raise TokenExpiredError("API code 1402: token expired")
if code == API_CODE_VEHICLE_NOT_LINKED:
raise VehicleNotLinkedError("API code 8006: vehicle not linked")
if code != API_CODE_SUCCESS:
raise SmartAPIError(f"API error code {code}: {data}")
return data
async def async_get_vehicles(self, account: Account) -> list[Vehicle]:
"""Fetch list of vehicles for the authenticated account."""
base_url = self._get_base_url(account)
url = (
f"{base_url}/device-platform/user/vehicle/secure"
f"?needSharedCar=1&userId={account.api_user_id}"
)
data = await self._signed_request("GET", url, account)
vehicles: list[Vehicle] = []
for item in data.get("data", {}).get("list", []):
vehicle = Vehicle(
vin=item.get("vin", ""),
model_name=item.get("modelName", ""),
model_year=item.get("modelYear", ""),
series_code=item.get("seriesCodeVs", ""),
base_url=base_url,
color_name=item.get("colorName", ""),
color_code=item.get("colorCode", ""),
model_code=item.get("modelCode", ""),
factory_code=item.get("factoryCode", ""),
vehicle_photo_small=item.get("vehiclePhotoSmall", ""),
vehicle_photo_big=item.get("vehiclePhotoBig", ""),
plate_no=item.get("plateNo", ""),
engine_no=item.get("engineNo", ""),
mat_code=item.get("matCode", ""),
series_name=item.get("seriesName", ""),
vehicle_type=item.get("vehicleType", ""),
fuel_tank_capacity=item.get("fuelTankCapacity", ""),
ihu_platform=item.get("ihuPlatform", ""),
tbox_platform=item.get("tboxPlatform", ""),
default_vehicle=bool(item.get("defaultVehicle", False)),
share_status=item.get("shareStatus", ""),
iccid=item.get("iccid", ""),
msisdn=item.get("msisdn", ""),
tem_id=item.get("temId", ""),
ihu_id=item.get("ihuId", ""),
tem_type=item.get("temType", ""),
)
vehicles.append(vehicle)
_LOGGER.debug("Discovered %d vehicle(s)", len(vehicles))
return vehicles
async def async_select_vehicle(
self, account: Account, vin: str
) -> None:
"""Select the active vehicle (required before fetching status)."""
base_url = self._get_base_url(account)
url = f"{base_url}/device-platform/user/session/update"
body = {
"vin": vin,
"sessionToken": account.api_access_token,
"language": "",
}
await self._signed_request("POST", url, account, json_body=body)
_LOGGER.debug("Selected vehicle %s", vin[:6] + "...")
async def async_get_vehicle_status(
self, account: Account, vin: str
) -> VehicleStatus:
"""Fetch current status for a vehicle."""
base_url = self._get_base_url(account)
if account.region == Region.EU:
latest = "true"
else:
# INTL: Python bool repr per reference
latest = "False"
target = "basic,more"
url = (
f"{base_url}/remote-control/vehicle/status/{vin}"
f"?latest={latest}&target={target}&userId={account.api_user_id}"
)
data = await self._signed_request("GET", url, account)
vehicle_status_data = (
data.get("data", {})
.get("vehicleStatus", {})
.get("additionalVehicleStatus", {})
)
return self._parse_vehicle_status(vehicle_status_data, data)
async def async_get_soc(
self, account: Account, vin: str
) -> dict:
"""Fetch SOC / charging target for a vehicle.
Returns dict with 'target_soc' (int, 0-100) extracted from the API's
soc field (which is percentage * 10, e.g. '1000' = 100%).
"""
base_url = self._get_base_url(account)
url = (
f"{base_url}/remote-control/vehicle/status/soc/{vin}"
f"?setting=charging"
)
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
result: dict = {}
if d.get("soc"):
try:
result["target_soc"] = int(d["soc"]) // 10
except (ValueError, TypeError):
pass
# Capture all other SOC endpoint fields
if d.get("chargeUAct"):
try:
result["charge_voltage"] = float(d["chargeUAct"])
except (ValueError, TypeError):
pass
if d.get("chargeIAct"):
try:
result["charge_current"] = float(d["chargeIAct"])
except (ValueError, TypeError):
pass
if d.get("timeToFullyCharged"):
try:
result["time_to_full"] = int(d["timeToFullyCharged"])
except (ValueError, TypeError):
pass
if d.get("chargeLevel"):
try:
result["charge_level"] = int(d["chargeLevel"])
except (ValueError, TypeError):
pass
if d.get("chargerState"):
try:
result["charger_state"] = int(d["chargerState"])
except (ValueError, TypeError):
pass
return result
async def async_get_ota_info(
self, account: Account, vin: str
) -> OTAInfo:
"""Fetch OTA firmware info for a vehicle (different host, no HMAC signing)."""
url = f"{OTA_BASE_URL}/app/info/{vin}"
self._validate_url(url)
headers = {
"id-token": account.device_id,
"access_token": account.api_access_token,
"content-type": "application/json",
}
async with self._session.get(url, headers=headers) as resp:
if resp.status == 403:
_LOGGER.debug("OTA endpoint returned 403 — may not be available for this region")
return OTAInfo(current_version="", target_version="")
resp.raise_for_status()
data = await resp.json()
return OTAInfo(
current_version=data.get("currentVersion", ""),
target_version=data.get("targetVersion", ""),
)
async def async_get_vehicle_state(
self, account: Account, vin: str
) -> VehicleRunningState:
"""Fetch condensed vehicle running state."""
base_url = self._get_base_url(account)
url = f"{base_url}/remote-control/vehicle/status/state/{vin}"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
return VehicleRunningState(
power_mode=power_mode_from_api(d.get("powerMode", "0")),
speed=float(d.get("speed", 0) or 0),
engine_status=d.get("engineStatus", ""),
usage_mode=d.get("usageMode", ""),
car_mode=d.get("carMode", ""),
)
async def async_get_telematics(
self, account: Account, vin: str
) -> TelematicsStatus:
"""Fetch telematics unit status."""
base_url = self._get_base_url(account)
url = f"{base_url}/remote-control/vehicle/telematics/{vin}"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
backup = d.get("backupBattery", {}) or {}
connected_raw = d.get("connectivityStatus", "")
return TelematicsStatus(
connected=connected_raw == "connected" if connected_raw else None,
sw_version=d.get("swVersion", ""),
hw_version=d.get("hwVersion", ""),
imei=d.get("imei", ""),
power_mode=power_mode_from_api(d.get("powerMode", "0")) if d.get("powerMode") else None,
backup_battery_voltage=float(backup.get("voltage", 0) or 0) if backup.get("voltage") else None,
backup_battery_level=float(backup.get("stateOfCharge", 0) or 0) if backup.get("stateOfCharge") else None,
)
async def async_get_diagnostic_history(
self, account: Account, vin: str
) -> DiagnosticEntry | None:
"""Fetch most recent diagnostic entry."""
base_url = self._get_base_url(account)
url = f"{base_url}/remote-control/vehicle/status/history/diagnostic/{vin}"
data = await self._signed_request("GET", url, account)
entries = data.get("data", {}).get("diagnosticList", [])
if not entries:
return None
latest = entries[0]
ts = None
if latest.get("timestamp"):
try:
ts = datetime.fromtimestamp(int(latest["timestamp"]) / 1000)
except (ValueError, TypeError, OSError):
pass
return DiagnosticEntry(
dtc_code=latest.get("dtcCode", ""),
severity=latest.get("severity", ""),
timestamp=ts,
status=latest.get("status", ""),
)
async def async_get_charging_reservation(
self, account: Account, vin: str
) -> ChargingReservation | None:
"""Fetch charging reservation / schedule.
The API returns a paginated command history. When list is null or
empty, no reservation exists. Otherwise parse the latest entry.
"""
base_url = self._get_base_url(account)
url = f"{base_url}/remote-control/charging/reservation/{vin}"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
# Real API returns {pagination, serviceResult, list}
entries = d.get("list")
if not entries:
return None
# Parse the latest reservation entry
latest = entries[0] if isinstance(entries, list) else None
if not latest:
return None
return ChargingReservation(
active=latest.get("reservationStatus") == "active",
start_time=latest.get("startTime", ""),
end_time=latest.get("endTime", ""),
target_soc=int(latest["targetSoc"]) if latest.get("targetSoc") else None,
)
async def async_get_climate_schedule(
self, account: Account, vin: str
) -> ClimateSchedule | None:
"""Fetch climate pre-conditioning schedule."""
base_url = self._get_base_url(account)
url = f"{base_url}/remote-control/schedule/{vin}"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
if isinstance(d, list):
schedules = d
elif isinstance(d, dict):
schedules = d.get("scheduleList", [])
else:
schedules = []
if not schedules:
return None
s = schedules[0]
return ClimateSchedule(
schedule_id=s.get("scheduleId", ""),
enabled=bool(s.get("enabled", False)),
scheduled_time=s.get("scheduledTime", ""),
temperature=float(s["temperature"]) if s.get("temperature") else None,
duration=int(s["duration"]) if s.get("duration") else None,
)
async def async_get_fridge_status(
self, account: Account, vin: str
) -> FridgeStatus:
"""Fetch mini-fridge status."""
base_url = self._get_base_url(account)
url = f"{base_url}/remote-control/getFridge/status/{vin}"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
return FridgeStatus(
active=d.get("fridgeStatus") == "on",
temperature=float(d["temperature"]) if d.get("temperature") else None,
mode=d.get("mode", ""),
)
async def async_get_locker_status(
self, account: Account, vin: str
) -> LockerStatus:
"""Fetch locker / front trunk status."""
base_url = self._get_base_url(account)
url = f"{base_url}/remote-control/getLocker/status/{vin}"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
return LockerStatus(
open=d.get("lockerStatus") == "open" if d.get("lockerStatus") else None,
locked=d.get("lockStatus") == "locked" if d.get("lockStatus") else None,
)
async def async_get_vtm_settings(
self, account: Account
) -> VtmSettings:
"""Fetch vehicle theft monitoring settings."""
base_url = self._get_base_url(account)
url = f"{base_url}/remote-control/getVtmSettingStatus"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
return VtmSettings(
enabled=bool(d.get("vtmEnabled", False)),
notification_enabled=bool(d.get("notificationEnabled", False)),
geofence_alert_enabled=bool(d.get("geofenceAlertEnabled", False)),
movement_alert_enabled=bool(d.get("movementAlertEnabled", False)),
)
async def async_get_fragrance(
self, account: Account, vin: str
) -> FragranceDetails:
"""Fetch extended fragrance system status."""
base_url = self._get_base_url(account)
url = f"{base_url}/remote-control/vehicle/fragrance/{vin}"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
return FragranceDetails(
active=bool(d.get("fragranceActive", False)),
level=d.get("fragranceLevel", ""),
fragrance_type=d.get("fragranceType", ""),
)
async def async_get_trip_journal(
self, account: Account, vin: str
) -> tuple[TripJournal | None, int | None]:
"""Fetch most recent trip from journal.
Returns a tuple of (trip, total_trips).
"""
base_url = self._get_base_url(account)
url = f"{base_url}/geelyTCAccess/tcservices/vehicle/status/journalLogV4/{vin}"
data = await self._signed_request("GET", url, account)
journal_data = data.get("data", {})
logs = journal_data.get("journalLogs", [])
total_trips = None
if journal_data.get("totalTrips"):
try:
total_trips = int(journal_data["totalTrips"])
except (ValueError, TypeError):
pass
if not logs:
return None, total_trips
t = logs[0]
start_time = None
end_time = None
if t.get("startTime"):
try:
start_time = datetime.fromtimestamp(int(t["startTime"]) / 1000)
except (ValueError, TypeError, OSError):
pass
if t.get("endTime"):
try:
end_time = datetime.fromtimestamp(int(t["endTime"]) / 1000)
except (ValueError, TypeError, OSError):
pass
trip = TripJournal(
trip_id=t.get("tripId", ""),
distance=float(t["distance"]) if t.get("distance") else None,
duration=int(t["duration"]) if t.get("duration") else None,
energy_consumption=float(t["energyConsumption"]) if t.get("energyConsumption") else None,
avg_energy_consumption=float(t["averageEnergyConsumption"]) if t.get("averageEnergyConsumption") else None,
avg_speed=float(t["averageSpeed"]) if t.get("averageSpeed") else None,
max_speed=float(t["maxSpeed"]) if t.get("maxSpeed") else None,
start_time=start_time,
end_time=end_time,
regenerated_energy=float(t["regeneratedEnergy"]) if t.get("regeneratedEnergy") else None,
start_address=t.get("startAddress", ""),
end_address=t.get("endAddress", ""),
)
return trip, total_trips
async def async_get_total_distance(
self, account: Account, vin: str
) -> tuple[float | None, datetime | None]:
"""Fetch total distance from TC endpoint.
Returns a tuple of (distance, update_time).
"""
base_url = self._get_base_url(account)
url = f"{base_url}/geelyTCAccess/tcservices/vehicle/status/getTotalDistanceByLabel/{vin}"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
distance = None
update_time = None
if d.get("totalDistance"):
try:
distance = float(d["totalDistance"])
except (ValueError, TypeError):
pass
if d.get("updateTime"):
try:
update_time = datetime.fromtimestamp(int(d["updateTime"]) / 1000)
except (ValueError, TypeError, OSError):
pass
return distance, update_time
async def async_get_geofences(
self, account: Account, vin: str
) -> GeofenceInfo:
"""Fetch geofence summary."""
base_url = self._get_base_url(account)
url = f"{base_url}/geelyTCAccess/tcservices/vehicle/geofence/all/{vin}"
data = await self._signed_request("GET", url, account)
d = data.get("data", [])
if isinstance(d, list):
fences = d
else:
fences = d.get("geofences", []) if isinstance(d, dict) else []
return GeofenceInfo(count=len(fences), geofences=fences)
async def async_get_capabilities(
self, account: Account, vin: str
) -> VehicleCapabilities:
"""Fetch vehicle capability flags."""
base_url = self._get_base_url(account)
url = f"{base_url}/geelyTCAccess/tcservices/capability/{vin}"
data = await self._signed_request("GET", url, account)
inner = data.get("data", {})
# Primary format: APK model (TscVehicleCapability) with data.list[]
cap_list = inner.get("list", [])
if cap_list:
_LOGGER.debug(
"Capability response uses 'list' format (%d entries) for %s",
len(cap_list),
vin[:6] + "...",
)
capability_flags = {
c["functionId"]: c.get("valueEnable", False)
for c in cap_list
if c.get("functionId")
}
# The API may return v2 capability IDs (with _2 suffix or
# renamed keys) while the APK FunctionId constants use v1
# names. Propagate v2 values to their v1 aliases so entity
# filtering works regardless of API version.
_V2_TO_V1: dict[str, list[str]] = {
"charging_status_2": ["charging_status"],
"remote_climate_control_2": [
"remote_air_condition_switch",
"climate_status",
],
"curtain_status_2": ["curtain_status"],
"sunroof_automatic_close": ["skylight_rolling_status"],
"recharge_lid_status_2": ["recharge_lid_status"],
"remote_control_lock_2": ["remote_control_lock"],
"remote_control_unlock_2": ["remote_control_unlock"],
"remote_control_window_2": [
"remote_window_close",
"remote_window_open",
],
"remote_control_ventilate_2": ["seat_ventilation_status"],
"tire_pressure_warning_2": ["tyre_pressure"],
}
for v2_key, v1_aliases in _V2_TO_V1.items():
if v2_key in capability_flags:
for v1_key in v1_aliases:
capability_flags.setdefault(v1_key, capability_flags[v2_key])
# IDs with no v2 equivalent in the API: assume enabled when
# the broader feature category is present.
# - remote_control_fragrance: enabled if fragrance warning exists
# - remote_seat_preheat_switch: enabled if climate control exists
# - remote_trunk_open: enabled if trunk_status exists
_INFER: dict[str, str] = {
"remote_control_fragrance": "fragrance_exhausted_warning_2",
"remote_seat_preheat_switch": "remote_climate_control_2",
"remote_trunk_open": "trunk_status",
}
for v1_key, indicator in _INFER.items():
if v1_key not in capability_flags and indicator in capability_flags:
capability_flags[v1_key] = capability_flags[indicator]
# Also extract service_ids if present in this format
service_ids = [
c.get("serviceId", "")
for c in cap_list
if c.get("serviceId") and c.get("enabled")
]
return VehicleCapabilities(
service_ids=service_ids,
capability_flags=capability_flags,
)
# Fallback: legacy format with data.capabilities[]
caps = inner.get("capabilities", [])
if caps:
_LOGGER.debug(
"Capability response uses 'capabilities' format (%d entries) for %s",
len(caps),
vin[:6] + "...",
)
service_ids = [c.get("serviceId", "") for c in caps if c.get("enabled")]
return VehicleCapabilities(service_ids=service_ids)
_LOGGER.debug("Capability response empty for %s", vin[:6] + "...")
return VehicleCapabilities()
async def async_get_energy_ranking(
self, account: Account, vin: str,
latitude: float = 0.0, longitude: float = 0.0,
) -> EnergyRanking:
"""Fetch energy consumption ranking."""
base_url = self._get_base_url(account)
url = (
f"{base_url}/geelyTCAccess/tcservices/vehicle/status/ranking/"
f"aveEnergyConsumption/vehicleModel/{vin}"
f"?topn=100&latitude={latitude}&longitude={longitude}"
)
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
return EnergyRanking(
my_ranking=int(d["myRanking"]) if d.get("myRanking") else None,
my_value=float(d["myValue"]) if d.get("myValue") else None,
total_participants=int(d["totalParticipants"]) if d.get("totalParticipants") else None,
)
async def async_get_fota_notification(
self, account: Account
) -> FOTANotification:
"""Fetch FOTA notification status."""
base_url = self._get_base_url(account)
url = f"{base_url}/fota/geea/assignment/notification"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
notifications = d.get("notifications", []) if isinstance(d, dict) else []
return FOTANotification(
has_notification=bool(notifications),
pending_count=len(notifications),
)
async def async_get_locker_secret(
self, account: Account, vin: str
) -> LockerSecret:
"""Fetch locker secret/PIN configuration status."""
base_url = self._get_base_url(account)
url = f"{base_url}/remote-control/locker/secret/{vin}"
data = await self._signed_request("GET", url, account)
d = data.get("data", {})
return LockerSecret(
has_secret=bool(d.get("hasSecret")),
secret_set=bool(d.get("secretSet")),
)
async def async_get_plant_no(
self, account: Account, vin: str
) -> str:
"""Fetch factory plant number."""
base_url = self._get_base_url(account)
url = f"{base_url}/geelyTCAccess/tcservices/customer/vehicle/plantNo/{vin}"
data = await self._signed_request("GET", url, account)
return data.get("data", {}).get("plantNo", "")
async def async_send_command(
self, account: Account, vin: str, payload: dict
) -> CommandResult:
"""Send a vehicle command via PUT to the telematics endpoint.
The JSON body is serialized with no spaces per API contract C-001.
The response has success/message at the top level of the envelope.
"""
base_url = self._get_base_url(account)
url = f"{base_url}{API_TELEMATICS_COMMAND_PATH}/{vin}"
self._validate_url(url)
body_str = json.dumps(payload, separators=(",", ":"))
headers = build_signed_headers("PUT", url, body_str, account)
service_id = payload.get("serviceId", "")
now = datetime.now()
async with self._session.put(url, headers=headers, data=body_str) as resp:
if resp.status == 401:
raise TokenExpiredError("HTTP 401 Unauthorized")
if resp.status == 429:
retry_after = int(resp.headers.get("Retry-After", "60"))
raise RateLimitedError(retry_after)
resp.raise_for_status()
data = await resp.json()
code = data.get("code")
if code is not None:
try:
code = int(code)
except (ValueError, TypeError):
pass
if code == API_CODE_TOKEN_EXPIRED:
raise TokenExpiredError("API code 1402: token expired")
_LOGGER.debug("Command %s response: %s", service_id, data)
# The standard API envelope has success/message at the top level:
# {"code": 1000, "data": {...}, "success": true, "message": "..."}
# Check top-level first, then fall back to nested data.data
if "success" in data:
success = data["success"]
error_msg = data.get("message")
elif "data" in data and isinstance(data["data"], dict):
success = data["data"].get("success", False)
error_msg = data["data"].get("message")
else:
success = False
error_msg = data.get("message")
return CommandResult(
success=bool(success),
service_id=service_id,
timestamp=now,
error_message=error_msg if not success else None,
)
async def async_set_charging_reservation(
self, account: Account, vin: str, data: dict
) -> CommandResult:
"""Update charging reservation via PUT."""
base_url = self._get_base_url(account)
url = f"{base_url}{API_CHARGING_RESERVATION_PATH}/{vin}"
self._validate_url(url)
body_str = json.dumps(data, separators=(",", ":"))
headers = build_signed_headers("PUT", url, body_str, account)
now = datetime.now()
async with self._session.put(url, headers=headers, data=body_str) as resp:
if resp.status == 401:
raise TokenExpiredError("HTTP 401 Unauthorized")
if resp.status == 429:
retry_after = int(resp.headers.get("Retry-After", "60"))
raise RateLimitedError(retry_after)
resp.raise_for_status()
resp_data = await resp.json()
success = resp_data.get("success", resp_data.get("code") == API_CODE_SUCCESS)
return CommandResult(
success=bool(success),
service_id="charging_reservation",
timestamp=now,
error_message=resp_data.get("message") if not success else None,
)
async def async_set_climate_schedule(
self, account: Account, vin: str, data: dict
) -> CommandResult:
"""Update climate schedule via PUT."""
base_url = self._get_base_url(account)
url = f"{base_url}{API_CLIMATE_SCHEDULE_PATH}/{vin}"
self._validate_url(url)
body_str = json.dumps(data, separators=(",", ":"))
headers = build_signed_headers("PUT", url, body_str, account)
now = datetime.now()
async with self._session.put(url, headers=headers, data=body_str) as resp:
if resp.status == 401:
raise TokenExpiredError("HTTP 401 Unauthorized")
if resp.status == 429:
retry_after = int(resp.headers.get("Retry-After", "60"))
raise RateLimitedError(retry_after)
resp.raise_for_status()
resp_data = await resp.json()
success = resp_data.get("success", resp_data.get("code") == API_CODE_SUCCESS)
return CommandResult(
success=bool(success),
service_id="climate_schedule",
timestamp=now,
error_message=resp_data.get("message") if not success else None,
)
@staticmethod
def _get_base_url(account: Account) -> str:
"""Get the API base URL for the account's region.
Both EU and INTL use api.ecloudeu.com for vehicle data.
apiv2.ecloudeu.com is only used for INTL session exchange (in auth.py).
"""
return EU_API_BASE_URL
@staticmethod
def _get_vc_base_url(account: Account) -> str:
"""Get the Vehicle Services (VC) base URL for ability/image endpoints."""
if account.region == Region.EU:
return VC_EU_BASE_URL
return VC_INTL_BASE_URL
async def async_get_vehicle_ability(
self, account: Account, vin: str, model_code: str
) -> VehicleAbility | None:
"""Fetch vehicle ability data including image URLs.
Calls the vc/vehicle/v1/ability/{modelCode}/{vin} endpoint.
For INTL: sg-app-api.smart.com uses Alibaba Cloud API Gateway HmacSHA256.
For EU: vehicle.vbs.srv.smart.com uses api_access_token directly.
"""
if not model_code:
_LOGGER.debug("No model_code for %s, skipping ability fetch", vin[:6] + "...")
return None
vc_base = self._get_vc_base_url(account)
url = f"{vc_base}{API_VC_ABILITY_PATH}/{model_code}/{vin}"
_LOGGER.debug("Fetching vehicle ability: %s", url)
self._validate_url(url)
if account.region == Region.INTL:
headers = build_vc_signed_headers("GET", url, account)
else:
# EU VC endpoint uses api_access_token
headers = {
"x-smart-id": account.api_user_id,
"authorization": account.api_access_token,
"accept": "application/json",
"content-type": "application/json",
}
async with self._session.request("GET", url, headers=headers) as resp:
if resp.status == 401:
raise TokenExpiredError("HTTP 401 from VC ability endpoint")
if resp.status == 429:
retry_after = int(resp.headers.get("Retry-After", "60"))
raise RateLimitedError(retry_after)
if resp.status != 200:
body = await resp.text()
ca_error = resp.headers.get("x-ca-error-message", "")
_LOGGER.debug(
"VC ability endpoint returned %d for %s: ca_error=%s body=%s",
resp.status, vin[:6] + "...", ca_error, body[:500],
)
return None
data = await resp.json()
code = data.get("code")
try:
code = int(code) if code is not None else None
except (ValueError, TypeError):
pass
if code not in (API_CODE_SUCCESS, 200):
_LOGGER.debug("VC ability API returned code %s", code)
return None
# VC ability uses "result" key (not "data" like other endpoints)
result = data.get("result") or data.get("data") or {}
vsc = result.get("vscData") or {}
_LOGGER.debug(
"VC ability: imagesPath=%s, model=%s, color=%s",
vsc.get("imagesPath", "")[:80] if vsc.get("imagesPath") else "none",
vsc.get("modelName", ""),
vsc.get("colorNameMss", ""),
)
_LOGGER.debug(
"VC ability images: top=%s, interior=%s, battery=%s",
vsc.get("topImagesPath", "")[:80] if vsc.get("topImagesPath") else "none",
vsc.get("interiorImagesPath", "")[:80] if vsc.get("interiorImagesPath") else "none",
vsc.get("batteryImagesPath", "")[:80] if vsc.get("batteryImagesPath") else "none",
)
return VehicleAbility(
images_path=vsc.get("imagesPath", ""),
top_images_path=vsc.get("topImagesPath", ""),
battery_images_path=vsc.get("batteryImagesPath", ""),
interior_images_path=vsc.get("interiorImagesPath", ""),
color_code=vsc.get("colorCode", ""),
color_name_mss=vsc.get("colorNameMss", ""),
contrast_color_code=vsc.get("contrastColorCode", ""),
contrast_color_name=vsc.get("contrastColorNameMSS", ""),
interior_color_name=vsc.get("interiorColorNameMss", ""),
hub_code=vsc.get("hubCode", ""),
hub_name=vsc.get("hubNameMSS", ""),
model_code_mss=vsc.get("modelCodeMss", ""),
model_code_vdp=vsc.get("modelCodeVdp", ""),
model_name=vsc.get("modelName", ""),
vehicle_name=vsc.get("vehicleName", ""),
vehicle_nickname=vsc.get("vehicleNickname", ""),
side_logo_light_name=vsc.get("sideLogoLightNameMSS", ""),
license_plate_number=vsc.get("licensePlateNumber", ""),
)
async def async_download_image(
self, url: str, dest_path: str
) -> bool:
"""Download an image from a URL to a local file path.
Only downloads if the file doesn't already exist.
Returns True if the file exists (downloaded or already present).
"""
import asyncio
import os
if await asyncio.to_thread(os.path.exists, dest_path):
return True
if not url:
return False
parsed = urlparse(url)
if parsed.scheme != "https":
_LOGGER.debug("Refusing non-HTTPS image URL: %s", url[:60])
return False
self._validate_url(url)
try:
async with self._session.get(
url,
timeout=aiohttp.ClientTimeout(total=30),
) as resp:
if resp.status != 200:
_LOGGER.debug("Image download failed: HTTP %d from %s", resp.status, url[:60])
return False
content_type = resp.headers.get("Content-Type", "")
if not content_type.startswith(("image/", "application/octet-stream")):
_LOGGER.debug("Unexpected content-type for image: %s", content_type)
return False
content = await resp.read()
# Size guard: reject files > 10 MB
if len(content) > 10 * 1024 * 1024:
_LOGGER.warning("Image too large (%d bytes), skipping", len(content))
return False
def _write_file() -> None:
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
with open(dest_path, "wb") as f:
f.write(content)
await asyncio.to_thread(_write_file)
_LOGGER.debug("Downloaded vehicle image to %s", dest_path)
return True
except Exception:
_LOGGER.debug("Failed to download image from %s", url[:60], exc_info=True)
return False
@staticmethod
def _parse_vehicle_status(
additional_status: dict, raw_data: dict
) -> VehicleStatus:
"""Parse the nested additionalVehicleStatus response into VehicleStatus."""
ev = additional_status.get("electricVehicleStatus", {})
doors_raw = additional_status.get("doorsStatus", {})
windows_raw = additional_status.get("windowStatus", {})
climate_raw = additional_status.get("climateStatus", {})
maintenance_raw = additional_status.get("maintenanceStatus", {})
basic_raw = additional_status.get("basicVehicleStatus", {})
# Parse battery and range
battery_level = int(ev.get("chargeLevel", 0) or 0)
battery_level = max(0, min(100, battery_level))