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