Shellcode is now only loaded when
[goodfet] / client / GoodFETCC.py
index 344d9a5..01b6668 100644 (file)
@@ -11,7 +11,7 @@ import binascii;
 from GoodFET import GoodFET;
 from intelhex import IntelHex;
 
-import xml.dom.minidom;
+import xml.dom.minidom, time;
 
 class GoodFETCC(GoodFET):
     """A GoodFET variant for use with Chipcon 8051 Zigbee SoC."""
@@ -24,7 +24,7 @@ class GoodFETCC(GoodFET):
     def loadsymbols(self):
         try: self.SRF_loadsymbols();
         except:
-            if self.verbose==1: print "SmartRF load failed.";
+            if self.verbose>0: print "SmartRF not found at %s." % self.smartrfpath;
     def SRF_chipdom(self,chip="cc1110", doc="register_definition.xml"):
         fn="%s/config/xml/%s/%s" % (self.smartrfpath,chip,doc);
         #print "Opening %s" % fn;
@@ -32,7 +32,11 @@ class GoodFETCC(GoodFET):
         
     def CMDrs(self,args=[]):
         """Chip command to grab the radio state."""
-        self.SRF_radiostate();
+        try:
+            self.SRF_radiostate();
+        except:
+            print "Error printing radio state.";
+            print "SmartRF not found at %s." % self.smartrfpath;
     def SRF_bitfieldstr(self,bf):
         name="unused";
         start=0;
@@ -72,10 +76,307 @@ class GoodFETCC(GoodFET):
                     print "%-10s=0x%02x; /* %-50s */" % (
                         name,self.CCpeekdatabyte(eval(address)), description);
                     if bitfields!="": print bitfields.rstrip();
