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