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
104 changes: 85 additions & 19 deletions src/rivian/parallax/vehicle_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from __future__ import annotations

from collections.abc import Callable
from typing import Any, Final
from typing import Any, Final, TypeGuard

from ..const import VehicleCommand
from ..exceptions import RivianBadRequestError
Expand Down Expand Up @@ -62,14 +62,82 @@
_Encode = Callable[[dict[str, Any]], bytes]


# Commands whose `level` param is 0..4: 0 is off, 1 is on, 2..4 are level_1..level_3
HVAC_LEVEL_COMMANDS: Final[frozenset[str]] = frozenset(
{
VehicleCommand.CABIN_HVAC_DEFROST_DEFOG,
VehicleCommand.CABIN_HVAC_LEFT_SEAT_HEAT,
VehicleCommand.CABIN_HVAC_LEFT_SEAT_VENT,
VehicleCommand.CABIN_HVAC_REAR_LEFT_SEAT_HEAT,
VehicleCommand.CABIN_HVAC_REAR_RIGHT_SEAT_HEAT,
VehicleCommand.CABIN_HVAC_RIGHT_SEAT_HEAT,
VehicleCommand.CABIN_HVAC_RIGHT_SEAT_VENT,
VehicleCommand.CABIN_HVAC_STEERING_HEAT,
VehicleCommand.CABIN_HVAC_3RD_ROW_REAR_LEFT_SEAT_HEAT,
VehicleCommand.CABIN_HVAC_3RD_ROW_REAR_RIGHT_SEAT_HEAT,
}
)


def _is_int(value: Any) -> TypeGuard[int]:
return isinstance(value, int) and not isinstance(value, bool)


def check_charge_limit(params: dict[str, Any] | None) -> int:
"""Return the `SOC_limit` param, or raise RivianBadRequestError if invalid."""
limit = (params or {}).get("SOC_limit")
if not (_is_int(limit) and 50 <= limit <= 100):
raise RivianBadRequestError(
"Charging limit must include parameter `SOC_limit` with a valid value between 50 and 100"
)
return limit


def check_hvac_level(params: dict[str, Any] | None) -> int:
"""Return the `level` param, or raise RivianBadRequestError if invalid."""
level = (params or {}).get("level")
if not (_is_int(level) and 0 <= level <= 4):
raise RivianBadRequestError(
"HVAC setting must include parameter `level` with a valid value between 0 and 4"
)
return level


def check_temperature(params: dict[str, Any] | None) -> float:
"""Return the `HVAC_set_temp` param, or raise RivianBadRequestError if invalid."""
temp = (params or {}).get("HVAC_set_temp")
if not (
(_is_int(temp) or isinstance(temp, float))
and (16 <= temp <= 29 or temp in (0, 63.5))
):
raise RivianBadRequestError(
"HVAC setting must include parameter `HVAC_set_temp` with a valid value between 16 and 29 or 0/63.5 for LO/HI, respectively"
)
return float(temp)


def _surface_level(
surface: comfort_pb2.CabinSurface,
params: dict[str, Any],
levels: dict[int, comfort_pb2.ConditioningLevel],
) -> comfort_pb2.ConditioningLevel:
if (level := check_hvac_level(params)) not in levels:
raise RivianBadRequestError(
f"{comfort_pb2.CabinSurface.Name(surface)} level {level} has no Parallax equivalent"
)
return levels[level]


def _seat(
surface: comfort_pb2.CabinSurface,
conditioning: comfort_pb2.ConditioningType = comfort_pb2.CONDITIONING_HEAT,
) -> tuple[str, str, _Encode]:
return (
"PVS_COMF_CMD",
SET_CABIN_SURFACE_RVM,
lambda p: encode_cabin_surface(surface, conditioning, _SEAT_LEVELS[p["level"]]),
lambda p: encode_cabin_surface(
surface, conditioning, _surface_level(surface, p, _SEAT_LEVELS)
),
)


