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