changes to the GoodFETMCPCANCommunication file. to make it reset filters
[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
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):
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 & 0x03) << 5;  # get SID bits 2:0, rotate them to bits 7:5
117                SIDhigh = (ID >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
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 = 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                     print self.client.packet2str(packet)
178                 
179                 if(debug == True):
180                     
181                     #check overflow
182                     MCPeflgReg=self.client.peek8(0x2D);
183                     print"EFLG register equals: %x" %MCPeflgReg;
184                     if((MCPeflgReg & 0xC0)==0xC0):
185                         print "WARNING: BOTH overflow flags set. Missed a packet. Clearing and proceeding."
186                     elif(MCPeflgReg & 0x80):
187                         print "WARNING: RXB1 overflow flag set. A packet has been missed. Clearing and proceeding."
188                     elif(MCPeflgReg & 0x40):
189                         print "WARNING: RXB0 overflow flag set. A packet has been missed. Clearing and proceeding."
190                     self.client.MCPbitmodify(0x2D,0xC0,0x00);
191                     print"EFLG register set to: %x" % self.client.peek(0x2D);
192                 
193                     #check for errors
194                     if (self.client.peek8(0x2C) & 0x80):
195                         self.client.MCPbitmodify(0x2C,0x80,0x00);
196                         print "ERROR: Malformed packet recieved: " + self.client.packet2str(packet);
197                         row.append(1);
198                     else:
199                         row.append(0);
200                 else:
201                     row.append(0);  #since we don't check for errors if we're not in debug mode...
202                             
203                 row.append(comment)
204                 #how long the sniff was for
205                 row.append(duration)
206                 #boolean that tells us if there was filtering. 0 == no filters, 1 == filters
207                 if(standardid != None):
208                     row.append(1)
209                 else:
210                     row.append(0)
211                 #write packet to file
212                 for byte in packet:
213                     row.append("%02x"%ord(byte));
214                 dataWriter.writerow(row);
215         
216         outfile.close()
217         print "Listened for %d seconds, captured %d packets." %(duration,packetcount);
218         return packetcount
219         
220         
221     def filterStdSweep(self, freq, time = 5):
222         msgIDs = []
223         for i in range(0, 2047, 6):
224             print "sniffing id: %d, %d, %d, %d, %d, %d" % (i,i+1,i+2,i+3,i+4,i+5)
225             comment = "sweepFilter_%d_%d_%d_%d_%d_%d" % (i,i+1,i+2,i+3,i+4,i+5)
226             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)
227             count = self.sniff(freq=freq, duration = time, description = description,comment = comment, standardid = [i, i+1, i+2, i+3, i+4, i+5])
228             if( count != 0):
229                 for j in range(i,i+5):
230                     comment = "sweepFilter: %d" % (j)
231                     description = "Running a sweep filer for all the possible standard IDs. This run filters for: %d " % j
232                     count = self.sniff(freq=freq, duration = time, description = description,comment = comment, standardid = [j])
233                     if( count != 0):
234                         msgIDs.append(j)
235         return msgIDs
236     
237     def sniffTest(self, freq):
238         
239         rate = freq;
240         
241         print "Calling MCPsetrate for %i." %rate;
242         self.client.MCPsetrate(rate);
243         self.client.MCPreqstatNormal();
244         
245         print "Mode: %s" % self.client.MCPcanstatstr();
246         print "CNF1: %02x" %self.client.peek8(0x2a);
247         print "CNF2: %02x" %self.client.peek8(0x29);
248         print "CNF3: %02x\n" %self.client.peek8(0x28);
249         
250         while(1):
251             packet=self.client.rxpacket();
252             
253             if packet!=None:                
254                 if (self.client.peek8(0x2C) & 0x80):
255                     self.client.MCPbitmodify(0x2C,0x80,0x00);
256                     print "malformed packet recieved: "+ self.client.packet2str(packet);
257                 else:
258                     print "properly formatted packet recieved" + self.client.packet2str(packet);
259    
260     
261     def freqtest(self,freq):
262         self.client.MCPsetup();
263
264         self.client.MCPsetrate(freq);
265         self.client.MCPreqstatListenOnly();
266     
267         print "CAN Freq Test: %3d kHz" %freq;
268     
269         x = 0;
270         errors = 0;
271     
272         starttime = time.time();
273         while((time.time()-starttime < args.time)):
274             packet=self.client.rxpacket();
275             if packet!=None:
276                 x+=1;
277                 
278                 if (self.client.peek8(0x2C) & 0x80):
279                     print "malformed packet recieved"
280                     errors+=1;
281                     self.client.MCPbitmodify(0x2C,0x80,0x00);
282                 else:         
283                     print self.client.packet2str(packet);
284     
285         print "Results for %3.1d kHz: recieved %3d packets, registered %3d RX errors." %(freq, x, errors);
286     
287
288     def isniff(self,freq):
289         """ An intelligent sniffer, decodes message format """
290         """ More features to be added soon """
291         
292         self.client.MCPsetrate(freq);
293         self.client.MCPreqstatListenOnly();
294         while 1:
295             packet=self.client.rxpacket();
296             if packet!=None:
297                 plist=[];
298                 for byte in packet:
299                     plist.append(byte);
300                 arbid=plist[0:2];
301                 eid=plist[2:4];
302                 dlc=plist[4:5];
303                 data=plist[5:13];         
304                 print "\nArbID: " + self.client.packet2str(arbid);
305                 print "EID: " + self.client.packet2str(eid);
306                 print "DLC: " + self.client.packet2str(dlc);
307                 print "Data: " + self.client.packet2str(data);
308
309     def test(self):
310         print "\nMCP2515 Self Test:";
311         
312         #Switch to config mode and try to rewrite TEC.
313         self.client.MCPreqstatConfiguration();
314         self.client.poke8(0x00,0xde);
315         if self.client.peek8(0x00)!=0xde:
316             print "ERROR: Poke to TEC failed.";
317         else:
318             print "SUCCESS: Register read/write.";
319         
320         #Switch to Loopback mode and try to catch our own packet.
321         self.client.MCPreqstatLoopback();
322     
323         packet1 = [0x00, 
324                    0x08, # LOWER nibble must be 8 or greater to set EXTENDED ID 
325                    0x00, 0x00,
326                    0x08, # UPPER nibble must be 0 to set RTR bit for DATA FRAME
327                          # LOWER nibble is DLC
328                    0x01,0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xFF]
329         self.client.txpacket(packet1);
330         self.client.txpacket(packet1);
331         print "Waiting on loopback packets.";
332         packet=None;
333         while(1):
334             packet=self.client.rxpacket();
335             if packet!=None:
336                 print "Message recieved: %s" % self.client.packet2str(packet);
337                 break;
338     
339         
340     def spit(self,freq, standardid,debug):
341         
342         comm.reset();
343         self.client.MCPsetrate(freq);
344         self.client.MCPreqstatNormal();
345         
346         if(debug==True):
347             print "\n\nATTEMPTING TRANSMISSION!!!"
348             print "Tx Errors:  %3d" % self.client.peek8(0x1c);
349             print "Rx Errors:  %3d" % self.client.peek8(0x1d);
350             print "Error Flags:  %02x\n" % self.client.peek8(0x2d);
351             print "TXB0CTRL: %02x" %self.client.peek8(0x30);
352             print "CANINTF: %02x\n"  %self.client.peek8(0x2C);
353     
354         #### split SID into different regs
355         SIDlow = (standardid[0] & 0x03) << 5;  # get SID bits 2:0, rotate them to bits 7:5
356         SIDhigh = (standardid[0] >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
357         
358         packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
359                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
360                   # lower nibble is DLC                   
361                   0x01,0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xFF]    
362         
363         self.client.txpacket(packet);
364         
365         TXB0CTRL = self.client.peek8(0x30);
366         
367         print "Tx Errors:  %3d" % self.client.peek8(0x1c);
368         print "Rx Errors:  %3d" % self.client.peek8(0x1d);
369         print "Error Flags:  %02x\n" % self.client.peek8(0x2d);
370         print "TXB0CTRL: %02x" %self.client.peek8(0x30);
371         self.client.MCPbitmodify(0x30,0x08,0x00);
372         print "TXB0CTRL modified to: %02x\n" %self.client.peek8(0x30);
373         
374         print "CANINTF: %02x"  %self.client.peek8(0x2C);
375         self.client.MCPbitmodify(0x2C,0x80,0x00);
376         print "INT Flags modified to:  %02x\n" % self.client.peek8(0x2c);
377
378         
379
380
381
382 if __name__ == "__main__":  
383
384     parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description='''\
385     
386         Run commands on the MCP2515. Valid commands are:
387         
388             info 
389             test
390             peek 0x(start) [0x(stop)]
391             reset
392             
393             sniff 
394             freqtest
395             snifftest
396             spit
397         ''')
398         
399     
400     parser.add_argument('verb', choices=['info', 'test','peek', 'reset', 'sniff', 'freqtest','snifftest', 'spit']);
401     parser.add_argument('-f', '--freq', type=int, default=500, help='The desired frequency (kHz)', choices=[100, 125, 250, 500, 1000]);
402     parser.add_argument('-t','--time', type=int, default=15, help='The duration to run the command (s)');
403     parser.add_argument('-o', '--output', default=None,help='Output file');
404     parser.add_argument("-d", "--description", help='Description of experiment (included in the output file)', default="");
405     parser.add_argument('-v',"--verbose",action='store_false',help='-v will stop packet output to terminal', default=True);
406     parser.add_argument('-c','--comment', help='Comment attached to ech packet uploaded',default=None);
407     parser.add_argument('-b', '--debug', action='store_true', help='-b will turn on debug mode, printing packet status', default=False);
408     parser.add_argument('-a', '--standardid', type=int, action='append', help='Standard ID to accept with filter 0 [1, 2, 3, 4, 5]', default=None);
409     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);
410
411     
412     args = parser.parse_args();
413     freq = args.freq
414     duration = args.time
415     filename = args.output
416     description = args.description
417     verbose = args.verbose
418     comments = args.comment
419     debug = args.debug
420     standardid = args.standardid
421     faster=args.faster
422
423     comm = GoodFETMCPCANCommunication();
424     
425     ##########################
426     #   INFO
427     ##########################
428     #
429     # Prints MCP state info
430     #
431     if(args.verb=="info"):
432         comm.printInfo()
433         
434            
435     ##########################
436     #   RESET
437     ##########################
438     #
439     #
440             
441     if(args.verb=="reset"):
442         comm.reset()
443         
444     ##########################
445     #   SNIFF
446     ##########################
447     #
448     #   runs in ListenOnly mode
449     #   utility function to pull info off the car's CAN bus
450     #
451     
452     if(args.verb=="sniff"):
453         comm.sniff(freq=freq,duration=duration,description=description,verbose=verbose,comment=comments,filename=filename, standardid=standardid, debug=debug, faster=faster)    
454                     
455     ##########################
456     #   SNIFF TEST
457     ##########################
458     #
459     #   runs in NORMAL mode
460     #   intended for NETWORKED MCP chips to verify proper operation
461     #
462        
463     if(args.verb=="snifftest"):
464         comm.sniffTest(freq=freq)
465         
466         
467     ##########################
468     #   FREQ TEST
469     ##########################
470     #
471     #   runs in LISTEN ONLY mode
472     #   tests bus for desired frequency --> sniffs bus for specified length of time and reports
473     #   if packets were properly formatted
474     #
475     #
476     
477     if(args.verb=="freqtest"):
478         comm.freqtest(freq=freq)
479
480
481
482     ##########################
483     #   iSniff
484     ##########################
485     #
486     #    """ An intelligent sniffer, decodes message format """
487     #    """ More features to be added soon """
488     if(args.verb=="isniff"):
489         comm.isniff(freq=freq)
490                 
491                 
492     ##########################
493     #   MCP TEST
494     ##########################
495     #
496     #   Runs in LOOPBACK mode
497     #   self-check diagnostic
498     #   wasn't working before due to improperly formatted packet
499     #
500     #   ...add automatic packet check rather than making user verify successful packet
501     if(args.verb=="test"):
502         comm.test()
503         
504     if(args.verb=="peek"):
505         start=0x0000;
506         if(len(sys.argv)>2):
507             start=int(sys.argv[2],16);
508         stop=start;
509         if(len(sys.argv)>3):
510             stop=int(sys.argv[3],16);
511         print "Peeking from %04x to %04x." % (start,stop);
512         while start<=stop:
513             print "%04x: %02x" % (start,client.peek8(start));
514             start=start+1;
515             
516     ##########################
517     #   SPIT
518     ##########################
519     #
520     #   Basic packet transmission
521     #   runs in NORMAL MODE!
522     # 
523     #   checking TX error flags--> currently throwing error flags on every
524     #   transmission (travis thinks this is because we're sniffing in listen-only
525     #   and thus not generating an ack bit on the recieving board)
526     if(args.verb=="spit"):
527         comm.spit(freq=freq, standardid=standardid, debug=debug)
528
529
530     
531     
532     
533     
534         
535         
536     
537     
538     
539