a22f50a811d716f99ccdc72a553053d5e6bf0253
[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             pass;
84         elif rate==83.3:
85             #What jackass made the rate uneven?
86             pass;
87         elif rate==100:
88             pass;
89         self.poke8(0x2a,CNF1);
90         self.poke8(0x29,CNF2);
91         self.poke8(0x28,CNF3);
92         
93     def MCPreset(self):
94         """Reset the MCP2515 chip."""
95         self.SPItrans([0xC0]);
96     def MCPcanstat(self):
97         """Get the CAN Status."""
98         return self.peek8(0x0E);
99     def MCPreqstatNormal(self):
100         """Set the CAN state."""
101         state=0x0;
102         self.MCPbitmodify(0x0F,0xE0,(state<<5));
103     def MCPreqstatSleep(self):
104         """Set the CAN state."""
105         state=0x1;
106         self.MCPbitmodify(0x0F,0xE0,(state<<5));
107     def MCPreqstatLoopback(self):
108         """Set the CAN state."""
109         state=0x2;
110         self.MCPbitmodify(0x0F,0xE0,(state<<5));
111     def MCPreqstatListenOnly(self):
112         """Set the CAN state."""
113         state=0x3;
114         self.MCPbitmodify(0x0F,0xE0,(state<<5));
115     def MCPreqstatConfiguration(self):
116         """Set the CAN state."""
117         state=0x4;
118         self.MCPbitmodify(0x0F,0xE0,(state<<5));
119     
120     def MCPcanstatstr(self):
121         """Read the present status as a string."""
122         status=self.MCPcanstat();
123         opmod=(status&0xE0)>>5;
124         return self.MCPMODES[opmod];
125     def MCPrxstatus(self):
126         """Reads the RX Status by the SPI verb of the same name."""
127         data=self.SPItrans([0xB0,0x00]);
128         return ord(data[1]);
129
130     def MCPreadstatus(self):
131         """Reads the Read Status by the SPI verb of the same name."""
132         #See page 67 of the datasheet for the flag names.
133         data=self.SPItrans([0xA0,0x00]);
134         return ord(data[1]);
135
136     def MCPrts(self,TXB0=False,TXB1=False,TXB2=False):
137         """Requests to send one of the transmit buffers."""
138         flags=0;
139         if TXB0: flags=flags|1;
140         if TXB1: flags=flags|2;
141         if TXB2: flags=flags|4;
142         
143         if flags==0:
144             print "Warning: Requesting to send no buffer.";
145         
146         self.SPItrans([0x80|flags]);
147     def readrxbuffer(self,packbuf=0):
148         """Reads the RX buffer.  Might have old data."""
149         data=self.SPItrans([0x90|(packbuf<<2),
150                        0x00,0x00, #SID
151                        0x00,0x00, #EID
152                        0x00,      #DLC
153                        0x00, 0x00, 0x00, 0x00,
154                        0x00, 0x00, 0x00, 0x00
155                        ]);
156         return data[1:len(data)];
157     def writetxbuffer(self,packet,packbuf=0):
158         """Writes the transmit buffer."""
159         self.SPItrans([0x40|(packbuf<<1)]+packet);
160         
161     def rxpacket(self):
162         """Reads the next incoming packet from either buffer.
163         Returns None immediately if no packet is waiting."""
164         status=self.MCPrxstatus()&0xC0;
165         if status&0x40:
166             #Buffer 0 has higher priority.
167             return self.readrxbuffer(0);
168         elif status&0x80:
169             #Buffer 1 has lower priority.
170             return self.readrxbuffer(1);
171         else:
172             return None;
173     def txpacket(self,packet):
174         """Transmits a packet through one of the outbound buffers.
175         As usual, the packet should begin with SIDH.
176         For now, only TXB0 is supported."""
177         self.writetxbuffer(packet,0);
178         self.MCPrts(TXB0=True);
179     def packet2str(self,packet):
180         """Converts a packet from the internal format to a string."""
181         toprint="";
182         for bar in packet:
183             toprint=toprint+("%02x "%ord(bar))
184         return toprint;
185     def peek8(self,adr):
186         """Read a byte from the given address.  Untested."""
187         data=self.SPItrans([0x03,adr&0xFF,00]);
188         return ord(data[2]);
189     def MCPbitmodify(self,adr,mask,data):
190         """Writes a byte with a mask.  Doesn't work for many registers."""
191         data=self.SPItrans([0x05,adr&0xFF,mask&0xFF,data&0xFF]);
192         return ord(data[2]);
193     def poke8(self,adr,val):
194         """Poke a value into RAM.  Untested"""
195         self.SPItrans([0x02,adr&0xFF,val&0xFF]);
196         return val;