165d972ce0150bf3b76a3d881899090e2690df5c
[goodfet] / client / GoodFETMCPCAN.py
1 #!/usr/bin/env python
2 # GoodFET MCP2515 CAN Bus Client
3
4 # (C) 2012 Travis Goodspeed <travis at radiantmachines.com>
5 #
6 # This code is being rewritten and refactored.  You've been warned!
7 #
8
9 # The MCP2515 is a CAN Bus to SPI adapter from Microchip Technology,
10 # as used in the Goodthopter series of boards.  It requires a separate
11 # chip for voltage level conversion, such as the MCP2551.
12
13 import sys, time, string, cStringIO, struct, glob, os;
14
15 from GoodFETSPI import GoodFETSPI;
16
17 class GoodFETMCPCAN(GoodFETSPI):
18     """This class uses the regular SPI app to implement a CAN Bus
19     adapter on the Goodthopter10 hardware."""
20     MCPMODES=["Normal","Sleep","Loopback","Listen-only","Configuration",
21               "UNKNOWN","UNKNOWN","PowerUp"];
22     def MCPsetup(self):
23         """Sets up the ports."""
24         self.SPIsetup();
25         self.MCPreset(); #Reset the chip.
26         
27         # We're going to set some registers, so we must be in config
28         # mode.
29         self.MCPreqstatConfiguration();
30         
31         # If we don't enable promiscous mode, we'll miss a lot of
32         # packets.  It can be manually disabled later.
33         self.poke8(0x60,0xFF); #TODO Does this have any unpleasant side effects?
34         
35         #Set the default rate.
36         self.MCPsetrate();
37     
38     #Array of supported rates.
39     MCPrates=[100,125,250,500,1000];
40     
41     def MCPsetrate(self,rate=125):
42         """Sets the data rate in kHz."""
43         # Now we need to set the timing registers.  See chapter 5 of
44         # the MCP2515 datasheet to get some clue as to how this
45         # arithmetic of this works, as my comments here will likely be
46         # rambling, incoherent, and unchanged after I get the infernal
47         # thing working.
48         
49         # First, we must chose a Time Quanta (QT) which is used to
50         # define the durations of these segments.  Section 5.3
51         # suggests setting BRP<5:0> to 0x04 to get a TQ=500ns, as a 20
52         # MHz crystal gives a clock period of 50ns.  This way, for 125
53         # kHz communication, the bit time must be 16 TQ.
54         
55         # A bit consists of four parts:
56         # 1: SyncSeg             1 TQ
57         # 2: PropSeg             2 TQ
58         # 3: PhaseSeg1 (PS1)     7 TQ
59         # 4: PhaseSeg2 (PS2)     6 TQ
60         
61         # CNF1 with a prescaler of 4 and a SJW of 1 TQ.  SJW of 4
62         # might be more stable.
63         #self.poke8(0x2a,0x04);
64         
65         # CNF2 with a BLTMODE of 1, SAM of 0, PS1 of 7TQ, and PRSEG of 2TQ
66         #self.poke8(0x29,
67         #           0x80   |  # BTLMODE=1
68         #           (6<<3) |  # 6+1=7TQ for PHSEG1
69         #           (1)       # 1+1=2TQ for PRSEG
70         #           );
71         
72         #CNF3 with a PS2 length of 6TQ.
73         #self.poke8(0x28,
74         #           5      #5+1=6TQ
75         #           );
76         
77         
78         #These are the new examples.
79         
80         if rate==125:
81             #125 kHz, 16 TQ, not quite as worked out above.
82             CNF1=0x04;
83             CNF2=0xB8;
84             CNF3=0x05;
85         elif rate==100:
86             #100 kHz, 20 TQ
87             CNF1=0x04;
88             CNF2=0xBA;
89             CNF3=0x07;
90         elif rate==250:
91             #256 kHz, 20 TQ
92             CNF1=0x01;
93             CNF2=0xBA;
94             CNF3=0x07;
95         elif rate==500:
96             #500 kHz, 20 TQ
97             CNF1=0x00;
98             CNF2=0xBA;
99             CNF3=0x07;
100         elif rate==1000:
101             #1,000 kHz, 10 TQ
102             CNF1=0x00;
103             CNF2=0xA0;
104             CNF3=0x02;
105             print "WARNING: Because of chip errata, this probably won't work."
106         else:
107             print "Given unsupported rate of %i kHz." % rate;
108             print "Defaulting to 125kHz.";
109             CNF1=0x04;
110             CNF2=0xB8;
111             CNF3=0x05;
112         self.poke8(0x2a,CNF1);
113         self.poke8(0x29,CNF2);
114         self.poke8(0x28,CNF3);
115         
116     def MCPreset(self):
117         """Reset the MCP2515 chip."""
118         self.SPItrans([0xC0]);
119     def MCPcanstat(self):
120         """Get the CAN Status."""
121         return self.peek8(0x0E);
122     def MCPreqstatNormal(self):
123         """Set the CAN state."""
124         state=0x0;
125         self.MCPbitmodify(0x0F,0xE0,(state<<5));
126     def MCPreqstatSleep(self):
127         """Set the CAN state."""
128         state=0x1;
129         self.MCPbitmodify(0x0F,0xE0,(state<<5));
130     def MCPreqstatLoopback(self):
131         """Set the CAN state."""
132         state=0x2;
133         self.MCPbitmodify(0x0F,0xE0,(state<<5));
134     def MCPreqstatListenOnly(self):
135         """Set the CAN state."""
136         state=0x3;
137         self.MCPbitmodify(0x0F,0xE0,(state<<5));
138     def MCPreqstatConfiguration(self):
139         """Set the CAN state."""
140         state=0x4;
141         self.MCPbitmodify(0x0F,0xE0,(state<<5));
142     
143     def MCPcanstatstr(self):
144         """Read the present status as a string."""
145         status=self.MCPcanstat();
146         opmod=(status&0xE0)>>5;
147         return self.MCPMODES[opmod];
148     def MCPrxstatus(self):
149         """Reads the RX Status by the SPI verb of the same name."""
150         data=self.SPItrans([0xB0,0x00]);
151         return ord(data[1]);
152
153     def MCPreadstatus(self):
154         """Reads the Read Status by the SPI verb of the same name."""
155         #See page 67 of the datasheet for the flag names.
156         data=self.SPItrans([0xA0,0x00]);
157         return ord(data[1]);
158
159     def MCPrts(self,TXB0=False,TXB1=False,TXB2=False):
160         """Requests to send one of the transmit buffers."""
161         flags=0;
162         if TXB0: flags=flags|1;
163         if TXB1: flags=flags|2;
164         if TXB2: flags=flags|4;
165         
166         if flags==0:
167             print "Warning: Requesting to send no buffer.";
168         
169         self.SPItrans([0x80|flags]);
170     def readrxbuffer(self,packbuf=0):
171         """Reads the RX buffer.  Might have old data."""
172         data=self.SPItrans([0x90|(packbuf<<2),
173                        0x00,0x00, #SID
174                        0x00,0x00, #EID
175                        0x00,      #DLC
176                        0x00, 0x00, 0x00, 0x00,
177                        0x00, 0x00, 0x00, 0x00
178                        ]);
179         return data[1:len(data)];
180     def writetxbuffer(self,packet,packbuf=0):
181         """Writes the transmit buffer."""
182         self.SPItrans([0x40|(packbuf<<1)]+packet);
183         
184     def rxpacket(self):
185         """Reads the next incoming packet from either buffer.
186         Returns None immediately if no packet is waiting."""
187         status=self.MCPrxstatus()&0xC0;
188         if status&0x40:
189             #Buffer 0 has higher priority.
190             return self.readrxbuffer(0);
191         elif status&0x80:
192             #Buffer 1 has lower priority.
193             return self.readrxbuffer(1);
194         else:
195             return None;
196     def txpacket(self,packet):
197         """Transmits a packet through one of the outbound buffers.
198         As usual, the packet should begin with SIDH.
199         For now, only TXB0 is supported."""
200         self.writetxbuffer(packet,0);
201         self.MCPrts(TXB0=True);
202     def packet2str(self,packet):
203         """Converts a packet from the internal format to a string."""
204         toprint="";
205         for bar in packet:
206             toprint=toprint+("%02x "%ord(bar))
207         return toprint;
208     def peek8(self,adr):
209         """Read a byte from the given address.  Untested."""
210         data=self.SPItrans([0x03,adr&0xFF,00]);
211         return ord(data[2]);
212     def MCPbitmodify(self,adr,mask,data):
213         """Writes a byte with a mask.  Doesn't work for many registers."""
214         data=self.SPItrans([0x05,adr&0xFF,mask&0xFF,data&0xFF]);
215         return ord(data[2]);
216     def poke8(self,adr,val):
217         """Poke a value into RAM.  Untested"""
218         self.SPItrans([0x02,adr&0xFF,val&0xFF]);
219         return val;