65fb46cce5a35170e660f25f95fb6ac7716b44ce
[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 import sqlite3;
10
11 fmt = ("B", "<H", None, "<L")
12
13 def getClient(name="GoodFET"):
14     import GoodFET, GoodFETCC, GoodFETAVR, GoodFETSPI, GoodFETMSP430, GoodFETNRF;
15     if(name=="GoodFET" or name=="monitor"): return GoodFET.GoodFET();
16     elif name=="cc" or name=="cc51": return GoodFETCC.GoodFETCC();
17     elif name=="cc2420" or name=="ccspi": return GoodFETCC.GoodFETCC();
18     elif name=="avr": return GoodFETAVR.GoodFETAVR();
19     elif name=="spi": return GoodFETSPI.GoodFETSPI();
20     elif name=="msp430": return GoodFETMSP430.GoodFETMSP430();
21     elif name=="nrf": return GoodFETNRF.GoodFETNRF();
22     
23     print "Unsupported target: %s" % name;
24     sys.exit(0);
25
26 class SymbolTable:
27     """GoodFET Symbol Table"""
28     db=sqlite3.connect(":memory:");
29     
30     def __init__(self, *args, **kargs):
31         self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
32     def get(self,name):
33         self.db.commit();
34         c=self.db.cursor();
35         try:
36             c.execute("select adr,memory from symbols where name=?",(name,));
37             for row in c:
38                 #print "Found it.";
39                 sys.stdout.flush();
40                 return row[0];
41             #print "No dice.";
42         except:# sqlite3.OperationalError:
43             #print "SQL error.";
44             return eval(name);
45         return eval(name);
46     def define(self,adr,name,comment="",memory="vn",size=16):
47         self.db.execute("insert into symbols(adr,name,memory,size,comment)"
48                         "values(?,?,?,?,?);", (
49                 adr,name,memory,size,comment));
50         #print "Set %s=%s." % (name,adr);
51
52 class GoodFET:
53     """GoodFET Client Library"""
54
55     besilent=0;
56     app=0;
57     verb=0;
58     count=0;
59     data="";
60     verbose=False
61     
62     GLITCHAPP=0x71;
63     MONITORAPP=0x00;
64     symbols=SymbolTable();
65     
66     def __init__(self, *args, **kargs):
67         self.data=[0];
68     def getConsole(self):
69         from GoodFETConsole import GoodFETConsole;
70         return GoodFETConsole(self);
71     def name2adr(self,name):
72         return self.symbols.get(name);
73     def timeout(self):
74         print "timeout\n";
75     def serInit(self, port=None, timeout=2):
76         """Open the serial port"""
77         # Make timeout None to wait forever, 0 for non-blocking mode.
78         
79         if port is None and os.environ.get("GOODFET")!=None:
80             glob_list = glob.glob(os.environ.get("GOODFET"));
81             if len(glob_list) > 0:
82                 port = glob_list[0];
83             else:
84                 port = os.environ.get("GOODFET");
85         if port is None:
86             glob_list = glob.glob("/dev/tty.usbserial*");
87             if len(glob_list) > 0:
88                 port = glob_list[0];
89         if port is None:
90             glob_list = glob.glob("/dev/ttyUSB*");
91             if len(glob_list) > 0:
92                 port = glob_list[0];
93         if os.name=='nt':
94             from scanwin32 import winScan;
95             scan=winScan();
96             for order,comport,desc,hwid in sorted(scan.comports()):
97                 try:
98                     if hwid.index('FTDI')==0:
99                         port=comport;
100                         #print "Using FTDI port %s" % port
101                 except:
102                     #Do nothing.
103                     a=1;
104         
105         self.serialport = serial.Serial(
106             port,
107             #9600,
108             115200,
109             parity = serial.PARITY_NONE,
110             timeout=timeout
111             )
112         
113         self.verb=0;
114         attempts=0;
115         connected=0;
116         while connected==0:
117             while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
118                 #print "Resyncing.";
119                 self.serialport.flushInput()
120                 self.serialport.flushOutput()
121                 #Explicitly set RTS and DTR to halt board.
122                 self.serialport.setRTS(1);
123                 self.serialport.setDTR(1);
124                 #Drop DTR, which is !RST, low to begin the app.
125                 self.serialport.setDTR(0);
126                 
127                 #TelosB reset, prefer software to I2C SPST Switch.
128                 if(os.environ.get("platform")=='telosb'):
129                     self.telosBReset();
130                 #self.serialport.write(chr(0x80));
131                 #self.serialport.write(chr(0x80));
132                 #self.serialport.write(chr(0x80));
133                 #self.serialport.write(chr(0x80));
134                 
135                 
136                 self.serialport.flushInput()
137                 self.serialport.flushOutput()
138                 #time.sleep(60);
139                 attempts=attempts+1;
140                 self.readcmd(); #Read the first command.
141             #Here we have a connection, but maybe not a good one.
142             connected=1;
143             olds=self.infostring();
144             clocking=self.monitorclocking();
145             for foo in range(1,30):
146                 if not self.monitorecho():
147                     if self.verbose: print "Comm error on %i try, resyncing out of %s." % (foo,
148                                                   clocking);
149                     connected=0;
150                     break;
151         if self.verbose: print "Connected after %02i attempts." % attempts;
152         self.mon_connected();
153     def telosSetSCL(self, level):
154         self.serialport.setRTS(not level)
155     def telosSetSDA(self, level):
156         self.serialport.setDTR(not level)
157
158     def telosI2CStart(self):
159         self.telosSetSDA(1)
160         self.telosSetSCL(1)
161         self.telosSetSDA(0)
162
163     def telosI2CStop(self):
164         self.telosSetSDA(0)
165         self.telosSetSCL(1)
166         self.telosSetSDA(1)
167
168     def telosI2CWriteBit(self, bit):
169         self.telosSetSCL(0)
170         self.telosSetSDA(bit)
171         time.sleep(2e-6)
172         self.telosSetSCL(1)
173         time.sleep(1e-6)
174         self.telosSetSCL(0)
175
176     def telosI2CWriteByte(self, byte):
177         self.telosI2CWriteBit( byte & 0x80 );
178         self.telosI2CWriteBit( byte & 0x40 );
179         self.telosI2CWriteBit( byte & 0x20 );
180         self.telosI2CWriteBit( byte & 0x10 );
181         self.telosI2CWriteBit( byte & 0x08 );
182         self.telosI2CWriteBit( byte & 0x04 );
183         self.telosI2CWriteBit( byte & 0x02 );
184         self.telosI2CWriteBit( byte & 0x01 );
185         self.telosI2CWriteBit( 0 );  # "acknowledge"
186
187     def telosI2CWriteCmd(self, addr, cmdbyte):
188         self.telosI2CStart()
189         self.telosI2CWriteByte( 0x90 | (addr << 1) )
190         self.telosI2CWriteByte( cmdbyte )
191         self.telosI2CStop()
192
193     def telosBReset(self,invokeBSL=0):
194         # "BSL entry sequence at dedicated JTAG pins"
195         # rst !s0: 0 0 0 0 1 1
196         # tck !s1: 1 0 1 0 0 1
197         #   s0|s1: 1 3 1 3 2 0
198
199         # "BSL entry sequence at shared JTAG pins"
200         # rst !s0: 0 0 0 0 1 1
201         # tck !s1: 0 1 0 1 1 0
202         #   s0|s1: 3 1 3 1 0 2
203
204         if invokeBSL:
205             self.telosI2CWriteCmd(0,1)
206             self.telosI2CWriteCmd(0,3)
207             self.telosI2CWriteCmd(0,1)
208             self.telosI2CWriteCmd(0,3)
209             self.telosI2CWriteCmd(0,2)
210             self.telosI2CWriteCmd(0,0)
211         else:
212             self.telosI2CWriteCmd(0,3)
213             self.telosI2CWriteCmd(0,2)
214
215         # This line was not defined inside the else: block, not sure where it
216         # should be however
217         self.telosI2CWriteCmd(0,0)
218         time.sleep(0.250)       #give MSP430's oscillator time to stabilize
219         self.serialport.flushInput()  #clear buffers
220
221
222     def getbuffer(self,size=0x1c00):
223         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
224         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
225     def writecmd(self, app, verb, count=0, data=[]):
226         """Write a command and some data to the GoodFET."""
227         self.serialport.write(chr(app));
228         self.serialport.write(chr(verb));
229         
230         #if data!=None:
231         #    count=len(data); #Initial count ignored.
232         
233         #print "TX %02x %02x %04x" % (app,verb,count);
234         
235         #little endian 16-bit length
236         self.serialport.write(chr(count&0xFF));
237         self.serialport.write(chr(count>>8));
238
239         if self.verbose:
240             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
241         
242         #print "count=%02x, len(data)=%04x" % (count,len(data));
243         
244         if count!=0:
245             if(isinstance(data,list)):
246                 for i in range(0,count):
247                 #print "Converting %02x at %i" % (data[i],i)
248                     data[i]=chr(data[i]);
249             #print type(data);
250             outstr=''.join(data);
251             self.serialport.write(outstr);
252         if not self.besilent:
253             return self.readcmd()
254         else:
255             return []
256
257     def readcmd(self):
258         """Read a reply from the GoodFET."""
259         while 1:#self.serialport.inWaiting(): # Loop while input data is available
260             try:
261                 #print "Reading...";
262                 self.app=ord(self.serialport.read(1));
263                 #print "APP=%2x" % self.app;
264                 self.verb=ord(self.serialport.read(1));
265                 #print "VERB=%02x" % self.verb;
266                 self.count=(
267                     ord(self.serialport.read(1))
268                     +(ord(self.serialport.read(1))<<8)
269                     );
270
271                 if self.verbose:
272                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
273             
274                 #Debugging string; print, but wait.
275                 if self.app==0xFF:
276                     if self.verb==0xFF:
277                         print "# DEBUG %s" % self.serialport.read(self.count)
278                     elif self.verb==0xFE:
279                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
280                     elif self.verb==0xFD:
281                         #Do nothing, just wait so there's no timeout.
282                         print "# NOP.";
283                         
284                     sys.stdout.flush();
285                 else:
286                     self.data=self.serialport.read(self.count);
287                     return self.data;
288             except TypeError:
289                 if self.connected:
290                     print "Warning: waiting for serial read timed out (most likely).";
291                     #print "This shouldn't happen after syncing.  Exiting for safety.";                    
292                     #sys.exit(-1)
293                 return self.data;
294     #Glitching stuff.
295     def glitchApp(self,app):
296         """Glitch into a device by its application."""
297         self.data=[app&0xff];
298         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
299         #return ord(self.data[0]);
300     def glitchVerb(self,app,verb,data):
301         """Glitch during a transaction."""
302         if data==None: data=[];
303         self.data=[app&0xff, verb&0xFF]+data;
304         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
305         #return ord(self.data[0]);
306     def glitchstart(self):
307         """Glitch into the AVR application."""
308         self.glitchVerb(self.APP,0x20,None);
309     def glitchstarttime(self):
310         """Measure the timer of the START verb."""
311         return self.glitchTime(self.APP,0x20,None);
312     def glitchTime(self,app,verb,data):
313         """Time the execution of a verb."""
314         if data==None: data=[];
315         self.data=[app&0xff, verb&0xFF]+data;
316         print "Timing app %02x verb %02x." % (app,verb);
317         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
318         time=ord(self.data[0])+(ord(self.data[1])<<8);
319         print "Timed to be %i." % time;
320         return time;
321     def glitchVoltages(self,low=0x0880, high=0x0fff):
322         """Set glitching voltages. (0x0fff is max.)"""
323         self.data=[low&0xff, (low>>8)&0xff,
324                    high&0xff, (high>>8)&0xff];
325         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
326         #return ord(self.data[0]);
327     def glitchRate(self,count=0x0800):
328         """Set glitching count period."""
329         self.data=[count&0xff, (count>>8)&0xff];
330         self.writecmd(self.GLITCHAPP,0x91,2,
331                       self.data);
332         #return ord(self.data[0]);
333     
334     
335     #Monitor stuff
336     def silent(self,s=0):
337         """Transmissions halted when 1."""
338         self.besilent=s;
339         print "besilent is %i" % self.besilent;
340         self.writecmd(0,0xB0,1,[s]);
341     connected=0;
342     def mon_connected(self):
343         """Announce to the monitor that the connection is good."""
344         self.connected=1;
345         self.writecmd(0,0xB1,0,[]);
346     def out(self,byte):
347         """Write a byte to P5OUT."""
348         self.writecmd(0,0xA1,1,[byte]);
349     def dir(self,byte):
350         """Write a byte to P5DIR."""
351         self.writecmd(0,0xA0,1,[byte]);
352     def call(self,adr):
353         """Call to an address."""
354         self.writecmd(0,0x30,2,
355                       [adr&0xFF,(adr>>8)&0xFF]);
356     def execute(self,code):
357         """Execute supplied code."""
358         self.writecmd(0,0x31,2,#len(code),
359                       code);
360     def peekbyte(self,address):
361         """Read a byte of memory from the monitor."""
362         self.data=[address&0xff,address>>8];
363         self.writecmd(0,0x02,2,self.data);
364         #self.readcmd();
365         return ord(self.data[0]);
366     def peekword(self,address):
367         """Read a word of memory from the monitor."""
368         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
369     def peek(self,address):
370         """Read a word of memory from the monitor."""
371         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
372     def eeprompeek(self,address):
373         """Read a word of memory from the monitor."""
374         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
375     def peekbysym(self,name):
376         """Read a value by its symbol name."""
377         #TODO include memory in symbol.
378         reg=self.symbols.get(name);
379         return self.peek8(reg,"data");
380     def pokebysym(self,name,val):
381         """Write a value by its symbol name."""
382         #TODO include memory in symbol.
383         reg=self.symbols.get(name);
384         return self.pokebyte(reg,val);
385     def pokebyte(self,address,value,memory="vn"):
386         """Set a byte of memory by the monitor."""
387         self.data=[address&0xff,address>>8,value];
388         self.writecmd(0,0x03,3,self.data);
389         return ord(self.data[0]);
390     def poke16(self,address,value):
391         """Set a word of memory by the monitor."""
392         self.pokebyte(address,value&0xFF);
393         self.pokebyte(address,(value>>8)&0xFF);
394         return value;
395     def setsecret(self,value):
396         """Set a secret word for later retreival.  Used by glitcher."""
397         self.eeprompoke(0,value);
398         self.eeprompoke(1,value);
399     def getsecret(self):
400         """Get a secret word.  Used by glitcher."""
401         self.eeprompeek(0);
402     
403     def dumpmem(self,begin,end):
404         i=begin;
405         while i<end:
406             print "%04x %04x" % (i, self.peekword(i));
407             i+=2;
408     def monitor_ram_pattern(self):
409         """Overwrite all of RAM with 0xBEEF."""
410         self.writecmd(0,0x90,0,self.data);
411         return;
412     def monitor_ram_depth(self):
413         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
414         self.writecmd(0,0x91,0,self.data);
415         return ord(self.data[0])+(ord(self.data[1])<<8);
416     
417     #Baud rates.
418     baudrates=[115200, 
419                9600,
420                19200,
421                38400,
422                57600,
423                115200];
424     def setBaud(self,baud):
425         """Change the baud rate.  TODO fix this."""
426         rates=self.baudrates;
427         self.data=[baud];
428         print "Changing FET baud."
429         self.serialport.write(chr(0x00));
430         self.serialport.write(chr(0x80));
431         self.serialport.write(chr(1));
432         self.serialport.write(chr(baud));
433         
434         print "Changed host baud."
435         self.serialport.setBaudrate(rates[baud]);
436         time.sleep(1);
437         self.serialport.flushInput()
438         self.serialport.flushOutput()
439         
440         print "Baud is now %i." % rates[baud];
441         return;
442     def readbyte(self):
443         return ord(self.serialport.read(1));
444     def findbaud(self):
445         for r in self.baudrates:
446             print "\nTrying %i" % r;
447             self.serialport.setBaudrate(r);
448             #time.sleep(1);
449             self.serialport.flushInput()
450             self.serialport.flushOutput()
451             
452             for i in range(1,10):
453                 self.readbyte();
454             
455             print "Read %02x %02x %02x %02x" % (
456                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
457     def monitortest(self):
458         """Self-test several functions through the monitor."""
459         print "Performing monitor self-test.";
460         self.monitorclocking();
461         for f in range(0,3000):
462             a=self.peekword(0x0c00);
463             b=self.peekword(0x0c02);
464             if a!=0x0c04 and a!=0x0c06:
465                 print "ERROR Fetched %04x, %04x" % (a,b);
466             self.pokebyte(0x0021,0); #Drop LED
467             if self.peekbyte(0x0021)!=0:
468                 print "ERROR, P1OUT not cleared.";
469             self.pokebyte(0x0021,1); #Light LED
470             if not self.monitorecho():
471                 print "Echo test failed.";
472         print "Self-test complete.";
473         self.monitorclocking();
474     def monitorecho(self):
475         data="The quick brown fox jumped over the lazy dog.";
476         self.writecmd(self.MONITORAPP,0x81,len(data),data);
477         if self.data!=data:
478             if self.verbose: print "Comm error recognized by monitorecho().";
479             return 0;
480         return 1;
481
482     def monitor_info(self):
483         print "GoodFET with %s MCU" % self.infostring();
484         print "Clocked at %s" % self.monitorclocking();
485         return 1;
486
487     def monitor_list_apps(self, full=False): 
488         self.monitor_info()
489         old_value = self.besilent
490         self.besilent = True    # turn off automatic call to readcmd
491         self.writecmd(self.MONITORAPP, 0x82, 1, [int(full)]);
492         self.besilent = old_value
493         
494         # read the build date string 
495         self.readcmd()
496         print "Build Date: %s" % self.data
497         print "Firmware apps:"
498         while True:
499             self.readcmd()
500             if self.count == 0:
501                 break
502             print self.data
503         return 1;
504
505     def monitorclocking(self):
506         """Return the 16-bit clocking value."""
507         return "0x%04x" % self.monitorgetclock();
508     
509     def monitorsetclock(self,clock):
510         """Set the clocking value."""
511         self.poke16(0x56, clock);
512     def monitorgetclock(self):
513         """Get the clocking value."""
514         return self.peek16(0x56);
515     # The following functions ought to be implemented in
516     # every client.
517     
518     def infostring(self):
519         a=self.peekbyte(0xff0);
520         b=self.peekbyte(0xff1);
521         return "%02x%02x" % (a,b);
522     def lock(self):
523         print "Locking Unsupported.";
524     def erase(self):
525         print "Erasure Unsupported.";
526     def setup(self):
527         return;
528     def start(self):
529         return;
530     def test(self):
531         print "Unimplemented.";
532         return;
533     def status(self):
534         print "Unimplemented.";
535         return;
536     def halt(self):
537         print "Unimplemented.";
538         return;
539     def resume(self):
540         print "Unimplemented.";
541         return;
542     def getpc(self):
543         print "Unimplemented.";
544         return 0xdead;
545     def flash(self,file):
546         """Flash an intel hex file to code memory."""
547         print "Flash not implemented.";
548     def dump(self,file,start=0,stop=0xffff):
549         """Dump an intel hex file from code memory."""
550         print "Dump not implemented.";
551     def peek32(self,address, memory="vn"):
552         """Peek 32 bits."""
553         return (self.peek16(address,memory)+
554                 (self.peek16(address+2,memory)<<16));
555     def peek16(self,address, memory="vn"):
556         """Peek 16 bits of memory."""
557         return (self.peek8(address,memory)+
558                 (self.peek8(address+1,memory)<<8));
559     def peek8(self,address, memory="vn"):
560         """Peek a byte of memory."""
561         return self.peekbyte(address); #monitor
562     def peekword(self,address, memory="vn"):
563         """Peek a natively sized word of memory."""
564         return self.peek16(address); #monitor
565     def peekblock(self,address,length,memory="vn"):
566         """Return a block of data."""
567         data=range(0,length);
568         for foo in range(0,length):
569             data[foo]=self.peek8(address+foo,memory);
570         return data;
571     def pokeblock(self,address,bytes,memory="vn"):
572         """Poke a block of a data into memory at an address."""
573         for foo in bytes:
574             self.pokebyte(address,foo,memory);
575             address=address+1;
576         return;
577     def loadsymbols(self):
578         """Load symbols from a file."""
579         return;