688219d76dd89a2c85465f033a89384e470edd9c
[goodfet] / client / GoodFETCC.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;
9 import binascii;
10
11 from GoodFET import GoodFET;
12 from intelhex import IntelHex;
13
14 import xml.dom.minidom;
15
16 class GoodFETCC(GoodFET):
17     """A GoodFET variant for use with Chipcon 8051 Zigbee SoC."""
18     APP=0x30;
19     
20     
21     
22     
23     smartrfpath="/opt/smartrf7";
24     def loadsymbols(self):
25         try: self.SRF_loadsymbols();
26         except:
27             if self.verbose>0: print "SmartRF not found at %s." % self.smartrfpath;
28     def SRF_chipdom(self,chip="cc1110", doc="register_definition.xml"):
29         fn="%s/config/xml/%s/%s" % (self.smartrfpath,chip,doc);
30         #print "Opening %s" % fn;
31         return xml.dom.minidom.parse(fn)
32         
33     def CMDrs(self,args=[]):
34         """Chip command to grab the radio state."""
35         try:
36             self.SRF_radiostate();
37         except:
38             print "Error printing radio state.";
39             print "SmartRF not found at %s." % self.smartrfpath;
40     def SRF_bitfieldstr(self,bf):
41         name="unused";
42         start=0;
43         stop=0;
44         access="";
45         reset="0x00";
46         description="";
47         for e in bf.childNodes:
48             if e.localName=="Name" and e.childNodes: name= e.childNodes[0].nodeValue;
49             elif e.localName=="Start": start=e.childNodes[0].nodeValue;
50             elif e.localName=="Stop": stop=e.childNodes[0].nodeValue;
51         return "   [%s:%s] %30s " % (start,stop,name);
52     def SRF_radiostate(self):
53         ident=self.CCident();
54         chip=self.CCversions.get(ident&0xFF00);
55         dom=self.SRF_chipdom(chip,"register_definition.xml");
56         for e in dom.getElementsByTagName("registerdefinition"):
57             for f in e.childNodes:
58                 if f.localName=="DeviceName":
59                     print "// %s RadioState" % (f.childNodes[0].nodeValue);
60                 elif f.localName=="Register":
61                     name="unknownreg";
62                     address="0xdead";
63                     description="";
64                     bitfields="";
65                     for g in f.childNodes:
66                         if g.localName=="Name":
67                             name=g.childNodes[0].nodeValue;
68                         elif g.localName=="Address":
69                             address=g.childNodes[0].nodeValue;
70                         elif g.localName=="Description":
71                             if g.childNodes:
72                                 description=g.childNodes[0].nodeValue;
73                         elif g.localName=="Bitfield":
74                             bitfields+="%17s/* %-50s */\n" % ("",self.SRF_bitfieldstr(g));
75                     #print "SFRX(%10s, %s); /* %50s */" % (name,address, description);
76                     print "%-10s=0x%02x; /* %-50s */" % (
77                         name,self.CCpeekdatabyte(eval(address)), description);
78                     if bitfields!="": print bitfields.rstrip();
79     def RF_setfreq(self,frequency):
80         """Set the frequency in Hz."""
81         #FIXME CC1110 specific
82         
83         hz=frequency;
84         freq=hz/396.728515625;
85         freq0=freq&0xFF;
86         freq1=(freq&0xFF00)>>8;
87         freq1=(freq&0xFF0000)>>16;
88         self.CCpokedatabyte(0xdf09,freq2);
89         self.CCpokedatabyte(0xdf09,freq1);
90         self.CCpokedatabyte(0xdf09,freq0);
91
92     def RF_getfreq(self):
93         """Get the frequency in Hz."""
94         #FIXME CC1110 specific
95         
96         #return (2400+self.peek(0x05))*10**6
97         #self.poke(0x05,chan);
98         freq2=self.CCpeekdatabyte(0xdf09);
99         freq1=self.CCpeekdatabyte(0xdf0a);
100         freq0=self.CCpeekdatabyte(0xdf0b);
101         freq=(freq2<<16)+(freq1<<8)+freq0;
102         hz=freq*396.728515625;
103         
104         return hz;
105     
106     def RF_carrier(self):
107         """Hold a carrier wave on the present frequency."""
108         # Set CONT_WAVE, PLL_LOCK, and 0dBm in RF_SETUP            
109         self.poke(0x06,8+10+4+2); 
110     
111     def RF_getrssi(self):
112         """Returns the received signal strenght, from 0 to 1."""
113         rssireg=self.symbols.get("RSSI");
114         return self.CCpeekdatabyte(rssireg);
115     def SRF_loadsymbols(self):
116         ident=self.CCident();
117         chip=self.CCversions.get(ident&0xFF00);
118         dom=self.SRF_chipdom(chip,"register_definition.xml");
119         for e in dom.getElementsByTagName("registerdefinition"):
120             for f in e.childNodes:
121                 if f.localName=="Register":
122                     name="unknownreg";
123                     address="0xdead";
124                     description="";
125                     bitfields="";
126                     for g in f.childNodes:
127                         if g.localName=="Name":
128                             name=g.childNodes[0].nodeValue;
129                         elif g.localName=="Address":
130                             address=g.childNodes[0].nodeValue;
131                         elif g.localName=="Description":
132                             if g.childNodes:
133                                 description=g.childNodes[0].nodeValue;
134                         elif g.localName=="Bitfield":
135                             bitfields+="%17s/* %-50s */\n" % ("",self.SRF_bitfieldstr(g));
136                     #print "SFRX(%10s, %s); /* %50s */" % (name,address, description);
137                     self.symbols.define(eval(address),name,description,"data");
138     def halt(self):
139         """Halt the CPU."""
140         self.CChaltcpu();
141     def CChaltcpu(self):
142         """Halt the CPU."""
143         self.writecmd(self.APP,0x86,0,self.data);
144     def resume(self):
145         self.CCreleasecpu();
146     def CCreleasecpu(self):
147         """Resume the CPU."""
148         self.writecmd(self.APP,0x87,0,self.data);
149     def test(self):
150         self.CCreleasecpu();
151         self.CChaltcpu();
152         #print "Status: %s" % self.CCstatusstr();
153         
154         #Grab ident three times, should be equal.
155         ident1=self.CCident();
156         ident2=self.CCident();
157         ident3=self.CCident();
158         if(ident1!=ident2 or ident2!=ident3):
159             print "Error, repeated ident attempts unequal."
160             print "%04x, %04x, %04x" % (ident1, ident2, ident3);
161         
162         #Single step, printing PC.
163         print "Tracing execution at startup."
164         for i in range(1,15):
165             pc=self.CCgetPC();
166             byte=self.CCpeekcodebyte(i);
167             #print "PC=%04x, %02x" % (pc, byte);
168             self.CCstep_instr();
169         
170         print "Verifying that debugging a NOP doesn't affect the PC."
171         for i in range(1,15):
172             pc=self.CCgetPC();
173             self.CCdebuginstr([0x00]);
174             if(pc!=self.CCgetPC()):
175                 print "ERROR: PC changed during CCdebuginstr([NOP])!";
176         
177         print "Checking pokes to XRAM."
178         for i in range(0xf000,0xf020):
179             self.CCpokedatabyte(i,0xde);
180             if(self.CCpeekdatabyte(i)!=0xde):
181                 print "Error in XDATA at 0x%04x" % i;
182         
183         #print "Status: %s." % self.CCstatusstr();
184         #Exit debugger
185         self.stop();
186         print "Done.";
187
188     def setup(self):
189         """Move the FET into the CC2430/CC2530 application."""
190         #print "Initializing Chipcon.";
191         self.writecmd(self.APP,0x10,0,self.data);
192     def CCrd_config(self):
193         """Read the config register of a Chipcon."""
194         self.writecmd(self.APP,0x82,0,self.data);
195         return ord(self.data[0]);
196     def CCwr_config(self,config):
197         """Write the config register of a Chipcon."""
198         self.writecmd(self.APP,0x81,1,[config&0xFF]);
199     def CClockchip(self):
200         """Set the flash lock bit in info mem."""
201         self.writecmd(self.APP, 0x9A, 0, None);
202     def lock(self):
203         """Set the flash lock bit in info mem."""
204         self.CClockchip();
205     
206
207     CCversions={0x0100:"cc1110",
208                 0x1100:"cc1111",
209                 0x8500:"cc2430",
210                 0x8900:"cc2431",
211                 0x8100:"cc2510",
212                 0x9100:"cc2511",
213                 0xA500:"cc2530", #page 52 of SWRU191
214                 0xB500:"cc2531",
215                 0xFF00:"CCmissing"};
216     CCpagesizes={0x01: 1024, #"CC1110",
217                  0x11: 1024, #"CC1111",
218                  0x85: 2048, #"CC2430",
219                  0x89: 2048, #"CC2431",
220                  0x81: 1024, #"CC2510",
221                  0x91: 1024, #"CC2511",
222                  0xA5: 2048, #"CC2530", #page 52 of SWRU191
223                  0xB5: 2048, #"CC2531",
224                  0xFF: 0    } #"CCmissing"};
225     def infostring(self):
226         return self.CCidentstr();
227     def CCidentstr(self):
228         ident=self.CCident();
229         chip=self.CCversions.get(ident&0xFF00);
230         pagesize=self.CCpagesizes.get(ident>0xFF);
231         try:
232             return "%s/r%0.4x/ps0x%0.4x" % (chip, ident, pagesize); 
233         except:
234             return "%04x" % ident;
235     def CCident(self):
236         """Get a chipcon's ID."""
237         self.writecmd(self.APP,0x8B,0,None);
238         chip=ord(self.data[0]);
239         rev=ord(self.data[1]);
240         return (chip<<8)+rev;
241     def CCpagesize(self):
242         """Get a chipcon's ID."""
243         self.writecmd(self.APP,0x8B,0,None);
244         chip=ord(self.data[0]);
245         size=self.CCpagesizes.get(chip);
246         if(size<10):
247             print "ERROR: Pagesize undefined.";
248             print "chip=%0.4x" %chip;
249             sys.exit(1);
250             #return 2048;
251         return size;
252     def getpc(self):
253         return self.CCgetPC();
254     def CCgetPC(self):
255         """Get a chipcon's PC."""
256         self.writecmd(self.APP,0x83,0,None);
257         hi=ord(self.data[0]);
258         lo=ord(self.data[1]);
259         return (hi<<8)+lo;
260     def CCcmd(self,phrase):
261         self.writecmd(self.APP,0x00,len(phrase),phrase);
262         val=ord(self.data[0]);
263         print "Got %02x" % val;
264         return val;
265     def CCdebuginstr(self,instr):
266         self.writecmd(self.APP,0x88,len(instr),instr);
267         return ord(self.data[0]);
268     def peekblock(self,adr,length,memory="vn"):
269         """Return a block of data."""
270         data=[adr&0xff, (adr&0xff00)>>8,
271               length&0xFF,(length&0xFF00)>>8];
272         self.writecmd(self.APP,0x91,4,data);
273         return [ord(x) for x in self.data]
274     def peek8(self,address, memory="code"):
275         if(memory=="code" or memory=="flash" or memory=="vn"):
276             return self.CCpeekcodebyte(address);
277         elif(memory=="data" or memory=="xdata" or memory=="ram"):
278             return self.CCpeekdatabyte(address);
279         elif(memory=="idata" or memory=="iram"):
280             return self.CCpeekirambyte(address);
281         print "%s is an unknown memory." % memory;
282         return 0xdead;
283     def CCpeekcodebyte(self,adr):
284         """Read the contents of code memory at an address."""
285         self.data=[adr&0xff, (adr&0xff00)>>8];
286         self.writecmd(self.APP,0x90,2,self.data);
287         return ord(self.data[0]);
288     def CCpeekdatabyte(self,adr):
289         """Read the contents of data memory at an address."""
290         self.data=[adr&0xff, (adr&0xff00)>>8];
291         self.writecmd(self.APP,0x91, 2, self.data);
292         return ord(self.data[0]);
293     def CCpeekirambyte(self,adr):
294         """Read the contents of IRAM at an address."""
295         self.data=[adr&0xff];
296         self.writecmd(self.APP,0x02, 1, self.data);
297         return ord(self.data[0]);
298     def CCpeekiramword(self,adr):
299         """Read the little-endian contents of IRAM at an address."""
300         return self.CCpeekirambyte(adr)+(
301             self.CCpeekirambyte(adr+1)<<8);
302     def CCpokeiramword(self,adr,val):
303         self.CCpokeirambyte(adr,val&0xff);
304         self.CCpokeirambyte(adr+1,(val>>8)&0xff);
305     def CCpokeirambyte(self,adr,val):
306         """Write the contents of IRAM at an address."""
307         self.data=[adr&0xff, val&0xff];
308         self.writecmd(self.APP,0x02, 2, self.data);
309         return ord(self.data[0]);
310     
311     def CCpokedatabyte(self,adr,val):
312         """Write a byte to data memory."""
313         self.data=[adr&0xff, (adr&0xff00)>>8, val];
314         self.writecmd(self.APP, 0x92, 3, self.data);
315         return ord(self.data[0]);
316     def CCchiperase(self):
317         """Erase all of the target's memory."""
318         self.writecmd(self.APP,0x80,0,None);
319     def erase(self):
320         """Erase all of the target's memory."""
321         self.CCchiperase();
322         self.start();
323     
324     def CCstatus(self):
325         """Check the status."""
326         self.writecmd(self.APP,0x84,0,None);
327         return ord(self.data[0])
328     #Same as CC2530
329     CCstatusbits={0x80 : "erase_busy",
330                   0x40 : "pcon_idle",
331                   0x20 : "cpu_halted",
332                   0x10 : "pm0",
333                   0x08 : "halt_status",
334                   0x04 : "locked",
335                   0x02 : "oscstable",
336                   0x01 : "overflow"
337                   };
338     CCconfigbits={0x20 : "soft_power_mode",   #new for CC2530
339                   0x08 : "timers_off",
340                   0x04 : "dma_pause",
341                   0x02 : "timer_suspend",
342                   0x01 : "sel_flash_info_page" #stricken from CC2530
343                   };
344                   
345     def status(self):
346         """Check the status as a string."""
347         status=self.CCstatus();
348         str="";
349         i=1;
350         while i<0x100:
351             if(status&i):
352                 str="%s %s" %(self.CCstatusbits[i],str);
353             i*=2;
354         return str;
355     def start(self):
356         """Start debugging."""
357         self.setup();
358         self.writecmd(self.APP,0x20,0,self.data);
359         ident=self.CCidentstr();
360         #print "Target identifies as %s." % ident;
361         #print "Status: %s." % self.status();
362         self.CCreleasecpu();
363         self.CChaltcpu();
364         #Get SmartRF Studio regs if they exist.
365         self.loadsymbols(); 
366         
367     def stop(self):
368         """Stop debugging."""
369         self.writecmd(self.APP,0x21,0,self.data);
370     def CCstep_instr(self):
371         """Step one instruction."""
372         self.writecmd(self.APP,0x89,0,self.data);
373     def CCeraseflashbuffer(self):
374         """Erase the 2kB flash buffer"""
375         self.writecmd(self.APP,0x99);
376     def CCflashpage(self,adr):
377         """Flash 2kB a page of flash from 0xF000 in XDATA"""
378         data=[adr&0xFF,
379               (adr>>8)&0xFF,
380               (adr>>16)&0xFF,
381               (adr>>24)&0xFF];
382         print "Flashing buffer to 0x%06x" % adr;
383         self.writecmd(self.APP,0x95,4,data);
384     
385     def setsecret(self,value):
386         """Set a secret word for later retreival.  Used by glitcher."""
387         page = 0x0000;
388         pagelen = self.CCpagesize(); #Varies by chip.
389         print "page=%04x, pagelen=%04x" % (page,pagelen);
390         
391         self.CCeraseflashbuffer();
392         print "Setting secret to %x" % value;
393         self.CCpokedatabyte(0xF000,value);
394         self.CCpokedatabyte(0xF800,value);
395         print "Setting secret to %x==%x" % (value,
396                                             self.CCpeekdatabyte(0xf000));
397         self.CCflashpage(0);
398         print "code[0]=%x" % self.CCpeekcodebyte(0);
399     def getsecret(self):
400         """Get a secret word.  Used by glitcher."""
401         secret=self.CCpeekcodebyte(0);
402         #print "Got secret %02x" % secret;
403         return secret;
404     
405     def dump(self,file,start=0,stop=0xffff):
406         """Dump an intel hex file from code memory."""
407         print "Dumping code from %04x to %04x as %s." % (start,stop,file);
408         h = IntelHex(None);
409         i=start;
410         while i<=stop:
411             h[i]=self.CCpeekcodebyte(i);
412             if(i%0x100==0):
413                 print "Dumped %04x."%i;
414                 h.write_hex_file(file); #buffer to disk.
415             i+=1;
416         h.write_hex_file(file);
417
418     def flash(self,file):
419         """Flash an intel hex file to code memory."""
420         print "Flashing %s" % file;
421         
422         h = IntelHex(file);
423         page = 0x0000;
424         pagelen = self.CCpagesize(); #Varies by chip.
425         
426         #print "page=%04x, pagelen=%04x" % (page,pagelen);
427         
428         bcount = 0;
429         
430         #Wipe the RAM buffer for the next flash page.
431         self.CCeraseflashbuffer();
432         for i in h._buf.keys():
433             while(i>=page+pagelen):
434                 if bcount>0:
435                     self.CCflashpage(page);
436                     #client.CCeraseflashbuffer();
437                     bcount=0;
438                     print "Flashed page at %06x" % page
439                 page+=pagelen;
440                     
441             #Place byte into buffer.
442             self.CCpokedatabyte(0xF000+i-page,
443                                 h[i]);
444             bcount+=1;
445             if(i%0x100==0):
446                 print "Buffering %04x toward %06x" % (i,page);
447         #last page
448         self.CCflashpage(page);
449         print "Flashed final page at %06x" % page;
450