Skip to content

Commit 5b69c31

Browse files
sshanegregjhogan
authored andcommitted
FPv2: log all present ECU addresses (commaai#24916)
* eliminate brands based on ECUs that respond to tester present * make it work * Add type hint for can message Use make_can_msg * Only query for addresses in fingerprints, and account for different busses * These need to be addresses, not response addresses * We need to listen to response addresses, not query addresses * add to files_common * Unused Optional Drain sock raw * add logging * only query essential ecus comments * simplify get_brand_candidates(), keep track of multiple request variants per make and request each subaddress * fixes make dat bytes bus is src Fix check * (addr, subaddr, bus) can be common across brands, add a match to each brand * fix length * query subaddrs in sequence * fix * candidate if a platform is a subset of responding ecu addresses comment comment * do logging for shadow mode * log responses so we can calculate candidates offline * get has_subaddress from response set * one liner * fix mypy * set to default at top * always log for now * log to make sure it's taking exactly timeout time * import time * fix logging * 0.1 timeout * clean up Co-authored-by: Greg Hogan <gregjhogan@gmail.com>
1 parent a37cf68 commit 5b69c31

File tree

4 files changed

+134
-5
lines changed

4 files changed

+134
-5
lines changed

release/files_common

+1
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ selfdrive/car/interfaces.py
105105
selfdrive/car/vin.py
106106
selfdrive/car/disable_ecu.py
107107
selfdrive/car/fw_versions.py
108+
selfdrive/car/ecu_addrs.py
108109
selfdrive/car/isotp_parallel_query.py
109110
selfdrive/car/tests/__init__.py
110111
selfdrive/car/tests/test_car_interfaces.py

selfdrive/car/car_helpers.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ def _get_interface_names() -> Dict[str, List[str]]:
7979
def fingerprint(logcan, sendcan):
8080
fixed_fingerprint = os.environ.get('FINGERPRINT', "")
8181
skip_fw_query = os.environ.get('SKIP_FW_QUERY', False)
82+
ecu_responses = set()
8283

8384
if not fixed_fingerprint and not skip_fw_query:
8485
# Vin query only reliably works thorugh OBDII
@@ -97,6 +98,7 @@ def fingerprint(logcan, sendcan):
9798
else:
9899
cloudlog.warning("Getting VIN & FW versions")
99100
_, vin = get_vin(logcan, sendcan, bus)
101+
ecu_responses = get_present_ecus(logcan, sendcan)
100102
car_fw = get_fw_versions(logcan, sendcan)
101103

102104
exact_fw_match, fw_candidates = match_fw_to_car(car_fw)
@@ -163,8 +165,8 @@ def fingerprint(logcan, sendcan):
163165
car_fingerprint = fixed_fingerprint
164166
source = car.CarParams.FingerprintSource.fixed
165167

166-
cloudlog.event("fingerprinted", car_fingerprint=car_fingerprint,
167-
source=source, fuzzy=not exact_match, fw_count=len(car_fw))
168+
cloudlog.event("fingerprinted", car_fingerprint=car_fingerprint, source=source, fuzzy=not exact_match,
169+
fw_count=len(car_fw), ecu_responses=ecu_responses, error=True)
168170
return car_fingerprint, finger, vin, car_fw, source, exact_match
169171

170172

selfdrive/car/ecu_addrs.py

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#!/usr/bin/env python3
2+
import capnp
3+
import time
4+
import traceback
5+
from typing import Optional, Set, Tuple
6+
7+
import cereal.messaging as messaging
8+
from panda.python.uds import SERVICE_TYPE
9+
from selfdrive.car import make_can_msg
10+
from selfdrive.boardd.boardd import can_list_to_can_capnp
11+
from system.swaglog import cloudlog
12+
13+
14+
def make_tester_present_msg(addr, bus, subaddr=None):
15+
dat = [0x02, SERVICE_TYPE.TESTER_PRESENT, 0x0]
16+
if subaddr is not None:
17+
dat.insert(0, subaddr)
18+
19+
dat.extend([0x0] * (8 - len(dat)))
20+
return make_can_msg(addr, bytes(dat), bus)
21+
22+
23+
def is_tester_present_response(msg: capnp.lib.capnp._DynamicStructReader, subaddr: Optional[int] = None) -> bool:
24+
# ISO-TP messages are always padded to 8 bytes
25+
# tester present response is always a single frame
26+
dat_offset = 1 if subaddr is not None else 0
27+
if len(msg.dat) == 8 and 1 <= msg.dat[dat_offset] <= 7:
28+
# success response
29+
if msg.dat[dat_offset + 1] == (SERVICE_TYPE.TESTER_PRESENT + 0x40):
30+
return True
31+
# error response
32+
if msg.dat[dat_offset + 1] == 0x7F and msg.dat[dat_offset + 2] == SERVICE_TYPE.TESTER_PRESENT:
33+
return True
34+
return False
35+
36+
37+
def get_all_ecu_addrs(logcan: messaging.SubSocket, sendcan: messaging.PubSocket, bus: int, timeout: float = 1, debug: bool = True) -> Set[Tuple[int, Optional[int], int]]:
38+
addr_list = [0x700 + i for i in range(256)] + [0x18da00f1 + (i << 8) for i in range(256)]
39+
queries: Set[Tuple[int, Optional[int], int]] = {(addr, None, bus) for addr in addr_list}
40+
responses = queries
41+
return get_ecu_addrs(logcan, sendcan, queries, responses, timeout=timeout, debug=debug)
42+
43+
44+
def get_ecu_addrs(logcan: messaging.SubSocket, sendcan: messaging.PubSocket, queries: Set[Tuple[int, Optional[int], int]],
45+
responses: Set[Tuple[int, Optional[int], int]], timeout: float = 1, debug: bool = False) -> Set[Tuple[int, Optional[int], int]]:
46+
ecu_responses: Set[Tuple[int, Optional[int], int]] = set() # set((addr, subaddr, bus),)
47+
try:
48+
msgs = [make_tester_present_msg(addr, bus, subaddr) for addr, subaddr, bus in queries]
49+
50+
messaging.drain_sock_raw(logcan)
51+
sendcan.send(can_list_to_can_capnp(msgs, msgtype='sendcan'))
52+
start_time = time.monotonic()
53+
while time.monotonic() - start_time < timeout:
54+
can_packets = messaging.drain_sock(logcan, wait_for_one=True)
55+
for packet in can_packets:
56+
for msg in packet.can:
57+
subaddr = None if (msg.address, None, msg.src) in responses else msg.dat[0]
58+
if (msg.address, subaddr, msg.src) in responses and is_tester_present_response(msg, subaddr):
59+
if debug:
60+
print(f"CAN-RX: {hex(msg.address)} - 0x{bytes.hex(msg.dat)}")
61+
if (msg.address, subaddr, msg.src) in ecu_responses:
62+
print(f"Duplicate ECU address: {hex(msg.address)}")
63+
ecu_responses.add((msg.address, subaddr, msg.src))
64+
except Exception:
65+
cloudlog.warning(f"ECU addr scan exception: {traceback.format_exc()}")
66+
return ecu_responses
67+
68+
69+
if __name__ == "__main__":
70+
import argparse
71+
72+
parser = argparse.ArgumentParser(description='Get addresses of all ECUs')
73+
parser.add_argument('--debug', action='store_true')
74+
args = parser.parse_args()
75+
76+
logcan = messaging.sub_sock('can')
77+
sendcan = messaging.pub_sock('sendcan')
78+
79+
time.sleep(1.0)
80+
81+
print("Getting ECU addresses ...")
82+
ecu_addrs = get_all_ecu_addrs(logcan, sendcan, 1, debug=args.debug)
83+
84+
print()
85+
print("Found ECUs on addresses:")
86+
for addr, subaddr, bus in ecu_addrs:
87+
msg = f" 0x{hex(addr)}"
88+
if subaddr is not None:
89+
msg += f" (sub-address: 0x{hex(subaddr)})"
90+
print(msg)

selfdrive/car/fw_versions.py

+39-3
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,20 @@
33
import traceback
44
from collections import defaultdict
55
from dataclasses import dataclass, field
6-
from typing import Any, List
6+
from typing import Any, List, Optional, Set, Tuple
77
from tqdm import tqdm
88

99
import panda.python.uds as uds
1010
from cereal import car
11+
from selfdrive.car.ecu_addrs import get_ecu_addrs
1112
from selfdrive.car.interfaces import get_interface_attr
1213
from selfdrive.car.fingerprints import FW_VERSIONS
1314
from selfdrive.car.isotp_parallel_query import IsoTpParallelQuery
1415
from selfdrive.car.toyota.values import CAR as TOYOTA
1516
from system.swaglog import cloudlog
1617

1718
Ecu = car.CarParams.Ecu
19+
ESSENTIAL_ECUS = [Ecu.engine, Ecu.eps, Ecu.esp, Ecu.fwdRadar, Ecu.fwdCamera, Ecu.vsa]
1820

1921

2022
def p16(val):
@@ -261,7 +263,6 @@ def match_fw_to_car_exact(fw_versions_dict):
261263
ecu_type = ecu[0]
262264
addr = ecu[1:]
263265
found_version = fw_versions_dict.get(addr, None)
264-
ESSENTIAL_ECUS = [Ecu.engine, Ecu.eps, Ecu.esp, Ecu.fwdRadar, Ecu.fwdCamera, Ecu.vsa]
265266
if ecu_type == Ecu.esp and candidate in (TOYOTA.RAV4, TOYOTA.COROLLA, TOYOTA.HIGHLANDER, TOYOTA.SIENNA, TOYOTA.LEXUS_IS) and found_version is None:
266267
continue
267268

@@ -299,11 +300,46 @@ def match_fw_to_car(fw_versions, allow_fuzzy=True):
299300
return exact_match, matches
300301

301302

303+
def get_present_ecus(logcan, sendcan):
304+
queries = list()
305+
parallel_queries = list()
306+
responses = set()
307+
versions = get_interface_attr('FW_VERSIONS', ignore_none=True)
308+
309+
for r in REQUESTS:
310+
if r.brand not in versions:
311+
continue
312+
313+
for brand_versions in versions[r.brand].values():
314+
for ecu_type, addr, sub_addr in brand_versions:
315+
# Only query ecus in whitelist if whitelist is not empty
316+
if len(r.whitelist_ecus) == 0 or ecu_type in r.whitelist_ecus:
317+
a = (addr, sub_addr, r.bus)
318+
# Build set of queries
319+
if sub_addr is None:
320+
if a not in parallel_queries:
321+
parallel_queries.append(a)
322+
else: # subaddresses must be queried one by one
323+
if [a] not in queries:
324+
queries.append([a])
325+
326+
# Build set of expected responses to filter
327+
response_addr = uds.get_rx_addr_for_tx_addr(addr, r.rx_offset)
328+
responses.add((response_addr, sub_addr, r.bus))
329+
330+
queries.insert(0, parallel_queries)
331+
332+
ecu_responses: Set[Tuple[int, Optional[int], int]] = set()
333+
for query in queries:
334+
ecu_responses.update(get_ecu_addrs(logcan, sendcan, set(query), responses, timeout=0.1))
335+
return ecu_responses
336+
337+
302338
def get_fw_versions(logcan, sendcan, extra=None, timeout=0.1, debug=False, progress=False):
303339
ecu_types = {}
304340

305341
# Extract ECU addresses to query from fingerprints
306-
# ECUs using a subadress need be queried one by one, the rest can be done in parallel
342+
# ECUs using a subaddress need be queried one by one, the rest can be done in parallel
307343
addrs = []
308344
parallel_addrs = []
309345

0 commit comments

Comments
 (0)