ca84e574a0364e87a1cfb9e26d50cdfb7a686101
[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 ugly as sin, for bootstrapping the firmware only.
7 # Rewrite cleanly as soon as is convenient.
8
9 import sys, time, string, cStringIO, struct, glob, serial, os;
10
11
12 class GoodFET:
13     """GoodFET Client Library"""
14     def __init__(self, *args, **kargs):
15         self.data=[0];
16     def timeout(self):
17         print "timeout\n";
18     def serInit(self, port=None):
19         """Open the serial port"""
20         
21         if port is None and os.environ.get("GOODFET")!=None:
22             glob_list = glob.glob(os.environ.get("GOODFET"));
23             if len(glob_list) > 0:
24                 port = glob_list[0];
25         if port is None:
26             glob_list = glob.glob("/dev/tty.usbserial*");
27             if len(glob_list) > 0:
28                 port = glob_list[0];
29         if port is None:
30             glob_list = glob.glob("/dev/ttyUSB*");
31             if len(glob_list) > 0:
32                 port = glob_list[0];
33         
34         self.serialport = serial.Serial(
35             port,
36             #9600,
37             115200,
38             parity = serial.PARITY_NONE
39             )
40         #Drop DTR, which is !RST, low to begin the app.
41         self.serialport.setDTR(0);
42         self.serialport.flushInput()
43         self.serialport.flushOutput()
44         
45         #Read and handle the initial command.
46         #time.sleep(1);
47         self.readcmd(); #Read the first command.
48         if(self.verb!=0x7F):
49             print "Verb %02x is wrong.  Incorrect firmware?" % self.verb;
50         #print "Connected."
51     def writecmd(self, app, verb, count=0, data=[], blocks=1):
52         """Write a command and some data to the GoodFET."""
53         self.serialport.write(chr(app));
54         self.serialport.write(chr(verb));
55         self.serialport.write(chr(count));
56         #print "count=%02x, len(data)=%04x" % (count,len(data));
57         if count!=0:
58             for d in data:
59                 self.serialport.write(chr(d));
60         
61         self.readcmd(blocks);  #Uncomment this later, to ensure a response.
62     def readcmd(self,blocks=1):
63         """Read a reply from the GoodFET."""
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         return self.data;
69         #print "READ %02x %02x %02x " % (self.app, self.verb, self.count);
70         
71     #Monitor stuff
72     def peekbyte(self,address):
73         """Read a byte of memory from the monitor."""
74         self.data=[address&0xff,address>>8];
75         self.writecmd(0,0x02,2,self.data);
76         #self.readcmd();
77         return ord(self.data[0]);
78     def peekword(self,address):
79         """Read a word of memory from the monitor."""
80         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
81     def pokebyte(self,address,value):
82         """Set a byte of memory by the monitor."""
83         self.data=[address&0xff,address>>8,value];
84         self.writecmd(0,0x03,3,self.data);
85         return ord(self.data[0]);
86     def dumpmem(self,begin,end):
87         i=begin;
88         while i<end:
89             print "%04x %04x" % (i, self.peekword(i));
90             i+=2;
91     def monitor_ram_pattern(self):
92         """Overwrite all of RAM with 0xBEEF."""
93         self.writecmd(0,0x90,0,self.data);
94         return;
95     def monitor_ram_depth(self):
96         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
97         self.writecmd(0,0x91,0,self.data);
98         return ord(self.data[0])+(ord(self.data[1])<<8);
99     
100     #Baud rates.
101     baudrates=[115200, 
102                9600,
103                19200,
104                38400,
105                57600,
106                115200];
107     def setBaud(self,baud):
108         """Change the baud rate.  TODO fix this."""
109         rates=self.baudrates;
110         self.data=[baud];
111         print "Changing FET baud."
112         self.serialport.write(chr(0x00));
113         self.serialport.write(chr(0x80));
114         self.serialport.write(chr(1));
115         self.serialport.write(chr(baud));
116         
117         print "Changed host baud."
118         self.serialport.setBaudrate(rates[baud]);
119         time.sleep(1);
120         self.serialport.flushInput()
121         self.serialport.flushOutput()
122         
123         print "Baud is now %i." % rates[baud];
124         return;
125     def readbyte(self):
126         return ord(self.serialport.read(1));
127     def findbaud(self):
128         for r in self.baudrates:
129             print "\nTrying %i" % r;
130             self.serialport.setBaudrate(r);
131             #time.sleep(1);
132             self.serialport.flushInput()
133             self.serialport.flushOutput()
134             
135             for i in range(1,10):
136                 self.readbyte();
137             
138             print "Read %02x %02x %02x %02x" % (
139                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
140     def monitortest(self):
141         """Self-test several functions through the monitor."""
142         print "Performing monitor self-test.";
143         
144         if self.peekword(0x0c00)!=0x0c04 and self.peekword(0x0c00)!=0x0c06:
145             print "ERROR Fetched wrong value from 0x0c04.";
146         self.pokebyte(0x0021,0); #Drop LED
147         if self.peekbyte(0x0021)!=0:
148             print "ERROR, P1OUT not cleared.";
149         self.pokebyte(0x0021,1); #Light LED
150         
151         print "Self-test complete.";
152     
153     
154
155     def I2Csetup(self):
156         """Move the FET into the I2C application."""
157         self.writecmd(0x02,0x10,0,self.data); #SPI/SETUP
158     def I2Cstart(self):
159         """Start an I2C transaction."""
160         self.writecmd(0x02,0x20,0,self.data); #SPI/SETUP
161     def I2Cstop(self):
162         """Stop an I2C transaction."""
163         self.writecmd(0x02,0x21,0,self.data); #SPI/SETUP
164     def I2Cread(self,len=1):
165         """Read len bytes by I2C."""
166         self.writecmd(0x02,0x00,1,[len]); #SPI/SETUP
167         return self.data;
168     def I2Cwrite(self,bytes):
169         """Write bytes by I2C."""
170         self.writecmd(0x02,0x01,len(bytes),bytes); #SPI/SETUP
171         return ord(self.data[0]);
172
173 class GoodFETMSP430(GoodFET):
174     def MSP430setup(self):
175         """Move the FET into the MSP430 JTAG application."""
176         print "Initializing MSP430.";
177         self.writecmd(0x11,0x10,0,self.data);
178     def MSP430stop(self):
179         """Stop debugging."""
180         self.writecmd(0x11,0x21,0,self.data);
181
182     def MSP430peek(self,adr):
183         """Read the contents of memory at an address."""
184         self.data=[adr&0xff, (adr&0xff00)>>8];
185         self.writecmd(0x11,0x02,2,self.data);
186         return ord(self.data[0])+(ord(self.data[1])<<8);
187     def MSP430poke(self,adr,val):
188         """Read the contents of memory at an address."""
189         self.data=[adr&0xff, (adr&0xff00)>>8, val&0xff, (val&0xff00)>>8];
190         self.writecmd(0x11,0x03,4,self.data);
191         return;# ord(self.data[0])+(ord(self.data[1])<<8);
192     def MSP430start(self):
193         """Start debugging."""
194         self.writecmd(0x11,0x20,0,self.data);
195         ident=self.MSP430ident();
196         print "Target identifies as %04x." % ident;
197     
198     def MSP430haltcpu(self):
199         """Halt the CPU."""
200         self.writecmd(0x11,0xA0,0,self.data);
201     def MSP430releasecpu(self):
202         """Resume the CPU."""
203         self.writecmd(0x11,0xA1,0,self.data);
204     def MSP430shiftir8(self,ins):
205         """Shift the 8-bit Instruction Register."""
206         data=[ins];
207         self.writecmd(0x11,0x80,1,data);
208         return ord(self.data[0]);
209     def MSP430shiftdr16(self,dat):
210         """Shift the 16-bit Data Register."""
211         data=[dat&0xFF,(dat&0xFF00)>>8];
212         self.writecmd(0x11,0x81,2,data);
213         return ord(self.data[0])#+(ord(self.data[1])<<8);
214     def MSP430setinstrfetch(self):
215         """Set the instruction fetch mode."""
216         self.writecmd(0x11,0xC1,0,self.data);
217         return self.data[0];
218     def MSP430ident(self):
219         """Grab self-identification word from 0x0FF0 as big endian."""
220         i=self.MSP430peek(0x0ff0);
221         return ((i&0xFF00)>>8)+((i&0xFF)<<8)
222     def MSP430test(self):
223         """Test MSP430 JTAG.  Requires that a chip be attached."""
224         if self.MSP430ident()==0xffff:
225             print "Is anything connected?";
226         print "Testing RAM.";
227         temp=self.MSP430peek(0x0200);
228         self.MSP430poke(0x0200,0xdead);
229         if(self.MSP430peek(0x0200)!=0xdead):
230             print "Poke of 0x0200 did not set to 0xDEAD properly.";
231             return;
232         self.MSP430poke(0x0200,temp); #restore old value.
233     def MSP430flashtest(self):
234         self.MSP430masserase();
235         i=0x2500;
236         while(i<0xFFFF):
237             if(self.MSP430peek(i)!=0xFFFF):
238                 print "ERROR: Unerased flash at %04x."%i;
239             self.MSP430writeflash(i,0xDEAD);
240             i+=2;
241     def MSP430masserase(self):
242         """Erase MSP430 flash memory."""
243         self.writecmd(0x11,0xE3,0,None);
244     def MSP430writeflash(self,adr,val):
245         """Write a word of flash memory."""
246         if(self.MSP430peek(adr)!=0xFFFF):
247             print "FLASH ERROR: %04x not clear." % adr;
248         data=[adr&0xFF,(adr&0xFF00)>>8,val&0xFF,(val&0xFF00)>>8];
249         self.writecmd(0x11,0xE1,4,data);
250         rval=ord(self.data[0])+(ord(self.data[1])<<8);
251         if(val!=rval):
252             print "FLASH WRITE ERROR AT %04x.  Found %04x, wrote %04x." % (adr,rval,val);
253             
254     def MSP430dumpbsl(self):
255         self.MSP430dumpmem(0xC00,0xfff);
256     def MSP430dumpallmem(self):
257         self.MSP430dumpmem(0x200,0xffff);
258     def MSP430dumpmem(self,begin,end):
259         i=begin;
260         while i<end:
261             print "%04x %04x" % (i, self.MSP430peek(i));
262             i+=2;
263 class GoodFETSPI(GoodFET):
264     def SPIsetup(self):
265         """Move the FET into the SPI application."""
266         self.writecmd(0x01,0x10,0,self.data); #SPI/SETUP
267         
268     def SPItrans8(self,byte):
269         """Read and write 8 bits by SPI."""
270         data=self.SPItrans([byte]);
271         return ord(data[0]);
272     
273     def SPItrans(self,data):
274         """Exchange data by SPI."""
275         self.data=data;
276         self.writecmd(0x01,0x00,len(data),data);
277         return self.data;
278
279 class GoodFETSPIFlash(GoodFETSPI):
280     JEDECmanufacturers={0xFF: "MISSING",
281                         0xEF: "Winbond",
282                         0xC2: "MXIC",
283                         0x20: "Numonyx/ST"
284                         };
285
286     JEDECdevices={0xFFFFFF: "MISSING",
287                   0xEF3014: "W25X80L",
288                   0xEF3013: "W25X40L",
289                   0xEF3012: "W25X20L",
290                   0xEF3011: "W25X10L",
291                   0xC22014: "MX25L8005",
292                   0xC22013: "MX25L4005",
293                   0x204011: "M45PE10"
294                   };
295     JEDECsizes={0x14: 0x100000,
296                 0x13: 0x080000,
297                 0x12: 0x040000,
298                 0x11: 0x020000}
299     JEDECsize=0;
300
301     def SPIjedec(self):
302         """Grab an SPI Flash ROM's JEDEC bytes."""
303         data=[0x9f, 0, 0, 0];
304         data=self.SPItrans(data);
305         #print "Manufacturer: %02x\nType: %02x\nCapacity: %02x" % (ord(data[1]),ord(data[2]),ord(data[3]));
306         self.JEDECmanufacturer=ord(data[1]);
307         self.JEDECtype=ord(data[2]);
308         self.JEDECcapacity=ord(data[3]);
309         self.JEDECsize=self.JEDECsizes.get(self.JEDECcapacity);
310         if self.JEDECsize==None:
311             self.JEDECsize=0;
312         self.JEDECdevice=(ord(data[1])<<16)+(ord(data[2])<<8)+ord(data[3]);
313         return data;
314     def SPIpeek(self,adr):
315         """Grab a byte from an SPI Flash ROM."""
316         data=[0x03,
317               (adr&0xFF0000)>>16,
318               (adr&0xFF00)>>8,
319               adr&0xFF,
320               0];
321         self.SPItrans(data);
322         return ord(self.data[4]);
323     def SPIpeekblock(self,adr,blocks=1):
324         """Grab a few block from an SPI Flash ROM.  Block size is unknown"""
325         data=[(adr&0xFF0000)>>16,
326               (adr&0xFF00)>>8,
327               adr&0xFF,
328               blocks];
329         
330         self.writecmd(0x01,0x02,4,data,blocks);
331         return self.data;
332     
333     def SPIpokebyte(self,adr,val):
334         self.SPIpokebytes(adr,[val]);
335     def SPIpokebytes(self,adr,data):
336         #self.SPIwriteenable();
337         adranddata=[(adr&0xFF0000)>>16,
338               (adr&0xFF00)>>8,
339               adr&0xFF
340               ]+data;
341         self.writecmd(0x01,0x03,
342                       len(adranddata),adranddata);
343         
344     def SPIchiperase(self):
345         """Mass erase an SPI Flash ROM."""
346         self.writecmd(0x01,0x81,0,[]);
347     def SPIwriteenable(self):
348         """SPI Flash Write Enable"""
349         data=[0x06];
350         self.SPItrans(data);
351         
352     def SPIjedecmanstr(self):
353         """Grab the JEDEC manufacturer string.  Call after SPIjedec()."""
354         man=self.JEDECmanufacturers.get(self.JEDECmanufacturer)
355         if man==0:
356             man="UNKNOWN";
357         return man;
358     
359     def SPIjedecstr(self):
360         """Grab the JEDEC manufacturer string.  Call after SPIjedec()."""
361         man=self.JEDECmanufacturers.get(self.JEDECmanufacturer);
362         if man==0:
363             man="UNKNOWN";
364         device=self.JEDECdevices.get(self.JEDECdevice);
365         if device==0:
366             device="???"
367         return "%s %s" % (man,device);
368 class GoodFETCC(GoodFET):
369     """A GoodFET variant for use with Chipcon 8051 Zigbe SoC."""
370     def CChaltcpu(self):
371         """Halt the CPU."""
372         self.writecmd(0x30,0x86,0,self.data);
373     def CCreleasecpu(self):
374         """Resume the CPU."""
375         self.writecmd(0x30,0x87,0,self.data);
376     def CCtest(self):
377         self.CCreleasecpu();
378         self.CChaltcpu();
379         #print "Status: %s" % self.CCstatusstr();
380         
381         #Grab ident three times, should be equal.
382         ident1=self.CCident();
383         ident2=self.CCident();
384         ident3=self.CCident();
385         if(ident1!=ident2 or ident2!=ident3):
386             print "Error, repeated ident attempts unequal."
387             print "%04x, %04x, %04x" % (ident1, ident2, ident3);
388         
389         #Single step, printing PC.
390         print "Tracing execution at startup."
391         for i in range(1,15):
392             pc=self.CCgetPC();
393             byte=self.CCpeekcodebyte(i);
394             #print "PC=%04x, %02x" % (pc, byte);
395             self.CCstep_instr();
396         
397         print "Verifying that debugging a NOP doesn't affect the PC."
398         for i in range(1,15):
399             pc=self.CCgetPC();
400             self.CCdebuginstr([0x00]);
401             if(pc!=self.CCgetPC()):
402                 print "ERROR: PC changed during CCdebuginstr([NOP])!";
403         
404         
405         #print "Status: %s." % self.CCstatusstr();
406         #Exit debugger
407         self.CCstop();
408         print "Done.";
409
410     def CCsetup(self):
411         """Move the FET into the CC2430/CC2530 application."""
412         #print "Initializing Chipcon.";
413         self.writecmd(0x30,0x10,0,self.data);
414     def CCrd_config(self):
415         """Read the config register of a Chipcon."""
416         self.writecmd(0x30,0x82,0,self.data);
417         return ord(self.data[0]);
418     def CCwr_config(self,config):
419         """Write the config register of a Chipcon."""
420         self.writecmd(0x30,0x81,1,[config&0xFF]);
421     
422     CCversions={0x0100:"CC1110",
423                 0x8500:"CC2430",
424                 0x8900:"CC2431",
425                 0x8100:"CC2510",
426                 0x9100:"CC2511",
427                 0xFF00:"CCmissing"};
428     def CCidentstr(self):
429         ident=self.CCident();
430         chip=self.CCversions.get(ident&0xFF00);
431         return "%s/r%02x" % (chip, ident&0xFF); 
432     def CCident(self):
433         """Get a chipcon's ID."""
434         self.writecmd(0x30,0x8B,0,None);
435         chip=ord(self.data[0]);
436         rev=ord(self.data[1]);
437         return (chip<<8)+rev;
438     def CCgetPC(self):
439         """Get a chipcon's PC."""
440         self.writecmd(0x30,0x83,0,None);
441         hi=ord(self.data[0]);
442         lo=ord(self.data[1]);
443         return (hi<<8)+lo;
444     def CCdebuginstr(self,instr):
445         self.writecmd(0x30,0x88,len(instr),instr);
446         return ord(self.data[0]);
447     def CCpeekcodebyte(self,adr):
448         """Read the contents of code memory at an address."""
449         self.data=[adr&0xff, (adr&0xff00)>>8];
450         self.writecmd(0x30,0x90,2,self.data);
451         return ord(self.data[0]);
452     def CCpeekdatabyte(self,adr):
453         """Read the contents of data memory at an address."""
454         self.data=[adr&0xff, (adr&0xff00)>>8];
455         self.writecmd(0x30,0x91, 2, self.data);
456         return ord(self.data[0]);
457     def CCpokedatabyte(self,adr,val):
458         """Write a byte to data memory."""
459         self.data=[adr&0xff, (adr&0xff00)>>8, val];
460         self.writecmd(0x30, 0x92, 3, self.data);
461         return ord(self.data[0]);
462     def CCchiperase(self):
463         """Erase all of the target's memory."""
464         self.writecmd(0x30,0x80,0,None);
465     def CCstatus(self):
466         """Check the status."""
467         self.writecmd(0x30,0x84,0,None);
468         return ord(self.data[0])
469     CCstatusbits={0x80 : "erased",
470                   0x40 : "pcon_idle",
471                   0x20 : "halted",
472                   0x10 : "pm0",
473                   0x08 : "halted",
474                   0x04 : "locked",
475                   0x02 : "oscstable",
476                   0x01 : "overflow"};
477     def CCstatusstr(self):
478         """Check the status as a string."""
479         status=self.CCstatus();
480         str="";
481         i=1;
482         while i<0x100:
483             if(status&i):
484                 str="%s %s" %(self.CCstatusbits[i],str);
485             i*=2;
486         return str;
487     def CCstart(self):
488         """Start debugging."""
489         self.writecmd(0x30,0x20,0,self.data);
490         ident=self.CCidentstr();
491         print "Target identifies as %s." % ident;
492         #print "Status: %s." % self.CCstatusstr();
493         self.CCreleasecpu();
494         self.CChaltcpu();
495         #print "Status: %s." % self.CCstatusstr();
496         
497     def CCstop(self):
498         """Stop debugging."""
499         self.writecmd(0x30,0x21,0,self.data);
500     def CCstep_instr(self):
501         """Step one instruction."""
502         self.writecmd(0x30,0x89,0,self.data);
503