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