Reflexive jamming works. Could be a lot cleaner.
[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 shellcode(self,code,wait=1):
119         """Copy a block of code into RAM and execute it."""
120         i=0;
121         ram=0xF000;
122         for byte in code:
123             self.pokebyte(0xF000+i,byte);
124             i=i+1;
125         #print "Code loaded, executing."
126         self.CCdebuginstr([0x02, 0xf0, 0x00]); #ljmp 0xF000
127         self.resume();
128         while wait>0 and (0==self.CCstatus()&0x20):
129             time.sleep(0.1);
130             #print "Waiting for shell code to return.";
131         return;
132     def CC1110_crystal(self):
133         """Start the main crystal of the CC1110 oscillating, needed for radio use."""
134         code=[0x53, 0xBE, 0xFB, #anl SLEEP, #0xFB
135               #one:
136               0xE5, 0xBE,       #mov a,SLEEP
137               0x30, 0xE6, 0xFB, #jnb acc.6, back
138               0x53, 0xc6, 0xB8, #anl CLKCON, #0xB8
139               #two
140               0xE5, 0xC6,       #mov a,CLKCON
141               0x20, 0xE6, 0xFB, #jb acc.6, two
142               0x43, 0xBE, 0x04, #orl SLEEP, #0x04
143               0xA5,             #HALT
144               ];
145         self.shellcode(code);
146         return;
147     def RF_idle(self):
148         RFST=0xDFE1
149         self.pokebyte(RFST,0x04); #Return to idle state.
150     
151     def config_simpliciti(self,band="none"):
152         self.pokebysym("FSCTRL1"  , 0x08)   # Frequency synthesizer control.
153         self.pokebysym("FSCTRL0"  , 0x00)   # Frequency synthesizer control.
154         
155         #Don't change these while the radio is active.
156         self.pokebysym("FSCAL3"   , 0xEA)   # Frequency synthesizer calibration.
157         self.pokebysym("FSCAL2"   , 0x2A)   # Frequency synthesizer calibration.
158         self.pokebysym("FSCAL1"   , 0x00)   # Frequency synthesizer calibration.
159         self.pokebysym("FSCAL0"   , 0x1F)   # Frequency synthesizer calibration.
160         
161         if band=="ismeu" or band=="eu":
162             self.pokebysym("FREQ2"    , 0x21)   # Frequency control word, high byte.
163             self.pokebysym("FREQ1"    , 0x71)   # Frequency control word, middle byte.
164             self.pokebysym("FREQ0"    , 0x7a)   # Frequency control word, low byte.
165         if band=="ismus" or band=="us":
166             self.pokebysym("FREQ2"    , 0x22)   # Frequency control word, high byte.
167             self.pokebysym("FREQ1"    , 0xB1)   # Frequency control word, middle byte.
168             self.pokebysym("FREQ0"    , 0x3B)   # Frequency control word, low byte.
169         if band=="ismlf" or band=="lf":
170             self.pokebysym("FREQ2"    , 0x10)   # Frequency control word, high byte.
171             self.pokebysym("FREQ1"    , 0xB0)   # Frequency control word, middle byte.
172             self.pokebysym("FREQ0"    , 0x71)   # Frequency control word, low byte.
173         
174         self.pokebysym("MDMCFG4"  , 0x7B)   # Modem configuration.
175         self.pokebysym("MDMCFG3"  , 0x83)   # Modem configuration.
176         self.pokebysym("MDMCFG2"  , 0x13)   # Modem configuration.
177         self.pokebysym("MDMCFG1"  , 0x22)   # Modem configuration.
178         self.pokebysym("MDMCFG0"  , 0xF8)   # Modem configuration.
179         self.pokebysym("CHANNR"   , 0x00)   # Channel number.
180         self.pokebysym("DEVIATN"  , 0x42)   # Modem deviation setting (when FSK modulation is enabled).
181         
182         self.pokebysym("FREND1"   , 0xB6)   # Front end RX configuration.
183         self.pokebysym("FREND0"   , 0x10)   # Front end RX configuration.
184         self.pokebysym("MCSM0"    , 0x18)   # Main Radio Control State Machine configuration.
185         self.pokebysym("FOCCFG"   , 0x1D)   # Frequency Offset Compensation Configuration.
186         self.pokebysym("BSCFG"    , 0x1C)   # Bit synchronization Configuration.
187         
188         self.pokebysym("AGCCTRL2" , 0xC7)   # AGC control.
189         self.pokebysym("AGCCTRL1" , 0x00)   # AGC control.
190         self.pokebysym("AGCCTRL0" , 0xB2)   # AGC control.
191         
192         self.pokebysym("TEST2"    , 0x81)   # Various test settings.
193         self.pokebysym("TEST1"    , 0x35)   # Various test settings.
194         self.pokebysym("TEST0"    , 0x09)   # Various test settings.
195         #self.pokebysym("PA_TABLE0", 0xC0)   # PA output power setting.
196         self.pokebysym("PKTCTRL1" , 0x04)   # Packet automation control.
197         self.pokebysym("PKTCTRL0" , 0x05)   # Packet automation control.
198         self.pokebysym("ADDR"     , 0x00)   # Device address.
199         self.pokebysym("PKTLEN"   , 0xFF)   # Packet length.
200         
201         self.pokebysym("SYNC1",0xAA);
202         self.pokebysym("SYNC0",0xAA);
203         
204     def RF_carrier(self):
205         """Hold a carrier wave on the present frequency."""
206         
207         self.CC1110_crystal(); #FIXME, '1110 specific.
208         self.RF_idle();
209         
210         #self.resume();
211         #time.sleep(1);
212         #self.halt();
213         
214         RFST=0xDFE1;
215         
216         
217         self.pokebysym("FSCTRL1"  , 0x0a)   # Frequency synthesizer control.
218         self.pokebysym("FSCTRL0"  , 0x00)   # Frequency synthesizer control.
219         
220         #Don't change these while the radio is active.
221         self.pokebysym("FSCAL3"   , 0xA9)   # Frequency synthesizer calibration.
222         self.pokebysym("FSCAL2"   , 0x0A)   # Frequency synthesizer calibration.
223         self.pokebysym("FSCAL1"   , 0x00)   # Frequency synthesizer calibration.
224         self.pokebysym("FSCAL0"   , 0x11)   # Frequency synthesizer calibration.
225         
226         
227         #self.pokebysym("FREQ2"    , 0x10)   # Frequency control word, high byte.
228         #self.pokebysym("FREQ1"    , 0xEC)   # Frequency control word, middle byte.
229         #self.pokebysym("FREQ0"    , 0x4E)   # Frequency control word, low byte.
230         self.pokebysym("MDMCFG4"  , 0x86)   # Modem configuration.
231         self.pokebysym("MDMCFG3"  , 0x83)   # Modem configuration.
232         self.pokebysym("MDMCFG2"  , 0x30)   # Modem configuration.
233         self.pokebysym("MDMCFG1"  , 0x22)   # Modem configuration.
234         self.pokebysym("MDMCFG0"  , 0xF8)   # Modem configuration.
235         self.pokebysym("CHANNR"   , 0x00)   # Channel number.
236         self.pokebysym("DEVIATN"  , 0x00)   # Modem deviation setting (when FSK modulation is enabled).
237         self.pokebysym("FREND1"   , 0x56)   # Front end RX configuration.
238         
239         self.pokebysym("FREND0"   , 0x10)   # Front end RX configuration.
240         self.pokebysym("MCSM0"    , 0x14)   # Main Radio Control State Machine configuration.
241         self.pokebysym("FOCCFG"   , 0x16)   # Frequency Offset Compensation Configuration.
242         self.pokebysym("BSCFG"    , 0x6C)   # Bit synchronization Configuration.
243         
244         self.pokebysym("AGCCTRL2" , 0x03)   # AGC control.
245         self.pokebysym("AGCCTRL1" , 0x40)   # AGC control.
246         self.pokebysym("AGCCTRL0" , 0x91)   # AGC control.
247         
248         self.pokebysym("TEST2"    , 0x88)   # Various test settings.
249         self.pokebysym("TEST1"    , 0x31)   # Various test settings.
250         self.pokebysym("TEST0"    , 0x09)   # Various test settings.
251         self.pokebysym("PA_TABLE0", 0xC0)   # PA output power setting.
252         self.pokebysym("PKTCTRL1" , 0x04)   # Packet automation control.
253         self.pokebysym("PKTCTRL0" , 0x22)   # Packet automation control.
254         self.pokebysym("ADDR"     , 0x00)   # Device address.
255         self.pokebysym("PKTLEN"   , 0xFF)   # Packet length.
256         
257         self.pokebysym("SYNC1",0xAA);
258         self.pokebysym("SYNC0",0xAA);
259         
260         
261         
262         #while ((MARCSTATE & MARCSTATE_MARC_STATE) != MARC_STATE_TX); 
263         state=0;
264         
265         while((state!=0x13)):
266             self.pokebyte(RFST,0x03); #RFST=RFST_STX
267             time.sleep(0.1);
268             state=self.peekbysym("MARCSTATE")&0x1F;
269             #print "state=%02x" % state;
270         print "Holding a carrier on %f MHz." % (self.RF_getfreq()/10**6);
271         
272         #Not needed, radio works when CPU is halted.
273         #self.resume();
274         
275         return;
276             
277     def RF_getsmac(self):
278         """Return the source MAC address."""
279         
280         #Register 0A is RX_ADDR_P0, five bytes.
281         mac=self.peekbysym("ADDR");
282         return mac;
283     def RF_setsmac(self,mac):
284         """Set the source MAC address."""
285         self.pokebysym("ADDR",mac);
286         return 0;
287     def RF_gettmac(self):
288         """Return the target MAC address."""
289         return 0;
290     def RF_settmac(self,mac):
291         """Set the target MAC address."""
292         return 0;
293     def RF_rxpacket(self):
294         """Get a packet from the radio.  Returns None if none is waiting."""
295         RFST=0xDFE1
296         self.pokebyte(RFST,0x01); #SCAL
297         self.pokebyte(RFST,0x02); #SRX
298         
299         print "Packet reception isn't working yet.  Returning [RSSI].";
300         time.sleep(0.1);
301         return [chr(self.RF_getrssi())];
302     def RF_txpacket(self,payload):
303         """Transmit a packet.  Untested."""
304         
305         print "FIXME, Chipcon packet transmission is not yet implemented.";
306         return;
307
308     def RF_getrssi(self):
309         """Returns the received signal strenght, with a weird offset."""
310         try:
311             rssireg=self.symbols.get("RSSI");
312             return self.CCpeekdatabyte(rssireg)^0x80;
313         except:
314             if self.verbose>0: print "RSSI reg doesn't exist.";
315         try:
316             #RSSI doesn't exist on 2.4GHz devices.  Maybe RSSIL and RSSIH?
317             rssilreg=self.symbols.get("RSSIL");
318             rssil=self.CCpeekdatabyte(rssilreg);
319             rssihreg=self.symbols.get("RSSIL");
320             rssih=self.CCpeekdatabyte(rssihreg);
321             return (rssih<<8)|rssil;
322         except:
323             if self.verbose>0: print "RSSIL/RSSIH regs don't exist.";
324         
325         return 0;
326     
327     
328     
329     def SRF_loadsymbols(self):
330         ident=self.CCident();
331         chip=self.CCversions.get(ident&0xFF00);
332         dom=self.SRF_chipdom(chip,"register_definition.xml");
333         for e in dom.getElementsByTagName("registerdefinition"):
334             for f in e.childNodes:
335                 if f.localName=="Register":
336                     name="unknownreg";
337                     address="0xdead";
338                     description="";
339                     bitfields="";
340                     for g in f.childNodes:
341                         if g.localName=="Name":
342                             name=g.childNodes[0].nodeValue;
343                         elif g.localName=="Address":
344                             address=g.childNodes[0].nodeValue;
345                         elif g.localName=="Description":
346                             if g.childNodes:
347                                 description=g.childNodes[0].nodeValue;
348                         elif g.localName=="Bitfield":
349                             bitfields+="%17s/* %-50s */\n" % ("",self.SRF_bitfieldstr(g));
350                     #print "SFRX(%10s, %s); /* %50s */" % (name,address, description);
351                     self.symbols.define(eval(address),name,description,"data");
352     def halt(self):
353         """Halt the CPU."""
354         self.CChaltcpu();
355     def CChaltcpu(self):
356         """Halt the CPU."""
357         self.writecmd(self.APP,0x86,0,self.data);
358     def resume(self):
359         self.CCreleasecpu();
360     def CCreleasecpu(self):
361         """Resume the CPU."""
362         self.writecmd(self.APP,0x87,0,self.data);
363     def test(self):
364         self.CCreleasecpu();
365         self.CChaltcpu();
366         #print "Status: %s" % self.CCstatusstr();
367         
368         #Grab ident three times, should be equal.
369         ident1=self.CCident();
370         ident2=self.CCident();
371         ident3=self.CCident();
372         if(ident1!=ident2 or ident2!=ident3):
373             print "Error, repeated ident attempts unequal."
374             print "%04x, %04x, %04x" % (ident1, ident2, ident3);
375         
376         #Single step, printing PC.
377         print "Tracing execution at startup."
378         for i in range(1,15):
379             pc=self.CCgetPC();
380             byte=self.CCpeekcodebyte(i);
381             #print "PC=%04x, %02x" % (pc, byte);
382             self.CCstep_instr();
383         
384         print "Verifying that debugging a NOP doesn't affect the PC."
385         for i in range(1,15):
386             pc=self.CCgetPC();
387             self.CCdebuginstr([0x00]);
388             if(pc!=self.CCgetPC()):
389                 print "ERROR: PC changed during CCdebuginstr([NOP])!";
390         
391         print "Checking pokes to XRAM."
392         for i in range(0xf000,0xf020):
393             self.CCpokedatabyte(i,0xde);
394             if(self.CCpeekdatabyte(i)!=0xde):
395                 print "Error in XDATA at 0x%04x" % i;
396         
397         #print "Status: %s." % self.CCstatusstr();
398         #Exit debugger
399         self.stop();
400         print "Done.";
401
402     def setup(self):
403         """Move the FET into the CC2430/CC2530 application."""
404         #print "Initializing Chipcon.";
405         self.writecmd(self.APP,0x10,0,self.data);
406     def CCrd_config(self):
407         """Read the config register of a Chipcon."""
408         self.writecmd(self.APP,0x82,0,self.data);
409         return ord(self.data[0]);
410     def CCwr_config(self,config):
411         """Write the config register of a Chipcon."""
412         self.writecmd(self.APP,0x81,1,[config&0xFF]);
413     def CClockchip(self):
414         """Set the flash lock bit in info mem."""
415         self.writecmd(self.APP, 0x9A, 0, None);
416     def lock(self):
417         """Set the flash lock bit in info mem."""
418         self.CClockchip();
419     
420
421     CCversions={0x0100:"cc1110",
422                 0x1100:"cc1111",
423                 0x8500:"cc2430",
424                 0x8900:"cc2431",
425                 0x8100:"cc2510",
426                 0x9100:"cc2511",
427                 0xA500:"cc2530", #page 52 of SWRU191
428                 0xB500:"cc2531",
429                 0xFF00:"CCmissing"};
430     CCpagesizes={0x01: 1024, #"CC1110",
431                  0x11: 1024, #"CC1111",
432                  0x85: 2048, #"CC2430",
433                  0x89: 2048, #"CC2431",
434                  0x81: 1024, #"CC2510",
435                  0x91: 1024, #"CC2511",
436                  0xA5: 2048, #"CC2530", #page 52 of SWRU191
437                  0xB5: 2048, #"CC2531",
438                  0xFF: 0    } #"CCmissing"};
439     def infostring(self):
440         return self.CCidentstr();
441     def CCidentstr(self):
442         ident=self.CCident();
443         chip=self.CCversions.get(ident&0xFF00);
444         pagesize=self.CCpagesizes.get(ident>0xFF);
445         try:
446             return "%s/r%0.4x/ps0x%0.4x" % (chip, ident, pagesize); 
447         except:
448             return "%04x" % ident;
449     def CCident(self):
450         """Get a chipcon's ID."""
451         self.writecmd(self.APP,0x8B,0,None);
452         chip=ord(self.data[0]);
453         rev=ord(self.data[1]);
454         return (chip<<8)+rev;
455     def CCpagesize(self):
456         """Get a chipcon's ID."""
457         self.writecmd(self.APP,0x8B,0,None);
458         chip=ord(self.data[0]);
459         size=self.CCpagesizes.get(chip);
460         if(size<10):
461             print "ERROR: Pagesize undefined.";
462             print "chip=%0.4x" %chip;
463             sys.exit(1);
464             #return 2048;
465         return size;
466     def getpc(self):
467         return self.CCgetPC();
468     def CCgetPC(self):
469         """Get a chipcon's PC."""
470         self.writecmd(self.APP,0x83,0,None);
471         hi=ord(self.data[0]);
472         lo=ord(self.data[1]);
473         return (hi<<8)+lo;
474     def CCcmd(self,phrase):
475         self.writecmd(self.APP,0x00,len(phrase),phrase);
476         val=ord(self.data[0]);
477         print "Got %02x" % val;
478         return val;
479     def CCdebuginstr(self,instr):
480         self.writecmd(self.APP,0x88,len(instr),instr);
481         return ord(self.data[0]);
482     def peekblock(self,adr,length,memory="vn"):
483         """Return a block of data."""
484         data=[adr&0xff, (adr&0xff00)>>8,
485               length&0xFF,(length&0xFF00)>>8];
486         self.writecmd(self.APP,0x91,4,data);
487         return [ord(x) for x in self.data]
488     def peek8(self,address, memory="code"):
489         if(memory=="code" or memory=="flash" or memory=="vn"):
490             return self.CCpeekcodebyte(address);
491         elif(memory=="data" or memory=="xdata" or memory=="ram"):
492             return self.CCpeekdatabyte(address);
493         elif(memory=="idata" or memory=="iram"):
494             return self.CCpeekirambyte(address);
495         print "%s is an unknown memory." % memory;
496         return 0xdead;
497     def CCpeekcodebyte(self,adr):
498         """Read the contents of code memory at an address."""
499         self.data=[adr&0xff, (adr&0xff00)>>8];
500         self.writecmd(self.APP,0x90,2,self.data);
501         return ord(self.data[0]);
502     def CCpeekdatabyte(self,adr):
503         """Read the contents of data memory at an address."""
504         self.data=[adr&0xff, (adr&0xff00)>>8];
505         self.writecmd(self.APP,0x91, 2, self.data);
506         return ord(self.data[0]);
507     def CCpeekirambyte(self,adr):
508         """Read the contents of IRAM at an address."""
509         self.data=[adr&0xff];
510         self.writecmd(self.APP,0x02, 1, self.data);
511         return ord(self.data[0]);
512     def CCpeekiramword(self,adr):
513         """Read the little-endian contents of IRAM at an address."""
514         return self.CCpeekirambyte(adr)+(
515             self.CCpeekirambyte(adr+1)<<8);
516     def CCpokeiramword(self,adr,val):
517         self.CCpokeirambyte(adr,val&0xff);
518         self.CCpokeirambyte(adr+1,(val>>8)&0xff);
519     def CCpokeirambyte(self,adr,val):
520         """Write the contents of IRAM at an address."""
521         self.data=[adr&0xff, val&0xff];
522         self.writecmd(self.APP,0x02, 2, self.data);
523         return ord(self.data[0]);
524     def pokebyte(self,adr,val,mem="data"):
525         if mem!="data":
526             print "FIXME: poking of non data bytes not yet supported.";
527         self.CCpokedatabyte(adr,val);
528     def CCpokedatabyte(self,adr,val):
529         """Write a byte to data memory."""
530         self.data=[adr&0xff, (adr&0xff00)>>8, val];
531         self.writecmd(self.APP, 0x92, 3, self.data);
532         return ord(self.data[0]);
533     def CCchiperase(self):
534         """Erase all of the target's memory."""
535         self.writecmd(self.APP,0x80,0,None);
536     def erase(self):
537         """Erase all of the target's memory."""
538         self.CCchiperase();
539         self.start();
540     
541     def CCstatus(self):
542         """Check the status."""
543         self.writecmd(self.APP,0x84,0,None);
544         return ord(self.data[0])
545     #Same as CC2530
546     CCstatusbits={0x80 : "erase_busy",
547                   0x40 : "pcon_idle",
548                   0x20 : "cpu_halted",
549                   0x10 : "pm0",
550                   0x08 : "halt_status",
551                   0x04 : "locked",
552                   0x02 : "oscstable",
553                   0x01 : "overflow"
554                   };
555     CCconfigbits={0x20 : "soft_power_mode",   #new for CC2530
556                   0x08 : "timers_off",
557                   0x04 : "dma_pause",
558                   0x02 : "timer_suspend",
559                   0x01 : "sel_flash_info_page" #stricken from CC2530
560                   };
561                   
562     def status(self):
563         """Check the status as a string."""
564         status=self.CCstatus();
565         str="";
566         i=1;
567         while i<0x100:
568             if(status&i):
569                 str="%s %s" %(self.CCstatusbits[i],str);
570             i*=2;
571         return str;
572     def start(self):
573         """Start debugging."""
574         self.setup();
575         self.writecmd(self.APP,0x20,0,self.data);
576         ident=self.CCidentstr();
577         #print "Target identifies as %s." % ident;
578         #print "Status: %s." % self.status();
579         self.CCreleasecpu();
580         self.CChaltcpu();
581         #Get SmartRF Studio regs if they exist.
582         self.loadsymbols(); 
583         
584     def stop(self):
585         """Stop debugging."""
586         self.writecmd(self.APP,0x21,0,self.data);
587     def CCstep_instr(self):
588         """Step one instruction."""
589         self.writecmd(self.APP,0x89,0,self.data);
590     def CCeraseflashbuffer(self):
591         """Erase the 2kB flash buffer"""
592         self.writecmd(self.APP,0x99);
593     def CCflashpage(self,adr):
594         """Flash 2kB a page of flash from 0xF000 in XDATA"""
595         data=[adr&0xFF,
596               (adr>>8)&0xFF,
597               (adr>>16)&0xFF,
598               (adr>>24)&0xFF];
599         print "Flashing buffer to 0x%06x" % adr;
600         self.writecmd(self.APP,0x95,4,data);
601     
602     def setsecret(self,value):
603         """Set a secret word for later retreival.  Used by glitcher."""
604         page = 0x0000;
605         pagelen = self.CCpagesize(); #Varies by chip.
606         print "page=%04x, pagelen=%04x" % (page,pagelen);
607         
608         self.CCeraseflashbuffer();
609         print "Setting secret to %x" % value;
610         self.CCpokedatabyte(0xF000,value);
611         self.CCpokedatabyte(0xF800,value);
612         print "Setting secret to %x==%x" % (value,
613                                             self.CCpeekdatabyte(0xf000));
614         self.CCflashpage(0);
615         print "code[0]=%x" % self.CCpeekcodebyte(0);
616     def getsecret(self):
617         """Get a secret word.  Used by glitcher."""
618         secret=self.CCpeekcodebyte(0);
619         #print "Got secret %02x" % secret;
620         return secret;
621     
622     def dump(self,file,start=0,stop=0xffff):
623         """Dump an intel hex file from code memory."""
624         print "Dumping code from %04x to %04x as %s." % (start,stop,file);
625         h = IntelHex(None);
626         i=start;
627         while i<=stop:
628             h[i]=self.CCpeekcodebyte(i);
629             if(i%0x100==0):
630                 print "Dumped %04x."%i;
631                 h.write_hex_file(file); #buffer to disk.
632             i+=1;
633         h.write_hex_file(file);
634
635     def flash(self,file):
636         """Flash an intel hex file to code memory."""
637         print "Flashing %s" % file;
638         
639         h = IntelHex(file);
640         page = 0x0000;
641         pagelen = self.CCpagesize(); #Varies by chip.
642         
643         #print "page=%04x, pagelen=%04x" % (page,pagelen);
644         
645         bcount = 0;
646         
647         #Wipe the RAM buffer for the next flash page.
648         self.CCeraseflashbuffer();
649         for i in h._buf.keys():
650             while(i>=page+pagelen):
651                 if bcount>0:
652                     self.CCflashpage(page);
653                     #client.CCeraseflashbuffer();
654                     bcount=0;
655                     print "Flashed page at %06x" % page
656                 page+=pagelen;
657                     
658             #Place byte into buffer.
659             self.CCpokedatabyte(0xF000+i-page,
660                                 h[i]);
661             bcount+=1;
662             if(i%0x100==0):
663                 print "Buffering %04x toward %06x" % (i,page);
664         #last page
665         self.CCflashpage(page);
666         print "Flashed final page at %06x" % page;
667