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