跳转至

CanBus

robodyno.interfaces.can_bus

This module provides CAN bus interface for robodyno devices.

Examples:

>>> from robodyno.interfaces import CanBus
>>> can_bus = CanBus()
>>> can_bus.send(0x10, 0x0e, 'fee', 50, 0.02, 0.1)
>>> can_bus.get(0x10, 0x0d, 'fee')
(50.0, 0.0200042724609375, 0.0999755859375)
>>> can_bus.subscribe(callback, 0x10, 0x02)
>>> can_bus.unsubscribe(callback, 0x10, 0x02)
>>> can_bus.disconnect()

CanBus

Bases: object

CAN bus interface for robodyno devices.

This class provides CAN bus interface for robodyno devices. It supports sending and receiving data from CAN bus. It also supports subscribing data from CAN bus.

A thread is created to receive data from CAN bus. When a device ID and a command ID is subscribed, the callback function will be called when the corresponding data is received.

__init__(bitrate=1000000, channel='can0', connect=True)

Initialize CAN bus interface with given channel and bitrate.

Parameters:

Name Type Description Default
bitrate int

CAN bus bitrate, e.g. 1000000.

1000000
channel str

CAN bus channel name, e.g. 'can0'.

'can0'
connect bool

Whether to connect to CAN bus.

True

Raises:

Type Description
NotImplementedError

If the platform is not supported.

connect()

Connect to CAN bus.

disconnect()

Disconnect from CAN bus.

send(device_id, cmd_id, fmt, *args)

Send data to CAN bus.

Parameters:

Name Type Description Default
device_id int

Device ID.

required
cmd_id int

Command ID.

required
fmt str

Format string for packing data. See struct module for details.

required
*args

Data to be sent.

()

get(device_id, cmd_id, fmt, timeout=None)

Get data from CAN bus.

Parameters:

Name Type Description Default
device_id int

Device ID.

required
cmd_id int

Command ID.

required
fmt str

Format string for unpacking data. See struct module for details.

required
timeout float

Timeout for receiving data.

None

Returns:

Type Description
tuple

Received data.

Raises:

Type Description
TimeoutError

If timeout.

subscribe(callback, device_id=-1, cmd_id=-1)

Subscribe data from CAN bus.

Parameters:

Name Type Description Default
callback func

Callback function.

The function should accept four arguments, e.g. callback(data, timestamp, device_id, cmd_id).

required
device_id int

Device ID. -1 for all devices.

-1
cmd_id int

Command ID. -1 for all commands.

-1

unsubscribe(callback, device_id=-1, cmd_id=-1)

Unsubscribe data from CAN bus.

Parameters:

Name Type Description Default
callback func

Callback function.

required
device_id int

Device ID. -1 for all devices.

-1
cmd_id int

Command ID. -1 for all commands.

-1