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