or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

bus-operations.mddocs/

0

# Core Bus Operations

1

2

Fundamental CAN bus operations that provide the foundation for all CAN communication. The Bus class serves as the central abstraction for connecting to CAN hardware, sending and receiving messages, and managing bus lifecycle.

3

4

## Capabilities

5

6

### Bus Creation and Connection

7

8

Create and configure CAN bus connections with automatic interface detection and configuration loading from default locations.

9

10

```python { .api }

11

def Bus(channel=None, interface=None, config_context=None, ignore_config=False, **kwargs):

12

"""

13

Create a new bus instance with configuration loading.

14

15

Parameters:

16

- channel: Channel identification (backend dependent)

17

- interface: Interface name (see VALID_INTERFACES)

18

- config_context: Extra context for config sources

19

- ignore_config: If True, only use provided arguments

20

- **kwargs: Backend-specific configuration parameters

21

22

Returns:

23

BusABC: Configured bus instance

24

25

Raises:

26

- CanInterfaceNotImplementedError: Interface not available

27

- CanInitializationError: Bus initialization failed

28

- ValueError: Invalid parameters

29

"""

30

```

31

32

### Message Transmission

33

34

Send CAN messages to the bus with optional timeout and error handling.

35

36

```python { .api }

37

def send(self, msg: Message, timeout=None) -> None:

38

"""

39

Transmit a message to the CAN bus.

40

41

Parameters:

42

- msg: Message object to transmit

43

- timeout: Maximum time to wait for transmission (seconds)

44

None blocks indefinitely, 0 for non-blocking

45

46

Raises:

47

- CanOperationError: Transmission failed

48

- CanTimeoutError: Timeout exceeded

49

"""

50

```

51

52

### Message Reception

53

54

Receive CAN messages from the bus with filtering and timeout support.

55

56

```python { .api }

57

def recv(self, timeout=None) -> Message | None:

58

"""

59

Block waiting for a message from the bus.

60

61

Parameters:

62

- timeout: Maximum time to wait for message (seconds)

63

None waits indefinitely

64

65

Returns:

66

Message object or None on timeout

67

68

Raises:

69

- CanOperationError: Reception failed

70

"""

71

```

72

73

### Periodic Message Transmission

74

75

Start sending messages at regular intervals with advanced configuration options.

76

77

```python { .api }

78

def send_periodic(self, msgs, period: float, duration=None, store_task=True,

79

autostart=True, modifier_callback=None):

80

"""

81

Start sending messages at a given period.

82

83

Parameters:

84

- msgs: Message or sequence of messages to transmit

85

- period: Period in seconds between each message

86

- duration: Duration to continue sending (None for indefinite)

87

- store_task: If True, attach task to bus instance

88

- autostart: If True, start task immediately

89

- modifier_callback: Function to modify message data before sending

90

91

Returns:

92

CyclicSendTaskABC: Task instance for controlling transmission

93

"""

94

95

def stop_all_periodic_tasks(self, remove_tasks=True) -> None:

96

"""

97

Stop all periodic message transmission tasks.

98

99

Parameters:

100

- remove_tasks: Whether to remove tasks from tracking

101

"""

102

```

103

104

### Message Filtering

105

106

Configure hardware and software message filtering to receive only relevant messages.

107

108

```python { .api }

109

def set_filters(self, filters=None) -> None:

110

"""

111

Apply filtering to all messages received by this bus.

112

113

Parameters:

114

- filters: List of filter dictionaries or None to receive all messages

115

Each filter: {"can_id": int, "can_mask": int, "extended": bool}

116

Filter matches when: (received_id & can_mask) == (can_id & can_mask)

117

"""

118

119

@property

120

def filters(self) -> CanFilters | None:

121

"""Get or set the current message filters."""

122

```

123

124

### Bus State Management

125

126

Monitor and control bus state and protocol information.

127

128

```python { .api }

129

@property

130

def state(self) -> BusState:

131

"""Return the current state of the hardware (ACTIVE/PASSIVE/ERROR)."""

132

133

@state.setter

134

def state(self, new_state: BusState) -> None:

135

"""Set the new state of the hardware."""

136

137

@property

138

def protocol(self) -> CanProtocol:

139

"""Return the CAN protocol used by this bus instance."""

140

```

