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