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