CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-can

Controller Area Network interface module for Python providing common abstractions for CAN hardware devices and message handling utilities

Pending
Overview
Eval results
Files

cli-tools.mddocs/

Command Line Tools

Complete suite of command-line utilities for CAN bus interaction, including message logging, log file conversion, message replay, bus monitoring, and bus bridging operations.

Capabilities

Message Logging (can_logger)

Log CAN messages to various file formats with filtering and configuration options.

can_logger [options] output_file

Options:
  -c, --channel CHANNEL     CAN channel (e.g., can0, vcan0)
  -i, --interface INTERFACE CAN interface (socketcan, vector, etc.)
  -f, --filter FILTER       Message filter (can_id:can_mask:extended)
  -v, --verbose             Verbose output
  --bitrate BITRATE         CAN bitrate
  --fd                      Enable CAN FD mode

Message Playback (can_player)

Replay CAN messages from log files with timing control and loop options.

can_player [options] input_file

Options:
  -c, --channel CHANNEL     Output CAN channel
  -i, --interface INTERFACE Output CAN interface  
  -g, --gap SECONDS         Minimum gap between messages
  -s, --skip SECONDS        Skip initial seconds of playback
  -l, --loop                Loop playback continuously
  --ignore-timestamps       Send messages as fast as possible

Message Monitoring (can_viewer)

Real-time terminal-based CAN message viewer with filtering and statistics.

can_viewer [options]

Options:  
  -c, --channel CHANNEL     CAN channel to monitor
  -i, --interface INTERFACE CAN interface
  -f, --filter FILTER       Message filter
  --decode DBC_FILE         DBC file for message decoding
  --sort-by ID|TIME|COUNT   Sort messages by criteria

Log Format Conversion (can_logconvert)

Convert between different CAN log file formats with filtering options.

can_logconvert [options] input_file output_file

Options:
  -f, --filter FILTER       Apply message filter during conversion
  -s, --start TIME          Start time for conversion
  -e, --end TIME            End time for conversion
  --input-format FORMAT     Force input format (auto-detected by default)
  --output-format FORMAT    Force output format (auto-detected by default)

Bus Bridging (can_bridge)

Bridge messages between different CAN interfaces or channels.

can_bridge [options]

Options:
  --input-channel CHANNEL    Input CAN channel
  --input-interface INTERFACE Input CAN interface
  --output-channel CHANNEL   Output CAN channel  
  --output-interface INTERFACE Output CAN interface
  -f, --filter FILTER        Filter messages to bridge
  --bidirectional           Enable bidirectional bridging

Usage Examples

Basic Message Logging

# Log SocketCAN traffic to BLF file
can_logger -i socketcan -c can0 traffic.blf

# Log with message filtering (only ID 0x123)
can_logger -i socketcan -c can0 -f 0x123:0x7FF:false filtered.asc

# Log CAN FD messages
can_logger -i socketcan -c can0 --fd canfd_traffic.blf

# Log with verbose output
can_logger -i socketcan -c can0 -v debug.log

Message Playback

# Replay messages with original timing
can_player -i socketcan -c can1 recorded_traffic.blf

# Replay as fast as possible
can_player -i socketcan -c can1 --ignore-timestamps fast_replay.asc

# Replay with minimum 1ms gap between messages
can_player -i socketcan -c can1 -g 0.001 spaced_replay.log

# Loop playback continuously
can_player -i socketcan -c can1 -l continuous_test.blf

# Skip first 30 seconds of recording
can_player -i socketcan -c can1 -s 30 partial_replay.asc

Real-time Monitoring

# Basic message monitoring
can_viewer -i socketcan -c can0

# Monitor with message filtering
can_viewer -i socketcan -c can0 -f 0x100:0x700:false

# Monitor with DBC decoding
can_viewer -i socketcan -c can0 --decode vehicle.dbc

# Monitor and sort by message count
can_viewer -i socketcan -c can0 --sort-by COUNT

Log File Conversion

# Convert BLF to ASC format
can_logconvert input.blf output.asc

# Convert with time range filtering
can_logconvert --start 10.5 --end 60.0 long_log.blf excerpt.csv

# Convert specific message IDs only
can_logconvert -f 0x123:0x7FF:false full_log.asc filtered.blf

# Force format specification (if auto-detection fails)
can_logconvert --input-format blf --output-format csv data.bin data.csv

Bus Bridging

# Bridge between SocketCAN and virtual interface
can_bridge --input-interface socketcan --input-channel can0 \
           --output-interface virtual --output-channel test

# Bidirectional bridge
can_bridge --input-interface socketcan --input-channel can0 \
           --output-interface vector --output-channel 0 \
           --bidirectional

# Bridge with message filtering
can_bridge --input-interface socketcan --input-channel can0 \
           --output-interface virtual --output-channel filtered \
           -f 0x100:0x7F0:false

