Script for sniffing OpenBeacon packets with NRF.
[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;
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     
21     print "Unsupported target: %s" % name;
22     sys.exit(0);
23
24 class SymbolTable:
25     """GoodFET Symbol Table"""
26     db=sqlite3.connect(":memory:");
27     
28     def __init__(self, *args, **kargs):
29         self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
30     def get(self,name):
31         self.db.commit();
32         c=self.db.cursor();
33         try:
34             c.execute("select adr,memory from symbols where name=?",(name,));
35             for row in c:
36                 #print "Found it.";
37                 sys.stdout.flush();
38                 return row[0];
39             #print "No dice.";
40         except:# sqlite3.OperationalError:
41             #print "SQL error.";
42             return eval(name);
43         return eval(name);
44     def define(self,adr,name,comment="",memory="vn",size=16):
45         self.db.execute("insert into symbols(adr,name,memory,size,comment)"
46                         "values(?,?,?,?,?);", (
47                 adr,name,memory,size,comment));
48         #print "Set %s=%s." % (name,adr);
49
50 class GoodFET:
51     """GoodFET Client Library"""
52
53     besilent=0;
54     app=0;
55     verb=0;
56     count=0;
57     data="";
58     verbose=False
59     
60     GLITCHAPP=0x71;
61     symbols=SymbolTable();
62     
63     def __init__(self, *args, **kargs):
64         self.data=[0];
65     def getConsole(self):
66         from GoodFETConsole import GoodFETConsole;
67         return GoodFETConsole(self);
68     def name2adr(self,name):
69         return self.symbols.get(name);
70     def timeout(self):
71         print "timeout\n";
72     def serInit(self, port=None, timeout=2):
73         """Open the serial port"""
74         # Make timeout None to wait forever, 0 for non-blocking mode.
75         
76         if port is None and os.environ.get("GOODFET")!=None:
77             glob_list = glob.glob(os.environ.get("GOODFET"));
78             if len(glob_list) > 0:
79                 port = glob_list[0];
80             else:
81                 port = os.environ.get("GOODFET");
82         if port is None:
83             glob_list = glob.glob("/dev/tty.usbserial*");
84             if len(glob_list) > 0:
85                 port = glob_list[0];
86         if port is None:
87             glob_list = glob.glob("/dev/ttyUSB*");
88             if len(glob_list) > 0:
89                 port = glob_list[0];
90         
91         
92         self.serialport = serial.Serial(
93             port,
94             #9600,
95             115200,
96             parity = serial.PARITY_NONE,
97             timeout=timeout
98             )
99         
100         self.verb=0;
101         attempts=0;
102         while self.verb!=0x7F:
103             self.serialport.flushInput()
104             self.serialport.flushOutput()
105             #Explicitly set RTS and DTR to halt board.
106             self.serialport.setRTS(1);
107             self.serialport.setDTR(1);
108             #Drop DTR, which is !RST, low to begin the app.
109             self.serialport.setDTR(0);
110             self.serialport.flushInput()
111             self.serialport.flushOutput()
112             #time.sleep(.1);
113             attempts=attempts+1;
114             self.readcmd(); #Read the first command.
115             
116         #print "Connected after %02i attempts." % attempts;
117         self.mon_connected();
118         
119     def getbuffer(self,size=0x1c00):
120         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
121         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
122     def writecmd(self, app, verb, count=0, data=[]):
123         """Write a command and some data to the GoodFET."""
124         self.serialport.write(chr(app));
125         self.serialport.write(chr(verb));
126         
127         #if data!=None:
128         #    count=len(data); #Initial count ignored.
129         
130         #print "TX %02x %02x %04x" % (app,verb,count);
131         
132         #little endian 16-bit length
133         self.serialport.write(chr(count&0xFF));
134         self.serialport.write(chr(count>>8));
135
136         if self.verbose:
137             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
138         
139         #print "count=%02x, len(data)=%04x" % (count,len(data));
140         
141         if count!=0:
142             if(isinstance(data,list)):
143                 for i in range(0,count):
144                 #print "Converting %02x at %i" % (data[i],i)
145                     data[i]=chr(data[i]);
146             #print type(data);
147             outstr=''.join(data);
148             self.serialport.write(outstr);
149         if not self.besilent:
150             return self.readcmd()
151         else:
152             return []
153
154     def readcmd(self):
155         """Read a reply from the GoodFET."""
156         while 1:#self.serialport.inWaiting(): # Loop while input data is available
157             try:
158                 #print "Reading...";
159                 self.app=ord(self.serialport.read(1));
160                 #print "APP=%2x" % self.app;
161                 self.verb=ord(self.serialport.read(1));
162                 #print "VERB=%02x" % self.verb;
163                 self.count=(
164                     ord(self.serialport.read(1))
165                     +(ord(self.serialport.read(1))<<8)
166                     );
167
168                 if self.verbose:
169                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
170             
171                 #Debugging string; print, but wait.
172                 if self.app==0xFF:
173                     if self.verb==0xFF:
174                         print "# DEBUG %s" % self.serialport.read(self.count)
175                     elif self.verb==0xFE:
176                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
177                     sys.stdout.flush();
178                 else:
179                     self.data=self.serialport.read(self.count);
180                     return self.data;
181             except TypeError:
182                 print "Error: waiting for serial read timed out (most likely)."
183                 sys.exit(-1)
184
185     #Glitching stuff.
186     def glitchApp(self,app):
187         """Glitch into a device by its application."""
188         self.data=[app&0xff];
189         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
190         #return ord(self.data[0]);
191     def glitchVerb(self,app,verb,data):
192         """Glitch during a transaction."""
193         if data==None: data=[];
194         self.data=[app&0xff, verb&0xFF]+data;
195         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
196         #return ord(self.data[0]);
197     def glitchstart(self):
198         """Glitch into the AVR application."""
199         self.glitchVerb(self.APP,0x20,None);
200     def glitchstarttime(self):
201         """Measure the timer of the START verb."""
202         return self.glitchTime(self.APP,0x20,None);
203     def glitchTime(self,app,verb,data):
204         """Time the execution of a verb."""
205         if data==None: data=[];
206         self.data=[app&0xff, verb&0xFF]+data;
207         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
208         return ord(self.data[0])+(ord(self.data[1])<<8);
209     def glitchVoltages(self,low=0x0880, high=0x0fff):
210         """Set glitching voltages. (0x0fff is max.)"""
211         self.data=[low&0xff, (low>>8)&0xff,
212                    high&0xff, (high>>8)&0xff];
213         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
214         #return ord(self.data[0]);
215     def glitchRate(self,count=0x0800):
216         """Set glitching count period."""
217         self.data=[count&0xff, (count>>8)&0xff];
218         self.writecmd(self.GLITCHAPP,0x91,2,
219                       self.data);
220         #return ord(self.data[0]);
221     
222     
223     #Monitor stuff
224     def silent(self,s=0):
225         """Transmissions halted when 1."""
226         self.besilent=s;
227         print "besilent is %i" % self.besilent;
228         self.writecmd(0,0xB0,1,[s]);
229     def mon_connected(self):
230         """Announce to the monitor that the connection is good."""
231         self.writecmd(0,0xB1,0,[]);
232     def out(self,byte):
233         """Write a byte to P5OUT."""
234         self.writecmd(0,0xA1,1,[byte]);
235     def dir(self,byte):
236         """Write a byte to P5DIR."""
237         self.writecmd(0,0xA0,1,[byte]);
238     def call(self,adr):
239         """Call to an address."""
240         self.writecmd(0,0x30,2,
241                       [adr&0xFF,(adr>>8)&0xFF]);
242     def execute(self,code):
243         """Execute supplied code."""
244         self.writecmd(0,0x31,2,#len(code),
245                       code);
246     def peekbyte(self,address):
247         """Read a byte of memory from the monitor."""
248         self.data=[address&0xff,address>>8];
249         self.writecmd(0,0x02,2,self.data);
250         #self.readcmd();
251         return ord(self.data[0]);
252     def peekword(self,address):
253         """Read a word of memory from the monitor."""
254         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
255     def pokebyte(self,address,value):
256         """Set a byte of memory by the monitor."""
257         self.data=[address&0xff,address>>8,value];
258         self.writecmd(0,0x03,3,self.data);
259         return ord(self.data[0]);
260     def dumpmem(self,begin,end):
261         i=begin;
262         while i<end:
263             print "%04x %04x" % (i, self.peekword(i));
264             i+=2;
265     def monitor_ram_pattern(self):
266         """Overwrite all of RAM with 0xBEEF."""
267         self.writecmd(0,0x90,0,self.data);
268         return;
269     def monitor_ram_depth(self):
270         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
271         self.writecmd(0,0x91,0,self.data);
272         return ord(self.data[0])+(ord(self.data[1])<<8);
273     
274     #Baud rates.
275     baudrates=[115200, 
276                9600,
277                19200,
278                38400,
279                57600,
280                115200];
281     def setBaud(self,baud):
282         """Change the baud rate.  TODO fix this."""
283         rates=self.baudrates;
284         self.data=[baud];
285         print "Changing FET baud."
286         self.serialport.write(chr(0x00));
287         self.serialport.write(chr(0x80));
288         self.serialport.write(chr(1));
289         self.serialport.write(chr(baud));
290         
291         print "Changed host baud."
292         self.serialport.setBaudrate(rates[baud]);
293         time.sleep(1);
294         self.serialport.flushInput()
295         self.serialport.flushOutput()
296         
297         print "Baud is now %i." % rates[baud];
298         return;
299     def readbyte(self):
300         return ord(self.serialport.read(1));
301     def findbaud(self):
302         for r in self.baudrates:
303             print "\nTrying %i" % r;
304             self.serialport.setBaudrate(r);
305             #time.sleep(1);
306             self.serialport.flushInput()
307             self.serialport.flushOutput()
308             
309             for i in range(1,10):
310                 self.readbyte();
311             
312             print "Read %02x %02x %02x %02x" % (
313                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
314     def monitortest(self):
315         """Self-test several functions through the monitor."""
316         print "Performing monitor self-test.";
317         
318         for f in range(0,30):
319             if self.peekword(0x0c00)!=0x0c04 and self.peekword(0x0c00)!=0x0c06:
320                 print "ERROR Fetched wrong value from 0x0c04.";
321             self.pokebyte(0x0021,0); #Drop LED
322             if self.peekbyte(0x0021)!=0:
323                 print "ERROR, P1OUT not cleared.";
324             self.pokebyte(0x0021,1); #Light LED
325         
326         print "Self-test complete.";
327     
328     
329     # The following functions ought to be implemented in
330     # every client.
331
332     def infostring(self):
333         a=self.peekbyte(0xff0);
334         b=self.peekbyte(0xff1);
335         return "%02x%02x" % (a,b);
336     def lock(self):
337         print "Locking Unsupported.";
338     def erase(self):
339         print "Erasure Unsupported.";
340     def setup(self):
341         return;
342     def start(self):
343         return;
344     def test(self):
345         print "Unimplemented.";
346         return;
347     def status(self):
348         print "Unimplemented.";
349         return;
350     def halt(self):
351         print "Unimplemented.";
352         return;
353     def resume(self):
354         print "Unimplemented.";
355         return;
356     def getpc(self):
357         print "Unimplemented.";
358         return 0xdead;
359     def flash(self,file):
360         """Flash an intel hex file to code memory."""
361         print "Flash not implemented.";
362     def dump(self,file,start=0,stop=0xffff):
363         """Dump an intel hex file from code memory."""
364         print "Dump not implemented.";
365
366     def peek32(self,address, memory="vn"):
367         return (self.peek16(address,memory)+
368                 (self.peek16(address+2,memory)<<16));
369     def peek16(self,address, memory="vn"):
370         return (self.peek8(address,memory)+
371                 (self.peek8(address+1,memory)<<8));
372     def peek8(self,address, memory="vn"):
373         return self.peekbyte(address); #monitor
374     def loadsymbols(self):
375         return;