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