SPI client refactoring and block read/write functions.
[goodfet] / client / GoodFET.py
1 #!/usr/bin/env python
2 # GoodFET Client Library
3
4 # (C) 2009 Travis Goodspeed <travis at radiantmachines.com>
5 #
6 # This code is being rewritten and refactored.  You've been warned!
7
8 import sys, time, string, cStringIO, struct, glob, serial, os;
9
10
11 class GoodFET:
12     """GoodFET Client Library"""
13     def __init__(self, *args, **kargs):
14         self.data=[0];
15     def timeout(self):
16         print "timeout\n";
17     def serInit(self, port=None):
18         """Open the serial port"""
19         
20         if port is None and os.environ.get("GOODFET")!=None:
21             glob_list = glob.glob(os.environ.get("GOODFET"));
22             if len(glob_list) > 0:
23                 port = glob_list[0];
24         if port is None:
25             glob_list = glob.glob("/dev/tty.usbserial*");
26             if len(glob_list) > 0:
27                 port = glob_list[0];
28         if port is None:
29             glob_list = glob.glob("/dev/ttyUSB*");
30             if len(glob_list) > 0:
31                 port = glob_list[0];
32         
33         self.serialport = serial.Serial(
34             port,
35             #9600,
36             115200,
37             parity = serial.PARITY_NONE
38             )
39         #Drop DTR, which is !RST, low to begin the app.
40         self.serialport.setDTR(0);
41         self.serialport.flushInput()
42         self.serialport.flushOutput()
43         
44         #Read and handle the initial command.
45         #time.sleep(1);
46         self.readcmd(); #Read the first command.
47         if(self.verb!=0x7F):
48             print "Verb %02x is wrong.  Incorrect firmware?" % self.verb;
49         #print "Connected."
50     def writecmd(self, app, verb, count=0, data=[], blocks=1):
51         """Write a command and some data to the GoodFET."""
52         self.serialport.write(chr(app));
53         self.serialport.write(chr(verb));
54         self.serialport.write(chr(count));
55         #print "count=%02x, len(data)=%04x" % (count,len(data));
56         if count!=0:
57             for d in data:
58                 self.serialport.write(chr(d));
59         
60         self.readcmd(blocks);  #Uncomment this later, to ensure a response.
61     def readcmd(self,blocks=1):
62         """Read a reply from the GoodFET."""
63         self.app=ord(self.serialport.read(1));
64         self.verb=ord(self.serialport.read(1));
65         self.count=ord(self.serialport.read(1));
66         self.data=self.serialport.read(self.count*blocks);
67         #print "READ %02x %02x %02x " % (self.app, self.verb, self.count);
68         return self.data;
69         
70     #Monitor stuff
71     def peekbyte(self,address):
72         """Read a byte of memory from the monitor."""
73         self.data=[address&0xff,address>>8];
74         self.writecmd(0,0x02,2,self.data);
75         #self.readcmd();
76         return ord(self.data[0]);
77     def peekword(self,address):
78         """Read a word of memory from the monitor."""
79         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
80     def pokebyte(self,address,value):
81         """Set a byte of memory by the monitor."""
82         self.data=[address&0xff,address>>8,value];
83         self.writecmd(0,0x03,3,self.data);
84         return ord(self.data[0]);
85     def dumpmem(self,begin,end):
86         i=begin;
87         while i<end:
88             print "%04x %04x" % (i, self.peekword(i));
89             i+=2;
90     def monitor_ram_pattern(self):
91         """Overwrite all of RAM with 0xBEEF."""
92         self.writecmd(0,0x90,0,self.data);
93         return;
94     def monitor_ram_depth(self):
95         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
96         self.writecmd(0,0x91,0,self.data);
97         return ord(self.data[0])+(ord(self.data[1])<<8);
98     
99     #Baud rates.
100     baudrates=[115200, 
101                9600,
102                19200,
103                38400,
104                57600,
105                115200];
106     def setBaud(self,baud):
107         """Change the baud rate.  TODO fix this."""
108         rates=self.baudrates;
109         self.data=[baud];
110         print "Changing FET baud."
111         self.serialport.write(chr(0x00));
112         self.serialport.write(chr(0x80));
113         self.serialport.write(chr(1));
114         self.serialport.write(chr(baud));
115         
116         print "Changed host baud."
117         self.serialport.setBaudrate(rates[baud]);
118         time.sleep(1);
119         self.serialport.flushInput()
120         self.serialport.flushOutput()
121         
122         print "Baud is now %i." % rates[baud];
123         return;
124     def readbyte(self):
125         return ord(self.serialport.read(1));
126     def findbaud(self):
127         for r in self.baudrates:
128             print "\nTrying %i" % r;
129             self.serialport.setBaudrate(r);
130             #time.sleep(1);
131             self.serialport.flushInput()
132             self.serialport.flushOutput()
133             
134             for i in range(1,10):
135                 self.readbyte();
136             
137             print "Read %02x %02x %02x %02x" % (
138                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
139     def monitortest(self):
140         """Self-test several functions through the monitor."""
141         print "Performing monitor self-test.";
142         
143         if self.peekword(0x0c00)!=0x0c04 and self.peekword(0x0c00)!=0x0c06:
144             print "ERROR Fetched wrong value from 0x0c04.";
145         self.pokebyte(0x0021,0); #Drop LED
146         if self.peekbyte(0x0021)!=0:
147             print "ERROR, P1OUT not cleared.";
148         self.pokebyte(0x0021,1); #Light LED
149         
150         print "Self-test complete.";
151     
152     
153
154     def I2Csetup(self):
155         """Move the FET into the I2C application."""
156         self.writecmd(0x02,0x10,0,self.data); #SPI/SETUP
157     def I2Cstart(self):
158         """Start an I2C transaction."""
159         self.writecmd(0x02,0x20,0,self.data); #SPI/SETUP
160     def I2Cstop(self):
161         """Stop an I2C transaction."""
162         self.writecmd(0x02,0x21,0,self.data); #SPI/SETUP
163     def I2Cread(self,len=1):
164         """Read len bytes by I2C."""
165         self.writecmd(0x02,0x00,1,[len]); #SPI/SETUP
166         return self.data;
167     def I2Cwrite(self,bytes):
168         """Write bytes by I2C."""
169         self.writecmd(0x02,0x01,len(bytes),bytes); #SPI/SETUP
170         return ord(self.data[0]);
171 class GoodFETCC(GoodFET):
172     """A GoodFET variant for use with Chipcon 8051 Zigbe SoC."""
173     def CChaltcpu(self):
174         """Halt the CPU."""
175         self.writecmd(0x30,0x86,0,self.data);
176     def CCreleasecpu(self):
177         """Resume the CPU."""
178         self.writecmd(0x30,0x87,0,self.data);
179     def CCtest(self):
180         self.CCreleasecpu();
181         self.CChaltcpu();
182         #print "Status: %s" % self.CCstatusstr();
183         
184         #Grab ident three times, should be equal.
185         ident1=self.CCident();
186         ident2=self.CCident();
187         ident3=self.CCident();
188         if(ident1!=ident2 or ident2!=ident3):
189             print "Error, repeated ident attempts unequal."
190             print "%04x, %04x, %04x" % (ident1, ident2, ident3);
191         
192         #Single step, printing PC.
193         print "Tracing execution at startup."
194         for i in range(1,15):
195             pc=self.CCgetPC();
196             byte=self.CCpeekcodebyte(i);
197             #print "PC=%04x, %02x" % (pc, byte);
198             self.CCstep_instr();
199         
200         print "Verifying that debugging a NOP doesn't affect the PC."
201         for i in range(1,15):
202             pc=self.CCgetPC();
203             self.CCdebuginstr([0x00]);
204             if(pc!=self.CCgetPC()):
205                 print "ERROR: PC changed during CCdebuginstr([NOP])!";
206         
207         
208         #print "Status: %s." % self.CCstatusstr();
209         #Exit debugger
210         self.CCstop();
211         print "Done.";
212
213     def CCsetup(self):
214         """Move the FET into the CC2430/CC2530 application."""
215         #print "Initializing Chipcon.";
216         self.writecmd(0x30,0x10,0,self.data);
217     def CCrd_config(self):
218         """Read the config register of a Chipcon."""
219         self.writecmd(0x30,0x82,0,self.data);
220         return ord(self.data[0]);
221     def CCwr_config(self,config):
222         """Write the config register of a Chipcon."""
223         self.writecmd(0x30,0x81,1,[config&0xFF]);
224     
225     CCversions={0x0100:"CC1110",
226                 0x8500:"CC2430",
227                 0x8900:"CC2431",
228                 0x8100:"CC2510",
229                 0x9100:"CC2511",
230                 0xFF00:"CCmissing"};
231     def CCidentstr(self):
232         ident=self.CCident();
233         chip=self.CCversions.get(ident&0xFF00);
234         return "%s/r%02x" % (chip, ident&0xFF); 
235     def CCident(self):
236         """Get a chipcon's ID."""
237         self.writecmd(0x30,0x8B,0,None);
238         chip=ord(self.data[0]);
239         rev=ord(self.data[1]);
240         return (chip<<8)+rev;
241     def CCgetPC(self):
242         """Get a chipcon's PC."""
243         self.writecmd(0x30,0x83,0,None);
244         hi=ord(self.data[0]);
245         lo=ord(self.data[1]);
246         return (hi<<8)+lo;
247     def CCdebuginstr(self,instr):
248         self.writecmd(0x30,0x88,len(instr),instr);
249         return ord(self.data[0]);
250     def CCpeekcodebyte(self,adr):
251         """Read the contents of code memory at an address."""
252         self.data=[adr&0xff, (adr&0xff00)>>8];
253         self.writecmd(0x30,0x90,2,self.data);
254         return ord(self.data[0]);
255     def CCpeekdatabyte(self,adr):
256         """Read the contents of data memory at an address."""
257         self.data=[adr&0xff, (adr&0xff00)>>8];
258         self.writecmd(0x30,0x91, 2, self.data);
259         return ord(self.data[0]);
260     def CCpokedatabyte(self,adr,val):
261         """Write a byte to data memory."""
262         self.data=[adr&0xff, (adr&0xff00)>>8, val];
263         self.writecmd(0x30, 0x92, 3, self.data);
264         return ord(self.data[0]);
265     def CCchiperase(self):
266         """Erase all of the target's memory."""
267         self.writecmd(0x30,0x80,0,None);
268     def CCstatus(self):
269         """Check the status."""
270         self.writecmd(0x30,0x84,0,None);
271         return ord(self.data[0])
272     CCstatusbits={0x80 : "erased",
273                   0x40 : "pcon_idle",
274                   0x20 : "halted",
275                   0x10 : "pm0",
276                   0x08 : "halted",
277                   0x04 : "locked",
278                   0x02 : "oscstable",
279                   0x01 : "overflow"};
280     def CCstatusstr(self):
281         """Check the status as a string."""
282         status=self.CCstatus();
283         str="";
284         i=1;
285         while i<0x100:
286             if(status&i):
287                 str="%s %s" %(self.CCstatusbits[i],str);
288             i*=2;
289         return str;
290     def CCstart(self):
291         """Start debugging."""
292         self.writecmd(0x30,0x20,0,self.data);
293         ident=self.CCidentstr();
294         print "Target identifies as %s." % ident;
295         #print "Status: %s." % self.CCstatusstr();
296         self.CCreleasecpu();
297         self.CChaltcpu();
298         #print "Status: %s." % self.CCstatusstr();
299         
300     def CCstop(self):
301         """Stop debugging."""
302         self.writecmd(0x30,0x21,0,self.data);
303     def CCstep_instr(self):
304         """Step one instruction."""
305         self.writecmd(0x30,0x89,0,self.data);
306