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