+    def RF_setfreq(self,frequency):
+        """Set the frequency in Hz."""
+        #FIXME CC1110 specific
+        #Some frequencies fail, probably and FSCAL thing.
+        
+        hz=frequency;
+        freq=int(hz/396.728515625);
+        
+        freq0=freq&0xFF;
+        freq1=(freq&0xFF00)>>8;
+        freq2=(freq&0xFF0000)>>16;
+        
+        self.pokebysym("FREQ2",freq2);
+        self.pokebysym("FREQ1",freq1);
+        self.pokebysym("FREQ0",freq0);
+        
+        self.pokebysym("TEST1",0x31);
+        self.pokebysym("TEST0",0x09);
+        
+        #self.pokebysym("PA_TABLE0" ,   0x60);  #above mid
+        
+        #self.pokebysym("FSCAL2" ,   0x2A);  #above mid
+        self.pokebysym("FSCAL2" ,   0x0A);  #beneath mid
+        
+        #self.CC_RFST_CAL(); #SCAL
+        #time.sleep(1);
+    
+        
+    def RF_getfreq(self):
+        """Get the frequency in Hz."""
+        #FIXME CC1110 specific
+        
+        #return (2400+self.peek(0x05))*10**6
+        #self.poke(0x05,chan);
+        
+        #freq2=self.CCpeekdatabyte(0xdf09);
+        #freq1=self.CCpeekdatabyte(0xdf0a);
+        #freq0=self.CCpeekdatabyte(0xdf0b);
+        freq=0;
+        try:
+            freq2=self.peekbysym("FREQ2");
+            freq1=self.peekbysym("FREQ1");
+            freq0=self.peekbysym("FREQ0");
+            freq=(freq2<<16)+(freq1<<8)+freq0;
+        except:
+            freq=0;
+            
+        hz=freq*396.728515625;
+        
+        return hz;
+    lastshellcode="none";
+    def shellcodefile(self,filename,wait=1):
+        """Run a fragment of shellcode by name."""
+        #FIXME: should identify chip model number, use shellcode for that chip.
+        
+        if self.lastshellcode!=filename:
+            self.lastshellcode=filename;
+            file=__file__;
+            file=file.replace("GoodFETCC.pyc","GoodFETCC.py");
+            path=file.replace("client/GoodFETCC.py","shellcode/chipcon/cc1110/");
+            filename=path+filename;
+        
+            #Load the shellcode.
+            h=IntelHex(filename);
+            for i in h._buf.keys():
+                self.CCpokedatabyte(i,h[i]);
+        
+        #Execute it.
+        self.CCdebuginstr([0x02, 0xf0, 0x00]); #ljmp 0xF000
+        self.resume();
+        while wait>0 and (0==self.CCstatus()&0x20):
+            a=1;
+            #time.sleep(0.1);
+            #print "Waiting for shell code to return.";
+        return;
+    def ishalted(self):
+        return self.CCstatus()&0x20;
+    def shellcode(self,code,wait=1):
+        """Copy a block of code into RAM and execute it."""
+        i=0;
+        ram=0xF000;
+        for byte in code:
+            self.pokebyte(0xF000+i,byte);
+            i=i+1;
+        #print "Code loaded, executing."
+        self.CCdebuginstr([0x02, 0xf0, 0x00]); #ljmp 0xF000
+        self.resume();
+        while wait>0 and (0==self.CCstatus()&0x20):
+            a=1;
+            #time.sleep(0.1);
+            #print "Waiting for shell code to return.";
+        return;
+    def CC1110_crystal(self):
+        """Start the main crystal of the CC1110 oscillating, needed for radio use."""
+        code=[0x53, 0xBE, 0xFB, #anl SLEEP, #0xFB
+              #one:
+              0xE5, 0xBE,       #mov a,SLEEP
+              0x30, 0xE6, 0xFB, #jnb acc.6, back
+              0x53, 0xc6, 0xB8, #anl CLKCON, #0xB8
+              #two
+              0xE5, 0xC6,       #mov a,CLKCON
+              0x20, 0xE6, 0xFB, #jb acc.6, two
+              0x43, 0xBE, 0x04, #orl SLEEP, #0x04
+              0xA5,             #HALT
+              ];
+        self.shellcode(code);
+        
+        #Slower to load, but produced from C.
+        #self.shellcodefile("crystal.ihx");
+        return;
+    def RF_idle(self):
+        """Move the radio to its idle state."""
+        self.CC_RFST_IDLE();
+        return;
+    
+    #Chipcon RF strobes.  CC1110 specific
+    RFST_IDLE=0x04;
+    RFST_RX=0x02;
+    RFST_TX=0x03;
+    RFST_CAL=0x01;
+    def CC_RFST_IDLE(self):
+        """Switch the radio to idle mode, clearing overflows and errors."""
+        self.CC_RFST(self.RFST_IDLE);
+    def CC_RFST_TX(self):
+        """Switch the radio to TX mode."""
+        self.CC_RFST(self.RFST_TX);
+    def CC_RFST_RX(self):
+        """Switch the radio to RX mode."""
+        self.CC_RFST(self.RFST_RX);
+    def CC_RFST_CAL(self):
+        """Calibrate strobe the radio."""
+        self.CC_RFST(self.RFST_CAL);
+    def CC_RFST(self,state=RFST_IDLE):
+        RFST=0xDFE1
+        self.pokebyte(RFST,state); #Return to idle state.
+        return;
+        
+    def config_simpliciti(self,band="none"):
+        self.pokebysym("FSCTRL1"  , 0x08)   # Frequency synthesizer control.
+        self.pokebysym("FSCTRL0"  , 0x00)   # Frequency synthesizer control.
+        
+        #Don't change these while the radio is active.
+        self.pokebysym("FSCAL3"   , 0xEA)   # Frequency synthesizer calibration.
+        self.pokebysym("FSCAL2"   , 0x2A)   # Frequency synthesizer calibration.
+        self.pokebysym("FSCAL1"   , 0x00)   # Frequency synthesizer calibration.
+        self.pokebysym("FSCAL0"   , 0x1F)   # Frequency synthesizer calibration.
+        
+        if band=="ismeu" or band=="eu":
+            self.pokebysym("FREQ2"    , 0x21)   # Frequency control word, high byte.
+            self.pokebysym("FREQ1"    , 0x71)   # Frequency control word, middle byte.
+            self.pokebysym("FREQ0"    , 0x7a)   # Frequency control word, low byte.
+        elif band=="ismus" or band=="us":
+            self.pokebysym("FREQ2"    , 0x22)   # Frequency control word, high byte.
+            self.pokebysym("FREQ1"    , 0xB1)   # Frequency control word, middle byte.
+            self.pokebysym("FREQ0"    , 0x3B)   # Frequency control word, low byte.
+        elif band=="ismlf" or band=="lf":
+            self.pokebysym("FREQ2"    , 0x10)   # Frequency control word, high byte.
+            self.pokebysym("FREQ1"    , 0xB0)   # Frequency control word, middle byte.
+            self.pokebysym("FREQ0"    , 0x71)   # Frequency control word, low byte.
+        elif band=="none":
+            band="none";
+        else:
+            #Got a frequency, not a band.
+            self.RF_setfreq(eval(band));
+        self.pokebysym("MDMCFG4"  , 0x7B)   # Modem configuration.
+        self.pokebysym("MDMCFG3"  , 0x83)   # Modem configuration.
+        self.pokebysym("MDMCFG2"  , 0x13)   # Modem configuration.
+        self.pokebysym("MDMCFG1"  , 0x22)   # Modem configuration.
+        self.pokebysym("MDMCFG0"  , 0xF8)   # Modem configuration.
+        if band=="ismus" or band=="us":
+            self.pokebysym("CHANNR"   , 20)   # Channel number.
+        else:
+            self.pokebysym("CHANNR"   , 0x00)   # Channel number.
+        self.pokebysym("DEVIATN"  , 0x42)   # Modem deviation setting (when FSK modulation is enabled).
+        
+        self.pokebysym("FREND1"   , 0xB6)   # Front end RX configuration.
+        self.pokebysym("FREND0"   , 0x10)   # Front end RX configuration.
+        self.pokebysym("MCSM0"    , 0x18)   # Main Radio Control State Machine configuration.
+        self.pokebysym("FOCCFG"   , 0x1D)   # Frequency Offset Compensation Configuration.
+        self.pokebysym("BSCFG"    , 0x1C)   # Bit synchronization Configuration.
+        
+        self.pokebysym("AGCCTRL2" , 0xC7)   # AGC control.
+        self.pokebysym("AGCCTRL1" , 0x00)   # AGC control.
+        self.pokebysym("AGCCTRL0" , 0xB2)   # AGC control.
+        
+        self.pokebysym("TEST2"    , 0x81)   # Various test settings.
+        self.pokebysym("TEST1"    , 0x35)   # Various test settings.
+        self.pokebysym("TEST0"    , 0x09)   # Various test settings.
+        self.pokebysym("PA_TABLE0", 0xC0)   # PA output power setting.
+        self.pokebysym("PKTCTRL1" , 0x04)   # Packet automation control, w/ lqi
+        #self.pokebysym("PKTCTRL1" , 0x00)   # Packet automation control. w/o lqi
+        self.pokebysym("PKTCTRL0" , 0x05)   # Packet automation control, w/ checksum.
+        #self.pokebysym("PKTCTRL0" , 0x00)   # Packet automation control, w/o checksum, fixed length
+        self.pokebysym("ADDR"     , 0x01)   # Device address.
+        self.pokebysym("PKTLEN"   , 0xFF)   # Packet length.
+        
+        self.pokebysym("SYNC1",0xD3);
+        self.pokebysym("SYNC0",0x91);
+        
+    def RF_carrier(self):
+        """Hold a carrier wave on the present frequency."""
+        
+        self.CC1110_crystal(); #FIXME, '1110 specific.
+        self.RF_idle();
+        
+        
+        RFST=0xDFE1;
+        
+        self.config_simpliciti();
+        
+        #Don't change these while the radio is active.
+        #self.pokebysym("FSCAL3"   , 0xA9)   # Frequency synthesizer calibration.
+        #self.pokebysym("FSCAL2"   , 0x0A)   # Frequency synthesizer calibration.
+        #self.pokebysym("FSCAL1"   , 0x00)   # Frequency synthesizer calibration.
+        #self.pokebysym("FSCAL0"   , 0x11)   # Frequency synthesizer calibration.
+        
+        #Ramp up the power.
+        #self.pokebysym("PA_TABLE0", 0xFF)   # PA output power setting.
+        
+        #This is what drops to OOK.
+        #Comment to keep GFSK, might be better at jamming.
+        self.pokebysym("MDMCFG4"  , 0x86)   # Modem configuration.
+        self.pokebysym("MDMCFG3"  , 0x83)   # Modem configuration.
+        self.pokebysym("MDMCFG2"  , 0x30)   # Modem configuration.
+        self.pokebysym("MDMCFG1"  , 0x22)   # Modem configuration.
+        self.pokebysym("MDMCFG0"  , 0xF8)   # Modem configuration.
+        
+        
+        self.pokebysym("SYNC1",0xAA);
+        self.pokebysym("SYNC0",0xAA);
+        
+        
+        
+        #while ((MARCSTATE & MARCSTATE_MARC_STATE) != MARC_STATE_TX); 
+        state=0;
+        
+        while((state!=0x13)):
+            self.pokebyte(RFST,0x03); #RFST=RFST_STX
+            time.sleep(0.1);
+            state=self.peekbysym("MARCSTATE")&0x1F;
+            #print "state=%02x" % state;
+        print "Holding a carrier on %f MHz." % (self.RF_getfreq()/10**6);
+        
+        return;
+            
+    def RF_getsmac(self):
+        """Return the source MAC address."""
+        
+        #Register 0A is RX_ADDR_P0, five bytes.
+        mac=self.peekbysym("ADDR");
+        return mac;
+    def RF_setsmac(self,mac):
+        """Set the source MAC address."""
+        self.pokebysym("ADDR",mac);
+        return 0;
+    def RF_gettmac(self):
+        """Return the target MAC address."""
+        return 0;
+    def RF_settmac(self,mac):
+        """Set the target MAC address."""
+        return 0;
+    def RF_rxpacket(self):
+        """Get a packet from the radio.  Returns None if none is waiting."""
+        self.shellcodefile("rxpacket.ihx");
+        len=self.peek8(0xFE00,"xdata");
+        return self.peekblock(0xFE00,len+1,"data");
+    def RF_txpacket(self,packet):
+        """Transmit a packet.  Untested."""
+        
+        self.pokeblock(0xFE00,packet,"data");
+        self.shellcodefile("txpacket.ihx");
+        return;
+    def RF_txrxpacket(self,packet):
+        """Transmit a packet.  Untested."""
+        
+        self.pokeblock(0xFE00,packet,"data");
+        self.shellcodefile("txrxpacket.ihx");
+        len=self.peek8(0xFE00,"xdata");
+        return self.peekblock(0xFE00,len+1,"data");
+
     def RF_getrssi(self):
