Added the capability to query the Special Registers for the ChipCon client.
[goodfet] / client / GoodFET.py
1 #!/usr/bin/env python
2 # GoodFET Client Library
3
4 # (C) 2009 Travis Goodspeed <travis at radiantmachines.com>
5 #
6 # This code is 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         return self.MONpeek8(address)+(self.MONpeek8(address+1)<<8);
386     def peekbysym(self,name):
387         """Read a value by its symbol name."""
388         #TODO include memory in symbol.
389         reg=self.symbols.get(name);
390         return self.peek8(reg,"data");
391     def pokebysym(self,name,val):
392         """Write a value by its symbol name."""
393         #TODO include memory in symbol.
394         reg=self.symbols.get(name);
395         return self.pokebyte(reg,val);
396     def pokebyte(self,address,value,memory="vn"):
397         """Set a byte of memory by the monitor."""
398         self.data=[address&0xff,address>>8,value];
399         self.writecmd(0,0x03,3,self.data);
400         return ord(self.data[0]);
401     def poke16(self,address,value):
402         """Set a word of memory by the monitor."""
403         self.pokebyte(address,value&0xFF);
404         self.pokebyte(address,(value>>8)&0xFF);
405         return value;
406     def setsecret(self,value):
407         """Set a secret word for later retreival.  Used by glitcher."""
408         self.eeprompoke(0,value);
409         self.eeprompoke(1,value);
410     def getsecret(self):
411         """Get a secret word.  Used by glitcher."""
412         self.eeprompeek(0);
413     
414     def dumpmem(self,begin,end):
415         i=begin;
416         while i<end:
417             print "%04x %04x" % (i, self.MONpeek16(i));
418             i+=2;
419     def monitor_ram_pattern(self):
420         """Overwrite all of RAM with 0xBEEF."""
421         self.writecmd(0,0x90,0,self.data);
422         return;
423     def monitor_ram_depth(self):
424         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
425         self.writecmd(0,0x91,0,self.data);
426         return ord(self.data[0])+(ord(self.data[1])<<8);
427     
428     #Baud rates.
429     baudrates=[115200, 
430                9600,
431                19200,
432                38400,
433                57600,
434                115200];
435     def setBaud(self,baud):
436         """Change the baud rate.  TODO fix this."""
437         rates=self.baudrates;
438         self.data=[baud];
439         print "Changing FET baud."
440         self.serialport.write(chr(0x00));
441         self.serialport.write(chr(0x80));
442         self.serialport.write(chr(1));
443         self.serialport.write(chr(baud));
444         
445         print "Changed host baud."
446         self.serialport.setBaudrate(rates[baud]);
447         time.sleep(1);
448         self.serialport.flushInput()
449         self.serialport.flushOutput()
450         
451         print "Baud is now %i." % rates[baud];
452         return;
453     def readbyte(self):
454         return ord(self.serialport.read(1));
455     def findbaud(self):
456         for r in self.baudrates:
457             print "\nTrying %i" % r;
458             self.serialport.setBaudrate(r);
459             #time.sleep(1);
460             self.serialport.flushInput()
461             self.serialport.flushOutput()
462             
463             for i in range(1,10):
464                 self.readbyte();
465             
466             print "Read %02x %02x %02x %02x" % (
467                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
468     def monitortest(self):
469         """Self-test several functions through the monitor."""
470         print "Performing monitor self-test.";
471         self.monitorclocking();
472         for f in range(0,3000):
473             a=self.MONpeek16(0x0c00);
474             b=self.MONpeek16(0x0c02);
475             if a!=0x0c04 and a!=0x0c06:
476                 print "ERROR Fetched %04x, %04x" % (a,b);
477             self.pokebyte(0x0021,0); #Drop LED
478             if self.MONpeek8(0x0021)!=0:
479                 print "ERROR, P1OUT not cleared.";
480             self.pokebyte(0x0021,1); #Light LED
481             if not self.monitorecho():
482                 print "Echo test failed.";
483         print "Self-test complete.";
484         self.monitorclocking();
485     def monitorecho(self):
486         data="The quick brown fox jumped over the lazy dog.";
487         self.writecmd(self.MONITORAPP,0x81,len(data),data);
488         if self.data!=data:
489             if self.verbose: print "Comm error recognized by monitorecho().";
490             return 0;
491         return 1;
492
493     def monitor_info(self):
494         print "GoodFET with %s MCU" % self.infostring();
495         print "Clocked at %s" % self.monitorclocking();
496         return 1;
497
498     def monitor_list_apps(self, full=False): 
499         self.monitor_info()
500         old_value = self.besilent
501         self.besilent = True    # turn off automatic call to readcmd
502         self.writecmd(self.MONITORAPP, 0x82, 1, [int(full)]);
503         self.besilent = old_value
504         
505         # read the build date string 
506         self.readcmd()
507         print "Build Date: %s" % self.data
508         print "Firmware apps:"
509         while True:
510             self.readcmd()
511             if self.count == 0:
512                 break
513             print self.data
514         return 1;
515
516     def monitorclocking(self):
517         """Return the 16-bit clocking value."""
518         return "0x%04x" % self.monitorgetclock();
519     
520     def monitorsetclock(self,clock):
521         """Set the clocking value."""
522         self.MONpoke16(0x56, clock);
523     def monitorgetclock(self):
524         """Get the clocking value."""
525         return self.MONpeek16(0x56);
526     # The following functions ought to be implemented in
527     # every client.
528     
529     def infostring(self):
530         a=self.MONpeek8(0xff0);
531         b=self.MONpeek8(0xff1);
532         return "%02x%02x" % (a,b);
533     def lock(self):
534         print "Locking Unsupported.";
535     def erase(self):
536         print "Erasure Unsupported.";
537     def setup(self):
538         return;
539     def start(self):
540         return;
541     def test(self):
542         print "Unimplemented.";
543         return;
544     def status(self):
545         print "Unimplemented.";
546         return;
547     def halt(self):
548         print "Unimplemented.";
549         return;
550     def resume(self):
551         print "Unimplemented.";
552         return;
553     def getpc(self):
554         print "Unimplemented.";
555         return 0xdead;
556     def flash(self,file):
557         """Flash an intel hex file to code memory."""
558         print "Flash not implemented.";
559     def dump(self,file,start=0,stop=0xffff):
560         """Dump an intel hex file from code memory."""
561         print "Dump not implemented.";
562     def peek32(self,address, memory="vn"):
563         """Peek 32 bits."""
564         return (self.peek16(address,memory)+
565                 (self.peek16(address+2,memory)<<16));
566     def peek16(self,address, memory="vn"):
567         """Peek 16 bits of memory."""
568         return (self.peek8(address,memory)+
569                 (self.peek8(address+1,memory)<<8));
570     def peek8(self,address, memory="vn"):
571         """Peek a byte of memory."""
572         return self.MONpeek8(address); #monitor
573     def peekblock(self,address,length,memory="vn"):
574         """Return a block of data."""
575         data=range(0,length);
576         for foo in range(0,length):
577             data[foo]=self.peek8(address+foo,memory);
578         return data;
579     def pokeblock(self,address,bytes,memory="vn"):
580         """Poke a block of a data into memory at an address."""
581         for foo in bytes:
582             self.pokebyte(address,foo,memory);
583             address=address+1;
584         return;
585     def loadsymbols(self):
586         """Load symbols from a file."""
587         return;