TelosB support by platform variable.
[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=="chipcon": return GoodFETCC.GoodFETCC();
17     elif name=="avr": return GoodFETAVR.GoodFETAVR();
18     elif name=="spi": return GoodFETSPI.GoodFETSPI();
19     elif name=="msp430": return GoodFETMSP430.GoodFETMSP430();
20     elif name=="nrf": return GoodFETNRF.GoodFETNRF();
21     
22     print "Unsupported target: %s" % name;
23     sys.exit(0);
24
25 class SymbolTable:
26     """GoodFET Symbol Table"""
27     db=sqlite3.connect(":memory:");
28     
29     def __init__(self, *args, **kargs):
30         self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
31     def get(self,name):
32         self.db.commit();
33         c=self.db.cursor();
34         try:
35             c.execute("select adr,memory from symbols where name=?",(name,));
36             for row in c:
37                 #print "Found it.";
38                 sys.stdout.flush();
39                 return row[0];
40             #print "No dice.";
41         except:# sqlite3.OperationalError:
42             #print "SQL error.";
43             return eval(name);
44         return eval(name);
45     def define(self,adr,name,comment="",memory="vn",size=16):
46         self.db.execute("insert into symbols(adr,name,memory,size,comment)"
47                         "values(?,?,?,?,?);", (
48                 adr,name,memory,size,comment));
49         #print "Set %s=%s." % (name,adr);
50
51 class GoodFET:
52     """GoodFET Client Library"""
53
54     besilent=0;
55     app=0;
56     verb=0;
57     count=0;
58     data="";
59     verbose=False
60     
61     GLITCHAPP=0x71;
62     MONITORAPP=0x00;
63     symbols=SymbolTable();
64     
65     def __init__(self, *args, **kargs):
66         self.data=[0];
67     def getConsole(self):
68         from GoodFETConsole import GoodFETConsole;
69         return GoodFETConsole(self);
70     def name2adr(self,name):
71         return self.symbols.get(name);
72     def timeout(self):
73         print "timeout\n";
74     def serInit(self, port=None, timeout=2):
75         """Open the serial port"""
76         # Make timeout None to wait forever, 0 for non-blocking mode.
77         
78         if port is None and os.environ.get("GOODFET")!=None:
79             glob_list = glob.glob(os.environ.get("GOODFET"));
80             if len(glob_list) > 0:
81                 port = glob_list[0];
82             else:
83                 port = os.environ.get("GOODFET");
84         if port is None:
85             glob_list = glob.glob("/dev/tty.usbserial*");
86             if len(glob_list) > 0:
87                 port = glob_list[0];
88         if port is None:
89             glob_list = glob.glob("/dev/ttyUSB*");
90             if len(glob_list) > 0:
91                 port = glob_list[0];
92         if os.name=='nt':
93             from scanwin32 import winScan;
94             scan=winScan();
95             for order,comport,desc,hwid in sorted(scan.comports()):
96                 try:
97                     if hwid.index('FTDI')==0:
98                         port=comport;
99                         #print "Using FTDI port %s" % port
100                 except:
101                     #Do nothing.
102                     a=1;
103         
104         self.serialport = serial.Serial(
105             port,
106             #9600,
107             115200,
108             parity = serial.PARITY_NONE,
109             timeout=timeout
110             )
111         
112         self.verb=0;
113         attempts=0;
114         connected=0;
115         while connected==0:
116             while self.verb!=0x7F or self.data!="http://goodfet.sf.net/":
117                 #print "Resyncing.";
118                 self.serialport.flushInput()
119                 self.serialport.flushOutput()
120                 #Explicitly set RTS and DTR to halt board.
121                 self.serialport.setRTS(1);
122                 self.serialport.setDTR(1);
123                 #Drop DTR, which is !RST, low to begin the app.
124                 self.serialport.setDTR(0);
125                 
126                 #TelosB reset, prefer software to I2C SPST Switch.
127                 if(os.environ.get("platform")=='telosb'):
128                     self.telosBReset();
129                 #self.serialport.write(chr(0x80));
130                 #self.serialport.write(chr(0x80));
131                 #self.serialport.write(chr(0x80));
132                 #self.serialport.write(chr(0x80));
133                 
134                 
135                 self.serialport.flushInput()
136                 self.serialport.flushOutput()
137                 #time.sleep(60);
138                 attempts=attempts+1;
139                 self.readcmd(); #Read the first command.
140             #Here we have a connection, but maybe not a good one.
141             connected=1;
142             olds=self.infostring();
143             clocking=self.monitorclocking();
144             for foo in range(1,30):
145                 if not self.monitorecho():
146                     if self.verbose: print "Comm error on %i try, resyncing out of %s." % (foo,
147                                                   clocking);
148                     connected=0;
149                     break;
150         if self.verbose: print "Connected after %02i attempts." % attempts;
151         self.mon_connected();
152     def telosSetSCL(self, level):
153         self.serialport.setRTS(not level)
154     def telosSetSDA(self, level):
155         self.serialport.setDTR(not level)
156
157     def telosI2CStart(self):
158         self.telosSetSDA(1)
159         self.telosSetSCL(1)
160         self.telosSetSDA(0)
161
162     def telosI2CStop(self):
163         self.telosSetSDA(0)
164         self.telosSetSCL(1)
165         self.telosSetSDA(1)
166
167     def telosI2CWriteBit(self, bit):
168         self.telosSetSCL(0)
169         self.telosSetSDA(bit)
170         time.sleep(2e-6)
171         self.telosSetSCL(1)
172         time.sleep(1e-6)
173         self.telosSetSCL(0)
174
175     def telosI2CWriteByte(self, byte):
176         self.telosI2CWriteBit( byte & 0x80 );
177         self.telosI2CWriteBit( byte & 0x40 );
178         self.telosI2CWriteBit( byte & 0x20 );
179         self.telosI2CWriteBit( byte & 0x10 );
180         self.telosI2CWriteBit( byte & 0x08 );
181         self.telosI2CWriteBit( byte & 0x04 );
182         self.telosI2CWriteBit( byte & 0x02 );
183         self.telosI2CWriteBit( byte & 0x01 );
184         self.telosI2CWriteBit( 0 );  # "acknowledge"
185
186     def telosI2CWriteCmd(self, addr, cmdbyte):
187         self.telosI2CStart()
188         self.telosI2CWriteByte( 0x90 | (addr << 1) )
189         self.telosI2CWriteByte( cmdbyte )
190         self.telosI2CStop()
191
192     def telosBReset(self,invokeBSL=0):
193         # "BSL entry sequence at dedicated JTAG pins"
194         # rst !s0: 0 0 0 0 1 1
195         # tck !s1: 1 0 1 0 0 1
196         #   s0|s1: 1 3 1 3 2 0
197
198         # "BSL entry sequence at shared JTAG pins"
199         # rst !s0: 0 0 0 0 1 1
200         # tck !s1: 0 1 0 1 1 0
201         #   s0|s1: 3 1 3 1 0 2
202
203         if invokeBSL:
204             self.telosI2CWriteCmd(0,1)
205             self.telosI2CWriteCmd(0,3)
206             self.telosI2CWriteCmd(0,1)
207             self.telosI2CWriteCmd(0,3)
208             self.telosI2CWriteCmd(0,2)
209             self.telosI2CWriteCmd(0,0)
210         else:
211             self.telosI2CWriteCmd(0,3)
212             self.telosI2CWriteCmd(0,2)
213
214         # This line was not defined inside the else: block, not sure where it
215         # should be however
216         self.telosI2CWriteCmd(0,0)
217         time.sleep(0.250)       #give MSP430's oscillator time to stabilize
218         self.serialport.flushInput()  #clear buffers
219
220
221     def getbuffer(self,size=0x1c00):
222         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
223         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
224     def writecmd(self, app, verb, count=0, data=[]):
225         """Write a command and some data to the GoodFET."""
226         self.serialport.write(chr(app));
227         self.serialport.write(chr(verb));
228         
229         #if data!=None:
230         #    count=len(data); #Initial count ignored.
231         
232         #print "TX %02x %02x %04x" % (app,verb,count);
233         
234         #little endian 16-bit length
235         self.serialport.write(chr(count&0xFF));
236         self.serialport.write(chr(count>>8));
237
238         if self.verbose:
239             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
240         
241         #print "count=%02x, len(data)=%04x" % (count,len(data));
242         
243         if count!=0:
244             if(isinstance(data,list)):
245                 for i in range(0,count):
246                 #print "Converting %02x at %i" % (data[i],i)
247                     data[i]=chr(data[i]);
248             #print type(data);
249             outstr=''.join(data);
250             self.serialport.write(outstr);
251         if not self.besilent:
252             return self.readcmd()
253         else:
254             return []
255
256     def readcmd(self):
257         """Read a reply from the GoodFET."""
258         while 1:#self.serialport.inWaiting(): # Loop while input data is available
259             try:
260                 #print "Reading...";
261                 self.app=ord(self.serialport.read(1));
262                 #print "APP=%2x" % self.app;
263                 self.verb=ord(self.serialport.read(1));
264                 #print "VERB=%02x" % self.verb;
265                 self.count=(
266                     ord(self.serialport.read(1))
267                     +(ord(self.serialport.read(1))<<8)
268                     );
269
270                 if self.verbose:
271                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
272             
273                 #Debugging string; print, but wait.
274                 if self.app==0xFF:
275                     if self.verb==0xFF:
276                         print "# DEBUG %s" % self.serialport.read(self.count)
277                     elif self.verb==0xFE:
278                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
279                     elif self.verb==0xFD:
280                         #Do nothing, just wait so there's no timeout.
281                         print "# NOP.";
282                         
283                     sys.stdout.flush();
284                 else:
285                     self.data=self.serialport.read(self.count);
286                     return self.data;
287             except TypeError:
288                 if self.connected:
289                     print "Error: waiting for serial read timed out (most likely).";
290                     print "This shouldn't happen after syncing.  Exiting for safety.";
291                     sys.exit(-1)
292                 return self.data;
293     #Glitching stuff.
294     def glitchApp(self,app):
295         """Glitch into a device by its application."""
296         self.data=[app&0xff];
297         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
298         #return ord(self.data[0]);
299     def glitchVerb(self,app,verb,data):
300         """Glitch during a transaction."""
301         if data==None: data=[];
302         self.data=[app&0xff, verb&0xFF]+data;
303         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
304         #return ord(self.data[0]);
305     def glitchstart(self):
306         """Glitch into the AVR application."""
307         self.glitchVerb(self.APP,0x20,None);
308     def glitchstarttime(self):
309         """Measure the timer of the START verb."""
310         return self.glitchTime(self.APP,0x20,None);
311     def glitchTime(self,app,verb,data):
312         """Time the execution of a verb."""
313         if data==None: data=[];
314         self.data=[app&0xff, verb&0xFF]+data;
315         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
316         return ord(self.data[0])+(ord(self.data[1])<<8);
317     def glitchVoltages(self,low=0x0880, high=0x0fff):
318         """Set glitching voltages. (0x0fff is max.)"""
319         self.data=[low&0xff, (low>>8)&0xff,
320                    high&0xff, (high>>8)&0xff];
321         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
322         #return ord(self.data[0]);
323     def glitchRate(self,count=0x0800):
324         """Set glitching count period."""
325         self.data=[count&0xff, (count>>8)&0xff];
326         self.writecmd(self.GLITCHAPP,0x91,2,
327                       self.data);
328         #return ord(self.data[0]);
329     
330     
331     #Monitor stuff
332     def silent(self,s=0):
333         """Transmissions halted when 1."""
334         self.besilent=s;
335         print "besilent is %i" % self.besilent;
336         self.writecmd(0,0xB0,1,[s]);
337     connected=0;
338     def mon_connected(self):
339         """Announce to the monitor that the connection is good."""
340         self.connected=1;
341         self.writecmd(0,0xB1,0,[]);
342     def out(self,byte):
343         """Write a byte to P5OUT."""
344         self.writecmd(0,0xA1,1,[byte]);
345     def dir(self,byte):
346         """Write a byte to P5DIR."""
347         self.writecmd(0,0xA0,1,[byte]);
348     def call(self,adr):
349         """Call to an address."""
350         self.writecmd(0,0x30,2,
351                       [adr&0xFF,(adr>>8)&0xFF]);
352     def execute(self,code):
353         """Execute supplied code."""
354         self.writecmd(0,0x31,2,#len(code),
355                       code);
356     def peekbyte(self,address):
357         """Read a byte of memory from the monitor."""
358         self.data=[address&0xff,address>>8];
359         self.writecmd(0,0x02,2,self.data);
360         #self.readcmd();
361         return ord(self.data[0]);
362     def peekword(self,address):
363         """Read a word of memory from the monitor."""
364         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
365     def peek(self,address):
366         """Read a word of memory from the monitor."""
367         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
368     def pokebyte(self,address,value):
369         """Set a byte of memory by the monitor."""
370         self.data=[address&0xff,address>>8,value];
371         self.writecmd(0,0x03,3,self.data);
372         return ord(self.data[0]);
373     def dumpmem(self,begin,end):
374         i=begin;
375         while i<end:
376             print "%04x %04x" % (i, self.peekword(i));
377             i+=2;
378     def monitor_ram_pattern(self):
379         """Overwrite all of RAM with 0xBEEF."""
380         self.writecmd(0,0x90,0,self.data);
381         return;
382     def monitor_ram_depth(self):
383         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
384         self.writecmd(0,0x91,0,self.data);
385         return ord(self.data[0])+(ord(self.data[1])<<8);
386     
387     #Baud rates.
388     baudrates=[115200, 
389                9600,
390                19200,
391                38400,
392                57600,
393                115200];
394     def setBaud(self,baud):
395         """Change the baud rate.  TODO fix this."""
396         rates=self.baudrates;
397         self.data=[baud];
398         print "Changing FET baud."
399         self.serialport.write(chr(0x00));
400         self.serialport.write(chr(0x80));
401         self.serialport.write(chr(1));
402         self.serialport.write(chr(baud));
403         
404         print "Changed host baud."
405         self.serialport.setBaudrate(rates[baud]);
406         time.sleep(1);
407         self.serialport.flushInput()
408         self.serialport.flushOutput()
409         
410         print "Baud is now %i." % rates[baud];
411         return;
412     def readbyte(self):
413         return ord(self.serialport.read(1));
414     def findbaud(self):
415         for r in self.baudrates:
416             print "\nTrying %i" % r;
417             self.serialport.setBaudrate(r);
418             #time.sleep(1);
419             self.serialport.flushInput()
420             self.serialport.flushOutput()
421             
422             for i in range(1,10):
423                 self.readbyte();
424             
425             print "Read %02x %02x %02x %02x" % (
426                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
427     def monitortest(self):
428         """Self-test several functions through the monitor."""
429         print "Performing monitor self-test.";
430         self.monitorclocking();
431         for f in range(0,3000):
432             a=self.peekword(0x0c00);
433             b=self.peekword(0x0c02);
434             if a!=0x0c04 and a!=0x0c06:
435                 print "ERROR Fetched %04x, %04x" % (a,b);
436             self.pokebyte(0x0021,0); #Drop LED
437             if self.peekbyte(0x0021)!=0:
438                 print "ERROR, P1OUT not cleared.";
439             self.pokebyte(0x0021,1); #Light LED
440             if not self.monitorecho():
441                 print "Echo test failed.";
442         print "Self-test complete.";
443         self.monitorclocking();
444     def monitorecho(self):
445         data="The quick brown fox jumped over the lazy dog.";
446         self.writecmd(self.MONITORAPP,0x81,len(data),data);
447         if self.data!=data:
448             if self.verbose: print "Comm error recognized by monitorecho().";
449             return 0;
450         return 1;
451     def monitorclocking(self):
452         DCOCTL=self.peekbyte(0x0056);
453         BCSCTL1=self.peekbyte(0x0057);
454         return "0x%02x, 0x%02x" % (DCOCTL, BCSCTL1);
455
456     # The following functions ought to be implemented in
457     # every client.
458
459     def infostring(self):
460         a=self.peekbyte(0xff0);
461         b=self.peekbyte(0xff1);
462         return "%02x%02x" % (a,b);
463     def lock(self):
464         print "Locking Unsupported.";
465     def erase(self):
466         print "Erasure Unsupported.";
467     def setup(self):
468         return;
469     def start(self):
470         return;
471     def test(self):
472         print "Unimplemented.";
473         return;
474     def status(self):
475         print "Unimplemented.";
476         return;
477     def halt(self):
478         print "Unimplemented.";
479         return;
480     def resume(self):
481         print "Unimplemented.";
482         return;
483     def getpc(self):
484         print "Unimplemented.";
485         return 0xdead;
486     def flash(self,file):
487         """Flash an intel hex file to code memory."""
488         print "Flash not implemented.";
489     def dump(self,file,start=0,stop=0xffff):
490         """Dump an intel hex file from code memory."""
491         print "Dump not implemented.";
492     def peek32(self,address, memory="vn"):
493         return (self.peek16(address,memory)+
494                 (self.peek16(address+2,memory)<<16));
495     def peek16(self,address, memory="vn"):
496         return (self.peek8(address,memory)+
497                 (self.peek8(address+1,memory)<<8));
498     def peek8(self,address, memory="vn"):
499         return self.peekbyte(address); #monitor
500     def peekword(self,address, memory="vn"):
501         return self.peek(address); #monitor
502     
503     def loadsymbols(self):
504         return;