diff --git a/src/rivian/rivian.py b/src/rivian/rivian.py index 8b69946..2724790 100644 --- a/src/rivian/rivian.py +++ b/src/rivian/rivian.py @@ -764,6 +764,58 @@ async def send_location_to_vehicle( } return await self.__graphql_query(headers, url, graphql_json) + async def plan_trip( + self, + vehicle_id: str, + origin: tuple[float, float], + stops: list[tuple[float, float]], + min_arrival_soc: int = 20, + starting_soc: float | None = None, + ) -> list[dict[str, Any]]: + """Plan a trip with Rivian's trip planner, without sending it to a vehicle. + + `origin` and `stops` are (latitude, longitude), in order. The planner adds + charging stops to arrive with at least `min_arrival_soc` percent, leaving + with `starting_soc` percent, or a full battery without one. + + Returns the plans, so far one, or none when there is no route. A plan's + `summary` has the drive, charging and total time in seconds, the distance in + meters and the charge on arrival. Its `waypoints` are the origin, the stops + and the added charging stops, each of those with its `charger`. Drive times + don't account for traffic. + """ + if not stops: + raise RivianBadRequestError("A trip needs at least one stop") + if not 0 <= min_arrival_soc <= 100: + raise RivianBadRequestError("Minimum arrival charge must be 0 to 100") + url = GRAPHQL_GATEWAY + headers = BASE_HEADERS | { + "Csrf-Token": self._csrf_token, + "A-Sess": self._app_session_token, + "U-Sess": self._user_session_token, + } + variables: dict[str, Any] = { + "vehicle": vehicle_id, + "waypoints": [ + {"latitude": latitude, "longitude": longitude} + for latitude, longitude in [origin, *stops] + ], + "targetArrivalSocPercent": min_arrival_soc, + } + if starting_soc is not None: + variables["startingSoc"] = starting_soc + graphql_json = { + "operationName": "planTripWithMultiStopV2", + "query": "query planTripWithMultiStopV2($waypoints: [RequestWaypointInput!]!, $vehicle: String!, $startingSoc: Float, $targetArrivalSocPercent: Float) { planTrip2(waypoints: $waypoints, vehicle: $vehicle, startingSoc: $startingSoc, targetArrivalSocPercent: $targetArrivalSocPercent) { plans { driveLegs { distanceMeters durationSeconds energyConsumptionKwh } waypoints { waypointType latitude longitude charger { entityId name maxPowerKw chargeDurationSeconds adapterRequired } arrivalSOCPercent departureSOCPercent arrivalTimeUTC departureTimeUTC distanceFromOriginMeters } summary { destinationReachable totalChargeDurationSeconds totalDriveDurationSeconds totalDriveDistanceMeters totalTripDurationSeconds arrivalSOCPercent arrivalRangeMeters } } status } }", + "variables": variables, + } + + response = await self.__graphql_query(headers, url, graphql_json) + if response.status == 200: + data = await response.json() + return (data.get("data", {}).get("planTrip2") or {}).get("plans") or [] + return [] + async def send_trip_to_vehicle( self, vehicle_id: str, diff --git a/tests/responses.py b/tests/responses.py index c885a93..76e3899 100644 --- a/tests/responses.py +++ b/tests/responses.py @@ -673,6 +673,80 @@ } } +PLAN_TRIP_RESPONSE = { + "data": { + "planTrip2": { + "plans": [ + { + "driveLegs": [ + { + "distanceMeters": 130629, + "durationSeconds": 5394, + "energyConsumptionKwh": 40.064617, + }, + { + "distanceMeters": 394936, + "durationSeconds": 13981, + "energyConsumptionKwh": 109.2556, + }, + ], + "waypoints": [ + { + "waypointType": "OTHER", + "latitude": 34.420815, + "longitude": -119.698169, + "charger": None, + "arrivalSOCPercent": 60.000004, + "departureSOCPercent": 60.000004, + "arrivalTimeUTC": "2026-11-26T19:24:58Z", + "departureTimeUTC": "2026-11-26T19:24:58Z", + "distanceFromOriginMeters": 0, + }, + { + "waypointType": "DC_CHARGE_STATION", + "latitude": 35.135562896728516, + "longitude": -120.62577056884766, + "charger": { + "entityId": "US-RIV-L4075861308012401216", + "name": "Pismo Beach, CA [Rivian Adventure Network]", + "maxPowerKw": 300, + "chargeDurationSeconds": 2418, + "adapterRequired": False, + }, + "arrivalSOCPercent": 28.748352, + "departureSOCPercent": 87.22277, + "arrivalTimeUTC": "2026-11-26T20:54:52Z", + "departureTimeUTC": "2026-11-26T21:38:53Z", + "distanceFromOriginMeters": 130629, + }, + { + "waypointType": "OTHER", + "latitude": 37.7749, + "longitude": -122.4194, + "charger": None, + "arrivalSOCPercent": 2, + "departureSOCPercent": 2, + "arrivalTimeUTC": "2026-11-27T01:31:54Z", + "departureTimeUTC": "2026-11-27T01:31:54Z", + "distanceFromOriginMeters": 525565, + }, + ], + "summary": { + "destinationReachable": True, + "totalChargeDurationSeconds": 2418, + "totalDriveDurationSeconds": 19375, + "totalDriveDistanceMeters": 525565, + "totalTripDurationSeconds": 22016, + "arrivalSOCPercent": 2, + "arrivalRangeMeters": 10389.434, + }, + } + ], + "status": "OK", + } + } +} + SEND_VEHICLE_OPERATION_RESPONSE = { "data": { "sendVehicleOperation": { diff --git a/tests/test_rivian.py b/tests/test_rivian.py index dfefd9f..7331300 100644 --- a/tests/test_rivian.py +++ b/tests/test_rivian.py @@ -46,6 +46,7 @@ DEPART_NOW_RESPONSE, OTP_TOKEN_RESPONSE, PLACES_RESPONSE, + PLAN_TRIP_RESPONSE, SEND_LOCATION_TO_VEHICLE_RESPONSE, SEND_PARALLAX_COMMAND_RESPONSE, SEND_VEHICLE_OPERATION_RESPONSE, @@ -498,6 +499,44 @@ async def test_trips(aresponses: ResponsesMockServer) -> None: assert not await rivian.end_trip("vehicle_id", "user") +async def test_plan_trip(aresponses: ResponsesMockServer) -> None: + """Test planning a trip.""" + requests = capture_requests( + aresponses, + PLAN_TRIP_RESPONSE, + {"data": {"planTrip2": {"plans": [], "status": "NO_ROUTE_FOUND"}}}, + ) + async with aiohttp.ClientSession(): + rivian = Rivian( + csrf_token="csrf", + app_session_token="token", + user_session_token="token", + ) + + stops = [(34.428, -119.875), (37.775, -122.419)] + plans = await rivian.plan_trip("vehicle_id", (34.421, -119.698), stops, 30, 60) + assert plans == PLAN_TRIP_RESPONSE["data"]["planTrip2"]["plans"] + assert requests[0]["variables"] == { + "vehicle": "vehicle_id", + "waypoints": [ + {"latitude": 34.421, "longitude": -119.698}, + {"latitude": 34.428, "longitude": -119.875}, + {"latitude": 37.775, "longitude": -122.419}, + ], + "targetArrivalSocPercent": 30, + "startingSoc": 60, + } + + assert await rivian.plan_trip("vehicle_id", (34.421, -119.698), stops) == [] + # the planner takes a full battery when it isn't told the charge + assert requests[1]["variables"]["targetArrivalSocPercent"] == 20 + assert "startingSoc" not in requests[1]["variables"] + + for bad in ({"stops": []}, {"min_arrival_soc": 101}): + with pytest.raises(RivianBadRequestError): + await rivian.plan_trip("vehicle_id", (0, 0), **({"stops": stops} | bad)) + + async def test_start_gear_guard_live_stream(aresponses: ResponsesMockServer) -> None: """Test starting a Gear Guard live stream.""" requests = capture_requests(