Expand Down Expand Up @@ -150,44 +218,47 @@ def _seat(
VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP: (
"PVS_COMF_CMD",
SET_PRECONDITIONING_TEMPERATURE_RVM,
lambda p: encode_preconditioning_temperature(float(p["HVAC_set_temp"])),
lambda p: encode_preconditioning_temperature(check_temperature(p)),
),
VehicleCommand.CABIN_HVAC_DEFROST_DEFOG: (
"PVS_COMF_CMD",
SET_DEFROST_DEFOG_RVM,
lambda p: encode_defrost_defog(bool(p["level"])),
# Levels 1..4 all turn it on
lambda p: encode_defrost_defog(check_hvac_level(p) != 0),
),
VehicleCommand.CABIN_HVAC_LEFT_SEAT_HEAT: _seat(comfort_pb2.SEAT_ROW_1_LEFT),
VehicleCommand.CABIN_HVAC_RIGHT_SEAT_HEAT: _seat(comfort_pb2.SEAT_ROW_1_RIGHT),
VehicleCommand.CABIN_HVAC_LEFT_SEAT_VENT: _seat(
comfort_pb2.SEAT_ROW_1_LEFT, comfort_pb2.CONDITIONING_VENT
comfort_pb2.SEAT_ROW_1_LEFT,
comfort_pb2.CONDITIONING_VENT,
),
VehicleCommand.CABIN_HVAC_RIGHT_SEAT_VENT: _seat(
comfort_pb2.SEAT_ROW_1_RIGHT, comfort_pb2.CONDITIONING_VENT
comfort_pb2.SEAT_ROW_1_RIGHT,
comfort_pb2.CONDITIONING_VENT,
),
VehicleCommand.CABIN_HVAC_REAR_LEFT_SEAT_HEAT: _seat(comfort_pb2.SEAT_ROW_2_LEFT),
VehicleCommand.CABIN_HVAC_REAR_RIGHT_SEAT_HEAT: _seat(comfort_pb2.SEAT_ROW_2_RIGHT),
VehicleCommand.CABIN_HVAC_3RD_ROW_REAR_LEFT_SEAT_HEAT: _seat(
comfort_pb2.SEAT_ROW_3_LEFT
comfort_pb2.SEAT_ROW_3_LEFT,
),
VehicleCommand.CABIN_HVAC_3RD_ROW_REAR_RIGHT_SEAT_HEAT: _seat(
comfort_pb2.SEAT_ROW_3_RIGHT
comfort_pb2.SEAT_ROW_3_RIGHT,
),
VehicleCommand.CABIN_HVAC_STEERING_HEAT: (
"PVS_COMF_CMD",
SET_CABIN_SURFACE_RVM,
lambda p: encode_cabin_surface(
comfort_pb2.STEERING_WHEEL,
comfort_pb2.CONDITIONING_HEAT,
_STEERING_WHEEL_LEVELS[p["level"]],
_surface_level(comfort_pb2.STEERING_WHEEL, p, _STEERING_WHEEL_LEVELS),
),
),
VehicleCommand.START_CHARGING: ("PVS_ENRG_CMD", START_CHARGING_RVM, lambda _: b""),
VehicleCommand.STOP_CHARGING: ("PVS_ENRG_CMD", STOP_CHARGING_RVM, lambda _: b""),
VehicleCommand.CHARGING_LIMITS: (
"PVS_ENRG_CMD",
SET_CHARGE_LIMIT_RVM,
lambda p: encode_charge_limit(p["SOC_limit"]),
lambda p: encode_charge_limit(check_charge_limit(p)),
),
}

Expand All @@ -206,16 +277,11 @@ def encode_vehicle_command(
) -> tuple[str, bytes]:
"""Return the RVM and payload for a command's Parallax equivalent.

`params` are those of `send_vehicle_command`, already checked with
`Rivian.validate_vehicle_command`. Seat level 1 and steering wheel level 4
have no Parallax equivalent.
`params` are those of `send_vehicle_command`, checked with the same rules
as `Rivian.validate_vehicle_command`. Seat level 1 and steering wheel
level 4 have no Parallax equivalent.
"""
if not (entry := _COMMANDS.get(command)):
raise RivianBadRequestError(f"{command} has no Parallax equivalent")
_, rvm, encode = entry
try:
return rvm, encode(params or {})
except KeyError as err:
raise RivianBadRequestError(
f"{command} {params} has no Parallax equivalent"
) from err
return rvm, encode(params or {})
56 changes: 17 additions & 39 deletions src/rivian/rivian.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@
encode_live_streaming,
encode_vehicle_operation,
)
from .parallax.vehicle_command import (
HVAC_LEVEL_COMMANDS,
check_charge_limit,
check_hvac_level,
check_temperature,
)
from .utils import generate_vehicle_command_hmac, send_deprecation_warning
from .ws_monitor import WebSocketMonitor

