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