Examples¶
These are the Python programs from the repository’s python/examples/ directory.
They run against real adapters and ECUs. Select a suitable adapter and ECU address
for your setup before running them.
Print CAN frames¶
Discover an adapter and print received CAN frames.
"""Print frames from the first available adapter. Requires CAN hardware or vcan0."""
import asyncio
from automotive.adapters import CanAdapter
async def main() -> None:
"""Discover an adapter and print frames until interrupted."""
adapter = CanAdapter()
stream = adapter.recv()
async for frame in stream:
print(frame)
if __name__ == "__main__":
asyncio.run(main())
Send a CAN frame¶
Discover an adapter and send one Classic CAN frame.
"""Send one Classic CAN frame through the first available adapter."""
import asyncio
from automotive.adapters import CanAdapter
from automotive.can import Frame
async def main() -> None:
"""Discover an adapter and send a frame."""
adapter = CanAdapter()
frame = Frame(id=0x123, data=b"\x01\x02\x03\x04")
await adapter.send(frame)
print("Sent", frame)
if __name__ == "__main__":
asyncio.run(main())
Send ISO-TP messages¶
Follow the Rust example’s four explicit exchanges: two short requests, a 33-byte segmented request, and another DID request that can produce a long reply.
"""Exchange short and segmented PDUs with an ECU at 0x7A1/0x7A9."""
import asyncio
from automotive.adapters import CanAdapter
from automotive.transports.isotp import IsoTP, IsoTPConfig
async def main() -> None:
"""Send short and segmented requests, printing each response as hex."""
adapter = CanAdapter()
config = IsoTPConfig(tx_id=0x7A1)
isotp = IsoTP(adapter, config)
stream = isotp.recv()
await isotp.send(b"\x3e\x00")
response = await anext(stream)
print("RX:", response.hex())
await isotp.send(b"\x22\xf1\x81")
response = await anext(stream)
print("RX:", response.hex())
long_request = b"\x10" + b"\x00" * 32
await isotp.send(long_request)
response = await anext(stream)
print("RX:", response.hex())
long_response = b"\x22\xf1\x81"
await isotp.send(long_response)
response = await anext(stream)
print("RX:", response.hex())
if __name__ == "__main__":
asyncio.run(main())
Query an ECU with UDS¶
Read diagnostic data through a persistent UDS client.
"""Read software identification from a diagnostic ECU at transmit ID 0x7A1."""
import asyncio
from automotive.adapters import CanAdapter
from automotive.protocols.uds import DataIdentifier, SessionType, UDSClient
from automotive.transports.isotp import IsoTP
async def main() -> None:
"""Use defaults, select a session, and read an ECU data identifier."""
adapter = CanAdapter()
isotp = IsoTP.from_id(adapter, 0x7A1)
uds = UDSClient(isotp)
await uds.tester_present()
await uds.diagnostic_session_control(SessionType.EXTENDED_DIAGNOSTIC)
did = DataIdentifier.APPLICATION_SOFTWARE_IDENTIFICATION
resp = await uds.read_data_by_identifier(did)
print(f"{did.name}: {resp!r}")
if __name__ == "__main__":
asyncio.run(main())
Discover vehicles and use UDS over DoIP¶
Select --discovery active (default) or --discovery passive, and --ipv4
(default) or --ipv6. IPv6 requires --adapter eth0 to select the multicast
interface. Active IPv4 requires --local-address, e.g. 169.254.0.1/16, to bind
its source IP and derive the subnet broadcast. Passive IPv4 needs neither
--adapter nor --local-address.
For a directly connected ECU on Linux, first run
sudo scripts/set_up_doip.sh eth0 from the repository root. From python/:
uv run examples/doip.py --ipv4 --discovery active --local-address 169.254.0.1/16
uv run examples/doip.py --adapter eth0 --ipv6 --discovery active
uv run examples/doip.py --ipv4 --discovery passive
uv run examples/doip.py --adapter eth0 --ipv6 --discovery passive
Each example connects to discovered entities and reads UDS VIN (0xF190).
Passive mode runs until Ctrl+C; start it before powering up the ECU. Active
mode uses a two-second collection window. The tester logical address defaults
to 0x0E89; use --source-address to override it. The Rust example
(cargo run --example doip -- ...) accepts the same options.
"""Read ECU VINs using active or passive DoIP discovery over IPv4 or IPv6."""
import argparse
import asyncio
import ipaddress
import socket
from collections.abc import AsyncIterator
from automotive.protocols.uds import DataIdentifier, UDSClient, UDSConfig
from automotive.transports.doip import Discovery, DiscoveryConfig, DoIPConfig, VehicleAnnouncement, discover
def parse_address(value: str) -> int:
return int(value, 0)
async def announcements(config: DiscoveryConfig, mode: str) -> AsyncIterator[VehicleAnnouncement]:
if mode == "active":
for vehicle in await discover(config):
yield vehicle
else:
async with await Discovery.listen(config) as listener:
print("Listening for announcements; power up the ECU. Press Ctrl+C to stop.", flush=True)
while True:
yield await listener.recv()
async def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--discovery", choices=("active", "passive"), default="active")
parser.add_argument("--adapter", help="IPv6 interface (required with --ipv6)")
parser.add_argument("--local-address", help="Local IPv4 address/prefix (required for active IPv4 discovery)")
family = parser.add_mutually_exclusive_group()
family.add_argument("--ipv4", action="store_true", help="Use IPv4 broadcast (default)")
family.add_argument("--ipv6", action="store_true", help="Use IPv6 multicast")
parser.add_argument("--source-address", type=parse_address, default=0x0E89)
args = parser.parse_args()
if args.ipv6 and not args.adapter:
parser.error("--ipv6 requires --adapter")
if not args.ipv6 and args.discovery == "active" and not args.local_address:
parser.error("active IPv4 discovery requires --local-address")
local_address = None
if args.ipv6:
config = DiscoveryConfig.ipv6(socket.if_nametoindex(args.adapter))
elif args.discovery == "active":
address = ipaddress.IPv4Interface(args.local_address)
local_address = f"{address.ip}:0"
config = DiscoveryConfig(
bind_address=local_address,
destination=f"{address.network.broadcast_address}:13400",
)
else:
config = DiscoveryConfig()
async for vehicle in announcements(config, args.discovery):
doip_config = DoIPConfig(
source_address=args.source_address,
protocol_version=vehicle.protocol_version,
local_address=local_address,
)
async with await vehicle.connect(doip_config) as transport:
uds = UDSClient(transport, UDSConfig(p2_timeout=1.0))
vin = await uds.read_data_by_identifier(DataIdentifier.VIN)
print(vehicle.address, f"0x{vehicle.logical_address:04x}", "VIN:", vin.decode("ascii"), flush=True)
if __name__ == "__main__":
asyncio.run(main())
XCP on CAN and Ethernet¶
Both examples set MTA, read 4 KiB with an explicit loop of UPLOAD commands,
and print the data as hex and ASCII without writing files. CAN uses hardcoded
settings and CanAdapter() discovery, TX
0x6C3, RX 0x6C4, and sends ten wake-up frames with ID 0x541 and eight FF
bytes, 100 ms apart, before connecting. The examples use straight-line code
without context managers or explicit cleanup.
CAN reads from 0x8000_0000. Ethernet requires --host, --port, --bind,
--bind-port, and --address arguments, with no defaults. It reads 4 KiB over
UDP from the supplied address, using the negotiated maximum upload size and
a two-second timeout. Addresses accept hexadecimal or decimal values.
"""Read 4 KiB using SET_MTA and UPLOAD over XCP on CAN and CAN FD."""
import asyncio
from automotive.adapters import CanAdapter
from automotive.can import Frame
from automotive.protocols.xcp import XCPCanConfig, XCPClient, XCPOnCAN
from automotive.utils import hexdump
async def main() -> None:
adapter = CanAdapter()
# Wake ECU
wake = Frame(id=0x541, data=b"\xff" * 8)
for _ in range(10):
await adapter.send(wake)
await asyncio.sleep(0.1)
config = XCPCanConfig(tx_id=0x6C3, rx_id=0x6C4, fd=False)
client = XCPClient(XCPOnCAN(adapter, config))
info = await client.connect()
print(f"Connected: {info}")
chunk_size = info.max_upload_size
# Read using UPLOAD
await client.set_mta(0x8000_0000)
data = bytearray()
while len(data) < 4096:
data.extend(await client.upload(min(chunk_size, 4096 - len(data))))
# Print all data
print(hexdump(data, 0x8000_0000, address_granularity=info.address_granularity))
if __name__ == "__main__":
asyncio.run(main())
"""Read 4 KiB using SET_MTA and UPLOAD over XCP on Ethernet."""
import argparse
import asyncio
from automotive.protocols.xcp import XCPClient, XCPConfig, XCPOnUDP
from automotive.utils import hexdump
def parse_address(value: str) -> int:
address = int(value, 0)
if not 0 <= address <= 0xFFFF_FFFF:
raise argparse.ArgumentTypeError("address must fit in 32 bits")
return address
async def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", required=True, help="ECU host")
parser.add_argument("--port", required=True, type=int, help="ECU UDP port")
parser.add_argument("--bind", required=True, help="Local host to bind")
parser.add_argument("--bind-port", required=True, type=int, help="Local UDP port to bind")
parser.add_argument("--address", required=True, type=parse_address, help="Start address in hexadecimal or decimal")
args = parser.parse_args()
transport = await XCPOnUDP.connect(args.host, args.port, timeout=2.0, local_addr=(args.bind, args.bind_port))
client = XCPClient(transport, XCPConfig(timeout=2.0))
info = await client.connect()
print(f"Connected: {info}")
chunk_size = info.max_upload_size
print(f"Reading 4096 bytes at {args.address:#010x}, up to {chunk_size} bytes per request")
# Read using UPLOAD
await client.set_mta(args.address)
data = bytearray()
while len(data) < 4096:
data.extend(await client.upload(min(chunk_size, 4096 - len(data))))
# Print all data
print(hexdump(data, args.address, address_granularity=info.address_granularity))
if __name__ == "__main__":
asyncio.run(main())
Configure bitrate and sample points¶
Configure a PEAK PCAN-USB FD adapter with 500 kbit/s nominal and 2 Mbit/s data timing, both with an 80% sample point.
"""Configure a PEAK PCAN-USB FD adapter for 500 kbit/s CAN and 2 Mbit/s CAN FD."""
import asyncio
from automotive.adapters import PeakAdapter, PeakConfig
from automotive.can.bitrate import BitrateSettings
async def main() -> None:
"""Configure nominal and data-phase timing, then print received frames."""
config = PeakConfig(
bitrate=BitrateSettings(
bitrate=500_000,
sample_point=0.8,
data_bitrate=2_000_000,
data_sample_point=0.8,
),
)
print("Resolved timing:", config.resolved_bitrate)
adapter = PeakAdapter(config)
stream = adapter.recv()
async for frame in stream:
print(frame)
if __name__ == "__main__":
asyncio.run(main())
Query firmware versions concurrently¶
Use independent ECU transports for concurrent diagnostic requests.
"""Query named DIDs across standard and extended ECU addresses."""
import asyncio
from automotive.adapters import CanAdapter
from automotive.errors import AutomotiveError
from automotive.protocols.uds import DataIdentifier, UDSClient, UDSConfig
from automotive.transports.isotp import IsoTP, IsoTPConfig
async def get_version(adapter: CanAdapter, identifier: int) -> None:
"""Query each named DID for one ECU, retaining its configured transport."""
# Increased timeout for adapters not supporting real ACKs.
config = IsoTPConfig(tx_id=identifier, timeout=1.0)
isotp = IsoTP(adapter, config)
uds = UDSClient(isotp, UDSConfig(p2_timeout=1.0))
await uds.tester_present()
for did in DataIdentifier:
try:
resp = await uds.read_data_by_identifier(did)
except (AutomotiveError, OSError):
continue
print(f"{identifier:x} 0x{did.value:x} {did.name}: {resp!r}")
async def main() -> None:
"""Scan the Rust example's standard/extended address ranges concurrently."""
adapter = CanAdapter()
standard_ids = range(0x700, 0x7F8)
extended_ids = (0x18DA0000 + (i << 8) + 0xF1 for i in range(0x100))
ids = [*standard_ids, *extended_ids]
await asyncio.gather(*(get_version(adapter, identifier) for identifier in ids), return_exceptions=True)
if __name__ == "__main__":
asyncio.run(main())
Synchronous examples¶
These programs use the matching modules under automotive.sync, including
automotive.sync.adapters, automotive.sync.transports.isotp, and
automotive.sync.protocols.uds, with the same configuration and value types.
They use ordinary constructors, blocking calls, and receive iterators. Both the
async and sync examples let ownership release resources when they go out of scope.
Their setup, requests, output, and flow follow the corresponding Rust programs.
Send a CAN frame¶
"""Send one Classic CAN frame through the first available adapter."""
from automotive.sync.adapters import CanAdapter
from automotive.sync.can import Frame
def main() -> None:
"""Discover an adapter and send a frame."""
adapter = CanAdapter()
frame = Frame(id=0x123, data=b"\x01\x02\x03\x04")
adapter.send(frame)
print("Sent", frame)
if __name__ == "__main__":
main()
Print CAN frames¶
"""Print frames from the first available adapter. Requires CAN hardware or vcan0."""
from automotive.sync.adapters import CanAdapter
def main() -> None:
"""Discover an adapter and print frames until interrupted."""
adapter = CanAdapter()
stream = adapter.recv()
for frame in stream:
print(frame)
if __name__ == "__main__":
main()
Send ISO-TP messages¶
"""Exchange short and segmented PDUs with an ECU at 0x7A1/0x7A9."""
from automotive.sync.adapters import CanAdapter
from automotive.sync.transports.isotp import IsoTP, IsoTPConfig
def main() -> None:
"""Send short and segmented requests, printing each response as hex."""
adapter = CanAdapter()
config = IsoTPConfig(tx_id=0x7A1)
isotp = IsoTP(adapter, config)
stream = isotp.recv()
isotp.send(b"\x3e\x00")
response = next(stream)
print("RX:", response.hex())
isotp.send(b"\x22\xf1\x81")
response = next(stream)
print("RX:", response.hex())
long_request = b"\x10" + b"\x00" * 32
isotp.send(long_request)
response = next(stream)
print("RX:", response.hex())
long_response = b"\x22\xf1\x81"
isotp.send(long_response)
response = next(stream)
print("RX:", response.hex())
if __name__ == "__main__":
main()
Query an ECU with UDS¶
"""Read software identification from a diagnostic ECU at transmit ID 0x7A1."""
from automotive.sync.adapters import CanAdapter
from automotive.sync.protocols.uds import DataIdentifier, SessionType, UDSClient
from automotive.sync.transports.isotp import IsoTP
def main() -> None:
"""Use defaults, select a session, and read an ECU data identifier."""
adapter = CanAdapter()
isotp = IsoTP.from_id(adapter, 0x7A1)
uds = UDSClient(isotp)
uds.tester_present()
uds.diagnostic_session_control(SessionType.EXTENDED_DIAGNOSTIC)
did = DataIdentifier.APPLICATION_SOFTWARE_IDENTIFICATION
resp = uds.read_data_by_identifier(did)
print(f"{did.name}: {resp!r}")
if __name__ == "__main__":
main()
Discover vehicles and use UDS over DoIP¶
The blocking example accepts the same arguments and reads the same UDS VIN.
Replace examples/doip.py with examples/sync/doip.py in the commands above.
"""Read ECU VINs with blocking UDS using active or passive DoIP discovery over IPv4 or IPv6."""
import argparse
import ipaddress
import socket
from collections.abc import Iterator
from automotive.sync.protocols.uds import DataIdentifier, UDSClient, UDSConfig
from automotive.sync.transports.doip import Discovery, DiscoveryConfig, DoIPConfig, VehicleAnnouncement, discover
def parse_address(value: str) -> int:
return int(value, 0)
def announcements(config: DiscoveryConfig, mode: str) -> Iterator[VehicleAnnouncement]:
if mode == "active":
yield from discover(config)
else:
with Discovery.listen(config) as listener:
print("Listening for announcements; power up the ECU. Press Ctrl+C to stop.", flush=True)
while True:
yield listener.recv()
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--discovery", choices=("active", "passive"), default="active")
parser.add_argument("--adapter", help="IPv6 interface (required with --ipv6)")
parser.add_argument("--local-address", help="Local IPv4 address/prefix (required for active IPv4 discovery)")
family = parser.add_mutually_exclusive_group()
family.add_argument("--ipv4", action="store_true", help="Use IPv4 broadcast (default)")
family.add_argument("--ipv6", action="store_true", help="Use IPv6 multicast")
parser.add_argument("--source-address", type=parse_address, default=0x0E89)
args = parser.parse_args()
if args.ipv6 and not args.adapter:
parser.error("--ipv6 requires --adapter")
if not args.ipv6 and args.discovery == "active" and not args.local_address:
parser.error("active IPv4 discovery requires --local-address")
local_address = None
if args.ipv6:
config = DiscoveryConfig.ipv6(socket.if_nametoindex(args.adapter))
elif args.discovery == "active":
address = ipaddress.IPv4Interface(args.local_address)
local_address = f"{address.ip}:0"
config = DiscoveryConfig(
bind_address=local_address,
destination=f"{address.network.broadcast_address}:13400",
)
else:
config = DiscoveryConfig()
for vehicle in announcements(config, args.discovery):
doip_config = DoIPConfig(
source_address=args.source_address,
protocol_version=vehicle.protocol_version,
local_address=local_address,
)
with vehicle.connect(doip_config) as transport:
uds = UDSClient(transport, UDSConfig(p2_timeout=1.0))
vin = uds.read_data_by_identifier(DataIdentifier.VIN)
print(vehicle.address, f"0x{vehicle.logical_address:04x}", "VIN:", vin.decode("ascii"), flush=True)
if __name__ == "__main__":
main()
XCP on CAN and Ethernet¶
"""Read 4 KiB using SET_MTA and UPLOAD over XCP on CAN and CAN FD."""
import time
from automotive.sync.adapters import CanAdapter
from automotive.sync.can import Frame
from automotive.sync.protocols.xcp import XCPCanConfig, XCPClient, XCPOnCAN
from automotive.utils import hexdump
def main() -> None:
adapter = CanAdapter()
# Wake ECU
wake = Frame(id=0x541, data=b"\xff" * 8)
for _ in range(10):
adapter.send(wake)
time.sleep(0.1)
config = XCPCanConfig(tx_id=0x6C3, rx_id=0x6C4, fd=False)
client = XCPClient(XCPOnCAN(adapter, config))
info = client.connect()
print(f"Connected: {info}")
chunk_size = info.max_upload_size
# Read using UPLOAD
client.set_mta(0x8000_0000)
data = bytearray()
while len(data) < 4096:
data.extend(client.upload(min(chunk_size, 4096 - len(data))))
# Print all data
print(hexdump(data, 0x8000_0000, address_granularity=info.address_granularity))
if __name__ == "__main__":
main()
"""Read 4 KiB using SET_MTA and UPLOAD over XCP on Ethernet."""
import argparse
from automotive.sync.protocols.xcp import XCPClient, XCPConfig, XCPOnUDP
from automotive.utils import hexdump
def parse_address(value: str) -> int:
address = int(value, 0)
if not 0 <= address <= 0xFFFF_FFFF:
raise argparse.ArgumentTypeError("address must fit in 32 bits")
return address
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--host", required=True, help="ECU host")
parser.add_argument("--port", required=True, type=int, help="ECU UDP port")
parser.add_argument("--bind", required=True, help="Local host to bind")
parser.add_argument("--bind-port", required=True, type=int, help="Local UDP port to bind")
parser.add_argument("--address", required=True, type=parse_address, help="Start address in hexadecimal or decimal")
args = parser.parse_args()
transport = XCPOnUDP.connect(args.host, args.port, timeout=2.0, local_addr=(args.bind, args.bind_port))
client = XCPClient(transport, XCPConfig(timeout=2.0))
info = client.connect()
print(f"Connected: {info}")
chunk_size = info.max_upload_size
print(f"Reading 4096 bytes at {args.address:#010x}, up to {chunk_size} bytes per request")
# Read using UPLOAD
client.set_mta(args.address)
data = bytearray()
while len(data) < 4096:
data.extend(client.upload(min(chunk_size, 4096 - len(data))))
# Print all data
print(hexdump(data, args.address, address_granularity=info.address_granularity))
if __name__ == "__main__":
main()
Configure bitrate and sample points¶
Configure the same PEAK timing through the synchronous API.
"""Configure a PEAK PCAN-USB FD adapter for 500 kbit/s CAN and 2 Mbit/s CAN FD."""
from automotive.sync.adapters import PeakAdapter, PeakConfig
from automotive.sync.can.bitrate import BitrateSettings
def main() -> None:
"""Configure nominal and data-phase timing, then print received frames."""
config = PeakConfig(
bitrate=BitrateSettings(
bitrate=500_000,
sample_point=0.8,
data_bitrate=2_000_000,
data_sample_point=0.8,
),
)
print("Resolved timing:", config.resolved_bitrate)
adapter = PeakAdapter(config)
stream = adapter.recv()
for frame in stream:
print(frame)
if __name__ == "__main__":
main()
Query firmware versions¶
Query the same DIDs and ECU address ranges as the Rust and async Python examples. The synchronous version visits ECUs sequentially; the async version queries them concurrently.
"""Query named DIDs across standard and extended ECU addresses."""
from automotive.sync.adapters import CanAdapter
from automotive.sync.errors import AutomotiveError
from automotive.sync.protocols.uds import DataIdentifier, UDSClient, UDSConfig
from automotive.sync.transports.isotp import IsoTP, IsoTPConfig
def get_version(adapter: CanAdapter, identifier: int) -> None:
"""Query each named DID for one ECU, retaining its configured transport."""
# Lower timeout for the sync version since we scan each ECU individually and bus load is low
config = IsoTPConfig(tx_id=identifier, timeout=0.05)
isotp = IsoTP(adapter, config)
uds = UDSClient(isotp, UDSConfig(p2_timeout=0.05))
uds.tester_present()
for did in DataIdentifier:
try:
resp = uds.read_data_by_identifier(did)
except (AutomotiveError, OSError):
continue
print(f"{identifier:x} 0x{did.value:x} {did.name}: {resp!r}")
def main() -> None:
"""Scan the Rust example's standard/extended address ranges sequentially."""
adapter = CanAdapter()
standard_ids = range(0x700, 0x7F8)
extended_ids = (0x18DA0000 + (i << 8) + 0xF1 for i in range(0x100))
ids = [*standard_ids, *extended_ids]
for identifier in ids:
try:
get_version(adapter, identifier)
except (AutomotiveError, OSError):
continue
if __name__ == "__main__":
main()
CCP memory transfers¶
Connect directly to the ECU and dump the first 4 KiB of
flash. These examples configure little-endian memory addresses and print
addresses, hex bytes and ASCII using the automotive.utils.hexdump helper shared
with the XCP examples.
"""Dump 4 KiB of ECU flash using CCP SHORT_UP."""
import asyncio
from automotive.adapters import CanAdapter
from automotive.protocols.ccp import CCPClient, CCPConfig
from automotive.utils import hexdump
async def main() -> None:
config = CCPConfig(tx_id=0x6EC, rx_id=0x6ED, byte_order="little")
adapter = CanAdapter()
# Connect to CCP
client = CCPClient(adapter, config)
await client.connect(station_address=0)
# Read using SHORT_UP
start = 0x8000_0000
data = bytearray()
while len(data) < 0x1000:
data.extend(await client.short_upload(start + len(data), 4))
# Print all data
print(hexdump(data, start))
if __name__ == "__main__":
asyncio.run(main())
Synchronous CCP¶
"""Dump 4 KiB of ECU flash using CCP SHORT_UP."""
from automotive.sync.adapters import CanAdapter
from automotive.sync.protocols.ccp import CCPClient, CCPConfig
from automotive.utils import hexdump
def main() -> None:
config = CCPConfig(tx_id=0x6EC, rx_id=0x6ED, byte_order="little")
adapter = CanAdapter()
# Connect to CCP
client = CCPClient(adapter, config)
client.connect(station_address=0)
# Read using SHORT_UP
start = 0x8000_0000
data = bytearray()
while len(data) < 0x1000:
data.extend(client.short_upload(start + len(data), 4))
# Print all data
print(hexdump(data, start))
if __name__ == "__main__":
main()