Expand Down Expand Up @@ -956,44 +962,15 @@ def validate_vehicle_command(
) -> None:
"""Raise RivianBadRequestError if a command's params are invalid.

Shared by `send_vehicle_command` and callers sending its Parallax
equivalent (`parallax.encode_vehicle_command`).
Used by `send_vehicle_command`; `parallax.encode_vehicle_command` checks
its params with the same rules.
"""
if command == VehicleCommand.CHARGING_LIMITS and not (
params
and isinstance((limit := params.get("SOC_limit")), int)
and 50 <= limit <= 100
):
raise RivianBadRequestError(
"Charging limit must include parameter `SOC_limit` with a valid value between 50 and 100"
)
if command in (
VehicleCommand.CABIN_HVAC_DEFROST_DEFOG,
VehicleCommand.CABIN_HVAC_LEFT_SEAT_HEAT,
VehicleCommand.CABIN_HVAC_LEFT_SEAT_VENT,
VehicleCommand.CABIN_HVAC_REAR_LEFT_SEAT_HEAT,
VehicleCommand.CABIN_HVAC_REAR_RIGHT_SEAT_HEAT,
VehicleCommand.CABIN_HVAC_RIGHT_SEAT_HEAT,
VehicleCommand.CABIN_HVAC_RIGHT_SEAT_VENT,
VehicleCommand.CABIN_HVAC_STEERING_HEAT,
VehicleCommand.CABIN_HVAC_3RD_ROW_REAR_LEFT_SEAT_HEAT,
VehicleCommand.CABIN_HVAC_3RD_ROW_REAR_RIGHT_SEAT_HEAT,
) and not (
params
and isinstance((level := params.get("level")), int)
and 0 <= level <= 4
):
raise RivianBadRequestError(
"HVAC setting must include parameter `level` with a valid value between 0 and 4"
)
if command == VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP and not (
params
and isinstance((temp := params.get("HVAC_set_temp")), (float, int))
and (16 <= temp <= 29 or temp in (0, 63.5))
):
raise RivianBadRequestError(
"HVAC setting must include parameter `HVAC_set_temp` with a valid value between 16 and 29 or 0/63.5 for LO/HI, respectively"
)
if command == VehicleCommand.CHARGING_LIMITS:
check_charge_limit(params)
if command in HVAC_LEVEL_COMMANDS:
check_hvac_level(params)
if command == VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP:
check_temperature(params)

