added fast packet sniffing option -x. doubles RX speed but could easily result in...
[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         #### ON-CHIP FILTERING
78         if(standardid != None):
79             comment = comment+"Filtering for SID ";
80             
81             self.client.MCPreqstatConfiguration();  
82             self.client.poke8(0x60,0x26); # set RXB0 CTRL register to ONLY accept STANDARD messages with filter match (RXM1=0, RMX0=1, BUKT=1)
83             self.client.poke8(0x20,0xFF); #set buffer 0 mask 1 (SID 10:3) to FF
84             self.client.poke8(0x21,0xE0); #set buffer 0 mask 2 bits 7:5 (SID 2:0) to 1s
85             if(len(standardid)>2):
86                self.client.poke8(0x70,0x20); # set RXB1 CTRL register to ONLY accept STANDARD messages with filter match (RXM1=0, RMX0=1)
87                self.client.poke8(0x24,0xFF); #set buffer 1 mask 1 (SID 10:3) to FF
88                self.client.poke8(0x25,0xE0); #set buffer 1 mask 2 bits 7:5 (SID 2:0) to 1s 
89             
90             for filter,ID in enumerate(standardid):
91         
92                if (filter==0):
93                 RXFSIDH = 0x00;
94                 RXFSIDL = 0x01;
95                elif (filter==1):
96                 RXFSIDH = 0x04;
97                 RXFSIDL = 0x05;
98                elif (filter==2):
99                 RXFSIDH = 0x08;
100                 RXFSIDL = 0x09;
101                elif (filter==3):
102                 RXFSIDH = 0x10;
103                 RXFSIDL = 0x11;
104                elif (filter==4):
105                 RXFSIDH = 0x14;
106                 RXFSIDL = 0x15;
107                else:
108                 RXFSIDH = 0x18;
109                 RXFSIDL = 0x19;
110         
111                #### split SID into different regs
112                SIDlow = (ID & 0x03) << 5;  # get SID bits 2:0, rotate them to bits 7:5
113                SIDhigh = (ID >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
114                
115                #write SID to regs 
116                self.client.poke8(RXFSIDH,SIDhigh);
117                self.client.poke8(RXFSIDL, SIDlow);
118         
119                if (verbose == True):
120                 print "Filtering for SID %d (0x%02xh) with filter #%d"%(ID, ID, filter);
121             comment = comment + ("%d " %(ID))
122         
123         
124         self.client.MCPsetrate(freq);
125         
126         # This will handle the files so that we do not loose them. each day we will create a new csv file
127         if( filename==None):
128             #get folder information (based on today's date)
129             now = datetime.datetime.now()
130             datestr = now.strftime("%Y%m%d")
131             path = self.DATALOCATION+datestr+".csv"
132             filename = path
133             
134         
135         outfile = open(filename,'a');
136         dataWriter = csv.writer(outfile,delimiter=',');
137         dataWriter.writerow(['# Time     Error        Bytes 1-13']);
138         dataWriter.writerow(['#' + description])
139         
140         self.client.MCPreqstatNormal();
141         print "Listening...";
142         packetcount = 0;
143         starttime = time.time();
144         
145         while((time.time()-starttime < duration)):
146             
147             if(faster):
148                 packet=self.client.fastrxpacket();
149             else:
150                 packet=self.client.rxpacket();
151             
152             if(debug == True):
153                 #check packet status
154                 MCPstatusReg = self.client.MCPrxstatus();
155                 messagestat=MCPstatusReg&0xC0;
156                 messagetype=MCPstatusReg&0x18;
157                 if(messagestat == 0xC0):
158                     print "Message in both buffers; message type is %02x (0x00 is standard data, 0x08 is standard remote)." %messagetype
159                 elif(messagestat == 0x80):
160                     print "Message in RXB1; message type is %02x (0x00 is standard data, 0x08 is standard remote)." %messagetype
161                 elif(messagestat == 0x40):
162                     print "Message in RXB0; message type is %02x (0x00 is standard data, 0x08 is standard remote)." %messagetype
163                 elif(messagestat == 0x00):
164                     print "No messages in buffers."
165             
166             if packet!=None:
167                 
168                 packetcount+=1;
169                 row = [];
170                 row.append("%f"%time.time());
171                 
172                 if( verbose==True):
173                     print self.client.packet2str(packet)
174                 
175                 if(debug == True):
176                     
177                     #check overflow
178                     MCPeflgReg=self.client.peek8(0x2D);
179                     print"EFLG register equals: %x" %MCPeflgReg;
180                     if((MCPeflgReg & 0xC0)==0xC0):
181                         print "WARNING: BOTH overflow flags set. Missed a packet. Clearing and proceeding."
182                     elif(MCPeflgReg & 0x80):
183                         print "WARNING: RXB1 overflow flag set. A packet has been missed. Clearing and proceeding."
184                     elif(MCPeflgReg & 0x40):
185                         print "WARNING: RXB0 overflow flag set. A packet has been missed. Clearing and proceeding."
186                     self.client.MCPbitmodify(0x2D,0xC0,0x00);
187                     print"EFLG register set to: %x" % self.client.peek(0x2D);
188                 
189                     #check for errors
190                     if (self.client.peek8(0x2C) & 0x80):
191                         self.client.MCPbitmodify(0x2C,0x80,0x00);
192                         print "ERROR: Malformed packet recieved: " + self.client.packet2str(packet);
193                         row.append(1);
194                     else:
195                         row.append(0);
196                 else:
197                     row.append(0);  #since we don't check for errors if we're not in debug mode...
198                             
199                 row.append(comment)
200                 #write packet to file
201                 for byte in packet:
202                     row.append("%02x"%ord(byte));
203                 dataWriter.writerow(row);
204         
205         outfile.close()
206         print "Listened for %d seconds, captured %d packets." %(duration,packetcount);
207         return packetcount
208         
209         
210     def filterStdSweep(self, freq, time = 5):
211         msgIDs = []
212         for i in range(0, 2047, 6):
213             print "sniffing id: %d, %d, %d, %d, %d, %d" % (i,i+1,i+2,i+3,i+4,i+5)
214             comment = "sweepFilter_%d_%d_%d_%d_%d_%d" % (i,i+1,i+2,i+3,i+4,i+5)
215             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)
216             count = self.sniff(freq=freq, duration = time, description = description,comment = comment, standardid = [i, i+1, i+2, i+3, i+4, i+5])
217             if( count != 0):
218                 for j in range(i,i+5):
219                     comment = "sweepFilter: %d" % (j)
220                     description = "Running a sweep filer for all the possible standard IDs. This run filters for: %d " % j
221                     count = self.sniff(freq=freq, duration = time, description = description,comment = comment, standardid = [j])
222                     if( count != 0):
223                         msgIDs.append(j)
224         return msgIDs
225     
226     def sniffTest(self, freq):
227         
228         rate = freq;
229         
230         print "Calling MCPsetrate for %i." %rate;
231         self.client.MCPsetrate(rate);
232         self.client.MCPreqstatNormal();
233         
234         print "Mode: %s" % self.client.MCPcanstatstr();
235         print "CNF1: %02x" %self.client.peek8(0x2a);
236         print "CNF2: %02x" %self.client.peek8(0x29);
237         print "CNF3: %02x\n" %self.client.peek8(0x28);
238         
239         while(1):
240             packet=self.client.rxpacket();
241             
242             if packet!=None:                
243                 if (self.client.peek8(0x2C) & 0x80):
244                     self.client.MCPbitmodify(0x2C,0x80,0x00);
245                     print "malformed packet recieved: "+ self.client.packet2str(packet);
246                 else:
247                     print "properly formatted packet recieved" + self.client.packet2str(packet);
248    
249     
250     def freqtest(self,freq):
251         self.client.MCPsetup();
252
253         self.client.MCPsetrate(freq);
254         self.client.MCPreqstatListenOnly();
255     
256         print "CAN Freq Test: %3d kHz" %freq;
257     
258         x = 0;
259         errors = 0;
260     
261         starttime = time.time();
262         while((time.time()-starttime < args.time)):
263             packet=self.client.rxpacket();
264             if packet!=None:
265                 x+=1;
266                 
267                 if (self.client.peek8(0x2C) & 0x80):
268                     print "malformed packet recieved"
269                     errors+=1;
270                     self.client.MCPbitmodify(0x2C,0x80,0x00);
271                 else:         
272                     print self.client.packet2str(packet);
273     
274         print "Results for %3.1d kHz: recieved %3d packets, registered %3d RX errors." %(freq, x, errors);
275     
276
277     def isniff(self,freq):
278         """ An intelligent sniffer, decodes message format """
279         """ More features to be added soon """
280         
281         self.client.MCPsetrate(freq);
282         self.client.MCPreqstatListenOnly();
283         while 1:
284             packet=self.client.rxpacket();
285             if packet!=None:
286                 plist=[];
287                 for byte in packet:
288                     plist.append(byte);
289                 arbid=plist[0:2];
290                 eid=plist[2:4];
291                 dlc=plist[4:5];
292                 data=plist[5:13];         
293                 print "\nArbID: " + self.client.packet2str(arbid);
294                 print "EID: " + self.client.packet2str(eid);
295                 print "DLC: " + self.client.packet2str(dlc);
296                 print "Data: " + self.client.packet2str(data);
297
298     def test(self):
299         print "\nMCP2515 Self Test:";
300         
301         #Switch to config mode and try to rewrite TEC.
302         self.client.MCPreqstatConfiguration();
303         self.client.poke8(0x00,0xde);
304         if self.client.peek8(0x00)!=0xde:
305             print "ERROR: Poke to TEC failed.";
306         else:
307             print "SUCCESS: Register read/write.";
308         
309         #Switch to Loopback mode and try to catch our own packet.
310         self.client.MCPreqstatLoopback();
311     
312         packet1 = [0x00, 
313                    0x08, # LOWER nibble must be 8 or greater to set EXTENDED ID 
314                    0x00, 0x00,
315                    0x08, # UPPER nibble must be 0 to set RTR bit for DATA FRAME
316                          # LOWER nibble is DLC
317                    0x01,0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xFF]
318         self.client.txpacket(packet1);
319         self.client.txpacket(packet1);
320         print "Waiting on loopback packets.";
321         packet=None;
322         while(1):
323             packet=self.client.rxpacket();
324             if packet!=None:
325                 print "Message recieved: %s" % self.client.packet2str(packet);
326                 break;
327     
328         
329     def spit(self,freq, standardid,debug):
330         
331         comm.reset();
332         self.client.MCPsetrate(freq);
333         self.client.MCPreqstatNormal();
334         
335         if(debug==True):
336             print "\n\nATTEMPTING TRANSMISSION!!!"
337             print "Tx Errors:  %3d" % self.client.peek8(0x1c);
338             print "Rx Errors:  %3d" % self.client.peek8(0x1d);
339             print "Error Flags:  %02x\n" % self.client.peek8(0x2d);
340             print "TXB0CTRL: %02x" %self.client.peek8(0x30);
341             print "CANINTF: %02x\n"  %self.client.peek8(0x2C);
342     
343         #### split SID into different regs
344         SIDlow = (standardid[0] & 0x03) << 5;  # get SID bits 2:0, rotate them to bits 7:5
345         SIDhigh = (standardid[0] >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
346         
347         packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
348                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
349                   # lower nibble is DLC                   
350                   0x01,0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xFF]    
351         
352         self.client.txpacket(packet);
353         
354         TXB0CTRL = self.client.peek8(0x30);
355         
356         print "Tx Errors:  %3d" % self.client.peek8(0x1c);
357         print "Rx Errors:  %3d" % self.client.peek8(0x1d);
358         print "Error Flags:  %02x\n" % self.client.peek8(0x2d);
359         print "TXB0CTRL: %02x" %self.client.peek8(0x30);
360         self.client.MCPbitmodify(0x30,0x08,0x00);
361         print "TXB0CTRL modified to: %02x\n" %self.client.peek8(0x30);
362         
363         print "CANINTF: %02x"  %self.client.peek8(0x2C);
364         self.client.MCPbitmodify(0x2C,0x80,0x00);
365         print "INT Flags modified to:  %02x\n" % self.client.peek8(0x2c);
366
367         
368
369
370
371 if __name__ == "__main__":  
372
373     parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description='''\
374     
375         Run commands on the MCP2515. Valid commands are:
376         
377             info 
378             test
379             peek 0x(start) [0x(stop)]
380             reset
381             
382             sniff 
383             freqtest
384             snifftest
385             spit
386         ''')
387         
388     
389     parser.add_argument('verb', choices=['info', 'test','peek', 'reset', 'sniff', 'freqtest','snifftest', 'spit']);
390     parser.add_argument('-f', '--freq', type=int, default=500, help='The desired frequency (kHz)', choices=[100, 125, 250, 500, 1000]);
391     parser.add_argument('-t','--time', type=int, default=15, help='The duration to run the command (s)');
392     parser.add_argument('-o', '--output', default=None,help='Output file');
393     parser.add_argument("-d", "--description", help='Description of experiment (included in the output file)', default="");
394     parser.add_argument('-v',"--verbose",action='store_false',help='-v will stop packet output to terminal', default=True);
395     parser.add_argument('-c','--comment', help='Comment attached to ech packet uploaded',default=None);
396     parser.add_argument('-b', '--debug', action='store_true', help='-b will turn on debug mode, printing packet status', default=False);
397     parser.add_argument('-a', '--standardid', type=int, action='append', help='Standard ID to accept with filter 0 [1, 2, 3, 4, 5]', default=None);
398     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);
399
400     
401     args = parser.parse_args();
402     freq = args.freq
403     duration = args.time
404     filename = args.output
405     description = args.description
406     verbose = args.verbose
407     comments = args.comment
408     debug = args.debug
409     standardid = args.standardid
410     faster=args.faster
411
412     comm = GoodFETMCPCANCommunication();
413     
414     ##########################
415     #   INFO
416     ##########################
417     #
418     # Prints MCP state info
419     #
420     if(args.verb=="info"):
421         comm.printInfo()
422         
423            
424     ##########################
425     #   RESET
426     ##########################
427     #
428     #
429             
430     if(args.verb=="reset"):
431         comm.reset()
432         
433     ##########################
434     #   SNIFF
435     ##########################
436     #
437     #   runs in ListenOnly mode
438     #   utility function to pull info off the car's CAN bus
439     #
440     
441     if(args.verb=="sniff"):
442         comm.sniff(freq=freq,duration=duration,description=description,verbose=verbose,comment=comments,filename=filename, standardid=standardid, debug=debug, faster=faster)    
443                     
444     ##########################
445     #   SNIFF TEST
446     ##########################
447     #
448     #   runs in NORMAL mode
449     #   intended for NETWORKED MCP chips to verify proper operation
450     #
451        
452     if(args.verb=="snifftest"):
453         comm.sniffTest(freq=freq)
454         
455         
456     ##########################
457     #   FREQ TEST
458     ##########################
459     #
460     #   runs in LISTEN ONLY mode
461     #   tests bus for desired frequency --> sniffs bus for specified length of time and reports
462     #   if packets were properly formatted
463     #
464     #
465     
466     if(args.verb=="freqtest"):
467         comm.freqtest(freq=freq)
468
469
470
471     ##########################
472     #   iSniff
473     ##########################
474     #
475     #    """ An intelligent sniffer, decodes message format """
476     #    """ More features to be added soon """
477     if(args.verb=="isniff"):
478         comm.isniff(freq=freq)
479                 
480                 
481     ##########################
482     #   MCP TEST
483     ##########################
484     #
485     #   Runs in LOOPBACK mode
486     #   self-check diagnostic
487     #   wasn't working before due to improperly formatted packet
488     #
489     #   ...add automatic packet check rather than making user verify successful packet
490     if(args.verb=="test"):
491         comm.test()
492         
493     if(args.verb=="peek"):
494         start=0x0000;
495         if(len(sys.argv)>2):
496             start=int(sys.argv[2],16);
497         stop=start;
498         if(len(sys.argv)>3):
499             stop=int(sys.argv[3],16);
500         print "Peeking from %04x to %04x." % (start,stop);
501         while start<=stop:
502             print "%04x: %02x" % (start,client.peek8(start));
503             start=start+1;
504             
505     ##########################
506     #   SPIT
507     ##########################
508     #
509     #   Basic packet transmission
510     #   runs in NORMAL MODE!
511     # 
512     #   checking TX error flags--> currently throwing error flags on every
513     #   transmission (travis thinks this is because we're sniffing in listen-only
514     #   and thus not generating an ack bit on the recieving board)
515     if(args.verb=="spit"):
516         comm.spit(freq=freq, standardid=standardid, debug=debug)
517
518
519     
520     
521     
522     
523         
524         
525     
526     
527     
528