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