async def send_vehicle_command(
self,
Expand All @@ -1014,12 +991,13 @@ async def send_vehicle_command(
Certain commands may require additional details via the `params` mapping.
Some known examples include:
- `CABIN_HVAC_*`: params = {"level": 0..4} where 0 is off, 1 is on, 2 is low/level_1, 3 is medium/level_2 and 4 is high/level_3
- `CABIN_PRECONDITIONING_SET_TEMP`: params = {"HVAC_set_temp": "deg_C"} where `deg_C` is a string value between 16 and 29 or 0/63.5 for LO/HI, respectively
- `CABIN_PRECONDITIONING_SET_TEMP`: params = {"HVAC_set_temp": deg_C} where `deg_C` is a number between 16 and 29 or 0/63.5 for LO/HI, respectively
- `CHARGING_LIMITS`: params = {"SOC_limit": 50..100}
"""
self.validate_vehicle_command(command, params)
if command == VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP and params:
params["HVAC_set_temp"] = str(params["HVAC_set_temp"])
# A copy, so the caller's params can be sent again
params = params | {"HVAC_set_temp": str(params["HVAC_set_temp"])}

command = str(command)
timestamp = str(int(time.time()))
Expand Down
80 changes: 75 additions & 5 deletions tests/parallax/test_vehicle_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@

import pytest

from rivian import VehicleCommand
from rivian import Rivian, VehicleCommand
from rivian.exceptions import RivianBadRequestError
from rivian.parallax import encode_vehicle_command, vehicle_command_feature
from rivian.parallax.vehicle_command import _COMMANDS


@pytest.mark.parametrize(
Expand Down Expand Up @@ -115,11 +116,80 @@ def test_feature() -> None:
(VehicleCommand.WAKE_VEHICLE, None),
(VehicleCommand.CABIN_HVAC_LEFT_SEAT_HEAT, {"level": 1}),
(VehicleCommand.CABIN_HVAC_STEERING_HEAT, {"level": 4}),
(VehicleCommand.CHARGING_LIMITS, None),
(VehicleCommand.CABIN_HVAC_DEFROST_DEFOG, {}),
],
)
def test_no_equivalent(command: VehicleCommand, params: dict[str, Any] | None) -> None:
"""Commands, levels or missing params with no Parallax equivalent are rejected."""
with pytest.raises(RivianBadRequestError):
"""Valid commands and levels with no Parallax equivalent are rejected."""
Rivian.validate_vehicle_command(command, params)
with pytest.raises(RivianBadRequestError, match="no Parallax equivalent"):
encode_vehicle_command(command, params)


_INVALID: list[tuple[VehicleCommand, dict[str, Any] | None]] = [
(VehicleCommand.CHARGING_LIMITS, None),
(VehicleCommand.CHARGING_LIMITS, {"SOC_limit": 49}),
(VehicleCommand.CHARGING_LIMITS, {"SOC_limit": 101}),
(VehicleCommand.CHARGING_LIMITS, {"SOC_limit": "80"}),
(VehicleCommand.CHARGING_LIMITS, {"SOC_limit": 80.0}),
(VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP, {}),
(VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP, {"HVAC_set_temp": 15.5}),
(VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP, {"HVAC_set_temp": 29.5}),
(VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP, {"HVAC_set_temp": "22"}),
(VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP, {"HVAC_set_temp": True}),
(VehicleCommand.CABIN_HVAC_DEFROST_DEFOG, {}),
(VehicleCommand.CABIN_HVAC_DEFROST_DEFOG, {"level": "0"}),
(VehicleCommand.CABIN_HVAC_DEFROST_DEFOG, {"level": 5}),
(VehicleCommand.CABIN_HVAC_LEFT_SEAT_HEAT, {"level": 3.0}),
(VehicleCommand.CABIN_HVAC_STEERING_HEAT, {"level": True}),
]
_VALID: list[tuple[VehicleCommand, dict[str, Any] | None]] = [
(VehicleCommand.CHARGING_LIMITS, {"SOC_limit": 50}),
(VehicleCommand.CHARGING_LIMITS, {"SOC_limit": 100}),
(VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP, {"HVAC_set_temp": 16}),
(VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP, {"HVAC_set_temp": 29.0}),
(VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP, {"HVAC_set_temp": 0}),
(VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP, {"HVAC_set_temp": 63.5}),
(VehicleCommand.CABIN_HVAC_DEFROST_DEFOG, {"level": 0}),
(VehicleCommand.CABIN_HVAC_DEFROST_DEFOG, {"level": 4}),
(VehicleCommand.CABIN_HVAC_LEFT_SEAT_HEAT, {"level": 4}),
(VehicleCommand.CABIN_HVAC_STEERING_HEAT, {"level": 3}),
]


@pytest.mark.parametrize(("command", "params"), _INVALID)
def test_invalid_params(command: VehicleCommand, params: dict[str, Any] | None) -> None:
"""Invalid params are rejected either way of sending."""
with pytest.raises(RivianBadRequestError, match="must include parameter"):
Rivian.validate_vehicle_command(command, params)
with pytest.raises(RivianBadRequestError, match="must include parameter"):
encode_vehicle_command(command, params)


@pytest.mark.parametrize(("command", "params"), _VALID)
def test_valid_params(command: VehicleCommand, params: dict[str, Any] | None) -> None:
"""Params at the edges of their ranges are accepted either way of sending."""
Rivian.validate_vehicle_command(command, params)
encode_vehicle_command(command, params)


def test_validation_agrees() -> None:
"""The validator and the encoder accept the same params for every command."""
samples = [params for _, params in _INVALID + _VALID] + [
{"level": level} for level in range(5)
]
for command in _COMMANDS:
for params in samples:
try:
Rivian.validate_vehicle_command(command, params)
valid = True
except RivianBadRequestError:
valid = False
try:
encode_vehicle_command(command, params)
encoded = True
except RivianBadRequestError as err:
encoded = False
if valid: # only seat level 1 and steering wheel level 4
assert "no Parallax equivalent" in str(err), (command, params)
if encoded:
assert valid, (command, params)
30 changes: 30 additions & 0 deletions tests/test_rivian.py
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,36 @@ def test_validate_vehicle_command_keeps_params() -> None:
assert params == {"HVAC_set_temp": 21}


async def test_send_vehicle_command_keeps_params(
aresponses: ResponsesMockServer,
) -> None:
"""The temperature is sent as a string, and the caller's params can be sent again."""
response = {"data": {"sendVehicleCommand": {"id": "command_id"}}}
requests = capture_requests(aresponses, response, response)
vehicle_key, private_key = generate_key_pair()
params = {"HVAC_set_temp": 21}
async with aiohttp.ClientSession():
rivian = parallax_rivian()
for _ in range(2):
assert (
await rivian.send_vehicle_command(
VehicleCommand.CABIN_PRECONDITIONING_SET_TEMP,
"vehicle_id",
"phone_id",
"identity_id",
vehicle_key,
private_key,
params=params,
)
== "command_id"
)
await rivian.close()
assert params == {"HVAC_set_temp": 21}
assert [r["variables"]["attrs"]["params"] for r in requests] == [
{"HVAC_set_temp": "21"}
] * 2


async def test_graphql_errors(aresponses: ResponsesMockServer) -> None:
"""Test GraphQL error responses."""
host = "rivian.com"
Expand Down
Loading