Esempio n. 1
0
 def test_init(self):
     frame = can.Frame(0x55, 6, [1, 2, 3, 4, 5, 6],
                       can.FrameType.ErrorFrame, True)
     self.assertEqual(frame.id, 0x55)
     self.assertEqual(frame.data, [1, 2, 3, 4, 5, 6, 0, 0])
     self.assertEqual(frame.frame_type, can.FrameType.ErrorFrame)
     self.assertEqual(frame.is_extended_id, True)
Esempio n. 2
0
 def buildSetVariable(self, dest, var_id, data):
   # TODO: Check for overflow when fixing inputs
   if not isinstance(data, int): data = int(round(data))
   
   # Frame ID is 0x600 + node ID
   header = (0x600)|dest
   frame = can.Frame(header)
   frame.dlc = 8
   frame.data = [
     0x20,            # Type = Command (2), no unused bytes
     0x05, 0x20,      # Set User Integer Variable
     var_id    &0xFF, # Variable index
      data     &0xFF, # Data (4 bytes)
     (data>>8) &0xFF,
     (data>>16)&0xFF,
     (data>>24)&0xFF,
   ]
   return frame
Esempio n. 3
0
 def buildRPDO(self, dest, index, int1, int2):
   # TODO: Check for overflow when fixing inputs
   if not isinstance(int1, int): int1 = int(round(int1))
   if not isinstance(int2, int): int2 = int(round(int2))
   
   # Frame ID is 0x200/300/400/500 + node ID
   header = (0x100 + 0x100*index)|dest
   #if header == 0x201: print("Building frame 0x%03X : %d, %d"%(header, int1, int2))
   frame = can.Frame(header)
   frame.dlc = 8
   frame.data = [
      int1     &0xFF,
     (int1>>8) &0xFF,
     (int1>>16)&0xFF,
     (int1>>24)&0xFF,
      int2     &0xFF,
     (int2>>8) &0xFF,
     (int2>>16)&0xFF,
     (int2>>24)&0xFF,
   ]
   return frame
Esempio n. 4
0
"""Connect to CANable; print and echo any received frames"""
from canard import can
from canard.hw import cantact
import time

dev = cantact.CantactDev("/dev/ttyACM1") # Connect to CANable on this /dev/ttyACM#
dev.set_bitrate(500000) # Set the bitrate to a 0.5Mb/s
dev.start() # Go on the bus
count = 0
dev_id = 0x1871

while True:
    count += 1
    frame = can.Frame(dev_id, dlc=8, data = [0x00]*8, is_extended_id=True)
    dev.send(frame) # Echo the CAN frame back out on the bus
    print(str(frame))
    time.sleep(1)
Esempio n. 5
0
import sys
import argparse
import time
import re

parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help="Input file.")
parser.add_argument("-s", "--serial", help="Serial port.")
parser.add_argument("-b", "--baud", help="Baud rate.", default=250000)
args = parser.parse_args()
print(f"Reading file '{args.file}', sending to {args.serial} @ {args.baud}")

dev = cantact.CantactDev(args.serial)
dev.set_bitrate(250000)
dev.start()
with open(args.file, "r") as f:
    count = 1
    for line in f:
        linennl = line.rstrip()
        lineparts = linennl.split(' ')
        lineid = int(re.search(r'<(.*)>', lineparts[0]).group(1), 0)
        linedata = [int(i, 16) for i in lineparts[2:]]
        print(f"{count}>{linennl}")
        frame = can.Frame(id=lineid,
                          dlc=len(linedata),
                          data=linedata,
                          is_extended_id=True)
        dev.send(frame)
        print("%d: %s" % (count, str(frame)))
        time.sleep(0.05)
        count += 1
Esempio n. 6
0
import sys

from canard.proto.uds import UdsInterface
from canard.hw.socketcan import SocketCanDev
from canard import can

d = SocketCanDev('vcan0')
d.start()

while True:
    frame = d.recv()
    if frame.id == 0x705:
        resp = can.Frame(0x725)
        resp.dlc = 8
        resp.data = [0x02, 0x41]
        d.send(resp)



Esempio n. 7
0
 def setUp(self):
     self.frame = can.Frame(0)
