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