from canlib import canlib
from canlib import Frame
from datetime import datetime
from datetime import timedelta

# 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)

# Enable the new can1 channel
can1.busOn()

# Set the transmit rate
txRate = timedelta(milliseconds=200)

# Set up a variable to keep track of the last TX timestamp
lastTx = datetime.now()

# Create a function to send a CAN message when called.
def sendCanMessage(frame, rate):
    # Bring the global variable lastTx into the function scope.
    global lastTx

    # Get the current time
    now = datetime.now()

    # Check to see if it's time to send another message.
    if(now - lastTx > rate):
        # Send the CAN message
        can1.write(frame)

        # Update the last TX timestamp.
        lastTx = datetime.now()
        

# Create a loop to periodically send the message.
while True:
    # Define the frame with the message ID, DLC, data, and STD or EXT message ID.
    frame = Frame(id_=0x18FEF007, dlc=8, data=[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], flags=canlib.canMSG_EXT)

    # Send the message.
    sendCanMessage(frame, txRate)

        