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