python-can 的使用
-
最近在搞 websocket, 服务端是用 python 写的,所以,我需要用python 控制 can 去传输相关信息。
-
python-can 模块就是 python 控制 can 的模仿。
-
利用 buildroot 去生成 python-can 模块
cd $BUILDROOT_PATH
make menuconfig
Target packages --->
Interpreter languages and scripting --->
[*] python3
External python modules --->
[*] python-can
make
// 生成的文件在 output/target/usr/lib/python3.5/site-packages/
// 将这个文件 拷贝到自己的文件系统的 ust/lib/python3.5 里面
-
python-can 文档地址:
https://python-can.readthedocs.io/en/latest/index.html#
-
python-can 的使用
#!/usr/bin/python3
import os; ''' 这是加载 os 模块, 调用shell 命令 '''
import can; ''' 加载python-can 模块 '''
can.rc['interface'] = 'socketcan_native' ``` Linux 里面的 socketcan 在am335x 上面应该使用这个 ```
can.rc['channel'] = 'can1' ''' can 接口名字 '''
can.rc['bitrate'] = 1000000 ''' 波特率 1M '''
from can.interfaces.interface import Bus
''' 这个函数是can 的启动函数 '''
def can_setup(can_name):
can_setup_command = "canconfig " + can_name + " bitrate 1000000 restart-ms 1000 ctrlmode triple-sampling on";
can_start_command = "canconfig " + can_name + " start";
pass;
os.system(can_setup_command);
os.system(can_start_command);
''' can 停止函数 '''
def can_stop(can_name):
can_stop_command = "canconfig " + can_name + " stop";
os.system(can_stop_command);
''' 发送信息 '''
def send_one():
bus = can.interface.Bus();
msg = can.Message(arbitration_id=0x7f,
data=[11, 25, 11, 1, 1, 2, 23, 18],
extended_id=False);
try:
bus.send(msg); ''' 发送信息 '''
print("Message sent on {}".format(bus.channel_info));
except can.CanError:
print("Message NOT sent");
def recv():
bus = can.interface.Bus();
msg = bus.recv(100); ''' 接收信息 '''
try:
bus.send(msg);
print(msg);
print(msg.data[0]); # 接收回来的第一个字节的数据
print(msg.arbitration_id); # 接收回来的ID
return msg;
except can.CanError:
print("Message NOT sent");
if __name__ == "__main__":
''' can_setup("can1"); '''
send_one();
recv();
''' can_stop("can1"); '''
Read The Fucking Source Code