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