1. Introduction to the tool library
1.1 python-can
Positioning: A common CAN bus communication library that supports multiple hardware interfaces (SocketCAN, PCAN, Kvaser, etc.).
Core functions:
Connect to a physical CAN device or a virtual interface.
Send/receive CAN messages (standard frame, extended frame).
Supports CAN FD (flexible data rate).
Applicable scenarios: Quickly build a CAN communication prototype, strong compatibility.
1.2 canard (CAN protocol stack)
Positioning: A library focusing on parsing high-level protocols such as UDS (ISO 14229) and J1939.
Core functions:
Parses DBC files and automatically generates signal values.
Supports UDS diagnostic services (such as 0x22 reading data and 0x2E writing data).
Handles multi-frame transmissions (such as the ISO-TP protocol).
Applicable scenarios: Automated testing of diagnostic interaction with the ECU is required.
2. Environmental preparation
2.1 Installation library
# Install the universal CAN librarypip install python-can # Install canard (UDS protocol support)pip install canard
2.2 Hardware preparation
Physical equipment: PCAN-USB, Kvaser, Vector equipment (relevant driver needs to be installed).
Virtual Testing: Use socketcan (Linux Virtual CAN interface) or CANoe to simulate the bus.
3. Core function implementation examples
3.1 Send and receive CAN messages using python-can
import can # Connect to the CAN interface (taking socketcan as an example)bus = (channel='vcan0', bustype='socketcan') # Send single frame datamsg = ( arbitration_id=0x123, # CAN ID data=[0x01, 0x02, 0x03, 0x04], is_extended_id=False # Standard frame) (msg) # Receive datafor msg in bus: print(f"Received: ID={hex(msg.arbitration_id)}, Data={}") # Close the connection()
3.2 Use canard to parse DBC files
from canard import Canard from import socketcan # Load DBC filedbc = Canard() dbc.load_dbc('') # Create a virtual CAN interfacedev = ('vcan0') () # parse received messagesdef on_message(msg): decoded = dbc.decode_message(msg.arbitration_id, ) print(f"Signal value: {decoded}") dev.add_listener(on_message)
3.3 Implementing UDS diagnostic service (based on canard)
from import UdsClient # Create a UDS clientuds = UdsClient(transport=(bustype='socketcan', channel='vcan0')) # Send diagnostic request: read the ECU serial number (service 0x22, parameter 0xF189)response = ([0x22, 0xF1, 0x89]) if response: print(f"ECU Serial number: {bytes([2:]).decode()}") else: print("Request timeout")
4. Automated test script design
4.1 Test scenario example: Door status verification
def test_door_status(): bus = (channel='vcan0', bustype='socketcan') # Send door control command (ID=0x200, data=[0x01] indicates door opening) ((arbitration_id=0x200, data=[0x01])) # Wait and verify door status feedback (expected ID=0x201, data[0]=0x01) for msg in bus: if msg.arbitration_id == 0x201: assert [0] == 0x01, "The door is not opened correctly" break ()
4.2 Integrated testing framework (such as pytest)
import pytest @ def can_bus(): bus = (channel='vcan0', bustype='socketcan') yield bus () def test_engine_rpm(can_bus): # Send speed request command can_bus.send((arbitration_id=0x700, data=[0x03])) # Verify that the response is within a reasonable range (such as 800-5000 RPM) for msg in can_bus: if msg.arbitration_id == 0x701: rpm = int.from_bytes([2:4], byteorder='big') assert 800 <= rpm <= 5000, "Abnormal speed" break
5. Advanced application skills
5.1 CAN FD Support
# Use python-can to send CAN FD messagesmsg = ( arbitration_id=0x123, data=[i % 256 for i in range(64)], # 64 bytes of data is_fd=True, bitrate_switch=True # Enable bit rate switching) (msg)
5.2 Integration with HIL system
# Connect Vector hardware (with XL Driver required)bus = ( bustype='vector', channel=1, app_name='Python_HIL_Test' ) # Send synchronous periodic messagestask = bus.send_periodic(msgs=[msg1, msg2], period=0.1) () # Stop sending
5.3 Automated test report generation
# Use pytest-html to generate a test report(["--html="])
6. FAQs and debugging
6.1 Hardware connection failed
Phenomenon: CanError: Error sending message
solve:
Check whether the device driver is installed (such as PCAN-Basic API required).
Confirm channel permissions (Linux requires sudo ip link set vcan0 up).
6.2 DBC parsing error
Phenomenon: KeyError: 'Unknown frame ID'
Solution: Make sure the DBC file contains the definition of the target CAN ID.
6.3 Multi-frame transmission processing
# Use canard to handle ISO-TP multi-frame transmissionfrom .iso_tp import IsoTpTransport tp = IsoTpTransport(can_bus, tx_id=0x7E0, rx_id=0x7E8) data = () # Receive long data(Automatic reorganization)
The above is the detailed content of how to write test scripts in Python. For more information about Python test scripts, please follow my other related articles!