b75c034ec380425987369b69a41fe8c69dae09fa
[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 of 125kHz.
36         self.MCPsetrate(125);
37     
38     def MCPsetrate(self,rate=125):
39         """Sets the data rate in kHz."""
40         # Now we need to set the timing registers.  See chapter 5 of
41         # the MCP2515 datasheet to get some clue as to how this
42         # arithmetic of this works, as my comments here will likely be
43         # rambling, incoherent, and unchanged after I get the infernal
44         # thing working.
45         
46         # First, we must chose a Time Quanta (QT) which is used to
47         # define the durations of these segments.  Section 5.3
48         # suggests setting BRP<5:0> to 0x04 to get a TQ=500ns, as a 20
49         # MHz crystal gives a clock period of 50ns.  This way, for 125
50         # kHz communication, the bit time must be 16 TQ.
51         
52         # A bit consists of four parts:
53         # 1: SyncSeg             1 TQ
54         # 2: PropSeg             2 TQ
55         # 3: PhaseSeg1 (PS1)     7 TQ
56         # 4: PhaseSeg2 (PS2)     6 TQ
57         
58         # CNF1 with a prescaler of 4 and a SJW of 1 TQ.  SJW of 4
59         # might be more stable.
60         #self.poke8(0x2a,0x04);
61         
62         # CNF2 with a BLTMODE of 1, SAM of 0, PS1 of 7TQ, and PRSEG of 2TQ
63         #self.poke8(0x29,
64         #           0x80   |  # BTLMODE=1
65         #           (6<<3) |  # 6+1=7TQ for PHSEG1
66         #           (1)       # 1+1=2TQ for PRSEG
67         #           );
68         
69         #CNF3 with a PS2 length of 6TQ.
70         #self.poke8(0x28,
71         #           5      #5+1=6TQ
72         #           );
73         
74         
75         #These are the new examples.
76         
77         if rate==125:
78             #125 kHz, 16 TQ, not quite as worked out above.
79             CNF1=0x04;
80             CNF2=0xB8;
81             CNF3=0x05;
82         elif rate==500:
83             #500 kHz, 20 TQ
84             CNF1=0x00;
85             CNF2=0xBA;
86             CNF3=0x07;
87             pass;
88         elif rate==100:
89             #100 kHz, 20 TQ
90             CNF1=0x04;
91             CNF2=0xBA;
92             CNF3=0x07;
93             pass;
94         elif rate==1000:
95             #1,000 kHz, 10 TQ
96             CNF1=0x00;
97             CNF2=0xA0;
98             CNF3=0x02;
99             print "WARNING: Because of chip errata, this probably won't work."
100         else:
101             print "Given unsupported rate of %i kHz.";
102             print "Defaulting to 125kHz.";
103             CNF1=0x04;
104             CNF2=0xB8;
105             CNF3=0x05;
106         self.poke8(0x2a,CNF1);
107         self.poke8(0x29,CNF2);
108         self.poke8(0x28,CNF3);
109         
110     def MCPreset(self):
111         """Reset the MCP2515 chip."""
112         self.SPItrans([0xC0]);
113     def MCPcanstat(self):
114         """Get the CAN Status."""
115         return self.peek8(0x0E);
116     def MCPreqstatNormal(self):
117         """Set the CAN state."""
118         state=0x0;
119         self.MCPbitmodify(0x0F,0xE0,(state<<5));
120     def MCPreqstatSleep(self):
121         """Set the CAN state."""
122         state=0x1;
123         self.MCPbitmodify(0x0F,0xE0,(state<<5));
124     def MCPreqstatLoopback(self):
125         """Set the CAN state."""
126         state=0x2;
127         self.MCPbitmodify(0x0F,0xE0,(state<<5));
128     def MCPreqstatListenOnly(self):
129         """Set the CAN state."""
130         state=0x3;
131         self.MCPbitmodify(0x0F,0xE0,(state<<5));
132     def MCPreqstatConfiguration(self):
133         """Set the CAN state."""
134         state=0x4;
135         self.MCPbitmodify(0x0F,0xE0,(state<<5));
136     
137     def MCPcanstatstr(self):
138         """Read the present status as a string."""
139         status=self.MCPcanstat();
140         opmod=(status&0xE0)>>5;
141         return self.MCPMODES[opmod];
142     def MCPrxstatus(self):
143         """Reads the RX Status by the SPI verb of the same name."""
144         data=self.SPItrans([0xB0,0x00]);
145         return ord(data[1]);
146
147     def MCPreadstatus(self):
148         """Reads the Read Status by the SPI verb of the same name."""
149         #See page 67 of the datasheet for the flag names.
150         data=self.SPItrans([0xA0,0x00]);
151         return ord(data[1]);
152
153     def MCPrts(self,TXB0=False,TXB1=False,TXB2=False):
154         """Requests to send one of the transmit buffers."""
155         flags=0;
156         if TXB0: flags=flags|1;
157         if TXB1: flags=flags|2;
158         if TXB2: flags=flags|4;
159         
160         if flags==0:
161             print "Warning: Requesting to send no buffer.";
162         
163         self.SPItrans([0x80|flags]);
164     def readrxbuffer(self,packbuf=0):
165         """Reads the RX buffer.  Might have old data."""
166         data=self.SPItrans([0x90|(packbuf<<2),
167                        0x00,0x00, #SID
168                        0x00,0x00, #EID
169                        0x00,      #DLC
170                        0x00, 0x00, 0x00, 0x00,
171                        0x00, 0x00, 0x00, 0x00
172                        ]);
173         return data[1:len(data)];
174     def writetxbuffer(self,packet,packbuf=0):
175         """Writes the transmit buffer."""
176         self.SPItrans([0x40|(packbuf<<1)]+packet);
177         
178     def rxpacket(self):
179         """Reads the next incoming packet from either buffer.
180         Returns None immediately if no packet is waiting."""
181         status=self.MCPrxstatus()&0xC0;
182         if status&0x40:
183             #Buffer 0 has higher priority.
184             return self.readrxbuffer(0);
185         elif status&0x80:
186             #Buffer 1 has lower priority.
187             return self.readrxbuffer(1);
188         else:
189             return None;
190     def txpacket(self,packet):
191         """Transmits a packet through one of the outbound buffers.
192         As usual, the packet should begin with SIDH.
193         For now, only TXB0 is supported."""
194         self.writetxbuffer(packet,0);
195         self.MCPrts(TXB0=True);
196     def packet2str(self,packet):
197         """Converts a packet from the internal format to a string."""
198         toprint="";
199         for bar in packet:
200             toprint=toprint+("%02x "%ord(bar))
201         return toprint;
202     def peek8(self,adr):
203         """Read a byte from the given address.  Untested."""
204         data=self.SPItrans([0x03,adr&0xFF,00]);
205         return ord(data[2]);
206     def MCPbitmodify(self,adr,mask,data):
207         """Writes a byte with a mask.  Doesn't work for many registers."""
208         data=self.SPItrans([0x05,adr&0xFF,mask&0xFF,data&0xFF]);
209         return ord(data[2]);
210     def poke8(self,adr,val):
211         """Poke a value into RAM.  Untested"""
212         self.SPItrans([0x02,adr&0xFF,val&0xFF]);
213         return val;