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