pythoncan-bus

How to run a simulation of CAN messages on Python


I have am currently learning how to use libraries in python and I have a project in mind, which requires me to use the CAN library https://python-can.readthedocs.io/en/master/index.html . I would like to simulate CAN messages to test and create a platform that can convert them into readable messages. I just can't seem to understand how to get the simulator from the library.


Solution

  • I'm unfamiliar with python-can but if all you want to do is import the module, here's a snippet that imports the library and sends out a simple message (receiving them is a whole other matter). You might want to keep exploring the docs for ways to capture messages and do stuff with them.

    import time
    import can
    
    bus = can.interface.Bus(interface='virtual', bustype='socketcan', 
                            channel='vcan0', bitrate=500000)
    
    def producer(bus, id):
        for i in range(10):
            msg = can.Message(arbitration_id=0xc0ffee, 
                              data=[id, i, 0, 1, 3, 1, 4, 1], is_extended_id=False)
            try:
                bus.send(msg)
                print("Message sent on {}".format(bus.channel_info))
                time.sleep(1)
            except can.CanError:
                print("Message NOT sent")
    
    producer(bus, 1)