Beginnings of an MCP2515 driver for communicating with a CAN bus.
[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     def MCPsetup(self):
19         """Sets up the ports."""
20         self.SPIsetup();
21         self.MCPreset(); #Reset the chip.
22         
23     def MCPreset(self):
24         """Reset the MCP2515 chip."""
25         self.SPItrans([0xC0]);
26     def MCPrxstatus(self):
27         """Reads the RX Status by the SPI verb of the same name."""
28         data=self.SPItrans([0xB0,0x00]);
29         return ord(data[1]);
30     def MCPreadstatus(self):
31         """Reads the RX Status by the SPI verb of the same name."""
32         data=self.SPItrans([0xA0,0x00]);
33         return ord(data[1]);
34     def peek8(self,adr):
35         """Read a byte from the given address.  Untested."""
36         data=self.SPItrans([0x03,adr&0xFF,00]);
37         return ord(data[2]);
38     
39     def poke8(self,adr,val):
40         """Poke a value into RAM.  Untested"""
41         self.SPItrans([0x02,adr&0xFF,val&0xFF]);
42         return val;
43     def rand16(self):
44         """Read a random 16-bit word."""
45         
46         data=self.EZSPtrans([0x49]);
47         if data==None:
48             print "Insufficient random data.";
49             return 0;
50         return ord(data[6])+(ord(data[7])<<8);
51
52     def info(self):
53         """Read the info bytes."""
54         print "Ember EM26 Z-Stack SPI Module.";
55         version=self.EM260spiversion();
56         status=self.EM260spistatus();
57         print "Version: %i" % (version); 
58         print "Status:  %s" % (["dead","alive"][status]);
59         print ""
60         self.setVersion();
61         print "Node ID: %04x" % (self.getNodeID());
62         print "Connected to %2i neighbors." % self.neighborCount();