Advanced Usage Patterns

# Log while monitoring (using named pipes on Linux)
mkfifo can_pipe
can_logger -i socketcan -c can0 can_pipe.blf &
can_viewer -i socketcan -c can0 &
# Both tools will see the same messages

# Chain operations: record, convert, and replay
can_logger -i socketcan -c can0 recording.blf &
# ... record for some time, then Ctrl+C
can_logconvert recording.blf recording.asc
can_player -i virtual -c test recording.asc

# Compare two CAN buses
can_logger -i socketcan -c can0 bus0.log &
can_logger -i socketcan -c can1 bus1.log &
# ... record, then analyze differences

# Automated testing workflow
#!/bin/bash
echo "Starting CAN test sequence..."

# Start logging
can_logger -i virtual -c test test_results.blf &
LOGGER_PID=$!

# Run test sequence
can_player -i virtual -c test test_inputs.asc

# Stop logging
kill $LOGGER_PID

# Convert and analyze
can_logconvert test_results.blf test_results.csv
echo "Test complete, results in test_results.csv"

Integration with Scripts

import subprocess
import time
import can

def automated_can_test():
    """Example of integrating CLI tools with Python scripts."""
    
    # Start logging in background
    logger_proc = subprocess.Popen([
        'can_logger', '-i', 'virtual', '-c', 'test', 'test_log.blf'
    ])
    
    try:
        # Generate test traffic with Python
        bus = can.Bus(channel='test', interface='virtual')
        
        for i in range(100):
            msg = can.Message(
                arbitration_id=0x123,
                data=[i & 0xFF, (i >> 8) & 0xFF]
            )
            bus.send(msg)
            time.sleep(0.01)
        
        bus.shutdown()
        
    finally:
        # Stop logging
        logger_proc.terminate()
        logger_proc.wait()
    
    # Convert log to CSV for analysis
    subprocess.run([
        'can_logconvert', 'test_log.blf', 'test_log.csv'
    ])
    
    print("Test complete, log converted to CSV")

# Run the test
automated_can_test()

Configuration Files

# Most tools support configuration files
# ~/.canrc or /etc/can.conf

[default]
interface = socketcan
channel = can0
bitrate = 500000

[logging]
format = blf
rotation_max_bytes = 100MB

[viewer]
sort_by = count
show_timestamp = true
decode_dbc = /path/to/standard.dbc

Error Handling and Troubleshooting

# Check available interfaces
python -c "import can; print(can.VALID_INTERFACES)"

# Test interface availability
can_logger -i socketcan -c can0 /dev/null &
TEST_PID=$!
sleep 1
if kill -0 $TEST_PID 2>/dev/null; then
    echo "SocketCAN interface working"
    kill $TEST_PID
else
    echo "SocketCAN interface not available"
fi

# Verbose output for debugging
can_logger -v -i socketcan -c can0 debug.log

# List available channels (interface-specific)
ip link show type can  # For SocketCAN on Linux

Common Options

All CLI tools support these common options:

-h, --help              Show help message
-v, --verbose           Enable verbose output
-c, --channel CHANNEL   CAN channel identifier
-i, --interface INTERFACE CAN interface name
--version              Show version information

Filter Format

Message filters use the format: can_id:can_mask:extended

# Examples:
0x123:0x7FF:false    # Exact match for standard ID 0x123
0x100:0x700:false    # Match IDs 0x100-0x1FF (mask 0x700)
0x18000000:0xFF000000:true  # Match extended IDs with specific prefix

Exit Codes

  • 0: Success
  • 1: General error
  • 2: Invalid arguments
  • 3: Interface not available
  • 4: File I/O error
  • 5: Hardware error

Types

from typing import List, Dict, Any, Optional
import argparse

def add_bus_arguments(parser: argparse.ArgumentParser, 
                     filter_arg: bool = False,
                     prefix: Optional[str] = None,
                     group_title: Optional[str] = None) -> None:
    """
    Add common CAN bus arguments to argument parser.
    
    Parameters:
    - parser: ArgumentParser to add arguments to
    - filter_arg: Whether to include filter argument
    - prefix: Prefix for argument names (for multiple buses)
    - group_title: Title for argument group
    """

# CLI utility functions
def cast_from_string(value: str, dtype: type) -> Any:
    """Cast string value to specified type."""

def _dict2timing(timing_dict: Dict[str, Any]) -> str:
    """Convert timing dictionary to string representation."""

Install with Tessl CLI

npx tessl i tessl/pypi-python-can

docs

bit-timing.md

bus-operations.md

cli-tools.md

event-system.md

file-io.md

hardware-interfaces.md

index.md

message-handling.md

periodic-transmission.md

tile.json