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