forked from SAIC-iSmart-API/saic-python-mqtt-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvehicle.py
801 lines (707 loc) · 40.2 KB
/
vehicle.py
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
import datetime
import json
import logging
import math
import os
from dataclasses import asdict
from enum import Enum
from typing import Optional
from apscheduler.job import Job
from apscheduler.schedulers.base import BaseScheduler
from apscheduler.triggers.cron import CronTrigger
from saic_ismart_client_ng.api.message.schema import MessageEntity
from saic_ismart_client_ng.api.vehicle import VehicleStatusResp
from saic_ismart_client_ng.api.vehicle.schema import VinInfo
from saic_ismart_client_ng.api.vehicle_charging import ChargeInfoResp, TargetBatteryCode, ChargeCurrentLimitCode, \
ScheduledChargingMode, ScheduledBatteryHeatingResp
from saic_ismart_client_ng.api.vehicle_charging.schema import ChrgMgmtData
import mqtt_topics
from charging_station import ChargingStation
from exceptions import MqttGatewayException
from publisher import Publisher
DEFAULT_AC_TEMP = 22
PRESSURE_TO_BAR_FACTOR = 0.04
LOG = logging.getLogger(__name__)
LOG.setLevel(level=os.getenv('LOG_LEVEL', 'INFO').upper())
class RefreshMode(Enum):
FORCE = 'force'
OFF = 'off'
PERIODIC = 'periodic'
@staticmethod
def get(mode: str):
return RefreshMode[mode.upper()]
class VehicleState:
def __init__(
self,
publisher: Publisher,
scheduler: BaseScheduler,
account_prefix: str,
vin: VinInfo,
charging_station: Optional[ChargingStation] = None,
charge_polling_min_percent: float = 1.0,
total_battery_capacity: Optional[float] = None,
):
self.publisher = publisher
self.vin = vin.vin
self.series = vin.series.strip().upper()
self.mqtt_vin_prefix = f'{account_prefix}'
self.charging_station = charging_station
self.last_car_activity = datetime.datetime.min
self.last_successful_refresh = datetime.datetime.min
self.last_car_shutdown = datetime.datetime.now()
self.last_car_vehicle_message = datetime.datetime.min
# treat high voltage battery as active, if we don't have any other information
self.hv_battery_active = True
self.is_charging = False
self.refresh_period_active = -1
self.refresh_period_inactive = -1
self.refresh_period_after_shutdown = -1
self.refresh_period_inactive_grace = -1
self.target_soc: Optional[TargetBatteryCode] = None
self.charge_current_limit: Optional[ChargeCurrentLimitCode] = None
self.refresh_period_charging = 0
self.charge_polling_min_percent = charge_polling_min_percent
self.refresh_mode = RefreshMode.OFF
self.previous_refresh_mode = RefreshMode.OFF
self.properties = {}
self.__remote_ac_temp: Optional[int] = None
self.__remote_ac_running: bool = False
self.__remote_heated_seats_front_left_level: int = 0
self.__remote_heated_seats_front_right_level: int = 0
self.__scheduler = scheduler
self.__total_battery_capacity = total_battery_capacity
self.__scheduled_battery_heating_enabled = False
self.__scheduled_battery_heating_start = None
def set_refresh_period_active(self, seconds: int):
self.publisher.publish_int(self.get_topic(mqtt_topics.REFRESH_PERIOD_ACTIVE), seconds)
human_readable_period = str(datetime.timedelta(seconds=seconds))
LOG.info(f'Setting active query interval in vehicle handler for VIN {self.vin} to {human_readable_period}')
self.refresh_period_active = seconds
# Recompute charging refresh period, if active refresh period is changed
self.set_refresh_period_charging(self.refresh_period_charging)
def set_refresh_period_inactive(self, seconds: int):
self.publisher.publish_int(self.get_topic(mqtt_topics.REFRESH_PERIOD_INACTIVE), seconds)
human_readable_period = str(datetime.timedelta(seconds=seconds))
LOG.info(f'Setting inactive query interval in vehicle handler for VIN {self.vin} to {human_readable_period}')
self.refresh_period_inactive = seconds
# Recompute charging refresh period, if active refresh period is changed
self.set_refresh_period_charging(self.refresh_period_charging)
def set_refresh_period_charging(self, seconds: int):
# Do not refresh more than the active period and less than the inactive one
seconds = min(max(seconds, self.refresh_period_active), self.refresh_period_inactive) if seconds > 0 else 0
self.publisher.publish_int(self.get_topic(mqtt_topics.REFRESH_PERIOD_CHARGING), seconds)
human_readable_period = str(datetime.timedelta(seconds=seconds))
LOG.info(f'Setting charging query interval in vehicle handler for VIN {self.vin} to {human_readable_period}')
self.refresh_period_charging = seconds
def set_refresh_period_after_shutdown(self, seconds: int):
self.publisher.publish_int(self.get_topic(mqtt_topics.REFRESH_PERIOD_AFTER_SHUTDOWN), seconds)
human_readable_period = str(datetime.timedelta(seconds=seconds))
LOG.info(
f'Setting after shutdown query interval in vehicle handler for VIN {self.vin} to {human_readable_period}'
)
self.refresh_period_after_shutdown = seconds
def set_refresh_period_inactive_grace(self, refresh_period_inactive_grace: int):
if (
self.refresh_period_inactive_grace == -1
or self.refresh_period_inactive_grace != refresh_period_inactive_grace
):
self.publisher.publish_int(self.get_topic(mqtt_topics.REFRESH_PERIOD_INACTIVE_GRACE),
refresh_period_inactive_grace)
self.refresh_period_inactive_grace = refresh_period_inactive_grace
def update_target_soc(self, target_soc: TargetBatteryCode):
if self.target_soc != target_soc and target_soc is not None:
self.publisher.publish_int(self.get_topic(mqtt_topics.DRIVETRAIN_SOC_TARGET), target_soc.percentage)
self.target_soc = target_soc
def update_charge_current_limit(self, charge_current_limit: ChargeCurrentLimitCode):
if self.charge_current_limit != charge_current_limit and charge_current_limit is not None:
try:
self.publisher.publish_str(
self.get_topic(mqtt_topics.DRIVETRAIN_CHARGECURRENT_LIMIT),
charge_current_limit.limit
)
self.charge_current_limit = charge_current_limit
except ValueError:
LOG.exception(f'Unhandled charge current limit {charge_current_limit}')
def update_scheduled_charging(
self,
start_time: datetime.time,
mode: ScheduledChargingMode
):
scheduled_charging_job_id = f'{self.vin}_scheduled_charging'
existing_job: Job | None = self.__scheduler.get_job(scheduled_charging_job_id)
if mode in [ScheduledChargingMode.UNTIL_CONFIGURED_TIME, ScheduledChargingMode.UNTIL_CONFIGURED_SOC]:
if self.refresh_period_inactive_grace > 0:
# Add a grace period to the start time, so that the car is not woken up too early
dt = (datetime.datetime.now()
.replace(hour=start_time.hour, minute=start_time.minute, second=0, microsecond=0)
+ datetime.timedelta(seconds=self.refresh_period_inactive_grace))
start_time = dt.time()
trigger = CronTrigger.from_crontab(f'{start_time.minute} {start_time.hour} * * *')
if existing_job is not None:
existing_job.reschedule(trigger=trigger)
LOG.info(f'Rescheduled check for charging start for VIN {self.vin} at {start_time}')
else:
self.__scheduler.add_job(
func=self.set_refresh_mode,
args=[RefreshMode.FORCE],
trigger=trigger,
kwargs={},
name=scheduled_charging_job_id,
id=scheduled_charging_job_id,
replace_existing=True,
)
LOG.info(f'Scheduled check for charging start for VIN {self.vin} at {start_time}')
elif existing_job is not None:
existing_job.remove()
LOG.info(f'Removed scheduled check for charging start for VIN {self.vin}')
def is_complete(self) -> bool:
return self.refresh_period_active != -1 \
and self.refresh_period_inactive != -1 \
and self.refresh_period_after_shutdown != -1 \
and self.refresh_period_inactive_grace != -1 \
and self.refresh_mode
def handle_vehicle_status(self, vehicle_status: VehicleStatusResp) -> None:
is_engine_running = vehicle_status.is_engine_running
self.is_charging = vehicle_status.is_charging
basic_vehicle_status = vehicle_status.basicVehicleStatus
remote_climate_status = basic_vehicle_status.remoteClimateStatus
self.set_hv_battery_active(self.is_charging or is_engine_running or remote_climate_status > 0)
self.publisher.publish_bool(self.get_topic(mqtt_topics.DRIVETRAIN_RUNNING), is_engine_running)
self.publisher.publish_bool(self.get_topic(mqtt_topics.DRIVETRAIN_CHARGING), self.is_charging)
interior_temperature = basic_vehicle_status.interiorTemperature
if interior_temperature > -128:
self.publisher.publish_int(self.get_topic(mqtt_topics.CLIMATE_INTERIOR_TEMPERATURE), interior_temperature)
exterior_temperature = basic_vehicle_status.exteriorTemperature
if exterior_temperature > -128:
self.publisher.publish_int(self.get_topic(mqtt_topics.CLIMATE_EXTERIOR_TEMPERATURE), exterior_temperature)
battery_voltage = basic_vehicle_status.batteryVoltage / 10.0
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_AUXILIARY_BATTERY_VOLTAGE), battery_voltage)
if vehicle_status.gpsPosition:
way_point = vehicle_status.gpsPosition.wayPoint
if way_point:
speed = way_point.speed / 10.0
self.publisher.publish_float(self.get_topic(mqtt_topics.LOCATION_SPEED), speed)
self.publisher.publish_int(self.get_topic(mqtt_topics.LOCATION_HEADING), way_point.heading)
position = way_point.position
if position:
latitude = None
if position.latitude and abs(position.latitude) > 0:
latitude = position.latitude / 1000000.0
self.publisher.publish_float(self.get_topic(mqtt_topics.LOCATION_LATITUDE), latitude)
longitude = None
if abs(position.longitude) > 0:
longitude = position.longitude / 1000000.0
self.publisher.publish_float(self.get_topic(mqtt_topics.LOCATION_LONGITUDE), longitude)
self.publisher.publish_int(self.get_topic(mqtt_topics.LOCATION_ELEVATION), position.altitude)
if latitude is not None and longitude is not None:
self.publisher.publish_json(self.get_topic(mqtt_topics.LOCATION_POSITION), {
'latitude': latitude,
'longitude': longitude,
})
self.publisher.publish_bool(self.get_topic(mqtt_topics.WINDOWS_DRIVER), basic_vehicle_status.driverWindow)
self.publisher.publish_bool(self.get_topic(mqtt_topics.WINDOWS_PASSENGER),
basic_vehicle_status.passengerWindow)
self.publisher.publish_bool(self.get_topic(mqtt_topics.WINDOWS_REAR_LEFT),
basic_vehicle_status.rearLeftWindow)
self.publisher.publish_bool(self.get_topic(mqtt_topics.WINDOWS_REAR_RIGHT),
basic_vehicle_status.rearRightWindow)
self.publisher.publish_bool(self.get_topic(mqtt_topics.WINDOWS_SUN_ROOF), basic_vehicle_status.sunroofStatus)
self.publisher.publish_bool(self.get_topic(mqtt_topics.DOORS_LOCKED), basic_vehicle_status.lockStatus)
self.publisher.publish_bool(self.get_topic(mqtt_topics.DOORS_DRIVER), basic_vehicle_status.driverDoor)
self.publisher.publish_bool(self.get_topic(mqtt_topics.DOORS_PASSENGER), basic_vehicle_status.passengerDoor)
self.publisher.publish_bool(self.get_topic(mqtt_topics.DOORS_REAR_LEFT), basic_vehicle_status.rearLeftDoor)
self.publisher.publish_bool(self.get_topic(mqtt_topics.DOORS_REAR_RIGHT), basic_vehicle_status.rearRightDoor)
self.publisher.publish_bool(self.get_topic(mqtt_topics.DOORS_BONNET), basic_vehicle_status.bonnetStatus)
self.publisher.publish_bool(self.get_topic(mqtt_topics.DOORS_BOOT), basic_vehicle_status.bootStatus)
if (
basic_vehicle_status.frontLeftTyrePressure is not None
and basic_vehicle_status.frontLeftTyrePressure > 0
):
front_left_tyre_bar = basic_vehicle_status.frontLeftTyrePressure * PRESSURE_TO_BAR_FACTOR
self.publisher.publish_float(self.get_topic(mqtt_topics.TYRES_FRONT_LEFT_PRESSURE),
round(front_left_tyre_bar, 2))
if (
basic_vehicle_status.frontRightTyrePressure is not None
and basic_vehicle_status.frontRightTyrePressure > 0
):
front_right_tyre_bar = basic_vehicle_status.frontRightTyrePressure * PRESSURE_TO_BAR_FACTOR
self.publisher.publish_float(self.get_topic(mqtt_topics.TYRES_FRONT_RIGHT_PRESSURE),
round(front_right_tyre_bar, 2))
if (
basic_vehicle_status.rearLeftTyrePressure
and basic_vehicle_status.rearLeftTyrePressure > 0
):
rear_left_tyre_bar = basic_vehicle_status.rearLeftTyrePressure * PRESSURE_TO_BAR_FACTOR
self.publisher.publish_float(self.get_topic(mqtt_topics.TYRES_REAR_LEFT_PRESSURE),
round(rear_left_tyre_bar, 2))
if (
basic_vehicle_status.rearRightTyrePressure is not None
and basic_vehicle_status.rearRightTyrePressure > 0
):
rear_right_tyre_bar = basic_vehicle_status.rearRightTyrePressure * PRESSURE_TO_BAR_FACTOR
self.publisher.publish_float(self.get_topic(mqtt_topics.TYRES_REAR_RIGHT_PRESSURE),
round(rear_right_tyre_bar, 2))
self.publisher.publish_bool(self.get_topic(mqtt_topics.LIGHTS_MAIN_BEAM), basic_vehicle_status.mainBeamStatus)
self.publisher.publish_bool(self.get_topic(mqtt_topics.LIGHTS_DIPPED_BEAM),
basic_vehicle_status.dippedBeamStatus)
self.publisher.publish_str(self.get_topic(mqtt_topics.CLIMATE_REMOTE_CLIMATE_STATE),
VehicleState.to_remote_climate(remote_climate_status))
self.__remote_ac_running = remote_climate_status == 2
rear_window_heat_state = basic_vehicle_status.rmtHtdRrWndSt
self.publisher.publish_str(self.get_topic(mqtt_topics.CLIMATE_BACK_WINDOW_HEAT),
'off' if rear_window_heat_state == 0 else 'on')
if basic_vehicle_status.frontLeftSeatHeatLevel is not None:
self.__remote_heated_seats_front_left_level = basic_vehicle_status.frontLeftSeatHeatLevel
self.publisher.publish_int(self.get_topic(mqtt_topics.CLIMATE_HEATED_SEATS_FRONT_LEFT_LEVEL),
self.__remote_heated_seats_front_left_level)
if basic_vehicle_status.frontRightSeatHeatLevel is not None:
self.__remote_heated_seats_front_right_level = basic_vehicle_status.frontRightSeatHeatLevel
self.publisher.publish_int(self.get_topic(mqtt_topics.CLIMATE_HEATED_SEATS_FRONT_RIGHT_LEVEL),
self.__remote_heated_seats_front_right_level)
if basic_vehicle_status.mileage > 0:
mileage = basic_vehicle_status.mileage / 10.0
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_MILEAGE), mileage)
if basic_vehicle_status.fuelRangeElec > 0:
electric_range = basic_vehicle_status.fuelRangeElec / 10.0
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_RANGE), electric_range)
self.publisher.publish_str(self.get_topic(mqtt_topics.REFRESH_LAST_VEHICLE_STATE),
VehicleState.datetime_to_str(datetime.datetime.now()))
def set_hv_battery_active(self, hv_battery_active: bool):
if (
not hv_battery_active
and self.hv_battery_active
):
self.last_car_shutdown = datetime.datetime.now()
self.hv_battery_active = hv_battery_active
self.publisher.publish_bool(self.get_topic(mqtt_topics.DRIVETRAIN_HV_BATTERY_ACTIVE), hv_battery_active)
if hv_battery_active:
self.notify_car_activity_time(datetime.datetime.now(), True)
def notify_car_activity_time(self, now: datetime.datetime, force: bool):
if (
self.last_car_activity == datetime.datetime.min
or force
or self.last_car_activity < now
):
self.last_car_activity = datetime.datetime.now()
self.publisher.publish_str(self.get_topic(mqtt_topics.REFRESH_LAST_ACTIVITY),
VehicleState.datetime_to_str(self.last_car_activity))
def notify_message(self, message: MessageEntity):
if (
self.last_car_vehicle_message == datetime.datetime.min
or message.message_time > self.last_car_vehicle_message
):
self.last_car_vehicle_message = message.message_time
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_LAST_MESSAGE_ID), str(message.messageId))
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_LAST_MESSAGE_TYPE), message.messageType)
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_LAST_MESSAGE_TITLE), message.title)
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_LAST_MESSAGE_TIME),
VehicleState.datetime_to_str(self.last_car_vehicle_message))
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_LAST_MESSAGE_SENDER), message.sender)
if message.content:
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_LAST_MESSAGE_CONTENT), message.content)
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_LAST_MESSAGE_STATUS), message.read_status)
if message.vin:
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_LAST_MESSAGE_VIN), message.vin)
self.notify_car_activity_time(message.message_time, True)
def should_refresh(self) -> bool:
match self.refresh_mode:
case RefreshMode.OFF:
return False
case RefreshMode.FORCE:
self.set_refresh_mode(self.previous_refresh_mode)
return True
# RefreshMode.PERIODIC is treated like default
case _:
if self.last_successful_refresh is None:
self.mark_successful_refresh()
return True
if self.last_car_activity > self.last_successful_refresh:
return True
if self.is_charging and self.refresh_period_charging > 0:
result = self.last_successful_refresh < datetime.datetime.now() - datetime.timedelta(
seconds=float(self.refresh_period_charging)
)
LOG.debug(f'HV battery is charging. Should refresh: {result}')
return result
if self.hv_battery_active:
result = self.last_successful_refresh < datetime.datetime.now() - datetime.timedelta(
seconds=float(self.refresh_period_active))
LOG.debug(f'HV battery is active. Should refresh: {result}')
return result
last_shutdown_plus_refresh = self.last_car_shutdown + datetime.timedelta(
seconds=float(self.refresh_period_inactive_grace))
if last_shutdown_plus_refresh > datetime.datetime.now():
result = self.last_successful_refresh < datetime.datetime.now() - datetime.timedelta(
seconds=float(self.refresh_period_after_shutdown))
LOG.debug(f'Refresh grace period after shutdown has not passed. Should refresh: {result}')
return result
result = self.last_successful_refresh < datetime.datetime.now() - datetime.timedelta(
seconds=float(self.refresh_period_inactive))
LOG.debug(
f'HV battery is inactive and refresh period after shutdown is over. Should refresh: {result}'
)
return result
def mark_successful_refresh(self):
self.last_successful_refresh = datetime.datetime.now()
def configure(self, vin_info: VinInfo):
self.publisher.publish_str(
self.get_topic(mqtt_topics.INTERNAL_CONFIGURATION_RAW),
json.dumps([asdict(x) for x in vin_info.vehicleModelConfiguration])
)
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_BRAND), vin_info.brandName)
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_MODEL), vin_info.modelName)
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_YEAR), vin_info.modelYear)
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_SERIES), vin_info.series)
if vin_info.colorName:
self.publisher.publish_str(self.get_topic(mqtt_topics.INFO_COLOR), vin_info.colorName)
self.properties = {}
for c in vin_info.vehicleModelConfiguration:
property_name = c.itemName
property_code = c.itemCode
property_value = c.itemValue
property_code_topic = f'{mqtt_topics.INFO_CONFIGURATION}/{property_code}'
property_name_topic = f'{mqtt_topics.INFO_CONFIGURATION}/{property_name}'
self.properties[property_name] = {'code': property_code, 'value': property_value}
self.properties[property_code] = {'name': property_name, 'value': property_value}
self.publisher.publish_str(self.get_topic(property_code_topic), property_value)
self.publisher.publish_str(self.get_topic(property_name_topic), property_value)
def configure_missing(self):
if self.refresh_period_active == -1:
self.set_refresh_period_active(30)
if self.refresh_period_after_shutdown == -1:
self.set_refresh_period_after_shutdown(120)
if self.refresh_period_inactive == -1:
# in seconds (Once a day to protect your 12V battery)
self.set_refresh_period_inactive(86400)
if self.refresh_period_inactive_grace == -1:
self.set_refresh_period_inactive_grace(600)
if self.__remote_ac_temp is not None:
self.set_ac_temperature(DEFAULT_AC_TEMP)
# Make sure the only refresh mode that is not supported at start is RefreshMode.PERIODIC
if self.refresh_mode in [RefreshMode.OFF, RefreshMode.FORCE]:
self.set_refresh_mode(RefreshMode.PERIODIC)
async def configure_by_message(self, *, topic: str, payload: str):
payload = payload.lower()
match topic:
case mqtt_topics.REFRESH_MODE:
try:
refresh_mode = RefreshMode.get(payload)
self.set_refresh_mode(refresh_mode)
except KeyError:
raise MqttGatewayException(f'Unsupported payload {payload}')
case mqtt_topics.REFRESH_PERIOD_ACTIVE:
try:
seconds = int(payload)
self.set_refresh_period_active(seconds)
except ValueError:
raise MqttGatewayException(f'Error setting value for payload {payload}')
case mqtt_topics.REFRESH_PERIOD_INACTIVE:
try:
seconds = int(payload)
self.set_refresh_period_inactive(seconds)
except ValueError:
raise MqttGatewayException(f'Error setting value for payload {payload}')
case mqtt_topics.REFRESH_PERIOD_AFTER_SHUTDOWN:
try:
seconds = int(payload)
self.set_refresh_period_after_shutdown(seconds)
except ValueError:
raise MqttGatewayException(f'Error setting value for payload {payload}')
case mqtt_topics.REFRESH_PERIOD_INACTIVE_GRACE:
try:
seconds = int(payload)
self.set_refresh_period_inactive_grace(seconds)
except ValueError:
raise MqttGatewayException(f'Error setting value for payload {payload}')
case _:
raise MqttGatewayException(f'Unsupported topic {topic}')
def handle_charge_status(self, charge_info_resp: ChargeInfoResp) -> None:
charge_mgmt_data = charge_info_resp.chrgMgmtData
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_CURRENT),
round(charge_mgmt_data.decoded_current, 3))
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_VOLTAGE),
round(charge_mgmt_data.decoded_voltage, 3))
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_POWER),
round(charge_mgmt_data.decoded_power, 3))
raw_charge_current_limit = charge_mgmt_data.bmsAltngChrgCrntDspCmd
if (
raw_charge_current_limit is not None
and raw_charge_current_limit != 0
):
try:
self.update_charge_current_limit(ChargeCurrentLimitCode(raw_charge_current_limit))
except ValueError:
LOG.warning(f'Invalid charge current limit received: {raw_charge_current_limit}')
raw_target_soc = charge_mgmt_data.bmsOnBdChrgTrgtSOCDspCmd
if raw_target_soc is not None:
try:
self.update_target_soc(TargetBatteryCode(raw_target_soc))
except ValueError:
LOG.warning(f'Invalid target SOC received: {raw_target_soc}')
soc = charge_mgmt_data.bmsPackSOCDsp / 10.0
if soc <= 100.0:
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_SOC), soc)
if (
self.charging_station
and self.charging_station.soc_topic
):
self.publisher.publish_int(self.charging_station.soc_topic, int(soc), True)
estimated_electrical_range = charge_mgmt_data.bmsEstdElecRng / 10.0
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_HYBRID_ELECTRICAL_RANGE),
estimated_electrical_range)
charge_status = charge_info_resp.rvsChargeStatus
if (
charge_status.mileageOfDay is not None
and charge_status.mileageOfDay > 0
):
mileage_of_the_day = charge_status.mileageOfDay / 10.0
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_MILEAGE_OF_DAY), mileage_of_the_day)
if (
charge_status.mileageSinceLastCharge is not None
and charge_status.mileageSinceLastCharge > 0
):
mileage_since_last_charge = charge_status.mileageSinceLastCharge / 10.0
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_MILEAGE_SINCE_LAST_CHARGE),
mileage_since_last_charge)
self.publisher.publish_int(self.get_topic(mqtt_topics.DRIVETRAIN_CHARGING_TYPE), charge_status.chargingType)
self.publisher.publish_bool(self.get_topic(mqtt_topics.DRIVETRAIN_CHARGER_CONNECTED),
charge_status.chargingGunState)
if has_scheduled_charging_info(charge_mgmt_data):
try:
start_hour = charge_mgmt_data.bmsReserStHourDspCmd
start_minute = charge_mgmt_data.bmsReserStMintueDspCmd
start_time = datetime.time(hour=start_hour, minute=start_minute)
end_hour = charge_mgmt_data.bmsReserSpHourDspCmd
end_minute = charge_mgmt_data.bmsReserSpMintueDspCmd
mode = ScheduledChargingMode(charge_mgmt_data.bmsReserCtrlDspCmd)
self.publisher.publish_json(self.get_topic(mqtt_topics.DRIVETRAIN_CHARGING_SCHEDULE), {
'startTime': "{:02d}:{:02d}".format(start_hour, start_minute),
'endTime': "{:02d}:{:02d}".format(end_hour, end_minute),
'mode': mode.name,
})
self.update_scheduled_charging(start_time, mode)
except ValueError:
LOG.exception("Error parsing scheduled charging info")
# Only publish remaining charging time if the car is charging and we have current flowing
remaining_charging_time = None
if charge_status.chargingGunState and charge_mgmt_data.decoded_current < 0:
remaining_charging_time = charge_mgmt_data.chrgngRmnngTime * 60
self.publisher.publish_int(self.get_topic(mqtt_topics.DRIVETRAIN_REMAINING_CHARGING_TIME),
remaining_charging_time)
else:
self.publisher.publish_int(self.get_topic(mqtt_topics.DRIVETRAIN_REMAINING_CHARGING_TIME), 0)
self.publisher.publish_str(self.get_topic(mqtt_topics.REFRESH_LAST_CHARGE_STATE),
VehicleState.datetime_to_str(datetime.datetime.now()))
if (
charge_status.lastChargeEndingPower is not None
and charge_status.lastChargeEndingPower > 0
):
last_charge_ending_power = charge_status.lastChargeEndingPower / 10.0
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_LAST_CHARGE_ENDING_POWER),
last_charge_ending_power)
real_total_battery_capacity = self.get_actual_battery_capacity()
raw_total_battery_capacity = None
if (
charge_status.totalBatteryCapacity is not None
and charge_status.totalBatteryCapacity > 0
):
raw_total_battery_capacity = charge_status.totalBatteryCapacity / 10.0
battery_capacity_correction_factor = 1.0
if real_total_battery_capacity is None and raw_total_battery_capacity is not None:
LOG.debug(f"Setting real battery capacity to raw battery capacity {raw_total_battery_capacity}")
real_total_battery_capacity = raw_total_battery_capacity
battery_capacity_correction_factor = 1.0
elif real_total_battery_capacity is not None and raw_total_battery_capacity is None:
LOG.debug(f"Setting raw battery capacity to real battery capacity {real_total_battery_capacity}")
battery_capacity_correction_factor = 1.0
elif real_total_battery_capacity is not None and raw_total_battery_capacity is not None:
LOG.debug(
f"Calculating full battery capacity correction factor based on "
f"real={real_total_battery_capacity} and raw={raw_total_battery_capacity}"
)
battery_capacity_correction_factor = real_total_battery_capacity / raw_total_battery_capacity
elif real_total_battery_capacity is None and raw_total_battery_capacity is None:
LOG.warning("No battery capacity information available")
battery_capacity_correction_factor = 1.0
if real_total_battery_capacity is not None and real_total_battery_capacity > 0:
self.publisher.publish_float(
self.get_topic(mqtt_topics.DRIVETRAIN_TOTAL_BATTERY_CAPACITY),
real_total_battery_capacity
)
soc_kwh = (battery_capacity_correction_factor * charge_status.realtimePower) / 10.0
self.publisher.publish_float(self.get_topic(mqtt_topics.DRIVETRAIN_SOC_KWH), soc_kwh)
if soc is not None and self.target_soc is not None and remaining_charging_time is not None:
target_soc_percentage = self.target_soc.percentage
# Default to 1% if we are really close (e.g. balancing)
delta_soc = max(1, int(target_soc_percentage - soc))
time_for_1pct = remaining_charging_time / delta_soc
time_for_min_pct = math.ceil(self.charge_polling_min_percent * time_for_1pct)
# It doesn't make sense to refresh less than the estimated time for completion
computed_refresh_period = min(remaining_charging_time, time_for_min_pct)
self.set_refresh_period_charging(computed_refresh_period)
else:
self.set_refresh_period_charging(0)
self.publisher.publish_bool(
self.get_topic(mqtt_topics.DRIVETRAIN_BATTERY_HEATING),
charge_mgmt_data.is_battery_heating
)
def handle_scheduled_battery_heating_status(self, scheduled_battery_heating_status: ScheduledBatteryHeatingResp):
if scheduled_battery_heating_status:
is_enabled = scheduled_battery_heating_status.status
if is_enabled:
start_time = scheduled_battery_heating_status.decoded_start_time
else:
start_time = self.__scheduled_battery_heating_start
else:
start_time = self.__scheduled_battery_heating_start
is_enabled = False
self.update_scheduled_battery_heating(
start_time,
is_enabled
)
def update_scheduled_battery_heating(self, start_time: datetime.time, enabled: bool):
changed = False
if self.__scheduled_battery_heating_start != start_time:
self.__scheduled_battery_heating_start = start_time
changed = True
if self.__scheduled_battery_heating_enabled != enabled:
self.__scheduled_battery_heating_enabled = enabled
changed = True
has_start_time = self.__scheduled_battery_heating_start is not None
computed_mode = 'on' if has_start_time and self.__scheduled_battery_heating_enabled else 'off'
computed_start_time = self.__scheduled_battery_heating_start.strftime('%H:%M') if has_start_time else '00:00'
self.publisher.publish_json(self.get_topic(mqtt_topics.DRIVETRAIN_BATTERY_HEATING_SCHEDULE), {
'mode': computed_mode,
'startTime': computed_start_time
})
return changed
def get_topic(self, sub_topic: str):
return f'{self.mqtt_vin_prefix}/{sub_topic}'
@staticmethod
def to_remote_climate(rmt_htd_rr_wnd_st: int) -> str:
match rmt_htd_rr_wnd_st:
case 0:
return 'off'
case 1:
return 'blowingonly'
case 2:
return 'on'
case 5:
return 'front'
return f'unknown ({rmt_htd_rr_wnd_st})'
@staticmethod
def datetime_to_str(dt: datetime.datetime) -> str:
return datetime.datetime.astimezone(dt, tz=datetime.timezone.utc).isoformat()
def set_refresh_mode(self, mode: RefreshMode):
if (
mode is not None and
(
self.refresh_mode is None
or self.refresh_mode != mode
)
):
new_mode_value = mode.value
LOG.info(f"Setting refresh mode to {new_mode_value}")
self.publisher.publish_str(self.get_topic(mqtt_topics.REFRESH_MODE), new_mode_value)
# Make sure we never store FORCE as previous refresh mode
if self.refresh_mode != RefreshMode.FORCE:
self.previous_refresh_mode = self.refresh_mode
self.refresh_mode = mode
LOG.debug(f'Refresh mode set to {new_mode_value}')
@property
def has_sunroof(self):
return self.__get_property_value('Sunroof') != '0'
@property
def has_on_off_heated_seats(self):
return self.__get_property_value('HeatedSeat') == '2'
@property
def has_level_heated_seats(self):
return self.__get_property_value('HeatedSeat') == '1'
@property
def has_heated_seats(self):
return self.has_level_heated_seats or self.has_on_off_heated_seats
@property
def is_heated_seats_running(self):
return (self.__remote_heated_seats_front_right_level + self.__remote_heated_seats_front_left_level) > 0
@property
def remote_heated_seats_front_left_level(self):
return self.__remote_heated_seats_front_left_level
def update_heated_seats_front_left_level(self, level):
if not self.__check_heated_seats_level(level):
return False
changed = self.__remote_heated_seats_front_left_level != level
self.__remote_heated_seats_front_left_level = level
return changed
@property
def remote_heated_seats_front_right_level(self):
return self.__remote_heated_seats_front_right_level
def update_heated_seats_front_right_level(self, level):
if not self.__check_heated_seats_level(level):
return False
changed = self.__remote_heated_seats_front_right_level != level
self.__remote_heated_seats_front_right_level = level
return changed
def __check_heated_seats_level(self, level: int) -> bool:
if not self.has_heated_seats:
return False
if self.has_level_heated_seats and not (0 <= level <= 3):
raise ValueError(f'Invalid heated seat level {level}. Range must be from 0 to 3 inclusive')
if self.has_on_off_heated_seats and not (0 <= level <= 1):
raise ValueError(f'Invalid heated seat level {level}. Range must be from 0 to 1 inclusive')
return True
@property
def supports_target_soc(self):
return self.__get_property_value('Battery') == '1'
def get_actual_battery_capacity(self) -> float | None:
if self.__total_battery_capacity is not None and self.__total_battery_capacity > 0:
return float(self.__total_battery_capacity)
# MG4 Lux/Trophy 2022
elif self.series.startswith('EH32 S'):
return 64.0
# MG4 Standard 2022
elif self.series.startswith('EH32 L'):
return 51.0
else:
return None
def __get_property_value(self, property_name: str) -> str | None:
if property_name in self.properties:
pdict = self.properties[property_name]
if pdict is not None and isinstance(pdict, dict) and 'value' in pdict:
return pdict['value']
return None
def get_remote_ac_temperature(self) -> int:
return self.__remote_ac_temp or DEFAULT_AC_TEMP
def set_ac_temperature(self, temp) -> bool:
if temp is None:
LOG.error("Cannot set AC temperature to None")
return False
temp = max(self.get_min_ac_temperature(), min(self.get_max_ac_temperature(), temp))
if self.__remote_ac_temp != temp:
self.__remote_ac_temp = temp
LOG.info(f"Updating remote AC temperature to {temp}")
self.publisher.publish_int(self.get_topic(mqtt_topics.CLIMATE_REMOTE_TEMPERATURE), temp)
return True
return False
def get_ac_temperature_idx(self) -> int:
if self.series.startswith('EH32'):
return 3 + self.get_remote_ac_temperature() - self.get_min_ac_temperature()
else:
return 2 + self.get_remote_ac_temperature() - self.get_min_ac_temperature()
def get_min_ac_temperature(self) -> int:
if self.series.startswith('EH32'):
return 17
else:
return 16
def get_max_ac_temperature(self) -> int:
if self.series.startswith('EH32'):
return 33
else:
return 28
@property
def is_remote_ac_running(self) -> bool:
return self.__remote_ac_running
def has_scheduled_charging_info(charge_mgmt_data: ChrgMgmtData):
return charge_mgmt_data.bmsReserStHourDspCmd is not None \
and charge_mgmt_data.bmsReserStMintueDspCmd is not None \
and charge_mgmt_data.bmsReserSpHourDspCmd is not None \
and charge_mgmt_data.bmsReserSpMintueDspCmd is not None