Added the option to automatically re-inject packets that we have fuzzed and injected...
[goodfet] / client / GoodFETMCPCANCommunication.py
1 #!/usr/bin/env python
2 # GoodFET SPI Flash Client
3 #
4 # (C) 2012 Travis Goodspeed <travis at radiantmachines.com>
5 #
6 #
7 # Ted's working copy
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
11 #
12 #
13
14 import sys;
15 import binascii;
16 import array;
17 import csv, time, argparse;
18 import datetime
19 import os
20 from random import randrange
21 from GoodFETMCPCAN import GoodFETMCPCAN;
22 from intelhex import IntelHex;
23 import Queue
24
25 class GoodFETMCPCANCommunication:
26     
27     def __init__(self):
28        self.client=GoodFETMCPCAN();
29        self.client.serInit()
30        self.client.MCPsetup();
31        self.DATALOCATION = "../../contrib/ThayerData/"
32        self.INJECTDATALOCATION  = self.DATALOCATION+"InjectedData/"
33        
34
35     
36     def printInfo(self):
37         
38         self.client.MCPreqstatConfiguration();
39         
40         print "MCP2515 Info:\n\n";
41         
42         print "Mode: %s" % self.client.MCPcanstatstr();
43         print "Read Status: %02x" % self.client.MCPreadstatus();
44         print "Rx Status:   %02x" % self.client.MCPrxstatus();
45         print "Error Flags:  %02x" % self.client.peek8(0x2D);
46         print "Tx Errors:  %3d" % self.client.peek8(0x1c);
47         print "Rx Errors:  %3d\n" % self.client.peek8(0x1d);
48         
49         print "Timing Info:";
50         print "CNF1: %02x" %self.client.peek8(0x2a);
51         print "CNF2: %02x" %self.client.peek8(0x29);
52         print "CNF3: %02x\n" %self.client.peek8(0x28);
53         print "RXB0 CTRL: %02x" %self.client.peek8(0x60);
54         print "RXB1 CTRL: %02x" %self.client.peek8(0x70);
55         
56         print "RX Info:";
57         print "RXB0: %02x" %self.client.peek8(0x60);
58         print "RXB1: %02x" %self.client.peek8(0x70);
59         print "RXB0 masks: %02x, %02x, %02x, %02x" %(self.client.peek8(0x20), self.client.peek8(0x21), self.client.peek8(0x22), self.client.peek8(0x23));
60         print "RXB1 masks: %02x, %02x, %02x, %02x" %(self.client.peek8(0x24), self.client.peek8(0x25), self.client.peek8(0x26), self.client.peek8(0x27));
61
62         
63         print "RX Buffers:"
64         packet0=self.client.readrxbuffer(0);
65         packet1=self.client.readrxbuffer(1);
66         for foo in [packet0, packet1]:
67            print self.client.packet2str(foo);
68            
69     def reset(self):
70         self.client.MCPsetup();
71     
72     
73     ##########################
74     #   SNIFF
75     ##########################
76          
77     def sniff(self,freq,duration,description, verbose=True, comment=None, filename=None, standardid=None, debug=False, faster=False, parsed=True, data = None,writeToFile=True):
78         
79         #reset eveything on the chip
80         self.client.serInit() 
81         self.reset()
82           
83         #### ON-CHIP FILTERING
84         if(standardid != None):
85             if( comment == None):
86                 comment = ""
87             self.client.MCPreqstatConfiguration();  
88             self.client.poke8(0x60,0x26); # set RXB0 CTRL register to ONLY accept STANDARD messages with filter match (RXM1=0, RMX0=1, BUKT=1)
89             self.client.poke8(0x20,0xFF); #set buffer 0 mask 1 (SID 10:3) to FF
90             self.client.poke8(0x21,0xE0); #set buffer 0 mask 2 bits 7:5 (SID 2:0) to 1s
91             if(len(standardid)>2):
92                self.client.poke8(0x70,0x20); # set RXB1 CTRL register to ONLY accept STANDARD messages with filter match (RXM1=0, RMX0=1)
93                self.client.poke8(0x24,0xFF); #set buffer 1 mask 1 (SID 10:3) to FF
94                self.client.poke8(0x25,0xE0); #set buffer 1 mask 2 bits 7:5 (SID 2:0) to 1s 
95             
96             for filter,ID in enumerate(standardid):
97         
98                if (filter==0):
99                 RXFSIDH = 0x00;
100                 RXFSIDL = 0x01;
101                elif (filter==1):
102                 RXFSIDH = 0x04;
103                 RXFSIDL = 0x05;
104                elif (filter==2):
105                 RXFSIDH = 0x08;
106                 RXFSIDL = 0x09;
107                elif (filter==3):
108                 RXFSIDH = 0x10;
109                 RXFSIDL = 0x11;
110                elif (filter==4):
111                 RXFSIDH = 0x14;
112                 RXFSIDL = 0x15;
113                else:
114                 RXFSIDH = 0x18;
115                 RXFSIDL = 0x19;
116         
117                #### split SID into different regs
118                SIDlow = (ID & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
119                SIDhigh = (ID >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
120                
121                #write SID to regs 
122                self.client.poke8(RXFSIDH,SIDhigh);
123                self.client.poke8(RXFSIDL, SIDlow);
124         
125                if (verbose == True):
126                    print "Filtering for SID %d (0x%02xh) with filter #%d"%(ID, ID, filter);
127                comment += ("f%d" %(ID))
128         
129         
130         self.client.MCPsetrate(freq);
131         
132         # This will handle the files so that we do not loose them. each day we will create a new csv file
133         if( filename==None and writeToFile == True):
134             #get folder information (based on today's date)
135             now = datetime.datetime.now()
136             datestr = now.strftime("%Y%m%d")
137             path = self.DATALOCATION+datestr+".csv"
138             filename = path
139             
140         if( writeToFile == True):
141             outfile = open(filename,'a');
142             dataWriter = csv.writer(outfile,delimiter=',');
143             dataWriter.writerow(['# Time     Error        Bytes 1-13']);
144             dataWriter.writerow(['#' + description])
145             
146         self.client.MCPreqstatNormal();
147         print "Listening...";
148         packetcount = 0;
149         starttime = time.time();
150         
151         while((time.time()-starttime < duration)):
152             
153             if(faster):
154                 packet=self.client.fastrxpacket();
155             else:
156                 packet=self.client.rxpacket();
157                 
158             #add the data to list if the pointer was included
159             if(data != None and packet != None):
160                 #data.append(self.client.packet2parsedstr(packet))
161                 packetParsed = self.client.packet2parsed(packet)
162                 packetParsed["time"] =time.time()
163                 data.put(packetParsed)
164             if(debug == True):
165                 #check packet status
166                 MCPstatusReg = self.client.MCPrxstatus();
167                 messagestat=MCPstatusReg&0xC0;
168                 messagetype=MCPstatusReg&0x18;
169                 if(messagestat == 0xC0):
170                     print "Message in both buffers; message type is %02x (0x00 is standard data, 0x08 is standard remote)." %messagetype
171                 elif(messagestat == 0x80):
172                     print "Message in RXB1; message type is %02x (0x00 is standard data, 0x08 is standard remote)." %messagetype
173                 elif(messagestat == 0x40):
174                     print "Message in RXB0; message type is %02x (0x00 is standard data, 0x08 is standard remote)." %messagetype
175                 elif(messagestat == 0x00):
176                     print "No messages in buffers."
177             #check to see if there was a packet
178             if( packet != None):
179                 packetcount+=1;
180             if (packet!=None and writeToFile == True):
181                 
182                 row = [];
183                 row.append("%f"%time.time());
184                 
185                 if( verbose==True):
186                     #if we want to print a parsed message
187                     if( parsed == True):
188                         packetParsed = self.client.packet2parsed(packet)
189                         sId = packetParsed.get('sID')
190                         msg = "sID: %04d" %sId
191                         if( packetParsed.get('eID')):
192                             msg += " eID: %d" %packetParsed.get('eID')
193                         msg += " rtr: %d"%packetParsed['rtr']
194                         length = packetParsed['length']
195                         msg += " length: %d"%length
196                         msg += " data:"
197                         for i in range(0,length):
198                             dbidx = 'db%d'%i
199                             msg +=" %03d"% ord(packetParsed[dbidx])
200                         #msg = self.client.packet2parsedstr(packet)
201                         print msg
202                     # if we want to print just the message as it is read off the chip
203                     else:
204                         print self.client.packet2str(packet)
205                 
206                 if(debug == True):
207                     
208                     #check overflow
209                     MCPeflgReg=self.client.peek8(0x2D);
210                     print"EFLG register equals: %x" %MCPeflgReg;
211                     if((MCPeflgReg & 0xC0)==0xC0):
212                         print "WARNING: BOTH overflow flags set. Missed a packet. Clearing and proceeding."
213                     elif(MCPeflgReg & 0x80):
214                         print "WARNING: RXB1 overflow flag set. A packet has been missed. Clearing and proceeding."
215                     elif(MCPeflgReg & 0x40):
216                         print "WARNING: RXB0 overflow flag set. A packet has been missed. Clearing and proceeding."
217                     self.client.MCPbitmodify(0x2D,0xC0,0x00);
218                     print"EFLG register set to: %x" % self.client.peek(0x2D);
219                 
220                     #check for errors
221                     if (self.client.peek8(0x2C) & 0x80):
222                         self.client.MCPbitmodify(0x2C,0x80,0x00);
223                         print "ERROR: Malformed packet recieved: " + self.client.packet2str(packet);
224                         row.append(1);
225                     else:
226                         row.append(0);
227                 else:
228                     row.append(0);  #since we don't check for errors if we're not in debug mode...
229                             
230                 row.append(comment)
231                 #how long the sniff was for
232                 row.append(duration)
233                 #boolean that tells us if there was filtering. 0 == no filters, 1 == filters
234                 if(standardid != None):
235                     row.append(1)
236                 else:
237                     row.append(0)
238                 #write packet to file
239                 for byte in packet:
240                     row.append("%02x"%ord(byte));
241                 dataWriter.writerow(row);
242         if(writeToFile == True):
243             outfile.close()
244         print "Listened for %d seconds, captured %d packets." %(duration,packetcount);
245         return packetcount
246         
247         
248 #    def filterStdSweep(self, freq, low, high, time = 5):
249 #        msgIDs = []
250 #        self.client.serInit()
251 #        self.client.MCPsetup()
252 #        for i in range(low, high+1, 6):
253 #            print "sniffing id: %d, %d, %d, %d, %d, %d" % (i,i+1,i+2,i+3,i+4,i+5)
254 #            comment= "sweepFilter: "
255 #            #comment = "sweepFilter_%d_%d_%d_%d_%d_%d" % (i,i+1,i+2,i+3,i+4,i+5)
256 #            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)
257 #            count = self.sniff(freq=freq, duration = time, description = description,comment = comment, standardid = [i, i+1, i+2, i+3, i+4, i+5])
258 #            if( count != 0):
259 #                for j in range(i,i+5):
260 #                    comment = "sweepFilter: "
261 #                    #comment = "sweepFilter: %d" % (j)
262 #                    description = "Running a sweep filer for all the possible standard IDs. This run filters for: %d " % j
263 #                    count = self.sniff(freq=freq, duration = time, description = description,comment = comment, standardid = [j, j, j, j])
264 #                    if( count != 0):
265 #                        msgIDs.append(j)
266 #        return msgIDs
267     
268 #    def sweepRandom(self, freq, number = 5, time = 200):
269 #        msgIDs = []
270 #        ids = []
271 #        self.client.serInit()
272 #        self.client.MCPsetup()
273 #        for i in range(0,number+1,6):
274 #            idsTemp = []
275 #            comment = "sweepFilter: "
276 #            for j in range(0,6,1):
277 #                id = randrange(2047)
278 #                #comment += "_%d" % id
279 #                idsTemp.append(id)
280 #                ids.append(id)
281 #            print comment
282 #            description = "Running a sweep filer for all the possible standard IDs. This runs the following : " + comment
283 #            count = self.sniff(freq=freq, duration=time, description=description, comment = comment, standardid = idsTemp)
284 #            if( count != 0):
285 #                for element in idsTemp:
286 #                    #comment = "sweepFilter: %d" % (element)
287 #                    comment="sweepFilter: "
288 #                    description = "Running a sweep filer for all the possible standard IDs. This run filters for: %d " % element
289 #                    count = self.sniff(freq=freq, duration = time, description = description,comment = comment, standardid = [element, element, element])
290 #                    if( count != 0):
291 #                        msgIDs.append(j)
292 #        return msgIDs, ids
293     
294     def sniffTest(self, freq):
295         
296         rate = freq;
297         
298         print "Calling MCPsetrate for %i." %rate;
299         self.client.MCPsetrate(rate);
300         self.client.MCPreqstatNormal();
301         
302         print "Mode: %s" % self.client.MCPcanstatstr();
303         print "CNF1: %02x" %self.client.peek8(0x2a);
304         print "CNF2: %02x" %self.client.peek8(0x29);
305         print "CNF3: %02x\n" %self.client.peek8(0x28);
306         
307         while(1):
308             packet=self.client.rxpacket();
309             
310             if packet!=None:                
311                 if (self.client.peek8(0x2C) & 0x80):
312                     self.client.MCPbitmodify(0x2C,0x80,0x00);
313                     print "malformed packet recieved: "+ self.client.packet2str(packet);
314                 else:
315                     print "properly formatted packet recieved" + self.client.packet2str(packet);
316    
317     
318     def freqtest(self,freq):
319         
320         self.client.MCPsetup();
321
322         self.client.MCPsetrate(freq);
323         self.client.MCPreqstatListenOnly();
324     
325         print "CAN Freq Test: %3d kHz" %freq;
326     
327         x = 0;
328         errors = 0;
329     
330         starttime = time.time();
331         while((time.time()-starttime < args.time)):
332             packet=self.client.rxpacket();
333             if packet!=None:
334                 x+=1;
335                 
336                 if (self.client.peek8(0x2C) & 0x80):
337                     print "malformed packet recieved"
338                     errors+=1;
339                     self.client.MCPbitmodify(0x2C,0x80,0x00);
340                 else:         
341                     print self.client.packet2str(packet);
342     
343         print "Results for %3.1d kHz: recieved %3d packets, registered %3d RX errors." %(freq, x, errors);
344     
345
346     def isniff(self,freq):
347         """ An intelligent sniffer, decodes message format """
348         """ More features to be added soon """
349         
350         self.client.MCPsetrate(freq);
351         self.client.MCPreqstatListenOnly();
352         while 1:
353             packet=self.client.rxpacket();
354             if packet!=None:
355                 plist=[];
356                 for byte in packet:
357                     plist.append(byte);
358                 arbid=plist[0:2];
359                 eid=plist[2:4];
360                 dlc=plist[4:5];
361                 data=plist[5:13];         
362                 print "\nArbID: " + self.client.packet2str(arbid);
363                 print "EID: " + self.client.packet2str(eid);
364                 print "DLC: " + self.client.packet2str(dlc);
365                 print "Data: " + self.client.packet2str(data);
366
367     def test(self):
368         
369         comm.reset();
370         print "Just reset..."
371         print "EFLG register:  %02x" % self.client.peek8(0x2d);
372         print "Tx Errors:  %3d" % self.client.peek8(0x1c);
373         print "Rx Errors:  %3d" % self.client.peek8(0x1d);
374         print "CANINTF: %02x"  %self.client.peek8(0x2C);
375         self.client.MCPreqstatConfiguration();
376         self.client.poke8(0x60,0x66);
377         self.client.MCPsetrate(500);
378         self.client.MCPreqstatNormal();
379         print "In normal mode now"
380         print "EFLG register:  %02x" % self.client.peek8(0x2d);
381         print "Tx Errors:  %3d" % self.client.peek8(0x1c);
382         print "Rx Errors:  %3d" % self.client.peek8(0x1d);
383         print "CANINTF: %02x"  %self.client.peek8(0x2C);
384         print "Waiting on packets.";
385         checkcount = 0;
386         packet=None;
387         while(1):
388             packet=self.client.rxpacket();
389             if packet!=None:
390                 print "Message recieved: %s" % self.client.packet2str(packet);
391             else:
392                 checkcount=checkcount+1;
393                 if (checkcount%30==0):
394                     print "EFLG register:  %02x" % self.client.peek8(0x2d);
395                     print "Tx Errors:  %3d" % self.client.peek8(0x1c);
396                     print "Rx Errors:  %3d" % self.client.peek8(0x1d);
397                     print "CANINTF: %02x"  %self.client.peek8(0x2C);
398
399     
400     
401     
402     def addFilter(self,standardid, verbose= True):
403         comment = None
404         ### ON-CHIP FILTERING
405         if(standardid != None):
406             self.client.MCPreqstatConfiguration();  
407             self.client.poke8(0x60,0x26); # set RXB0 CTRL register to ONLY accept STANDARD messages with filter match (RXM1=0, RMX0=1, BUKT=1)
408             self.client.poke8(0x20,0xFF); #set buffer 0 mask 1 (SID 10:3) to FF
409             self.client.poke8(0x21,0xE0); #set buffer 0 mask 2 bits 7:5 (SID 2:0) to 1s
410             if(len(standardid)>2):
411                self.client.poke8(0x70,0x20); # set RXB1 CTRL register to ONLY accept STANDARD messages with filter match (RXM1=0, RMX0=1)
412                self.client.poke8(0x24,0xFF); #set buffer 1 mask 1 (SID 10:3) to FF
413                self.client.poke8(0x25,0xE0); #set buffer 1 mask 2 bits 7:5 (SID 2:0) to 1s 
414             
415             for filter,ID in enumerate(standardid):
416         
417                if (filter==0):
418                 RXFSIDH = 0x00;
419                 RXFSIDL = 0x01;
420                elif (filter==1):
421                 RXFSIDH = 0x04;
422                 RXFSIDL = 0x05;
423                elif (filter==2):
424                 RXFSIDH = 0x08;
425                 RXFSIDL = 0x09;
426                elif (filter==3):
427                 RXFSIDH = 0x10;
428                 RXFSIDL = 0x11;
429                elif (filter==4):
430                 RXFSIDH = 0x14;
431                 RXFSIDL = 0x15;
432                else:
433                 RXFSIDH = 0x18;
434                 RXFSIDL = 0x19;
435         
436                #### split SID into different regs
437                SIDlow = (ID & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
438                SIDhigh = (ID >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
439                
440                #write SID to regs 
441                self.client.poke8(RXFSIDH,SIDhigh);
442                self.client.poke8(RXFSIDL, SIDlow);
443         
444                if (verbose == True):
445                    print "Filtering for SID %d (0x%02xh) with filter #%d"%(ID, ID, filter);
446                
447         self.client.MCPreqstatNormal();
448     
449     
450    
451         
452     def spitSetup(self,freq):
453         self.reset();
454         self.client.MCPsetrate(freq);
455         self.client.MCPreqstatNormal();
456         
457     
458     def spitSingle(self,freq, standardid, repeat, duration = None, debug = False, packet = None):
459         self.spitSetup(freq);
460         spit(self,freq, standardid, repeat, duration = None, debug = False, packet = None)
461
462     def spit(self,freq, standardid, repeat,writes, period = None, debug = False, packet = None):
463     
464
465         #### split SID into different regs
466         SIDlow = (standardid[0] & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
467         SIDhigh = (standardid[0] >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
468         
469         if(packet == None):
470             
471             # if no packet, RTR for inputted arbID
472             # so packet to transmit is SID + padding out EID registers + RTR request (set bit 6, clear lower nibble of DLC register)
473             packet = [SIDhigh, SIDlow, 0x00,0x00,0x40] 
474         
475         
476                 #packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
477                 #         0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
478                 #        # lower nibble is DLC                   
479                 #        0x00,0x01,0x02,0x03,0x04,0x05,0x06,0xFF]
480         else:
481
482             # if we do have a packet, packet is SID + padding out EID registers + DLC of 8 + packet
483             #
484             #    TODO: allow for variable-length packets
485             #
486             packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
487                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
488                   # lower nibble is DLC                   
489                  packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]]
490             
491         
492         if(debug):
493             if self.client.MCPcanstat()>>5!=0:
494                 print "Warning: currently in %s mode. NOT in normal mode! May not transmit.\n" %self.client.MCPcanstatstr();
495             print "\nInitial state:"
496             print "Tx Errors:  %3d" % self.client.peek8(0x1c);
497             print "Rx Errors:  %3d" % self.client.peek8(0x1d);
498             print "Error Flags:  %02x\n" % self.client.peek8(0x2d);
499             print "TXB0CTRL: %02x" %self.client.peek8(0x30);
500             print "CANINTF: %02x\n"  %self.client.peek8(0x2C);
501             print "\n\nATTEMPTING TRANSMISSION!!!"
502         
503                 
504         print "Transmitting packet: "
505         #print self.client.packet2str(packet)
506                 
507         self.client.txpacket(packet);
508             
509         if repeat:
510             print "\nNow looping on transmit. "
511             if period != None:
512                 for i in range(0,writes):
513                     self.client.MCPrts(TXB0=True);
514                     #tic = time.time()
515                     time.sleep(period/1000) # pause for period ms before sending again
516                     #print time.time()-tic
517                 #starttime = time.time();
518                 #while((time.time()-starttime < duration)):
519                 #    self.client.MCPrts(TXB0=True);
520                 #    print "MSG printed"
521             else:
522                 for i in range(0,writes): 
523                     self.client.MCPrts(TXB0=True);
524         print "messages injected"
525         
526         # MORE DEBUGGING        
527         if(debug): 
528             checkcount = 0;
529             TXB0CTRL = self.client.peek8(0x30);
530         
531             print "Tx Errors:  %3d" % self.client.peek8(0x1c);
532             print "Rx Errors:  %3d" % self.client.peek8(0x1d);
533             print "EFLG register:  %02x" % self.client.peek8(0x2d);
534             print "TXB0CTRL: %02x" %TXB0CTRL;
535             print "CANINTF: %02x\n"  %self.client.peek8(0x2C);
536         
537             while(TXB0CTRL | 0x00 != 0x00):
538                 checkcount+=1;
539                 TXB0CTRL = self.client.peek8(0x30);
540                 if (checkcount %30 ==0):
541                     print "Tx Errors:  %3d" % self.client.peek8(0x1c);
542                     print "Rx Errors:  %3d" % self.client.peek8(0x1d);
543                     print "EFLG register:  %02x" % self.client.peek8(0x2d);
544                     print "TXB0CTRL: %02x" %TXB0CTRL;
545                     print "CANINTF: %02x\n"  %self.client.peek8(0x2C);
546
547
548     def setRate(self,freq):
549         self.client.MCPsetrate(freq);
550         
551
552     # This will write the data provided in the packets which is expected to be a list of lists
553     # of the following form:
554     # for a given row = packets[i]
555     # row[0] time delay relative to the last packet. if 0 or empty there will be no delay
556     # row[1] = Standard ID (integer)
557     # row[2] = Data Length (0-8) (if it is zero we assume an Remote Transmit Request)
558     # row[3] = Data Byte 0
559     # row[4] = Data Byte 1
560     #    .... up to Data Byte 8 ( THIS ASSUMES A PACKET OF LENGTH 8!!!
561     def writeData(self,packets,freq):
562         self.client.serInit()
563         self.spitSetup(freq)
564         for row in packets:
565             if( row[0] != 0 and row[0] != ""):
566                 time.sleep(row[0])
567             sID = row[1]
568             #### split SID into different regs
569             SIDlow = (sID & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
570             SIDhigh = (sID >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
571             packet = [SIDhigh,SIDlow,0x00,0x00,0x08]
572             #dlc = row[2]
573             dlc = 8
574             for i in range(3,dlc+3):
575                 packet.append(row[i])
576             print packet
577             self.client.txpacket(packet)
578                 
579         
580         
581         
582
583 if __name__ == "__main__":  
584
585     parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description='''\
586     
587         Run commands on the MCP2515. Valid commands are:
588         
589             info 
590             test
591             peek 0x(start) [0x(stop)]
592             reset
593             
594             sniff 
595             freqtest
596             snifftest
597             spit
598         ''')
599         
600     
601     parser.add_argument('verb', choices=['info', 'test','peek', 'reset', 'sniff', 'freqtest','snifftest', 'spit']);
602     parser.add_argument('-f', '--freq', type=int, default=500, help='The desired frequency (kHz)', choices=[100, 125, 250, 500, 1000]);
603     parser.add_argument('-t','--time', type=int, default=15, help='The duration to run the command (s)');
604     parser.add_argument('-o', '--output', default=None,help='Output file');
605     parser.add_argument("-d", "--description", help='Description of experiment (included in the output file)', default="");
606     parser.add_argument('-v',"--verbose",action='store_false',help='-v will stop packet output to terminal', default=True);
607     parser.add_argument('-c','--comment', help='Comment attached to ech packet uploaded',default=None);
608     parser.add_argument('-b', '--debug', action='store_true', help='-b will turn on debug mode, printing packet status', default=False);
609     parser.add_argument('-a', '--standardid', type=int, action='append', help='Standard ID to accept with filter 0 [1, 2, 3, 4, 5]', default=None);
610     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);
611     parser.add_argument('-r', '--repeat', action='store_true', help='-r with "spit" will continuously send the inputted packet. This will put the GoodTHOPTHER into an infinite loop.', default=False);
612     
613     
614     args = parser.parse_args();
615     freq = args.freq
616     duration = args.time
617     filename = args.output
618     description = args.description
619     verbose = args.verbose
620     comments = args.comment
621     debug = args.debug
622     standardid = args.standardid
623     faster=args.faster
624     repeat = args.repeat
625
626     comm = GoodFETMCPCANCommunication();
627     
628     ##########################
629     #   INFO
630     ##########################
631     #
632     # Prints MCP state info
633     #
634     if(args.verb=="info"):
635         comm.printInfo()
636         
637            
638     ##########################
639     #   RESET
640     ##########################
641     #
642     #
643             
644     if(args.verb=="reset"):
645         comm.reset()
646         
647     ##########################
648     #   SNIFF
649     ##########################
650     #
651     #   runs in ListenOnly mode
652     #   utility function to pull info off the car's CAN bus
653     #
654     
655     if(args.verb=="sniff"):
656         comm.sniff(freq=freq,duration=duration,description=description,verbose=verbose,comment=comments,filename=filename, standardid=standardid, debug=debug, faster=faster)    
657                     
658     ##########################
659     #   SNIFF TEST
660     ##########################
661     #
662     #   runs in NORMAL mode
663     #   intended for NETWORKED MCP chips to verify proper operation
664     #
665        
666     if(args.verb=="snifftest"):
667         comm.sniffTest(freq=freq)
668         
669         
670     ##########################
671     #   FREQ TEST
672     ##########################
673     #
674     #   runs in LISTEN ONLY mode
675     #   tests bus for desired frequency --> sniffs bus for specified length of time and reports
676     #   if packets were properly formatted
677     #
678     #
679     
680     if(args.verb=="freqtest"):
681         comm.freqtest(freq=freq)
682
683
684
685     ##########################
686     #   iSniff
687     ##########################
688     #
689     #    """ An intelligent sniffer, decodes message format """
690     #    """ More features to be added soon """
691     if(args.verb=="isniff"):
692         comm.isniff(freq=freq)
693                 
694                 
695     ##########################
696     #   MCP TEST
697     ##########################
698     #
699     #   Runs in LOOPBACK mode
700     #   self-check diagnostic
701     #   wasn't working before due to improperly formatted packet
702     #
703     #   ...add automatic packet check rather than making user verify successful packet
704     if(args.verb=="test"):
705         comm.test()
706         
707     if(args.verb=="peek"):
708         start=0x0000;
709         if(len(sys.argv)>2):
710             start=int(sys.argv[2],16);
711         stop=start;
712         if(len(sys.argv)>3):
713             stop=int(sys.argv[3],16);
714         print "Peeking from %04x to %04x." % (start,stop);
715         while start<=stop:
716             print "%04x: %02x" % (start,client.peek8(start));
717             start=start+1;
718             
719     ##########################
720     #   SPIT
721     ##########################
722     #
723     #   Basic packet transmission
724     #   runs in NORMAL MODE!
725     # 
726     #   checking TX error flags--> currently throwing error flags on every
727     #   transmission (travis thinks this is because we're sniffing in listen-only
728     #   and thus not generating an ack bit on the recieving board)
729     if(args.verb=="spit"):
730         comm.spitSingle(freq=freq, standardid=standardid,duration=duration, repeat=repeat, debug=debug)
731
732
733     
734     
735     
736     
737         
738         
739     
740     
741     
742