2 # GoodFET SPI Flash Client
4 # (C) 2012 Travis Goodspeed <travis at radiantmachines.com>
8 # 1) getting hot reads on frequency
9 # 2) allow sniffing in "normal" mode to get ack bits
10 # --check if that's whats causing error flags in board-to-board transmission
17 import csv, time, argparse;
20 from random import randrange
21 from GoodFETMCPCAN import GoodFETMCPCAN;
22 from intelhex import IntelHex;
24 class GoodFETMCPCANCommunication:
27 self.client=GoodFETMCPCAN();
29 self.client.MCPsetup();
30 self.DATALOCATION = "../../contrib/ThayerData/"
36 self.client.MCPreqstatConfiguration();
38 print "MCP2515 Info:\n\n";
40 print "Mode: %s" % self.client.MCPcanstatstr();
41 print "Read Status: %02x" % self.client.MCPreadstatus();
42 print "Rx Status: %02x" % self.client.MCPrxstatus();
43 print "Error Flags: %02x" % self.client.peek8(0x2D);
44 print "Tx Errors: %3d" % self.client.peek8(0x1c);
45 print "Rx Errors: %3d\n" % self.client.peek8(0x1d);
48 print "CNF1: %02x" %self.client.peek8(0x2a);
49 print "CNF2: %02x" %self.client.peek8(0x29);
50 print "CNF3: %02x\n" %self.client.peek8(0x28);
51 print "RXB0 CTRL: %02x" %self.client.peek8(0x60);
52 print "RXB1 CTRL: %02x" %self.client.peek8(0x70);
55 print "RXB0: %02x" %self.client.peek8(0x60);
56 print "RXB1: %02x" %self.client.peek8(0x70);
57 print "RXB0 masks: %02x, %02x, %02x, %02x" %(self.client.peek8(0x20), self.client.peek8(0x21), self.client.peek8(0x22), self.client.peek8(0x23));
58 print "RXB1 masks: %02x, %02x, %02x, %02x" %(self.client.peek8(0x24), self.client.peek8(0x25), self.client.peek8(0x26), self.client.peek8(0x27));
62 packet0=self.client.readrxbuffer(0);
63 packet1=self.client.readrxbuffer(1);
64 for foo in [packet0, packet1]:
65 print self.client.packet2str(foo);
68 self.client.MCPsetup();
71 ##########################
73 ##########################
75 def sniff(self,freq,duration,description, verbose=True, comment=None, filename=None, standardid=None, debug=False, faster=False, parsed=True):
77 #reset eveything on the chip
81 #### ON-CHIP FILTERING
82 if(standardid != None):
85 self.client.MCPreqstatConfiguration();
86 self.client.poke8(0x60,0x26); # set RXB0 CTRL register to ONLY accept STANDARD messages with filter match (RXM1=0, RMX0=1, BUKT=1)
87 self.client.poke8(0x20,0xFF); #set buffer 0 mask 1 (SID 10:3) to FF
88 self.client.poke8(0x21,0xE0); #set buffer 0 mask 2 bits 7:5 (SID 2:0) to 1s
89 if(len(standardid)>2):
90 self.client.poke8(0x70,0x20); # set RXB1 CTRL register to ONLY accept STANDARD messages with filter match (RXM1=0, RMX0=1)
91 self.client.poke8(0x24,0xFF); #set buffer 1 mask 1 (SID 10:3) to FF
92 self.client.poke8(0x25,0xE0); #set buffer 1 mask 2 bits 7:5 (SID 2:0) to 1s
94 for filter,ID in enumerate(standardid):
115 #### split SID into different regs
116 SIDlow = (ID & 0x03) << 5; # get SID bits 2:0, rotate them to bits 7:5
117 SIDhigh = (ID >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
120 self.client.poke8(RXFSIDH,SIDhigh);
121 self.client.poke8(RXFSIDL, SIDlow);
123 if (verbose == True):
124 print "Filtering for SID %d (0x%02xh) with filter #%d"%(ID, ID, filter);
125 comment = comment + ("f%d" %(ID))
128 self.client.MCPsetrate(freq);
130 # This will handle the files so that we do not loose them. each day we will create a new csv file
132 #get folder information (based on today's date)
133 now = datetime.datetime.now()
134 datestr = now.strftime("%Y%m%d")
135 path = self.DATALOCATION+datestr+".csv"
139 outfile = open(filename,'a');
140 dataWriter = csv.writer(outfile,delimiter=',');
141 dataWriter.writerow(['# Time Error Bytes 1-13']);
142 dataWriter.writerow(['#' + description])
144 self.client.MCPreqstatNormal();
145 print "Listening...";
147 starttime = time.time();
149 while((time.time()-starttime < duration)):
152 packet=self.client.fastrxpacket();
154 packet=self.client.rxpacket();
158 MCPstatusReg = self.client.MCPrxstatus();
159 messagestat=MCPstatusReg&0xC0;
160 messagetype=MCPstatusReg&0x18;
161 if(messagestat == 0xC0):
162 print "Message in both buffers; message type is %02x (0x00 is standard data, 0x08 is standard remote)." %messagetype
163 elif(messagestat == 0x80):
164 print "Message in RXB1; message type is %02x (0x00 is standard data, 0x08 is standard remote)." %messagetype
165 elif(messagestat == 0x40):
166 print "Message in RXB0; message type is %02x (0x00 is standard data, 0x08 is standard remote)." %messagetype
167 elif(messagestat == 0x00):
168 print "No messages in buffers."
174 row.append("%f"%time.time());
177 #if we want to print a parsed message
181 if( packet.get('eID')):
182 msg += " eID: %d" %packet.get('eID')
183 msg += " rtr: %d"%packet['rtr']
184 length = packet['length']
185 msg += " length: %d"%length
187 for i in range(0,length):
189 msg +=" %d"% packet[dbidx]
191 # if we want to print just the message as it is read off the chip
193 print self.client.packet2str(packet)
198 MCPeflgReg=self.client.peek8(0x2D);
199 print"EFLG register equals: %x" %MCPeflgReg;
200 if((MCPeflgReg & 0xC0)==0xC0):
201 print "WARNING: BOTH overflow flags set. Missed a packet. Clearing and proceeding."
202 elif(MCPeflgReg & 0x80):
203 print "WARNING: RXB1 overflow flag set. A packet has been missed. Clearing and proceeding."
204 elif(MCPeflgReg & 0x40):
205 print "WARNING: RXB0 overflow flag set. A packet has been missed. Clearing and proceeding."
206 self.client.MCPbitmodify(0x2D,0xC0,0x00);
207 print"EFLG register set to: %x" % self.client.peek(0x2D);
210 if (self.client.peek8(0x2C) & 0x80):
211 self.client.MCPbitmodify(0x2C,0x80,0x00);
212 print "ERROR: Malformed packet recieved: " + self.client.packet2str(packet);
217 row.append(0); #since we don't check for errors if we're not in debug mode...
220 #how long the sniff was for
222 #boolean that tells us if there was filtering. 0 == no filters, 1 == filters
223 if(standardid != None):
227 #write packet to file
229 row.append("%02x"%ord(byte));
230 dataWriter.writerow(row);
233 print "Listened for %d seconds, captured %d packets." %(duration,packetcount);
237 def filterStdSweep(self, freq, time = 5):
239 for i in range(0, 2047, 6):
240 print "sniffing id: %d, %d, %d, %d, %d, %d" % (i,i+1,i+2,i+3,i+4,i+5)
241 comment = "sweepFilter_%d_%d_%d_%d_%d_%d" % (i,i+1,i+2,i+3,i+4,i+5)
242 description = "Running a sweep filer for all the possible standard IDs. This run filters for: %d, %d, %d, %d, %d, %d" % (i,i+1,i+2,i+3,i+4,i+5)
243 count = self.sniff(freq=freq, duration = time, description = description,comment = comment, standardid = [i, i+1, i+2, i+3, i+4, i+5])
245 for j in range(i,i+5):
246 comment = "sweepFilter: %d" % (j)
247 description = "Running a sweep filer for all the possible standard IDs. This run filters for: %d " % j
248 count = self.sniff(freq=freq, duration = time, description = description,comment = comment, standardid = [j])
253 def sweepRandom(self, freq, number = 5, time = 5,):
256 for i in range(0,number,6):
258 comment = "sweepFilter"
259 for j in range(0,6,1):
261 comment += "_%d" % id
265 description = "Running a sweep filer for all the possible standard IDs. This runs the following : " + comment
266 count = self.sniff(freq=freq, duration=time, description=description, comment = comment, standardid = idsTemp)
268 for element in idsTemp:
269 comment = "sweepFilter: %d" % (element)
270 description = "Running a sweep filer for all the possible standard IDs. This run filters for: %d " % element
271 count = self.sniff(freq=freq, duration = time, description = description,comment = comment, standardid = [element, element, element])
276 def sniffTest(self, freq):
280 print "Calling MCPsetrate for %i." %rate;
281 self.client.MCPsetrate(rate);
282 self.client.MCPreqstatNormal();
284 print "Mode: %s" % self.client.MCPcanstatstr();
285 print "CNF1: %02x" %self.client.peek8(0x2a);
286 print "CNF2: %02x" %self.client.peek8(0x29);
287 print "CNF3: %02x\n" %self.client.peek8(0x28);
290 packet=self.client.rxpacket();
293 if (self.client.peek8(0x2C) & 0x80):
294 self.client.MCPbitmodify(0x2C,0x80,0x00);
295 print "malformed packet recieved: "+ self.client.packet2str(packet);
297 print "properly formatted packet recieved" + self.client.packet2str(packet);
300 def freqtest(self,freq):
302 self.client.MCPsetup();
304 self.client.MCPsetrate(freq);
305 self.client.MCPreqstatListenOnly();
307 print "CAN Freq Test: %3d kHz" %freq;
312 starttime = time.time();
313 while((time.time()-starttime < args.time)):
314 packet=self.client.rxpacket();
318 if (self.client.peek8(0x2C) & 0x80):
319 print "malformed packet recieved"
321 self.client.MCPbitmodify(0x2C,0x80,0x00);
323 print self.client.packet2str(packet);
325 print "Results for %3.1d kHz: recieved %3d packets, registered %3d RX errors." %(freq, x, errors);
328 def isniff(self,freq):
329 """ An intelligent sniffer, decodes message format """
330 """ More features to be added soon """
332 self.client.MCPsetrate(freq);
333 self.client.MCPreqstatListenOnly();
335 packet=self.client.rxpacket();
344 print "\nArbID: " + self.client.packet2str(arbid);
345 print "EID: " + self.client.packet2str(eid);
346 print "DLC: " + self.client.packet2str(dlc);
347 print "Data: " + self.client.packet2str(data);
352 print "Just reset..."
353 print "EFLG register: %02x" % self.client.peek8(0x2d);
354 print "Tx Errors: %3d" % self.client.peek8(0x1c);
355 print "Rx Errors: %3d" % self.client.peek8(0x1d);
356 print "CANINTF: %02x" %self.client.peek8(0x2C);
357 self.client.MCPreqstatConfiguration();
358 self.client.poke8(0x60,0x66);
359 self.client.MCPsetrate(500);
360 self.client.MCPreqstatNormal();
361 print "In normal mode now"
362 print "EFLG register: %02x" % self.client.peek8(0x2d);
363 print "Tx Errors: %3d" % self.client.peek8(0x1c);
364 print "Rx Errors: %3d" % self.client.peek8(0x1d);
365 print "CANINTF: %02x" %self.client.peek8(0x2C);
366 print "Waiting on packets.";
370 packet=self.client.rxpacket();
372 print "Message recieved: %s" % self.client.packet2str(packet);
374 checkcount=checkcount+1;
375 if (checkcount%30==0):
376 print "EFLG register: %02x" % self.client.peek8(0x2d);
377 print "Tx Errors: %3d" % self.client.peek8(0x1c);
378 print "Rx Errors: %3d" % self.client.peek8(0x1d);
379 print "CANINTF: %02x" %self.client.peek8(0x2C);
383 def spit(self,freq, standardid,debug):
386 self.client.MCPsetrate(freq);
387 self.client.MCPreqstatNormal();
389 print "initial state:"
390 print "Tx Errors: %3d" % self.client.peek8(0x1c);
391 print "Rx Errors: %3d" % self.client.peek8(0x1d);
392 print "Error Flags: %02x\n" % self.client.peek8(0x2d);
393 print "TXB0CTRL: %02x" %self.client.peek8(0x30);
394 print "CANINTF: %02x\n" %self.client.peek8(0x2C);
395 print "\n\nATTEMPTING TRANSMISSION!!!"
398 #### split SID into different regs
399 SIDlow = (standardid[0] & 0x03) << 5; # get SID bits 2:0, rotate them to bits 7:5
400 SIDhigh = (standardid[0] >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
402 packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
403 0x08, # bit 6 must be set to 0 for data frame (1 for RTR)
404 # lower nibble is DLC
405 0x01,0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xFF]
407 packetE = [SIDhigh, SIDlow | 0x80, 0x00,0x00, # pad out EID regs
408 0x08, # bit 6 must be set to 0 for data frame (1 for RTR)
409 # lower nibble is DLC
410 0x01,0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xFF]
413 self.client.txpacket(packetE);
416 TXB0CTRL = self.client.peek8(0x30);
418 while(TXB0CTRL | 0x00 != 0x00):
420 TXB0CTRL = self.client.peek8(0x30);
421 if (checkcount %30 ==0):
422 print "Tx Errors: %3d" % self.client.peek8(0x1c);
423 print "Rx Errors: %3d" % self.client.peek8(0x1d);
424 print "EFLG register: %02x" % self.client.peek8(0x2d);
425 print "TXB0CTRL: %02x" %TXB0CTRL;
426 print "CANINTF: %02x\n" %self.client.peek8(0x2C);
433 if __name__ == "__main__":
435 parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description='''\
437 Run commands on the MCP2515. Valid commands are:
441 peek 0x(start) [0x(stop)]
451 parser.add_argument('verb', choices=['info', 'test','peek', 'reset', 'sniff', 'freqtest','snifftest', 'spit']);
452 parser.add_argument('-f', '--freq', type=int, default=500, help='The desired frequency (kHz)', choices=[100, 125, 250, 500, 1000]);
453 parser.add_argument('-t','--time', type=int, default=15, help='The duration to run the command (s)');
454 parser.add_argument('-o', '--output', default=None,help='Output file');
455 parser.add_argument("-d", "--description", help='Description of experiment (included in the output file)', default="");
456 parser.add_argument('-v',"--verbose",action='store_false',help='-v will stop packet output to terminal', default=True);
457 parser.add_argument('-c','--comment', help='Comment attached to ech packet uploaded',default=None);
458 parser.add_argument('-b', '--debug', action='store_true', help='-b will turn on debug mode, printing packet status', default=False);
459 parser.add_argument('-a', '--standardid', type=int, action='append', help='Standard ID to accept with filter 0 [1, 2, 3, 4, 5]', default=None);
460 parser.add_argument('-x', '--faster', action='store_true', help='-x will use "fast packet recieve," which may duplicate packets and/or cause other weird behavior', default=False);
463 args = parser.parse_args();
466 filename = args.output
467 description = args.description
468 verbose = args.verbose
469 comments = args.comment
471 standardid = args.standardid
474 comm = GoodFETMCPCANCommunication();
476 ##########################
478 ##########################
480 # Prints MCP state info
482 if(args.verb=="info"):
486 ##########################
488 ##########################
492 if(args.verb=="reset"):
495 ##########################
497 ##########################
499 # runs in ListenOnly mode
500 # utility function to pull info off the car's CAN bus
503 if(args.verb=="sniff"):
504 comm.sniff(freq=freq,duration=duration,description=description,verbose=verbose,comment=comments,filename=filename, standardid=standardid, debug=debug, faster=faster)
506 ##########################
508 ##########################
510 # runs in NORMAL mode
511 # intended for NETWORKED MCP chips to verify proper operation
514 if(args.verb=="snifftest"):
515 comm.sniffTest(freq=freq)
518 ##########################
520 ##########################
522 # runs in LISTEN ONLY mode
523 # tests bus for desired frequency --> sniffs bus for specified length of time and reports
524 # if packets were properly formatted
528 if(args.verb=="freqtest"):
529 comm.freqtest(freq=freq)
533 ##########################
535 ##########################
537 # """ An intelligent sniffer, decodes message format """
538 # """ More features to be added soon """
539 if(args.verb=="isniff"):
540 comm.isniff(freq=freq)
543 ##########################
545 ##########################
547 # Runs in LOOPBACK mode
548 # self-check diagnostic
549 # wasn't working before due to improperly formatted packet
551 # ...add automatic packet check rather than making user verify successful packet
552 if(args.verb=="test"):
555 if(args.verb=="peek"):
558 start=int(sys.argv[2],16);
561 stop=int(sys.argv[3],16);
562 print "Peeking from %04x to %04x." % (start,stop);
564 print "%04x: %02x" % (start,client.peek8(start));
567 ##########################
569 ##########################
571 # Basic packet transmission
572 # runs in NORMAL MODE!
574 # checking TX error flags--> currently throwing error flags on every
575 # transmission (travis thinks this is because we're sniffing in listen-only
576 # and thus not generating an ack bit on the recieving board)
577 if(args.verb=="spit"):
578 comm.spit(freq=freq, standardid=standardid, debug=debug)