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