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