Esempio n. 8
0
    def run(self):
        global frames
        global frameCounts
        global lastFramesByID

        frames = []
        frameCounts = {}
        lastFrameByID = {}

        startTime = getts()
        lastRefresh = startTime
        lastErrorCheck = startTime
        while not self._abort:
            # Check for bus errors once per second
            # if (getts()-lastErrorCheck) > 1.0:
            #     lastErrorCheck = getts()
            #     status_response = self._canusb.get_status_flags()

            #     print status_response

            #     if len(status_response) > 2:
            #         # status is 'F' followed by  2 bytes of hexadecimal BCD that represent the 8 bit status
            #         status = (int(chr(status_response[1]),16) << 4) + int(chr(status_response[2]),16)

            #         if status > 0:
            #             status_message = ""
            #             rxFifoFull = status & 0x01
            #             if rxFifoFull > 0:
            #                 status_message += " (RX Fifo full) "
            #             txFifoFull = status & 0x02
            #             if txFifoFull > 0:
            #                 status_message += " (TX Fifo full) "
            #             errorWarning = status & 0x04
            #             if errorWarning > 0:
            #                 status_message += " (Error Warning) "
            #             dataOverrun = status & 0x08
            #             if dataOverrun > 0:
            #                 status_message += " (Data Overrun) "
            #             errorPassive = status & 0x20
            #             if errorPassive > 0:
            #                 status_message += " (Error Passive) "
            #             arbitrationLost = status & 0x40
            #             if arbitrationLost > 0:
            #                 status_message += " (Arbitration Lost) "
            #             busError = status & 0x80
            #             if busError > 0:
            #                 status_message += " (Bus Error) "

            #             print "Bus status changed: 0x%x %s" % (status, status_message)

            # Check whether it is time to send scheduled frames
            # and insert scheduled frames in the tx queue
            if 0 == len(self._tx_frames):
                for f in self._tx_scheduled_frames:
                    self._tx_frames.appendleft(f)

            try:
                # is it time to send a scheduled frame
                if len(self._tx_frames) > 0:
                    # send any available frame, this will also read incoming frames
                    f = self._tx_frames.pop()
                    # r = self._canusb.transmit_frame(f)
                    # print "Send Frame ",str(f)
                    # print type(f.rtr)
                    # print "f.rtr",f.rtr
                    if f.rtr == 0:
                        tempframe = can.Frame(
                            f.msg_id,
                            f.ndata, [
                                f.data[0], f.data[1], f.data[2], f.data[3],
                                f.data[4], f.data[5], f.data[6], f.data[7]
                            ],
                            frame_type=can.FrameType.DataFrame,
                            is_extended_id=f.xtd)
                    elif f.rtr == 1:
                        tempframe = can.Frame(
                            f.msg_id,
                            f.ndata, [
                                f.data[0], f.data[1], f.data[2], f.data[3],
                                f.data[4], f.data[5], f.data[6], f.data[7]
                            ],
                            frame_type=can.FrameType.RemoteFrame,
                            is_extended_id=f.xtd)
                    self._canusb.send(tempframe)
                    # print "pop a frame"
                else:
                    # poll if there are no frames to send
                    # r = self._canusb.poll()
                    # print "poll a frame"
                    pass
            # except lawicel_canusb.CANUSBError, e:
            except Exception, e:
                # re-raise error if it's not timeout
                # if str(e).find("timeout") < 0:
                #     raise
                # else:
                #     continue
                print e
                print "There is some error"
            rawframe = self._canusb.recv_buff(8192)
            # rxfifoLen = self._canusb.get_rxfifo_len()
            rxfifoLen = len(rawframe)
            self._lock.acquire()
            if rxfifoLen != 0:
                for i in range(0, rxfifoLen):
                    # f = self._canusb.get_rx_frame()
                    tempf = rawframe[i]
                    # print "Get a Frame ",str(tempf)

                    f = CANMessage.CANFrame(msg_id=(tempf.id), xtd=tempf.is_extended_id, \
                        rtr=tempf.frame_type, ndata=tempf.dlc, \
                        data=(tempf.data[0],tempf.data[1],tempf.data[2],tempf.data[3],\
                            tempf.data[4],tempf.data[5],tempf.data[6],tempf.data[7]) )
                    print "f ", str(f)
                    frames.append(f)
                    if f.get_msg_id() not in frameCounts:
                        frameCounts[f.get_msg_id()] = 1
                    else:
                        frameCounts[
                            f.get_msg_id()] = frameCounts[f.get_msg_id()] + 1

                    lastFramesByID[f.get_msg_id()] = f
            self._lock.release()

            # notify that new frames have been received if a callback
            # was provided
            # Only notify 5 times/s or every 100 frames to avoid
            # over-loading the UI thread with events
            if rxfifoLen != 0:
                if (self._callback != None) and ((len(frames) % 100 == 0) or (
                    (getts() - lastRefresh) > 0.2)):
                    self._callback(len(frames))
                    lastRefresh = getts()
