跳转至

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.

参数:

名称 类型 描述 默认
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

引发:

类型 描述
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.

参数:

名称 类型 描述 默认
device_id int

Device ID.

必需
cmd_id int

Command ID.

必需
fmt str

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

必需
*args

Data to be sent.

()

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

Get data from CAN bus.

参数:

名称 类型 描述 默认
device_id int

Device ID.

必需
cmd_id int

Command ID.

必需
fmt str

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

必需
timeout float

Timeout for receiving data.

None

返回:

类型 描述
tuple

Received data.

引发:

类型 描述
TimeoutError

If timeout.

mi_motor_send(msg, timeout=None, master_id=255)

Send a CAN message and wait for the matching response from an MI motor.

参数:

名称 类型 描述 默认
msg Message

The CAN message to send.

必需
timeout Optional[float]

Timeout in seconds. If 0, return immediately without waiting.

None
master_id int

Master device ID used for response filtering.

255

返回:

类型 描述
Optional[Message]

The matching response message, or None if no response is expected.

引发:

类型 描述
TimeoutError

If no response is received within the timeout.

ValueError

If the sent command is not recognized.

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

Subscribe data from CAN bus.

参数:

名称 类型 描述 默认
callback func

Callback function.

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

必需
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.

参数:

名称 类型 描述 默认
callback func

Callback function.

必需
device_id int

Device ID. -1 for all devices.

-1
cmd_id int

Command ID. -1 for all commands.

-1