Controller Area Network interface module for Python providing common abstractions for CAN hardware devices and message handling utilities
npx @tessl/cli install tessl/pypi-python-can@4.6.00
# Python-CAN
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: python-can
7
- **Language**: Python
8
- **Installation**: `pip install python-can`
9
10
## Core Imports
11
12
```python
13
import can
14
```
15
16
Common imports for specific functionality:
17
18
```python
19
from can import Bus, Message, Notifier, Listener
20
from can import BusState, CanProtocol, CanError
21
```
22
23
## Basic Usage
24
25
```python
26
import can
27
28
# Create a CAN bus connection
29
bus = can.Bus(channel='can0', interface='socketcan')
30
31
# Create and send a message
32
msg = can.Message(
33
arbitration_id=0x123,
34
data=[1, 2, 3, 4, 5, 6, 7, 8],
35
is_extended_id=False
36
)
37
bus.send(msg)
38
39
# Receive a message
40
received_msg = bus.recv(timeout=1.0)
41
if received_msg:
42
print(f"Received: {received_msg}")
43
44
# Clean up
45
bus.shutdown()
46
```
47
48
## Architecture
49
50
Python-CAN uses a modular architecture built around several key abstractions:
51
52
- **Bus**: The central abstraction for CAN communication, with hardware-specific implementations
53
- **Message**: Standardized representation of CAN messages with support for standard/extended IDs and CAN FD
54
- **Listeners**: Event-driven message handling with built-in and custom listener implementations
55
- **Notifier**: Routes messages from buses to multiple listeners simultaneously
56
- **IO System**: Comprehensive logging and replay capabilities supporting multiple file formats
57
- **Interface Abstraction**: Hardware-agnostic interface layer supporting 20+ different CAN hardware backends
58
59
This design enables maximum reusability across automotive applications, industrial control systems, embedded development, and any application requiring reliable real-time CAN network communication.
60
61
## Capabilities
62
63
### Core Bus Operations
64
65
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.
66
67
```python { .api }
68
class Bus:
69
def __init__(self, channel=None, interface=None, **kwargs): ...
70
def send(self, msg: Message, timeout=None) -> None: ...
71
def recv(self, timeout=None) -> Message | None: ...
72
def send_periodic(self, msgs, period: float, duration=None, **kwargs): ...
73
def shutdown(self) -> None: ...
74
```
75
76
[Core Bus Operations](./bus-operations.md)
77
78
### Message Handling
79
80
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.
81
82
```python { .api }
83
class Message:
84
def __init__(self, timestamp=0.0, arbitration_id=0, is_extended_id=True,
85
is_remote_frame=False, is_error_frame=False, channel=None,
86
dlc=None, data=None, is_fd=False, is_rx=True, **kwargs): ...
87
def equals(self, other: Message, timestamp_delta=1e-6, check_channel=True,
88
check_direction=True) -> bool: ...
89
```
90
91
[Message Handling](./message-handling.md)
92
93
### Hardware Interfaces
94
95
Support for 20+ different CAN hardware interfaces including SocketCAN, Vector, PCAN, Kvaser, IXXAT, and virtual interfaces. Automatic interface detection and configuration management.
96
97
```python { .api }
98
VALID_INTERFACES: frozenset[str]
99
def detect_available_configs() -> list[dict]: ...
100
```
101
102
[Hardware Interfaces](./hardware-interfaces.md)
103
104
### File I/O and Logging
105
106
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.
107
108
```python { .api }
109
class Logger:
110
def __init__(self, filename: str): ...
111
def __call__(self, msg: Message) -> None: ...
112
113
class LogReader:
114
def __init__(self, filename: str): ...
115
def __iter__(self): ...
116
```
117
118
[File I/O and Logging](./file-io.md)
119
120
### Event System
121
122
Event-driven message handling through listeners and notifiers, enabling asynchronous message processing, message filtering, buffering, and routing to multiple handlers.
123
124
```python { .api }
125
class Listener:
126
def on_message_received(self, msg: Message) -> None: ...
127
def stop(self) -> None: ...
128
129
class Notifier:
130
def __init__(self, bus: Bus, listeners: list[Listener], timeout=1.0): ...
131
def add_listener(self, listener: Listener) -> None: ...
132
def stop(self) -> None: ...
133
```
134
135
[Event System](./event-system.md)
136
137
### Periodic Message Transmission
138
139
Advanced cyclic message transmission capabilities with configurable periods, durations, message modification callbacks, and lifecycle management for automotive and industrial applications.
140
141
```python { .api }
142
class CyclicSendTaskABC:
143
def stop(self) -> None: ...
144
def modify_data(self, msg: Message) -> None: ...
145
```
146
147
[Periodic Transmission](./periodic-transmission.md)
148
149
### Bit Timing Configuration
150
151
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.
152
153
```python { .api }
154
class BitTiming:
155
def __init__(self, f_clock: int, brp: int, tseg1: int, tseg2: int, sjw: int): ...
156
@classmethod
157
def from_sample_point(cls, f_clock: int, bitrate: int, sample_point: float): ...
158
159
class BitTimingFd:
160
def __init__(self, f_clock: int, nom_brp: int, nom_tseg1: int, nom_tseg2: int,
161
nom_sjw: int, data_brp: int, data_tseg1: int, data_tseg2: int,
162
data_sjw: int): ...
163
```
164
165
[Bit Timing Configuration](./bit-timing.md)
166
167
### Command Line Tools
168
169
Complete suite of command-line utilities for CAN bus interaction, including message logging, log file conversion, message replay, bus monitoring, and bus bridging operations.
170
171
```bash
172
can_logger --interface socketcan --channel can0 output.log
173
can_player --interface socketcan --channel can0 input.log
174
can_viewer --interface socketcan --channel can0
175
can_logconvert input.blf output.asc
176
can_bridge --input-interface socketcan --input-channel can0 --output-interface virtual --output-channel test
177
```
178
179
[Command Line Tools](./cli-tools.md)
180
181
## Types
182
183
```python { .api }
184
from typing import Union, Optional, Any, Dict, List
185
from enum import Enum
186
187
# Core types
188
Channel = Union[str, int, Any]
189
CanData = Union[bytes, bytearray, List[int]]
190
CanFilter = Dict[str, Union[int, bool]]
191
CanFilters = List[CanFilter]
192
193
class BusState(Enum):
194
ACTIVE = "active"
195
PASSIVE = "passive"
196
ERROR = "error"
197
198
class CanProtocol(Enum):
199
CAN_20 = "can_20"
200
CAN_FD = "can_fd"
201
CAN_FD_NON_ISO = "can_fd_non_iso"
202
CAN_XL = "can_xl"
203
204
class ThreadSafeBus:
205
"""Thread-safe wrapper around any bus implementation."""
206
207
def __init__(self, channel=None, interface=None, **kwargs): ...
208
# Provides same interface as Bus but with thread safety
209
```