#!/usr/bin/env python3 """ MIT License Permission is hereby granted, free of charge, to any person obtaining a copy in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This example sends one message at start and then echos the received CAN messages back. """ from __future__ import print_function import can from time import sleep def send_first_msg(): # Using specific bus can0 with 125kbit baud rate on bus type socketcan bus = can.interface.Bus(bustype='socketcan', channel='can0', bitrate=125000) # Create the a message to be sent out at the start of the program msg = can.Message(arbitration_id=0x234, data=[0xDE, 0xAD, 0xBE, 0xEF], is_extended_id=False) try: # Send the message bus.send(msg) print("First message sent on {}".format(bus.channel_info)) except can.CanError: print("First message NOT sent") def do_echo(): # Using specific bus can0 with 125kbit baud rate on bus type socketcan bus = can.interface.Bus(bustype='socketcan', channel='can0', bitrate=125000) while True: try: # Wait indefinitely for a CAN message to arrive message = bus.recv() # Print error message if something went wrong if message is None: print("Error: No message received, but receive aborted!") else: # Print the received message to the console print("Message: ") print(message) # Now echo the received message back try: # Change the message ID before sending the message message.arbitration_id = 0x321 bus.send(message) print("Echo message sent on {}".format(bus.channel_info)) except can.CanError: print("Echo message NOT sent!") except: pass # Short wait, then loop back to receiving messages sleep(0.5) if __name__ == '__main__': # Send one message at the start of the program send_first_msg() # Loop indefinitely echoing received CAN messages do_echo()