141

142

### Resource Management

143

144

Proper cleanup and resource management with context manager support.

145

146

```python { .api }

147

def shutdown(self) -> None:

148

"""

149

Carry out interface-specific cleanup for shutting down the bus.

150

Can be safely called multiple times.

151

"""

152

153

def flush_tx_buffer(self) -> None:

154

"""Discard every message queued in the output buffer(s)."""

155

156

def __enter__(self):

157

"""Context manager entry."""

158

159

def __exit__(self, exc_type, exc_value, traceback):

160

"""Context manager exit with automatic shutdown."""

161

```

162

163

### Iterator Interface

164

165

Use the bus as an iterator to continuously receive messages.

166

167

```python { .api }

168

def __iter__(self):

169

"""

170

Allow iteration over messages as they are received.

171

172

Yields:

173

Message objects as they arrive

174

175

Example:

176

for msg in bus:

177

print(msg)

178

"""

179

```

180

181

## Usage Examples

182

183

### Basic Bus Operations

184

185

```python

186

import can

187

188

# Create bus with automatic interface detection

189

bus = can.Bus(channel='can0')

190

191

# Send a message

192

msg = can.Message(arbitration_id=0x123, data=[1, 2, 3, 4])

193

bus.send(msg)

194

195

# Receive with timeout

196

received = bus.recv(timeout=5.0)

197

if received:

198

print(f"Received: {received}")

199

200

# Use as iterator

201

for msg in bus:

202

print(f"Got message: {msg}")

203

if some_condition:

204

break

205

206

bus.shutdown()

207

```

208

209

### Context Manager Usage

210

211

```python

212

import can

213

214

with can.Bus(channel='can0', interface='socketcan') as bus:

215

# Bus automatically cleaned up on exit

216

bus.send(can.Message(arbitration_id=0x456, data=[0x11, 0x22]))

217

218

# Receive multiple messages

219

for _ in range(10):

220

msg = bus.recv(timeout=1.0)

221

if msg:

222

process_message(msg)

223

```

224

225

### Message Filtering

226

227

```python

228

import can

229

230

bus = can.Bus(channel='can0')

231

232

# Filter for specific message IDs

233

filters = [

234

{"can_id": 0x123, "can_mask": 0x7FF, "extended": False},

235

{"can_id": 0x456, "can_mask": 0x7FF, "extended": False},

236

]

237

bus.set_filters(filters)

238

239

# Only messages with ID 0x123 or 0x456 will be received

240

msg = bus.recv()

241

```

242

243

### Periodic Transmission

244

245

```python

246

import can

247

248

bus = can.Bus(channel='can0')

249

250

# Send heartbeat message every 100ms

251

heartbeat = can.Message(arbitration_id=0x700, data=[0x00])

252

task = bus.send_periodic(heartbeat, period=0.1)

253

254

# Modify message data over time

255

def update_counter(msg):

256

msg.data[0] = (msg.data[0] + 1) % 256

257

258

task_with_counter = bus.send_periodic(

259

heartbeat,

260

period=0.1,

261

modifier_callback=update_counter

262

)

263

264

# Stop after 5 seconds

265

import time

266

time.sleep(5)

267

task.stop()

268

bus.shutdown()

269

```

270

271

## Types

272

273

```python { .api }

274

from abc import ABC, abstractmethod

275

from typing import Optional, Union, Sequence, Callable

276

from collections.abc import Iterator

277

278

class BusABC(ABC):

279

"""Abstract base class for all CAN bus implementations."""

280

281

channel_info: str # Description of underlying bus/channel

282

RECV_LOGGING_LEVEL: int # Log level for received messages

283

284

@abstractmethod

285

def __init__(self, channel, can_filters=None, **kwargs): ...

286

287

@abstractmethod

288

def send(self, msg: Message, timeout=None) -> None: ...

289

290

def recv(self, timeout=None) -> Message | None: ...

291

def send_periodic(self, msgs, period: float, **kwargs): ...

292

def set_filters(self, filters=None) -> None: ...

293

def shutdown(self) -> None: ...

294

```