a31676ce0fed9976f94e930a6300fd5c2a39d51b
[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 getbuffer(self,size=0x1c00):
51         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
52         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
53     def writecmd(self, app, verb, count=0, data=[], blocks=1):
54         """Write a command and some data to the GoodFET."""
55         self.serialport.write(chr(app));
56         self.serialport.write(chr(verb));
57         self.serialport.write(chr(count));
58         #print "count=%02x, len(data)=%04x" % (count,len(data));
59         if count!=0:
60             for d in data:
61                 self.serialport.write(chr(d));
62         
63         #self.serialport.flushOutput();
64         #self.serialport.flushInput();
65         
66         
67         if not self.besilent:
68             self.readcmd(blocks);
69         
70     besilent=0;
71     app=0;
72     verb=0;
73     count=0;
74     data="";
75
76     def readcmd(self,blocks=1):
77         """Read a reply from the GoodFET."""
78         while 1:
79             #print "Reading...";
80             self.app=ord(self.serialport.read(1));
81             #print "APP=%2x" % self.app;
82             self.verb=ord(self.serialport.read(1));
83             #print "VERB=%02x" % self.verb;
84             self.count=ord(self.serialport.read(1));
85             #print "Waiting for %i bytes." % self.count;
86             
87             #print "READ %02x %02x %02x " % (self.app, self.verb, self.count);
88             
89             #Debugging string; print, but wait.
90             if self.app==0xFF and self.verb==0xFF:
91                 print "DEBUG %s" % self.serialport.read(self.count);
92             else:
93                 self.data=self.serialport.read(self.count*blocks);
94                 return self.data;
95     
96     #Monitor stuff
97     def silent(self,s=0):
98         """Transmissions halted when 1."""
99         self.besilent=s;
100         print "besilent is %i" % self.besilent;
101         self.writecmd(0,0xB0,1,[s]);
102         
103     def out(self,byte):
104         """Write a byte to P5OUT."""
105         self.writecmd(0,0xA1,1,[byte]);
106     def dir(self,byte):
107         """Write a byte to P5DIR."""
108         self.writecmd(0,0xA0,1,[byte]);
109     def peekbyte(self,address):
110         """Read a byte of memory from the monitor."""
111         self.data=[address&0xff,address>>8];
112         self.writecmd(0,0x02,2,self.data);
113         #self.readcmd();
114         return ord(self.data[0]);
115     def peekword(self,address):
116         """Read a word of memory from the monitor."""
117         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
118     def pokebyte(self,address,value):
119         """Set a byte of memory by the monitor."""
120         self.data=[address&0xff,address>>8,value];
121         self.writecmd(0,0x03,3,self.data);
122         return ord(self.data[0]);
123     def dumpmem(self,begin,end):
124         i=begin;
125         while i<end:
126             print "%04x %04x" % (i, self.peekword(i));
127             i+=2;
128     def monitor_ram_pattern(self):
129         """Overwrite all of RAM with 0xBEEF."""
130         self.writecmd(0,0x90,0,self.data);
131         return;
132     def monitor_ram_depth(self):
133         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
134         self.writecmd(0,0x91,0,self.data);
135         return ord(self.data[0])+(ord(self.data[1])<<8);
136     
137     #Baud rates.
138     baudrates=[115200, 
139                9600,
140                19200,
141                38400,
142                57600,
143                115200];
144     def setBaud(self,baud):
145         """Change the baud rate.  TODO fix this."""
146         rates=self.baudrates;
147         self.data=[baud];
148         print "Changing FET baud."
149         self.serialport.write(chr(0x00));
150         self.serialport.write(chr(0x80));
151         self.serialport.write(chr(1));
152         self.serialport.write(chr(baud));
153         
154         print "Changed host baud."
155         self.serialport.setBaudrate(rates[baud]);
156         time.sleep(1);
157         self.serialport.flushInput()
158         self.serialport.flushOutput()
159         
160         print "Baud is now %i." % rates[baud];
161         return;
162     def readbyte(self):
163         return ord(self.serialport.read(1));
164     def findbaud(self):
165         for r in self.baudrates:
166             print "\nTrying %i" % r;
167             self.serialport.setBaudrate(r);
168             #time.sleep(1);
169             self.serialport.flushInput()
170             self.serialport.flushOutput()
171             
172             for i in range(1,10):
173                 self.readbyte();
174             
175             print "Read %02x %02x %02x %02x" % (
176                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
177     def monitortest(self):
178         """Self-test several functions through the monitor."""
179         print "Performing monitor self-test.";
180         
181         if self.peekword(0x0c00)!=0x0c04 and self.peekword(0x0c00)!=0x0c06:
182             print "ERROR Fetched wrong value from 0x0c04.";
183         self.pokebyte(0x0021,0); #Drop LED
184         if self.peekbyte(0x0021)!=0:
185             print "ERROR, P1OUT not cleared.";
186         self.pokebyte(0x0021,1); #Light LED
187         
188         print "Self-test complete.";
189     
190     
191
192     def I2Csetup(self):
193         """Move the FET into the I2C application."""
194         self.writecmd(0x02,0x10,0,self.data); #SPI/SETUP
195     def I2Cstart(self):
196         """Start an I2C transaction."""
197         self.writecmd(0x02,0x20,0,self.data); #SPI/SETUP
198     def I2Cstop(self):
199         """Stop an I2C transaction."""
200         self.writecmd(0x02,0x21,0,self.data); #SPI/SETUP
201     def I2Cread(self,len=1):
202         """Read len bytes by I2C."""
203         self.writecmd(0x02,0x00,1,[len]); #SPI/SETUP
204         return self.data;
205     def I2Cwrite(self,bytes):
206         """Write bytes by I2C."""
207         self.writecmd(0x02,0x01,len(bytes),bytes); #SPI/SETUP
208         return ord(self.data[0]);
209 class GoodFETCC(GoodFET):
210     """A GoodFET variant for use with Chipcon 8051 Zigbe SoC."""
211     def CChaltcpu(self):
212         """Halt the CPU."""
213         self.writecmd(0x30,0x86,0,self.data);
214     def CCreleasecpu(self):
215         """Resume the CPU."""
216         self.writecmd(0x30,0x87,0,self.data);
217     def CCtest(self):
218         self.CCreleasecpu();
219         self.CChaltcpu();
220         #print "Status: %s" % self.CCstatusstr();
221         
222         #Grab ident three times, should be equal.
223         ident1=self.CCident();
224         ident2=self.CCident();
225         ident3=self.CCident();
226         if(ident1!=ident2 or ident2!=ident3):
227             print "Error, repeated ident attempts unequal."
228             print "%04x, %04x, %04x" % (ident1, ident2, ident3);
229         
230         #Single step, printing PC.
231         print "Tracing execution at startup."
232         for i in range(1,15):
233             pc=self.CCgetPC();
234             byte=self.CCpeekcodebyte(i);
235             #print "PC=%04x, %02x" % (pc, byte);
236             self.CCstep_instr();
237         
238         print "Verifying that debugging a NOP doesn't affect the PC."
239         for i in range(1,15):
240             pc=self.CCgetPC();
241             self.CCdebuginstr([0x00]);
242             if(pc!=self.CCgetPC()):
243                 print "ERROR: PC changed during CCdebuginstr([NOP])!";
244         
245         
246         #print "Status: %s." % self.CCstatusstr();
247         #Exit debugger
248         self.CCstop();
249         print "Done.";
250
251     def CCsetup(self):
252         """Move the FET into the CC2430/CC2530 application."""
253         #print "Initializing Chipcon.";
254         self.writecmd(0x30,0x10,0,self.data);
255     def CCrd_config(self):
256         """Read the config register of a Chipcon."""
257         self.writecmd(0x30,0x82,0,self.data);
258         return ord(self.data[0]);
259     def CCwr_config(self,config):
260         """Write the config register of a Chipcon."""
261         self.writecmd(0x30,0x81,1,[config&0xFF]);
262     
263     CCversions={0x0100:"CC1110",
264                 0x8500:"CC2430",
265                 0x8900:"CC2431",
266                 0x8100:"CC2510",
267                 0x9100:"CC2511",
268                 0xFF00:"CCmissing"};
269     def CCidentstr(self):
270         ident=self.CCident();
271         chip=self.CCversions.get(ident&0xFF00);
272         return "%s/r%02x" % (chip, ident&0xFF); 
273     def CCident(self):
274         """Get a chipcon's ID."""
275         self.writecmd(0x30,0x8B,0,None);
276         chip=ord(self.data[0]);
277         rev=ord(self.data[1]);
278         return (chip<<8)+rev;
279     def CCgetPC(self):
280         """Get a chipcon's PC."""
281         self.writecmd(0x30,0x83,0,None);
282         hi=ord(self.data[0]);
283         lo=ord(self.data[1]);
284         return (hi<<8)+lo;
285     def CCdebuginstr(self,instr):
286         self.writecmd(0x30,0x88,len(instr),instr);
287         return ord(self.data[0]);
288     def CCpeekcodebyte(self,adr):
289         """Read the contents of code memory at an address."""
290         self.data=[adr&0xff, (adr&0xff00)>>8];
291         self.writecmd(0x30,0x90,2,self.data);
292         return ord(self.data[0]);
293     def CCpeekdatabyte(self,adr):
294         """Read the contents of data memory at an address."""
295         self.data=[adr&0xff, (adr&0xff00)>>8];
296         self.writecmd(0x30,0x91, 2, self.data);
297         return ord(self.data[0]);
298     def CCpokedatabyte(self,adr,val):
299         """Write a byte to data memory."""
300         self.data=[adr&0xff, (adr&0xff00)>>8, val];
301         self.writecmd(0x30, 0x92, 3, self.data);
302         return ord(self.data[0]);
303     def CCchiperase(self):
304         """Erase all of the target's memory."""
305         self.writecmd(0x30,0x80,0,None);
306     def CCstatus(self):
307         """Check the status."""
308         self.writecmd(0x30,0x84,0,None);
309         return ord(self.data[0])
310     CCstatusbits={0x80 : "erased",
311                   0x40 : "pcon_idle",
312                   0x20 : "halted",
313                   0x10 : "pm0",
314                   0x08 : "halted",
315                   0x04 : "locked",
316                   0x02 : "oscstable",
317                   0x01 : "overflow"};
318     def CCstatusstr(self):
319         """Check the status as a string."""
320         status=self.CCstatus();
321         str="";
322         i=1;
323         while i<0x100:
324             if(status&i):
325                 str="%s %s" %(self.CCstatusbits[i],str);
326             i*=2;
327         return str;
328     def CCstart(self):
329         """Start debugging."""
330         self.writecmd(0x30,0x20,0,self.data);
331         ident=self.CCidentstr();
332         print "Target identifies as %s." % ident;
333         #print "Status: %s." % self.CCstatusstr();
334         self.CCreleasecpu();
335         self.CChaltcpu();
336         #print "Status: %s." % self.CCstatusstr();
337         
338     def CCstop(self):
339         """Stop debugging."""
340         self.writecmd(0x30,0x21,0,self.data);
341     def CCstep_instr(self):
342         """Step one instruction."""
343         self.writecmd(0x30,0x89,0,self.data);
344