From 19e68ea79ae0c9058a1064a888490f66ea00e8a7 Mon Sep 17 00:00:00 2001 From: Ellie Smith Date: Fri, 13 Nov 2026 15:46:59 -0500 Subject: [PATCH 1/4] volvo: add safety tests for CMA and SPA Ported from cschmittiey/opendbc main (56b1b58). --- opendbc/safety/tests/test_volvo.py | 242 +++++++++++++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 opendbc/safety/tests/test_volvo.py diff --git a/opendbc/safety/tests/test_volvo.py b/opendbc/safety/tests/test_volvo.py new file mode 100644 index 00000000000..7c5d19697ad --- /dev/null +++ b/opendbc/safety/tests/test_volvo.py @@ -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() From ec9d29e2e54360ea824d32ae75d7adfaa334c826 Mon Sep 17 00:00:00 2001 From: joey Date: Fri, 13 Nov 2026 15:47:08 -0500 Subject: [PATCH 2/4] safety tests: skip CMA<->SPA in wrong-safety-mode TX test Both use the volvo safety mode with a different safetyParam and share TX_MSGS. --- opendbc/safety/tests/common.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/opendbc/safety/tests/common.py b/opendbc/safety/tests/common.py index 267736cfac6..2d11be743d3 100644 --- a/opendbc/safety/tests/common.py +++ b/opendbc/safety/tests/common.py @@ -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', From 6c6fc8a13fb824d728ddea1a88ea4b90753f615d Mon Sep 17 00:00:00 2001 From: Ellie Smith Date: Sat, 14 Nov 2026 10:06:14 -0500 Subject: [PATCH 3/4] volvo safety: mark unreachable wrong-bus TX branches GCOV_EXCL Ported from cschmittiey/opendbc 9efaf9de. Comment-only: the TX allowlist already pins each address to one bus, so these branches can't be reached. Brings volvo.h to 100% line coverage so opendbc/safety/tests/test.sh passes. --- opendbc/safety/modes/volvo.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/opendbc/safety/modes/volvo.h b/opendbc/safety/modes/volvo.h index 439aa25a26e..20c60ce4f14 100644 --- a/opendbc/safety/modes/volvo.h +++ b/opendbc/safety/modes/volvo.h @@ -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; From 7693973b6ec303decdc226dabfa0a855a93e50bd Mon Sep 17 00:00:00 2001 From: joey Date: Sat, 14 Nov 2026 10:06:29 -0500 Subject: [PATCH 4/4] volvo: document how to run the safety tests --- opendbc/car/volvo/README.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100755 opendbc/car/volvo/README.md diff --git a/opendbc/car/volvo/README.md b/opendbc/car/volvo/README.md new file mode 100755 index 00000000000..21ea7dd3269 --- /dev/null +++ b/opendbc/car/volvo/README.md @@ -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.