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