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