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