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