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