Esempio n. 9
0
import struct
import time
from canard import can
from canard.hw import cantact

dev = cantact.CantactDev("/dev/cu.usbmodem141101")  # Connect to CANable that enumerated as ttyACM0

dev.set_bitrate(500000)  # Set the bitrate to a 1Mbaud
dev.start() # Go on the bus

def create_az(az):
    struct.pack("HH")

    # 00 00 f1 ff 20 ff 64 8c

while True:
    bs = bytes(bytearray.fromhex('0000f1ff20ff648c'))
    ints = [int(b) for b in bs]
    frame = can.Frame(251598624, dlc=8, data=ints, is_extended_id=True)
    dev.send(frame)  # Echo the CAN frame back out on the bus

    print("Sending frame ", frame)

    time.sleep(0.1)

Esempio n. 10
0
#Connect to the Device
dev.start()

print("Opening log file...")

for line in data:  #Parse each line
    #Split each line at the comma
    message = line.rstrip('\n').split(',', 11)

    #build the can frame
    # Parse the id, create a frame
    #frame_id = int(message.id, 16)
    frame_id = int(message[1], 16)
    frame_id_hex = hex(frame_id)

    frame = can.Frame(frame_id)

    # Set our frame equal to message data
    frame.dlc = int(message[2])

    #convert list of nibbles from strings to ints
    message_value = []
    message_value = map(int, message[3:11])
    #set out frames data to our new value
    frame.data = message_value

    #print raw from file
    #print(message)
    #print process frame ready to be sent
    print(frame)
Esempio n. 11
0
from canard import can
from canard.hw import socketcan

dev = socketcan.SocketCanDev('vcan0')

frame = can.Frame(id=0x100)
frame.dlc = 8
frame.data=[1,2,3,4,5,6,7,8]

while True:
    dev.send(frame)
    
Esempio n. 12
0
from canard.proto.isotp import IsoTpProtocol, IsoTpMessage
from canard import can 

p = IsoTpProtocol()


f = can.Frame(0x100)
f.data = [3,1,2,3]
f.dlc = 4

#print(p.parse_frame(f))

f.data = [0x10, 20, 1, 2, 3, 4, 5, 6]
f.dlc = 8
print(p.parse_frame(f))
f.data = [0x21, 7, 8, 9, 10, 11, 12, 13]
#print(p.parse_frame(f))
f.data = [0x22, 7, 8, 9, 10, 11, 12, 13]
#print(p.parse_frame(f))

m = IsoTpMessage(0x100)
m.data = range(1,0xFF)
m.length = 0x1FF
for fr in p.generate_frames(m):
    print fr
Esempio n. 13
0
from canard import can
from canard.hw import peak
from canard.hw import socketcan

#dev = peak.PcanDev()
dev = socketcan.SocketCanDev("vcan0")

dev.start()

frame = can.Frame(0)
frame.dlc = 8

while True:
    dev.send(frame)
Esempio n. 14
0
from canard import can
from canard.hw import peak
from canard.hw import socketcan

#dev = peak.PcanDev()
dev = socketcan.SocketCanDev("vcan0")

dev.start()

frame = can.Frame(0x7DF)
frame.dlc = 8

# frame data
# byte 0: number of additional bytes (1)
# byte 1: mode. mode 04 clears MIL
# other bytes not used, set to 0x55
frame.data = [1, 4, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55]

dev.send(frame)
Esempio n. 15
0
 def buildRawCommand(self, dest, headerBase, dlc, data):
   frame = can.Frame(headerBase | dest)
   frame.dlc=dlc
   frame.data=data
   return frame
Esempio n. 16
0
from canard import can
from canard.hw import cantact
from canard.utils.queue import CanQueue
import time
import sys

dev = cantact.CantactDev(sys.argv[1])
dev.set_bitrate(125000)
cq = CanQueue(dev)

cq.start()

print cq.recv()

req = can.Frame(0x6A5)
req.dlc = 8
req.data = [0x10,0xFF, 0xFF]

cq.send(req)

print cq.recv(filter=0x625, timeout=10)

cq.stop()

#dev.stop()
#dev.ser.write('S0\r')
#dev.start()

#while True:
#    frame = can.Frame(0x10)
#    frame.dlc=3