Skip to content
Open
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
34 changes: 34 additions & 0 deletions opendbc/car/volvo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Volvo / Polestar dev notes

## Safety tests

`opendbc/safety/tests/test_volvo.py` covers `opendbc/safety/modes/volvo.h` for CMA and SPA:
gas/brake/cruise disengage, standstill, TX allowed buses, relay malfunction, and that the
speed scale / gas thresholds match `carstate.py`.

Not tested yet because `volvo.h` doesn't check them yet: LCA_5 angle limits, RX counters/checksums.

### Setup

```bash
git clone -b master-cma-dev5 https://github.com/paper5590/opendbc # default branch is master-cma, use dev5
cd opendbc
bash setup.sh # bash, not source: setup.sh has set -e and will close your terminal on any error
source .venv/bin/activate
```

### Run

```bash
python -m unittest opendbc.safety.tests.test_volvo # Volvo only, should end with OK (skipped=9)
unittest-parallel -s opendbc/safety/tests -t . # all cars, run this if you touch common.py or safety.h
bash opendbc/safety/tests/test.sh # what CI runs, also requires 100% line coverage
```

### Gotchas

- `GcovrMergeAssertionError ... on multiple lines` from test.sh: stale coverage files from an older
build or another branch. `git clean -fdX opendbc/safety/tests/libsafety` and rerun.
- If you change the speed scale or a gas threshold, change `volvo.h`, `carstate.py` and
`test_volvo.py` together. The self-consistency tests fail otherwise.
- New TX message: add it to `VOLVO_TX_MSGS` in `volvo.h` and to the `_TX_*_BUS_ADDRS` lists in the test.
22 changes: 22 additions & 0 deletions opendbc/safety/modes/volvo.h
Original file line number Diff line number Diff line change
Expand Up @@ -136,43 +136,65 @@ static bool volvo_tx_hook(const CANPacket_t *msg) {
bool tx = true;

// Very relaxed safety policy - only basic frame ID checks
// NOTE: the wrong-bus rejections below are unreachable defense-in-depth:
// safety_tx_hook() only calls this hook after the message passes the
// VOLVO_TX_MSGS allowlist, which already pins each TX address to a single
// bus (and VOLVO_DRIVER_INPUT/VOLVO_SAS are not TX'able on any bus).
// Hence the GCOV_EXCL markers, following the defaults.h convention.
// test_volvo.py's test_tx_hook_wrong_bus_blocked pins down the blocked
// wrong-bus TX behavior at the safety_tx_hook() level.
if (msg->addr == VOLVO_LCA_STEER) {
// LCA message flows: VCU1 (main bus) -> PSCM (party bus)
// We're acting as VCU1, so we send LCA message to party bus (bus 2)
// GCOV_EXCL_START
// Unreachable by design (allowlist pins VOLVO_LCA_STEER to the party bus)
if (msg->bus != VOLVO_PARTY_BUS) {
tx = false; // Wrong bus
}
// GCOV_EXCL_STOP
}

if (msg->addr == VOLVO_PSCM) {
// PSCM message: we relay from party bus (bus 2) to main bus (bus 0)
// So we TX on main bus (bus 0)
// GCOV_EXCL_START
// Unreachable by design (allowlist pins VOLVO_PSCM to the main bus)
if (msg->bus != VOLVO_MAIN_BUS) {
tx = false; // Wrong bus
}
// GCOV_EXCL_STOP
}

if (msg->addr == VOLVO_DRIVER_INPUT) {
// Driver input message: we relay from party bus (bus 2) to main bus (bus 0)
// So we TX on main bus (bus 0)
// GCOV_EXCL_START
// Unreachable by design (VOLVO_DRIVER_INPUT is not in VOLVO_TX_MSGS)
if (msg->bus != VOLVO_MAIN_BUS) {
tx = false; // Wrong bus
}
}
// GCOV_EXCL_STOP

if (msg->addr == VOLVO_SAS) {
// SAS message: we relay from party bus (bus 2) to main bus (bus 0)
// So we TX on main bus (bus 0)
// GCOV_EXCL_START
// Unreachable by design (VOLVO_SAS is not in VOLVO_TX_MSGS)
if (msg->bus != VOLVO_MAIN_BUS) {
tx = false; // Wrong bus
}
}
// GCOV_EXCL_STOP

if (msg->addr == VOLVO_LCA_2) {
// LCA_2 -> PSCM
// GCOV_EXCL_START
// Unreachable by design (allowlist pins VOLVO_LCA_2 to the party bus)
if (msg->bus != VOLVO_PARTY_BUS) {
tx = false; // Wrong bus
}
// GCOV_EXCL_STOP
}

return tx;
Expand Down
2 changes: 2 additions & 0 deletions opendbc/safety/tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -898,6 +898,8 @@ def test_tx_hook_on_wrong_safety_mode(self):
continue
if attr.startswith('TestSubaruPreglobal') and current_test.startswith('TestSubaruPreglobal'):
continue
if attr.startswith('TestVolvo') and current_test.startswith('TestVolvo'):
continue
if {attr, current_test}.issubset({'TestVolkswagenPqSafety', 'TestVolkswagenPqStockSafety', 'TestVolkswagenPqLongSafety'}):
continue
if {attr, current_test}.issubset({'TestGmCameraSafety', 'TestGmCameraLongitudinalSafety', 'TestGmAscmSafety',
Expand Down
242 changes: 242 additions & 0 deletions opendbc/safety/tests/test_volvo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
#!/usr/bin/env python3
"""
Safety tests for Volvo CMA/SPA.

The safety mode lives at ``opendbc/safety/modes/volvo.h`` and is parameterized
by ``safetyParam``:

- ``safetyParam == 0`` → CMA platform (Volvo XC40 Recharge)
- ``safetyParam == VOLVO_FLAG_SPA`` → SPA platform (Volvo S60 Recharge,
Polestar 2)

The two platforms share LCA/PSCM/etc. addresses on the main and party buses
but use *different* PT-bus addresses and signal scales for ECM_1 and
BUS1_CRUISE_CONTROL. Vehicle speed is read from main-bus SPEED on both, so it
is not platform-dependent. This test file exercises both platforms through the
same generic ``CarSafetyTest`` harness so that any future divergence between
``carstate.py`` and ``volvo.h`` — e.g. a threshold drifting out of sync — is
caught on a laptop instead of in the car.

Companion to: ``opendbc/car/volvo/carstate.py`` (must agree on thresholds).
"""

import pathlib
import re
import unittest

from opendbc.car.structs import CarParams
from opendbc.safety.tests.libsafety import libsafety_py
import opendbc.safety.tests.common as common
from opendbc.safety.tests.common import CANPackerSafety


# Must match VOLVO_FLAG_SPA in opendbc/safety/modes/volvo.h
VOLVO_FLAG_SPA = 1

# Must match VOLVO_SPEED_TO_MS in volvo.h and SPEED_TO_MS in carstate.py
VOLVO_SPEED_TO_MS = 0.003977

# Bus layout (must match volvo.h)
VOLVO_MAIN_BUS = 0
VOLVO_PT_BUS = 1
VOLVO_PARTY_BUS = 2

# Shared platform-independent addresses
VOLVO_SPEED = 0x60
VOLVO_LCA_STEER = 0x58
VOLVO_LCA_2 = 0x69
VOLVO_LCA_3 = 0x57
VOLVO_LCA_4 = 0x90
VOLVO_LCA_5 = 0x67
VOLVO_LCA_6 = 0x97
VOLVO_LCA_7 = 0x92
VOLVO_PSCM = 0x16
VOLVO_PSCM_RELATED = 0x17
VOLVO_SAS = 0x55
VOLVO_DRIVER_INPUT = 0x15

# Addresses panda TX'd with .check_relay = true, grouped by bus
_TX_PARTY_BUS_ADDRS = (
VOLVO_LCA_STEER, VOLVO_LCA_2, VOLVO_LCA_3, VOLVO_LCA_4,
VOLVO_LCA_5, VOLVO_LCA_6, VOLVO_LCA_7,
)
_TX_MAIN_BUS_ADDRS = (VOLVO_PSCM, VOLVO_PSCM_RELATED)


class TestVolvoSafetyBase(common.CarSafetyTest):
"""Shared RX/TX/relay tests for both CMA and SPA.

Subclasses pin down the PT-bus DBC and per-platform gas/cruise encoding.
"""

TX_MSGS = (
[[a, VOLVO_PARTY_BUS] for a in _TX_PARTY_BUS_ADDRS]
+ [[a, VOLVO_MAIN_BUS] for a in _TX_MAIN_BUS_ADDRS]
)
RELAY_MALFUNCTION_ADDRS = {
VOLVO_PARTY_BUS: _TX_PARTY_BUS_ADDRS,
VOLVO_MAIN_BUS: _TX_MAIN_BUS_ADDRS,
}
# volvo.h installs no custom fwd hook, so the panda uses the default main<->party
# forwarding (bus 0 <-> bus 2). For each TX addr with .check_relay=true, the panda
# automatically refuses to forward from the bus where stock traffic lives TO the
# bus where openpilot is TX'ing — that's what keeps the stock ECU from fighting us.
FWD_BLACKLISTED_ADDRS = {
VOLVO_MAIN_BUS: list(_TX_PARTY_BUS_ADDRS), # stock on 0 must not forward to 2
VOLVO_PARTY_BUS: list(_TX_MAIN_BUS_ADDRS), # stock on 2 must not forward to 0
}
STANDSTILL_THRESHOLD = 0.1 # m/s, matches volvo.h

# Subclasses set these
SAFETY_PARAM: int = 0
PT_DBC: str = ""

MID_DBC = "volvo_mid_1"

@classmethod
def setUpClass(cls):
if cls.__name__ == "TestVolvoSafetyBase":
cls.safety = None
raise unittest.SkipTest
super().setUpClass()

def setUp(self):
self.pt_packer = CANPackerSafety(self.PT_DBC)
self.mid_packer = CANPackerSafety(self.MID_DBC)
# CarSafetyTest.packer is referenced by a few generic tests; point it at
# the mid-bus DBC since most shared messages live there.
self.packer = self.mid_packer
self.safety = libsafety_py.libsafety
self.safety.set_safety_hooks(CarParams.SafetyModel.volvo, self.SAFETY_PARAM)
self.safety.init_tests()

# ---- Abstract methods from CarSafetyTest ----

def _user_brake_msg(self, brake):
# volvo.h reads BRAKE_PEDAL_PRESSED_B (bit 46, factor 1, active high)
values = {"BRAKE_PEDAL_PRESSED_B": 1 if brake else 0}
return self.mid_packer.make_can_msg_safety("LCA_2", VOLVO_MAIN_BUS, values)

def _speed_msg(self, speed):
# Main-bus SPEED, the same message on both platforms. The DBC carries it as
# raw counts (factor 1) and volvo.h applies VOLVO_SPEED_TO_MS, so convert here.
values = {"SPEED": round(speed / VOLVO_SPEED_TO_MS)}
return self.mid_packer.make_can_msg_safety("SPEED", VOLVO_MAIN_BUS, values)

def _speed_msg_2(self, speed):
# Volvo's safety mode only consumes a single vehicle-speed source, so the
# generic rx_hook_speed_mismatch test doesn't apply. Returning None asks
# the harness to skip it (see common.CarSafetyTest.test_rx_hook_speed_mismatch).
return None

# ---- Volvo-specific consistency tests ----

def test_tx_hook_wrong_bus_blocked(self):
"""
Every TX address is pinned to exactly one bus by the VOLVO_TX_MSGS
allowlist, which safety_tx_hook() enforces before volvo_tx_hook() runs.
TX attempts anywhere off the allowlisted bus must be rejected, even with
controls allowed. Also covers the relayed-RX addresses (SAS, DRIVER_INPUT)
that volvo_tx_hook() used to re-check: they are not TX'able on any bus.
"""
tx_msgs = {tuple(m) for m in self.TX_MSGS}
addrs = {addr for addr, _ in tx_msgs} | {VOLVO_SAS, VOLVO_DRIVER_INPUT}
self.safety.set_controls_allowed(True)
for addr in sorted(addrs):
for bus in range(4):
if (addr, bus) in tx_msgs:
self.assertTrue(self._tx(common.make_msg(bus, addr)),
f"blocked TX addr={hex(addr)} on allowlisted bus={bus}")
else:
self.assertFalse(self._tx(common.make_msg(bus, addr)),
f"allowed TX addr={hex(addr)} on wrong bus={bus}")

def test_gas_threshold_self_consistent(self):
"""
Sanity: the panda's gas_pressed edge is exactly where GAS_PRESSED_THRESHOLD
is defined. Regression guard for the CMA-vs-SPA scale mismatch bug where
carstate.py applied CMA thresholds (raw 0-255) to SPA's DBC-scaled percent.
If you change the threshold in volvo.h, update carstate.py AND this test.
"""
# Just below threshold → not pressed. Use a value strictly less than threshold.
just_below = max(self.GAS_PRESSED_THRESHOLD - 1, 0)
self._rx(self._user_gas_msg(just_below))
self.assertFalse(self.safety.get_gas_pressed_prev(),
f"gas flagged at {just_below} (threshold={self.GAS_PRESSED_THRESHOLD})")

# Just above threshold → pressed.
self._rx(self._user_gas_msg(self.GAS_PRESSED_THRESHOLD + 1))
self.assertTrue(self.safety.get_gas_pressed_prev(),
f"gas not flagged above {self.GAS_PRESSED_THRESHOLD}")

def test_speed_scale_self_consistent(self):
"""
The main-bus SPEED LSB is written out in three places: volvo.h, carstate.py
and this file. They must agree, or the panda and openpilot disagree about
vehicle speed. Parsed as text so this holds without importing either.
"""
root = pathlib.Path(__file__).parents[3]
sources = {
"volvo.h": (root / "opendbc/safety/modes/volvo.h",
r"#define\s+VOLVO_SPEED_TO_MS\s+([0-9.]+)f?"),
"carstate.py": (root / "opendbc/car/volvo/carstate.py",
r"^SPEED_TO_MS\s*=\s*([0-9.]+)"),
}
for name, (path, pattern) in sources.items():
m = re.search(pattern, path.read_text(), re.MULTILINE)
self.assertIsNotNone(m, f"could not find the speed LSB in {name}")
self.assertEqual(float(m.group(1)), VOLVO_SPEED_TO_MS,
f"{name} speed LSB disagrees with test_volvo.py")


class TestVolvoCMA(TestVolvoSafetyBase):
"""
Volvo CMA: XC40 Recharge.

ECM_1.ACCELERATOR_PEDAL_POS is raw 0-255 (DBC factor 1). Idle is ~20; panda
fires gas_pressed above 21. carstate.py uses the same raw threshold.
"""
SAFETY_PARAM = 0
PT_DBC = "volvo_front_1_cma"
GAS_PRESSED_THRESHOLD = 21 # raw counts

def _user_gas_msg(self, gas):
values = {"ACCELERATOR_PEDAL_POS": gas}
return self.pt_packer.make_can_msg_safety("ECM_1", VOLVO_PT_BUS, values)

def _pcm_status_msg(self, enable):
# CMA cruise is a pair of bools; either one being high enables cruise.
values = {"CRUISE_CONTROL_ENABLED": 1 if enable else 0,
"CRUISE_CONTROL_ENABLED_IDLE_TRAFFIC": 0}
return self.pt_packer.make_can_msg_safety(
"BUS1_CRUISE_CONTROL", VOLVO_PT_BUS, values)


class TestVolvoSPA(TestVolvoSafetyBase):
"""
Volvo SPA: S60 Recharge, Polestar 2.

ECM_1.ACCELERATOR_PEDAL_POS is DBC-scaled to percent (factor 0.00390625,
range 0-100%). Idle is ~0; panda fires gas_pressed above 1.0%.
carstate.py MUST use the same percent-based threshold — see
opendbc/car/volvo/carstate.py. A mismatch here manifests in test_models.py
as persistent ``panda safety doesn't agree with openpilot: {'gasPressed': N}``.
"""
SAFETY_PARAM = VOLVO_FLAG_SPA
PT_DBC = "volvo_front_1_spa"
GAS_PRESSED_THRESHOLD = 1.0 # percent

def _user_gas_msg(self, gas):
values = {"ACCELERATOR_PEDAL_POS": gas}
return self.pt_packer.make_can_msg_safety("ECM_1", VOLVO_PT_BUS, values)

def _pcm_status_msg(self, enable):
# SPA cruise signal has DBC factor -1 offset 1, so the "enabled" DBC value
# is 1 (which encodes as raw bit 0 — panda inverts it).
values = {"CRUISE_CONTROL_SPA_ENABLED": 1 if enable else 0}
return self.pt_packer.make_can_msg_safety(
"BUS1_CRUISE_CONTROL", VOLVO_PT_BUS, values)


if __name__ == "__main__":
unittest.main()
Loading