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