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