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