-        """Returns the received signal strenght, from 0 to 1."""
-        rssireg=self.symbols.get("RSSI");
-        return self.CCpeekdatabyte(rssireg);
+        """Returns the received signal strenght, with a weird offset."""
+        try:
+            rssireg=self.symbols.get("RSSI");
+            return self.CCpeekdatabyte(rssireg)^0x80;
+        except:
+            if self.verbose>0: print "RSSI reg doesn't exist.";
+        try:
+            #RSSI doesn't exist on 2.4GHz devices.  Maybe RSSIL and RSSIH?
+            rssilreg=self.symbols.get("RSSIL");
+            rssil=self.CCpeekdatabyte(rssilreg);
+            rssihreg=self.symbols.get("RSSIL");
+            rssih=self.CCpeekdatabyte(rssihreg);
+            return (rssih<<8)|rssil;
+        except:
+            if self.verbose>0: print "RSSIL/RSSIH regs don't exist.";
+        
+        return 0;
+    
+    
+    
     def SRF_loadsymbols(self):
         ident=self.CCident();
         chip=self.CCversions.get(ident&0xFF00);
@@ -169,6 +470,7 @@ class GoodFETCC(GoodFET):
     
 
     CCversions={0x0100:"cc1110",
+                0x1100:"cc1111",
                 0x8500:"cc2430",
                 0x8900:"cc2431",
                 0x8100:"cc2510",
@@ -177,6 +479,7 @@ class GoodFETCC(GoodFET):
                 0xB500:"cc2531",
                 0xFF00:"CCmissing"};
     CCpagesizes={0x01: 1024, #"CC1110",
+                 0x11: 1024, #"CC1111",
                  0x85: 2048, #"CC2430",
                  0x89: 2048, #"CC2431",
                  0x81: 1024, #"CC2510",
@@ -189,7 +492,11 @@ class GoodFETCC(GoodFET):
     def CCidentstr(self):
         ident=self.CCident();
         chip=self.CCversions.get(ident&0xFF00);
-        return "%s/r%02x" % (chip, ident&0xFF); 
+        pagesize=self.CCpagesizes.get(ident>0xFF);
+        try:
+            return "%s/r%0.4x/ps0x%0.4x" % (chip, ident, pagesize); 
+        except:
+            return "%04x" % ident;
     def CCident(self):
         """Get a chipcon's ID."""
         self.writecmd(self.APP,0x8B,0,None);
@@ -203,7 +510,7 @@ class GoodFETCC(GoodFET):
         size=self.CCpagesizes.get(chip);
         if(size<10):
             print "ERROR: Pagesize undefined.";
-            print "chip=%02x" %chip;
+            print "chip=%0.4x" %chip;
             sys.exit(1);
             #return 2048;
         return size;
@@ -223,6 +530,12 @@ class GoodFETCC(GoodFET):
     def CCdebuginstr(self,instr):
         self.writecmd(self.APP,0x88,len(instr),instr);
         return ord(self.data[0]);
+    #def peekblock(self,adr,length,memory="vn"):
+    #    """Return a block of data, broken"""
+    #    data=[adr&0xff, (adr&0xff00)>>8,
+    #          length&0xFF,(length&0xFF00)>>8];
+    #    self.writecmd(self.APP,0x91,4,data);
+    #    return [ord(x) for x in self.data]
     def peek8(self,address, memory="code"):
         if(memory=="code" or memory=="flash" or memory=="vn"):
             return self.CCpeekcodebyte(address);
@@ -259,7 +572,8 @@ class GoodFETCC(GoodFET):
         self.data=[adr&0xff, val&0xff];
         self.writecmd(self.APP,0x02, 2, self.data);
         return ord(self.data[0]);
-    
+    def pokebyte(self,adr,val,mem="xdata"):
+        self.CCpokedatabyte(adr,val);
     def CCpokedatabyte(self,adr,val):
         """Write a byte to data memory."""
         self.data=[adr&0xff, (adr&0xff00)>>8, val];
@@ -315,8 +629,6 @@ class GoodFETCC(GoodFET):
         self.CChaltcpu();
         #Get SmartRF Studio regs if they exist.
         self.loadsymbols(); 
-
-        #print "Status: %s." % self.status();
         
     def stop(self):
         """Stop debugging."""