0
# Hardware Interfaces
1
2
Support for 20+ different CAN hardware interfaces enabling cross-platform CAN communication on Linux, Windows, and macOS. Python-CAN provides a unified API that abstracts hardware differences while allowing access to interface-specific features.
3
4
## Capabilities
5
6
### Interface Discovery
7
8
Discover available CAN interfaces and their configurations automatically.
9
10
```python { .api }
11
VALID_INTERFACES: frozenset[str]
12
"""Set of all supported interface names."""
13
14
def detect_available_configs() -> list[dict]:
15
"""
16
Detect all available CAN configurations across all interfaces.
17
18
Returns:
19
List of configuration dictionaries suitable for Bus() constructor
20
Each dict contains interface-specific connection parameters
21
22
Note: May be time-consuming as it probes all interfaces
23
"""
24
```
25
26
### Linux SocketCAN
27
28
Native Linux CAN interface with kernel-level filtering and high performance.
29
30
```python { .api }
31
# Interface name: 'socketcan'
32
# Channels: 'can0', 'can1', 'vcan0', etc.
33
# Features: Hardware filtering, high throughput, native Linux support
34
35
bus = can.Bus(channel='can0', interface='socketcan')
36
```
37
38
### Vector Informatik Interfaces
39
40
Professional CAN interfaces from Vector Informatik for automotive development.
41
42
```python { .api }
43
# Interface name: 'vector'
44
# Channels: Hardware-dependent (e.g., 0, 1 for CANoe/CANalyzer)
45
# Features: High-precision timestamps, advanced filtering, automotive protocols
46
47
bus = can.Bus(channel=0, interface='vector', app_name='MyApp')
48
```
49
50
### PEAK-System PCAN
51
52
PCAN interfaces for automotive and industrial applications.
53
54
```python { .api }
55
# Interface name: 'pcan'
56
# Channels: 'PCAN_USBBUS1', 'PCAN_USBBUS2', etc.
57
# Features: Wide hardware range, Windows/Linux support
58
59
bus = can.Bus(channel='PCAN_USBBUS1', interface='pcan', bitrate=500000)
60
```
61
62
### Kvaser Interfaces
63
64
Professional CAN interfaces with advanced features and analysis tools.
65
66
```python { .api }
67
# Interface name: 'kvaser'
68
# Channels: Hardware channel numbers (0, 1, 2, etc.)
69
# Features: Advanced timestamps, scripting support, extensive hardware range
70
71
bus = can.Bus(channel=0, interface='kvaser')
72
```
73
74
### Virtual CAN Interface
75
76
Software-only CAN interface for testing and simulation without hardware.
77
78
```python { .api }
79
# Interface name: 'virtual'
80
# Channels: Any string identifier
81
# Features: No hardware required, multiple virtual buses, message routing
82
83
bus = can.Bus(channel='test', interface='virtual')
84
```
85
86
### Serial/UART CAN Adapters
87
88
CAN communication over serial connections using various protocols.
89
90
```python { .api }
91
# Interface name: 'serial'
92
# Channels: Serial port names ('/dev/ttyUSB0', 'COM1', etc.)
93
# Features: Low-cost hardware, works with many adapters
94
95
bus = can.Bus(channel='/dev/ttyUSB0', interface='serial',
96
baudrate=115200, timeout=0.1)
97
```
98
99
### USB-to-CAN Adapters
100
101
Various USB-to-CAN adapter support including common low-cost interfaces.
102
103
```python { .api }
104
# Interface name: 'usb2can'
105
# Channels: Device-dependent
106
# Features: Plug-and-play USB, multiple vendor support
107
108
bus = can.Bus(channel=0, interface='usb2can')
109
```
110
111
### IXXAT CAN Interfaces
112
113
HMS Industrial Networks (IXXAT) CAN interfaces for industrial applications.
114
115
```python { .api }
116
# Interface name: 'ixxat'
117
# Channels: Hardware channel numbers
118
# Features: Industrial-grade hardware, Windows support
119
120
bus = can.Bus(channel=0, interface='ixxat', bitrate=250000)
121
```
122
123
### Additional Interfaces
124
125
Support for many other CAN hardware vendors and protocols.
126
127
```python { .api }
128
# National Instruments
129
'nican' # NI-CAN interfaces
130
'nixnet' # NI-XNET interfaces
131
132
# Specialized hardware
133
'gs_usb' # Candlelight/GS_USB compatible devices
134
'cantact' # CANtact devices
135
'slcan' # Serial Line CAN protocol
136
'robotell' # Robotell CAN interfaces
137
'canalystii' # CANalyst-II devices
138
'systec' # SYS TEC electronic devices
139
'seeedstudio' # Seeed Studio CAN devices
140
'neousys' # Neousys CAN devices
141
'etas' # ETAS CAN interfaces
142
143
# Network protocols
144
'udp_multicast' # UDP multicast CAN
145
'socketcand' # SocketCAN daemon
146
```
147
148
### Interface Configuration
149
150
Access to interface-specific configuration options and capabilities.
151
152
```python { .api }
153
def _get_class_for_interface(interface: str) -> type[BusABC]:
154
"""
155
Get the bus class for a specific interface.
156
157
Parameters:
158
- interface: Interface name from VALID_INTERFACES
159
160
Returns:
161
Bus class for the interface
162
163
Raises:
164
- NotImplementedError: Unknown interface
165
- CanInterfaceNotImplementedError: Interface not available
166
"""
167
```
168
169
## Usage Examples
170
171
### Automatic Interface Detection
172
173
```python
174
import can
175
176
# Find all available CAN configurations
177
configs = can.detect_available_configs()
178
179
for config in configs:
180
print(f"Interface: {config['interface']}")
181
print(f"Channel: {config['channel']}")
182
print(f"Additional options: {config}")
183
print("---")
184
185
# Use first available configuration
186
if configs:
187
bus = can.Bus(**configs[0])
188
print(f"Connected to: {bus.channel_info}")
189
bus.shutdown()
190
```
191
192
### Platform-Specific Interface Selection
193
194
```python
195
import can
196
import platform
197
198
# Choose interface based on platform
199
system = platform.system()
200
201
if system == "Linux":
202
# Use SocketCAN on Linux
203
interface = 'socketcan'
204
channel = 'can0'
205
elif system == "Windows":
206
# Use Vector or PCAN on Windows
207
interface = 'vector' # or 'pcan'
208
channel = 0 # or 'PCAN_USBBUS1'
209
else:
210
# Use virtual interface as fallback
211
interface = 'virtual'
212
channel = 'test'
213
214
bus = can.Bus(channel=channel, interface=interface)
215
print(f"Using {interface} interface on {system}")
216
```
217
218
### Interface-Specific Configuration
219
220
```python
221
import can
222
223
# SocketCAN with kernel filtering
224
socketcan_bus = can.Bus(
225
channel='can0',
226
interface='socketcan',
227
can_filters=[
228
{"can_id": 0x123, "can_mask": 0x7FF, "extended": False}
229
]
230
)
231
232
# Vector with application name and specific timing
233
vector_bus = can.Bus(
234
channel=0,
235
interface='vector',
236
app_name='MyCANApp',
237
bitrate=500000,
238
data_bitrate=2000000 # CAN FD data phase
239
)
240
241
# PCAN with specific bitrate
242
pcan_bus = can.Bus(
243
channel='PCAN_USBBUS1',
244
interface='pcan',
245
bitrate=250000
246
)
247
248
# Serial interface with custom parameters
249
serial_bus = can.Bus(
250
channel='/dev/ttyUSB0',
251
interface='serial',
252
baudrate=115200,
253
timeout=0.1
254
)
255
```
256
257
### Error Handling for Missing Interfaces
258
259
```python
260
import can
261
262
try:
263
bus = can.Bus(channel='can0', interface='socketcan')
264
print("SocketCAN interface available")
265
except can.CanInterfaceNotImplementedError:
266
print("SocketCAN not available, trying virtual interface")
267
try:
268
bus = can.Bus(channel='test', interface='virtual')
269
print("Using virtual interface")
270
except can.CanInterfaceNotImplementedError:
271
print("No interfaces available")
272
bus = None
273
274
if bus:
275
# Use the bus
276
bus.shutdown()
277
```
278
279
### Multi-Interface Bridge
280
281
```python
282
import can
283
import threading
284
import time
285
286
def bridge_messages(source_bus, dest_bus, stop_event):
287
"""Bridge messages between two CAN buses."""
288
while not stop_event.is_set():
289
msg = source_bus.recv(timeout=0.1)
290
if msg:
291
try:
292
dest_bus.send(msg)
293
print(f"Bridged: {msg}")
294
except Exception as e:
295
print(f"Bridge error: {e}")
296
297
# Create buses on different interfaces
298
bus1 = can.Bus(channel='can0', interface='socketcan')
299
bus2 = can.Bus(channel='test', interface='virtual')
300
301
# Start bidirectional bridging
302
stop_event = threading.Event()
303
304
thread1 = threading.Thread(target=bridge_messages, args=(bus1, bus2, stop_event))
305
thread2 = threading.Thread(target=bridge_messages, args=(bus2, bus1, stop_event))
306
307
thread1.start()
308
thread2.start()
309
310
# Run for 10 seconds
311
time.sleep(10)
312
stop_event.set()
313
314
thread1.join()
315
thread2.join()
316
317
bus1.shutdown()
318
bus2.shutdown()
319
```
320
321
## Types
322
323
```python { .api }
324
from typing import Dict, List, Any, Tuple
325
from abc import ABC
326
327
# Backend configuration
328
BACKENDS: Dict[str, Tuple[str, str]]
329
"""Maps interface names to (module_name, class_name) tuples."""
330
331
# Auto-detected configuration
332
AutoDetectedConfig = Dict[str, Any]
333
"""Configuration dictionary suitable for Bus() constructor."""
334
335
# Interface capabilities
336
class BusABC(ABC):
337
"""Abstract base class defining interface requirements."""
338
339
@staticmethod
340
def _detect_available_configs() -> List[AutoDetectedConfig]:
341
"""Detect configurations for this specific interface."""
342
```