Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ When using combinations of configuration methods, the order of precedence is as
| --saic-relogin-delay | SAIC_RELOGIN_DELAY | The gateway detects logins from other devices (e.g. the iSMART app). It then pauses it's activity for 900 seconds (default value). The delay can be configured with this parameter. |
| --messages-request-interval | MESSAGES_REQUEST_INTERVAL | The interval for retrieving messages in seconds. Default is 60 seconds. |
| --battery-capacity-mapping | BATTERY_CAPACITY_MAPPING | Mapping of VIN to full battery capacity. Multiple mappings can be provided separated by ',' Example: LSJXXXX=54.0,LSJYYYY=64.0 |
| --power-tailgate-vins | POWER_TAILGATE_VINS | VINs of the cars with a power tailgate, separated by ','. Enables `/doors/boot/powerTailgate/set` and the Home Assistant "Power Tailgate" cover for these cars only. Example: LSJXXXX,LSJYYYY |
| --charge-min-percentage | CHARGE_MIN_PERCENTAGE | How many % points we should try to refresh the charge state. 1.0 by default |
| --account-refresh-interval | ACCOUNT_REFRESH_INTERVAL | Interval in seconds for refreshing account-level data (vehicle list, timezone). Default is 86400 (24 hours). |
| --saic-user-timezone | SAIC_USER_TIMEZONE | Force the account timezone instead of trusting the SAIC API value. Accepts an IANA name (e.g. `Australia/Sydney`) or `GMT+HH:MM`. Mismatches with the API offset are logged. |
Expand Down Expand Up @@ -220,6 +221,7 @@ with the default vehicle prefix: `saic/<saic_user>/vehicles/<vehicle_id>`
| /drivetrain/batteryHeating/set | true/false | Start (true) or stop (false) battery heating. The car may refuse the command if it is deemed unnecessary |
| /drivetrain/batteryHeatingSchedule/set | JSON Payload. Fields are startTime and mode | Set the battery heating schedule. Mode can be either on or off |
| /doors/boot/set | true/false | Lock or unlock boot |
| /doors/boot/powerTailgate/set | open/close | Open or close the power tailgate. Only for cars listed in `POWER_TAILGATE_VINS`. Tested on an MG S6 EV only; cars without a power tailgate are expected to refuse it. The state is reported on `/doors/boot`. |
| /doors/locked/set | true/false | Lock or unlock your car. This is not always working. It might take some time until it takes effect. Don't trust this feature. Use your car key! |
| /climate/remoteTemperature/set | temperature | Set A/C temperature |
| /climate/remoteClimateState/set | on/off/front/blowingonly | Turn A/C on or off, activate A/C blowing (front) or blowing only (blowingonly) |
Expand Down
8 changes: 4 additions & 4 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ classifiers = [

requires-python = '>=3.12,<4.0'
dependencies = [
"saic-ismart-client-ng (>=0.14.0,<0.15.0)",
"saic-ismart-client-ng (>=0.15.0,<0.16.0)",
'httpx (>=0.28.1,<0.29.0)',
'inflection (>=0.5.1,<0.6.0)',
'apscheduler (>=3.11.0,<4.0.0)',
Expand Down
1 change: 1 addition & 0 deletions src/configuration/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def __init__(self) -> None:
self.saic_read_timeout: float = 10.0 # in seconds
self.saic_user_timezone: ZoneInfo | None = None
self.battery_capacity_map: dict[str, float] = {}
self.power_tailgate_vins: set[str] = set()
self.mqtt_host: str | None = None
self.mqtt_port: int = 1883
self.mqtt_transport_protocol: TransportProtocol = TransportProtocol.TCP
Expand Down
16 changes: 16 additions & 0 deletions src/configuration/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ def __setup_gateway_features(args: Namespace, config: Configuration) -> None:
config.battery_capacity_map,
value_type=check_positive_float,
)
if args.power_tailgate_vins:
config.power_tailgate_vins = {
vin.strip() for vin in args.power_tailgate_vins.split(",") if vin.strip()
}
try:
config.messages_request_interval = int(args.messages_request_interval)
except ValueError as ve:
Expand Down Expand Up @@ -381,6 +385,18 @@ def __add_saic_api_argument_group(
envvar="BATTERY_CAPACITY_MAPPING",
type=str,
)
saic_api.add_argument(
"--power-tailgate-vins",
help="""VINs of the cars with a power tailgate, separated by comma.
Enables the doors/boot/powerTailgate/set command and its
Home Assistant cover for these cars only.
Example: LSJXXXX,LSJYYYY""",
dest="power_tailgate_vins",
required=False,
action=EnvDefault,
envvar="POWER_TAILGATE_VINS",
type=str,
)
saic_api.add_argument(
"--saic-relogin-delay",
help="""How long to wait before attempting another login to the SAIC API.""",
Expand Down
2 changes: 2 additions & 0 deletions src/handlers/command/doors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@

from handlers.command.doors.doors_boot import DoorsBootCommand
from handlers.command.doors.doors_locked import DoorsLockedCommand
from handlers.command.doors.doors_power_tailgate import DoorsPowerTailgateCommand

if TYPE_CHECKING:
from handlers.command import CommandHandlerBase

ALL_COMMAND_HANDLERS: list[type[CommandHandlerBase]] = [
DoorsBootCommand,
DoorsLockedCommand,
DoorsPowerTailgateCommand,
]
47 changes: 47 additions & 0 deletions src/handlers/command/doors/doors_power_tailgate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from __future__ import annotations

import logging
from typing import TYPE_CHECKING, override

from saic_ismart_client_ng.api.vehicle.locks import TailgateAction

from exceptions import MqttGatewayException
from handlers.command.base import (
RESULT_REFRESH_AND_CLEAR,
CommandProcessingResult,
MultiValuedCommandHandler,
)
import mqtt_topics

if TYPE_CHECKING:
from collections.abc import Awaitable, Callable

LOG = logging.getLogger(__name__)


class DoorsPowerTailgateCommand(MultiValuedCommandHandler[None]):
@classmethod
@override
def topic(cls) -> str:
return mqtt_topics.DOORS_BOOT_POWER_TAILGATE_SET

@override
def options(self) -> dict[str, Callable[[], Awaitable[None]]]:
return {
"open": lambda: self.__control_tailgate(TailgateAction.OPEN),
"close": lambda: self.__control_tailgate(TailgateAction.CLOSE),
}

async def __control_tailgate(self, action: TailgateAction) -> None:
if not self.vehicle_state.vehicle.has_power_tailgate:
msg = (
f"Power tailgate is not enabled for vehicle {self.vin}. "
"Add its VIN to POWER_TAILGATE_VINS to enable it"
)
raise MqttGatewayException(msg)
LOG.info(f"Vehicle {self.vin} power tailgate will {action.name.lower()}")
await self.saic_api.control_tailgate(self.vin, action=action)

@override
async def _get_action_result(self, _action_result: None) -> CommandProcessingResult:
return RESULT_REFRESH_AND_CLEAR
38 changes: 38 additions & 0 deletions src/integrations/home_assistant/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,44 @@ def _publish_lock(
"lock", name, payload, custom_availability
)

def _publish_cover(
self,
state_topic: str,
command_topic: str,
name: str,
*,
enabled: bool = True,
device_class: str | None = None,
icon: str | None = None,
payload_open: str = "open",
payload_close: str = "close",
state_open: str = "True",
state_closed: str = "False",
custom_availability: HaCustomAvailabilityConfig | None = None,
) -> str:
# State and command use different topics: the state comes from a
# read-only status topic, the command goes to command_topic + /set.
payload: dict[str, Any] = {
"state_topic": self._get_state_topic(state_topic),
"command_topic": self._get_command_topic(command_topic),
"payload_open": payload_open,
"payload_close": payload_close,
# None disables the stop button
"payload_stop": None,
"state_open": state_open,
"state_closed": state_closed,
"optimistic": False,
"qos": 0,
"enabled_by_default": enabled,
}
if device_class is not None:
payload["device_class"] = device_class
if icon is not None:
payload["icon"] = icon
return self._publish_ha_discovery_message(
"cover", name, payload, custom_availability
)

def _publish_event(
self,
topic: str,
Expand Down
20 changes: 18 additions & 2 deletions src/integrations/home_assistant/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,7 @@ def __publish_ha_discovery_messages_real(self) -> None:
"Battery heating",
icon="mdi:heat-wave",
)
self.__publish_windows_sensors()
self.__publish_doors_sensors()
self.__publish_body_sensors()
self.__publish_drivetrain_charging_sensors()

# Target SoC — only offer the entity if the vehicle actually supports it
Expand Down Expand Up @@ -633,6 +632,11 @@ def __publish_tyres_sensors(self) -> None:
icon="mdi:tire",
)

def __publish_body_sensors(self) -> None:
self.__publish_windows_sensors()
self.__publish_doors_sensors()
self.__publish_power_tailgate()

def __publish_doors_sensors(self) -> None:
self._publish_lock(
mqtt_topics.DOORS_LOCKED, "Doors Lock", icon="mdi:car-door-lock"
Expand Down Expand Up @@ -675,6 +679,18 @@ def __publish_doors_sensors(self) -> None:
mqtt_topics.DOORS_BOOT, "Boot", device_class="door", icon="mdi:car-door"
)

def __publish_power_tailgate(self) -> None:
if self.__vin_info.has_power_tailgate:
self._publish_cover(
mqtt_topics.DOORS_BOOT,
mqtt_topics.DOORS_BOOT_POWER_TAILGATE,
"Power Tailgate",
# No static icon: HA then shows an open or closed door icon
device_class="door",
)
else:
self.__unpublish_ha_discovery_message("cover", "Power Tailgate")

def __publish_gateway_sensors(self) -> None:
options = [m.value for m in RefreshMode]
self._publish_select(
Expand Down
6 changes: 5 additions & 1 deletion src/mqtt_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,11 @@ def __create_vehicle_handler(self, vin_info: VinInfo) -> VehicleHandler:
total_battery_capacity = (
self.configuration.battery_capacity_map.get(vin, None) if vin else None
)
info = VehicleInfo(vin_info, total_battery_capacity)
info = VehicleInfo(
vin_info,
total_battery_capacity,
has_power_tailgate=vin in self.configuration.power_tailgate_vins,
)
account_prefix = f"{self.configuration.saic_user}/{mqtt_topics.VEHICLES}/{vin}"
vehicle_state = VehicleState(
self.publisher,
Expand Down
2 changes: 2 additions & 0 deletions src/mqtt_topics.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
DOORS_BONNET = DOORS + "/bonnet"
DOORS_BOOT = DOORS + "/boot"
DOORS_BOOT_SET = DOORS_BOOT + "/" + SET_SUFFIX
DOORS_BOOT_POWER_TAILGATE = DOORS_BOOT + "/powerTailgate"
DOORS_BOOT_POWER_TAILGATE_SET = DOORS_BOOT_POWER_TAILGATE + "/" + SET_SUFFIX
DOORS_DRIVER = DOORS + "/driver"
DOORS_LOCKED = DOORS + "/locked"
DOORS_LOCKED_SET = DOORS_LOCKED + "/" + SET_SUFFIX
Expand Down
9 changes: 9 additions & 0 deletions src/vehicle_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ def __init__(
self,
vin_info: VinInfo,
custom_battery_capacity: float | None,
*,
has_power_tailgate: bool = False,
) -> None:
if not vin_info.vin:
raise MqttGatewayException("Could not handle a car without a vin")
Expand All @@ -32,6 +34,13 @@ def __init__(
self.__properties_from_configuration(self.configuration)
)
self.__custom_battery_capacity: float | None = custom_battery_capacity
# No model configuration flag tells us if the car has a power tailgate,
# so the user opts in per VIN (POWER_TAILGATE_VINS).
self.__has_power_tailgate: Final[bool] = has_power_tailgate

@property
def has_power_tailgate(self) -> bool:
return self.__has_power_tailgate

@property
def custom_battery_capacity(self) -> float | None:
Expand Down
103 changes: 103 additions & 0 deletions tests/handlers/command/test_doors_power_tailgate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
from __future__ import annotations

import unittest
from unittest.mock import AsyncMock, MagicMock

import pytest
from saic_ismart_client_ng.api.vehicle.locks import TailgateAction
from saic_ismart_client_ng.api.vehicle.schema import VinInfo

from exceptions import MqttGatewayException
from handlers.command.base import RESULT_DO_NOTHING, RESULT_REFRESH_AND_CLEAR
from handlers.command.doors.doors_boot import DoorsBootCommand
from handlers.command.doors.doors_power_tailgate import DoorsPowerTailgateCommand
import mqtt_topics
from vehicle_info import VehicleInfo


def _make_vehicle_state(*, has_power_tailgate: bool) -> MagicMock:
vin_info = VinInfo()
vin_info.vin = "vin_test_000000000"
vehicle_info = VehicleInfo(vin_info, None, has_power_tailgate=has_power_tailgate)

vehicle_state = MagicMock()
vehicle_state.vehicle = vehicle_info
vehicle_state.vin = vehicle_info.vin
return vehicle_state


class TestDoorsPowerTailgateCommand(unittest.IsolatedAsyncioTestCase):
def test_topic(self) -> None:
assert DoorsPowerTailgateCommand.topic() == "doors/boot/powerTailgate/set"
assert DoorsPowerTailgateCommand.topic() != DoorsBootCommand.topic()
assert (
DoorsPowerTailgateCommand.topic()
== mqtt_topics.DOORS_BOOT_POWER_TAILGATE_SET
)

async def test_open(self) -> None:
vehicle_state = _make_vehicle_state(has_power_tailgate=True)
saic_api = AsyncMock()
handler = DoorsPowerTailgateCommand(saic_api, vehicle_state)

result = await handler.handle("open")

assert result == RESULT_REFRESH_AND_CLEAR
saic_api.control_tailgate.assert_awaited_once_with(
vehicle_state.vin, action=TailgateAction.OPEN
)

async def test_close(self) -> None:
vehicle_state = _make_vehicle_state(has_power_tailgate=True)
saic_api = AsyncMock()
handler = DoorsPowerTailgateCommand(saic_api, vehicle_state)

result = await handler.handle(" CLOSE ")

assert result == RESULT_REFRESH_AND_CLEAR
saic_api.control_tailgate.assert_awaited_once_with(
vehicle_state.vin, action=TailgateAction.CLOSE
)

async def test_reject_when_not_enabled(self) -> None:
vehicle_state = _make_vehicle_state(has_power_tailgate=False)
saic_api = AsyncMock()
handler = DoorsPowerTailgateCommand(saic_api, vehicle_state)

with pytest.raises(MqttGatewayException, match="POWER_TAILGATE_VINS"):
await handler.handle("open")

saic_api.control_tailgate.assert_not_called()

async def test_reject_unknown_payload(self) -> None:
vehicle_state = _make_vehicle_state(has_power_tailgate=True)
saic_api = AsyncMock()
handler = DoorsPowerTailgateCommand(saic_api, vehicle_state)

with pytest.raises(MqttGatewayException, match="Unsupported payload"):
await handler.handle("true")

saic_api.control_tailgate.assert_not_called()

async def test_empty_payload_does_nothing(self) -> None:
vehicle_state = _make_vehicle_state(has_power_tailgate=True)
saic_api = AsyncMock()
handler = DoorsPowerTailgateCommand(saic_api, vehicle_state)

result = await handler.handle("")

assert result == RESULT_DO_NOTHING
saic_api.control_tailgate.assert_not_called()


class TestDoorsBootCommandUnchanged(unittest.IsolatedAsyncioTestCase):
async def test_false_still_unlocks_the_latch(self) -> None:
vehicle_state = _make_vehicle_state(has_power_tailgate=True)
saic_api = AsyncMock()
handler = DoorsBootCommand(saic_api, vehicle_state)

result = await handler.handle("false")

assert result == RESULT_REFRESH_AND_CLEAR
saic_api.open_tailgate.assert_awaited_once_with(vehicle_state.vin)
saic_api.control_tailgate.assert_not_called()
Loading
Loading