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