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