or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

bit-timing.mdbus-operations.mdcli-tools.mdevent-system.mdfile-io.mdhardware-interfaces.mdindex.mdmessage-handling.mdperiodic-transmission.md
tile.json

tessl/pypi-python-can

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-can@4.6.x

To install, run

npx @tessl/cli install tessl/pypi-python-can@4.6.0

index.mddocs/

Python-CAN

A comprehensive Controller Area Network (CAN) interface module for Python that provides common abstractions for interacting with different CAN hardware devices and a suite of utilities for sending, receiving, and logging CAN messages. Python-CAN supports multiple backends and interfaces including SocketCAN, Vector, PCAN, Kvaser, and many others, enabling cross-platform CAN communication on Linux, Windows, and macOS.

Package Information

  • Package Name: python-can
  • Language: Python
  • Installation: pip install python-can

Core Imports

import can

Common imports for specific functionality:

from can import Bus, Message, Notifier, Listener
from can import BusState, CanProtocol, CanError

Basic Usage

import can

# Create a CAN bus connection
bus = can.Bus(channel='can0', interface='socketcan')

# Create and send a message
msg = can.Message(
    arbitration_id=0x123,
    data=[1, 2, 3, 4, 5, 6, 7, 8],
    is_extended_id=False
)
bus.send(msg)

# Receive a message
received_msg = bus.recv(timeout=1.0)
if received_msg:
    print(f"Received: {received_msg}")

# Clean up
bus.shutdown()

Architecture

Python-CAN uses a modular architecture built around several key abstractions:

  • Bus: The central abstraction for CAN communication, with hardware-specific implementations
  • Message: Standardized representation of CAN messages with support for standard/extended IDs and CAN FD
  • Listeners: Event-driven message handling with built-in and custom listener implementations
  • Notifier: Routes messages from buses to multiple listeners simultaneously
  • IO System: Comprehensive logging and replay capabilities supporting multiple file formats
  • Interface Abstraction: Hardware-agnostic interface layer supporting 20+ different CAN hardware backends

This design enables maximum reusability across automotive applications, industrial control systems, embedded development, and any application requiring reliable real-time CAN network communication.

Capabilities

Core Bus Operations

Fundamental CAN bus operations including connection management, message transmission and reception, periodic message sending, and bus configuration. These operations form the foundation of all CAN communication.

class Bus:
    def __init__(self, channel=None, interface=None, **kwargs): ...
    def send(self, msg: Message, timeout=None) -> None: ...
    def recv(self, timeout=None) -> Message | None: ...
    def send_periodic(self, msgs, period: float, duration=None, **kwargs): ...
    def shutdown(self) -> None: ...

Core Bus Operations

Message Handling

CAN message creation, manipulation, and validation with support for standard and extended arbitration IDs, remote frames, error frames, and CAN FD messages. Includes comprehensive message comparison and copying utilities.

class Message:
    def __init__(self, timestamp=0.0, arbitration_id=0, is_extended_id=True, 
                 is_remote_frame=False, is_error_frame=False, channel=None,
                 dlc=None, data=None, is_fd=False, is_rx=True, **kwargs): ...
    def equals(self, other: Message, timestamp_delta=1e-6, check_channel=True, 
              check_direction=True) -> bool: ...

Message Handling

Hardware Interfaces

Support for 20+ different CAN hardware interfaces including SocketCAN, Vector, PCAN, Kvaser, IXXAT, and virtual interfaces. Automatic interface detection and configuration management.

VALID_INTERFACES: frozenset[str]
def detect_available_configs() -> list[dict]: ...

Hardware Interfaces

File I/O and Logging

Comprehensive logging and replay system supporting multiple file formats (ASC, BLF, CSV, MF4, TRC, SQLite) with both reader and writer implementations. Includes rotating loggers and message synchronization.

class Logger:
    def __init__(self, filename: str): ...
    def __call__(self, msg: Message) -> None: ...

class LogReader:
    def __init__(self, filename: str): ...
    def __iter__(self): ...

File I/O and Logging

Event System

Event-driven message handling through listeners and notifiers, enabling asynchronous message processing, message filtering, buffering, and routing to multiple handlers.

class Listener:
    def on_message_received(self, msg: Message) -> None: ...
    def stop(self) -> None: ...

class Notifier:
    def __init__(self, bus: Bus, listeners: list[Listener], timeout=1.0): ...
    def add_listener(self, listener: Listener) -> None: ...
    def stop(self) -> None: ...

Event System

Periodic Message Transmission

Advanced cyclic message transmission capabilities with configurable periods, durations, message modification callbacks, and lifecycle management for automotive and industrial applications.

class CyclicSendTaskABC:
    def stop(self) -> None: ...
    def modify_data(self, msg: Message) -> None: ...

Periodic Transmission

Bit Timing Configuration

CAN bit timing calculation and configuration utilities for both CAN 2.0 and CAN FD, supporting various calculation methods including sample point-based timing and register-based configuration.

class BitTiming:
    def __init__(self, f_clock: int, brp: int, tseg1: int, tseg2: int, sjw: int): ...
    @classmethod
    def from_sample_point(cls, f_clock: int, bitrate: int, sample_point: float): ...

class BitTimingFd:
    def __init__(self, f_clock: int, nom_brp: int, nom_tseg1: int, nom_tseg2: int, 
                 nom_sjw: int, data_brp: int, data_tseg1: int, data_tseg2: int, 
                 data_sjw: int): ...

Bit Timing Configuration

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.

can_logger --interface socketcan --channel can0 output.log
can_player --interface socketcan --channel can0 input.log
can_viewer --interface socketcan --channel can0
can_logconvert input.blf output.asc
can_bridge --input-interface socketcan --input-channel can0 --output-interface virtual --output-channel test

Command Line Tools

Types

from typing import Union, Optional, Any, Dict, List
from enum import Enum

# Core types
Channel = Union[str, int, Any]
CanData = Union[bytes, bytearray, List[int]]
CanFilter = Dict[str, Union[int, bool]]
CanFilters = List[CanFilter]

class BusState(Enum):
    ACTIVE = "active"
    PASSIVE = "passive" 
    ERROR = "error"

class CanProtocol(Enum):
    CAN_20 = "can_20"
    CAN_FD = "can_fd"
    CAN_FD_NON_ISO = "can_fd_non_iso"
    CAN_XL = "can_xl"

class ThreadSafeBus:
    """Thread-safe wrapper around any bus implementation."""
    
    def __init__(self, channel=None, interface=None, **kwargs): ...
    # Provides same interface as Bus but with thread safety