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