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