from canlib import canlib
from canlib import Frame
#from datetime import datetime

# Create a new CAN channel can1
can1 = canlib.openChannel(channel=0)

# Set the baud rate: canBITRATE_250K or canBITRATE_500k
can1.setBusParams(canlib.canBITRATE_500K)

# Set standard message ID filters if necessary
can1.canAccept(0x000, canlib.AcceptFilterFlag.SET_MASK_STD)
can1.canAccept(0x000, canlib.AcceptFilterFlag.SET_CODE_STD)

# Set extended message ID filters if necessary
can1.canAccept(0x1FFFFFFF, canlib.AcceptFilterFlag.SET_MASK_EXT)
can1.canAccept(0x18FEF121, canlib.AcceptFilterFlag.SET_CODE_EXT)

# Enable the new can1 channel
can1.busOn()

while True:
    # Read the next incoming CAN frame, function will timeout if no new message within 10 seconds
    frame = can1.read(timeout=10000)

    # Print the CAN frame
    print(hex(frame.id).upper(), 
          frame.dlc, 
          "0x" + hex(frame.data[0])[2:].zfill(2).upper(),
          "0x" + hex(frame.data[1])[2:].zfill(2).upper(),
          "0x" + hex(frame.data[2])[2:].zfill(2).upper(),
          "0x" + hex(frame.data[3])[2:].zfill(2).upper(),
          "0x" + hex(frame.data[4])[2:].zfill(2).upper(),
          "0x" + hex(frame.data[5])[2:].zfill(2).upper(),
          "0x" + hex(frame.data[6])[2:].zfill(2).upper(),
          "0x" + hex(frame.data[7])[2:].zfill(2).upper(),
          frame.timestamp, "ms")
