Linux下can和canopen同时用

本代码主要介绍Linux下在使用can的同时使用canopen,并且对can总线的数据进行监测的。

Linux系统:Ubuntu

Python版本:Python3

环境:已安装好can canopen模块

#!/usr/bin/env python3
# coding: utf-8

import multiprocessing
import time
import os
import can
import canopen

def canBusInit():
    try:
        os.system(sudo ifconfig can0 down)
        os.system(sudo ip link set can0 type can bitrate 250000)
        os.system(sudo ifconfig can0 up)
        return can.interface.Bus(bustype=socketcan, channel=can0, bitrate=250000)
    except:
        time.sleep(5)
        print("canbus  restart")
        canBusInit()

def canTest():
    print("canTestProcess start")
    while(1):
        time.sleep(1)
        msg = can.Message(arbitration_id=0x123, data=[0, 1, 2, 3, 4, 5, 6, 7], extended_id=False)
        bus.send(msg)

def canopenTest():
    print("canopenTest start")
    while(1):
        time.sleep(1)
        node.nmt.state = PRE-OPERATIONAL
        # 等待3s
        time.sleep(1)
        # 把slave从PRE-OPERATIONAL设置为OPERATIONAL状态
        node.nmt.state = OPERATIONAL

def listenTest():
    print("shellTest start")
    bus = can.interface.Bus(channel=can0, bustype=socketcan,bitrate=250000) 
    while(1):
        msgFrombed = bus.recv(timeout=0)
        if msgFrombed is not None:
            print(msgFrombed)

def main(): 
    p1 = multiprocessing.Process(target=canTest)
    p2 = multiprocessing.Process(target=canopenTest)
    p3 = multiprocessing.Process(target=listenTest)
    p1.start()
    p2.start()
    p3.start()    

if __name__ == __main__: 
    #init canbus
    bus = canBusInit()

    #re-using a bus
    network = canopen.Network()
    network.bus = bus
    listeners = network.listeners
    notifier = can.Notifier(bus, listeners, 0.5)

    # 添加slave节点,其id是6,对象字典为CANopenSocket.eds
    node = canopen.RemoteNode(6, CANopenSocket.eds)
    network.add_node(node)

    #start main
    main()

运行该脚本,可以在终端打印如下信息,说明can和canopen能同时用,并且能监控到发送出去的数据。

经验分享 程序员 微信小程序 职场和发展