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