Ejemplo n.º 1
0
/*********************************************************************
 * Function:        BOOL DataEncrypt(IOPUT BYTE *Input, IOPUT BYTE *DataLen, INPUT BYTE *Header, INPUT BYTE HeaderLen, INPUT KEY_IDENTIFIER KeyIdentifier, BOOL bExtendedNonce)
 *
 * PreCondition:    Input and Header has been filled
 *
 * Input:           BYTE *Header                 - Point to MiWi header
 *                  BYTE HeaderLen               - MiWi header length
 *                  KEY_IDENTIFIER KeyIdentifier - Identifier to specify key type. reserved for commercial mode
 *                  BOOL bExtendedNonce          - if extended nonce being used.
 *
 * Output:          BOOL           - If data encryption successful
 *
 * Input/Output:    BYTE *Input    - Pointer to the data to be encrypted. The encrypted data will be write back to the pointer
 *                  BYTE *DataLen  - Input as the length of the data to be encrypted. The encrypted data length (including MICs) will be written back
 *
 * Side Effects:    Input data get encrypted and written back to the input pointer
 *
 * Overview:        This is the function that call the hardware cipher to encrypt input data
 ********************************************************************/
BOOL DataEncrypt(IOPUT BYTE *Input, IOPUT BYTE *DataLen, INPUT BYTE *Header, INPUT BYTE HeaderLen, INPUT KEY_IDENTIFIER KeyIdentifier, BOOL bExtendedNonce)
{
    SECURITY_INPUT SecurityInput;
    BYTE EncryptedLen;
    BYTE i;
    BYTE Counter;
    BYTE ActiveKeyIndex;
    LONG_ADDR myAddress;
    // reserve space for multiple try of encryption
    BYTE *tmpBuf = (BYTE *)SRAMalloc(*DataLen + 18);
    if( tmpBuf == NULL )
    {
        return FALSE;
    }

    // get the IEEE 802.15.4 security mode
    SecurityInput.cipherMode = SecurityLevel_ZIGBEE_2_IEEE(nwkSecurityLevel);

    // get security key
    GetNwkActiveKeyNumber(&ActiveKeyIndex);
    if( ActiveKeyIndex != 0x01 && ActiveKeyIndex != 0x02 ) // no valid key
    {
        nfree(tmpBuf);
        return FALSE;
    }

    // handle the frame counter
    SecurityInput.FrameCounter = (OutgoingFrameCount[ActiveKeyIndex-1]);
    OutgoingFrameCount[ActiveKeyIndex-1].Val++;

    // fill the secuirty input
    SecurityInput.SecurityControl.Val = nwkSecurityLevel | (KeyIdentifier << 3);
    if( bExtendedNonce )
    {
        SecurityInput.SecurityControl.Val |= 0x20;
    }
#ifdef USE_EXTERNAL_NVM
    currentNetworkKeyInfo = plainSecurityKey[ActiveKeyIndex-1];
#else
    GetNwkKeyInfo( &currentNetworkKeyInfo, &(networkKeyInfo[ActiveKeyIndex-1]) );
#endif

    SecurityInput.SecurityKey = currentNetworkKeyInfo.NetKey.v;
    SecurityInput.KeySeq = currentNetworkKeyInfo.SeqNumber.v[0];
    GetMACAddress(&myAddress);
    SecurityInput.SourceAddress = &myAddress;
    SecurityInput.Header = Header;
    SecurityInput.HeaderLen = HeaderLen;

    // in rare cases, the hardware encryption engine may not suceed for the
    // first time. Retry a few times will solve the problem
    Counter = CIPHER_RETRY;
    while(Counter)
    {
        // fill the input data and data length
        SecurityInput.InputText = Input;
        SecurityInput.TextLen = *DataLen;
        // call hardware cipher and store the output to the temporary buffer
        PHYCipher(MODE_ENCRYPTION, SecurityInput, tmpBuf, &EncryptedLen);

        // try to decrypt the buffer to make sure that encryption is correct
        SecurityInput.InputText = tmpBuf;
        SecurityInput.TextLen = EncryptedLen;
        if( PHYCipher(MODE_DECRYPTION, SecurityInput, Input, &i) == CIPHER_SUCCESS )
        {
            break;
        }
        Counter--;
    }

    // fill the auxilary header
    Input[0] = SecurityInput.SecurityControl.Val & 0xF8; // set security level
    for(i = 0; i < 4; i++)
    {
        Input[i+1] = SecurityInput.FrameCounter.v[i];
    }
    Counter = i+1;
    if( bExtendedNonce )
    {
        for(i = 0; i < 8; i++)
        {
            Input[Counter++] = SecurityInput.SourceAddress->v[i];
        }
    }

    if( KeyIdentifier == ID_NetworkKey )
    {
        Input[Counter++] = currentNetworkKeyInfo.SeqNumber.v[0];
    }

    // fill the encrypted data
    for(i = 0; i < EncryptedLen; i++)
    {
        Input[Counter++] = tmpBuf[i];
    }

    nfree(tmpBuf);

    *DataLen = Counter;

    return TRUE;
}
Ejemplo n.º 2
0
    void NVMWrite( NVM_ADDR *dest, BYTE *src, BYTE count )
    {
    NVM_ADDR *pEraseBlock;
    BYTE    *memBlock;
    BYTE *pMemBlock;
    BYTE writeIndex;
    BYTE writeStart;
    BYTE writeCount;
    BYTE oldGIEH;
    DWORD oldTBLPTR;

    #if defined(VERIFY_WRITE)
        while (memcmppgm2ram( src, (ROM void *)dest, count ))
    #elif defined(CHECK_BEFORE_WRITE)
        if (memcmppgm2ram( src, (ROM void *)dest, count ))
    #endif
        {
            if ((memBlock = SRAMalloc( ERASE_BLOCK_SIZE )) == NULL)
                return;

            #if 0
                ConsolePutROMString( (ROM char * const)"NVMWrite at " );
                PrintChar( (BYTE)(((WORD)dest>>8)&0xFF) );
                PrintChar( (BYTE)((WORD)dest&0xFF) );
                ConsolePutROMString( (ROM char * const)" count " );
                PrintChar( count );
                ConsolePutROMString( (ROM char * const)"\r\n" );
            #endif

            // First, get the nearest "left" erase block boundary
            pEraseBlock = (NVM_ADDR*)((long)dest & (long)(~(ERASE_BLOCK_SIZE-1)));
            writeStart = (BYTE)((BYTE)dest & (BYTE)(ERASE_BLOCK_SIZE-1));

            while( count )
            {
                // Now read the entire erase block size into RAM.
                NVMRead(memBlock, (ROM void*)pEraseBlock, ERASE_BLOCK_SIZE);

                // Erase the block.
                // Erase flash memory, enable write control.
                EECON1 = 0x94;

                oldGIEH = 0;
                if ( INTCONbits.GIEH )
                    oldGIEH = 1;
                INTCONbits.GIEH = 0;

                #if defined(MCHP_C18)
                    TBLPTR = (unsigned short long)pEraseBlock;
                #elif defined(HI_TECH_C)
                    TBLPTR = (void*)pEraseBlock;
                #endif

                CLRWDT();

                EECON2 = 0x55;
                EECON2 = 0xaa;
                EECON1bits.WR = 1;
                NOP();

                EECON1bits.WREN = 0;

                oldTBLPTR = TBLPTR;

                if ( oldGIEH )
                    INTCONbits.GIEH = 1;

                // Modify 64-byte block of RAM buffer as per what is required.
                pMemBlock = &memBlock[writeStart];
                while( writeStart < ERASE_BLOCK_SIZE && count )
                {
                    *pMemBlock++ = *src++;

                    count--;
                    writeStart++;
                }

                // After first block write, next start would start from 0.
                writeStart = 0;

                // Now write entire 64 byte block in one write block at a time.
                writeIndex = ERASE_BLOCK_SIZE / WRITE_BLOCK_SIZE;
                pMemBlock = memBlock;
                while( writeIndex )
                {

                    oldGIEH = 0;
                    if ( INTCONbits.GIEH )
                        oldGIEH = 1;
                    INTCONbits.GIEH = 0;

                    TBLPTR = oldTBLPTR;

                    // Load individual block
                    writeCount = WRITE_BLOCK_SIZE;
                    while( writeCount-- )
                    {
                        TABLAT = *pMemBlock++;

                        TBLWTPOSTINC();
                    }

                    // Start the write process: reposition tblptr back into memory block that we want to write to.
                    #if defined(MCHP_C18)
                        _asm tblrdpostdec _endasm
                    #elif defined(HITECH_C18)
                        asm(" tblrd*-");
                    #endif

                    // Write flash memory, enable write control.
                    EECON1 = 0x84;

                    CLRWDT();

                    EECON2 = 0x55;
                    EECON2 = 0xaa;
                    EECON1bits.WR = 1;
                    NOP();
                    EECON1bits.WREN = 0;

                    // One less block to write
                    writeIndex--;

                    TBLPTR++;

                    oldTBLPTR = TBLPTR;

                    if ( oldGIEH )
                        INTCONbits.GIEH = 1;
                }

                // Go back and do it all over again until we write all
                // data bytes - this time the next block.
        #if !defined(WIN32)
                pEraseBlock += ERASE_BLOCK_SIZE;
        #endif
            }

            SRAMfree( memBlock );
        }
    }
Ejemplo n.º 3
0
    BYTE NVMInit( void )
    {
        BYTE    *memBlock;
        BYTE    result = 0;

        SPIUnselectEEPROM();

        CLRWDT();

        #ifdef ENABLE_DEBUG
            ConsolePutROMString((ROM char * const)"NVMInit started...\r\n");
        #endif

        #if defined(USE_EXTERNAL_NVM) && defined(STORE_MAC_EXTERNAL)
            result |= NVMalloc(sizeof (LONG_ADDR), &macLongAddrEE );
            #ifdef ZCP_DEBUG
                PutMACAddress(macLongAddrByte);
            #endif
        #endif

        #if defined(I_SUPPORT_BINDINGS)
            result |= NVMalloc( sizeof(WORD), &bindingValidityKey );
            result |= NVMalloc( sizeof(BINDING_RECORD) * MAX_BINDINGS, &apsBindingTable );
            result |= NVMalloc( BINDING_USAGE_MAP_SIZE, &bindingTableUsageMap );
            result |= NVMalloc( BINDING_USAGE_MAP_SIZE, &bindingTableSourceNodeMap );
        #endif

        #if defined(I_SUPPORT_GROUP_ADDRESSING)
            result |= NVMalloc( sizeof(APS_GROUP_RECORD) * MAX_GROUP, &apsGroupAddressTable);
        #endif

        result |= NVMalloc( sizeof(NEIGHBOR_TABLE_INFO), &neighborTableInfo );
        result |= NVMalloc( sizeof(NEIGHBOR_RECORD) * MAX_NEIGHBORS, &neighborTable );

        #if defined(I_SUPPORT_ROUTING) && !defined(USE_TREE_ROUTING_ONLY)
            result |= NVMalloc( sizeof(ROUTING_ENTRY) * ROUTING_TABLE_SIZE, &routingTable );
        #endif


        result |= NVMalloc( sizeof(NODE_DESCRIPTOR), &configNodeDescriptor );
        result |= NVMalloc( sizeof(NODE_POWER_DESCRIPTOR), &configPowerDescriptor );
        // NOTE - the simple descriptor for the ZDO has been removed in later specs, so the "+1" will go away.
        result |= NVMalloc( sizeof(NODE_SIMPLE_DESCRIPTOR) * (NUM_USER_ENDPOINTS+1), &configSimpleDescriptors );


        #if MAX_APS_ADDRESSES > 0
            result |= NVMalloc( sizeof(WORD), &apsAddressMapValidityKey );
            result |= NVMalloc( sizeof(APS_ADDRESS_MAP) * MAX_APS_ADDRESSES, &apsAddressMap );
        #endif

        #if defined(I_SUPPORT_SECURITY)
            result |= NVMalloc( sizeof(BYTE), &nwkActiveKeyNumber );
            result |= NVMalloc( sizeof(NETWORK_KEY_INFO) * NUM_NWK_KEYS, &networkKeyInfo );
            #if !(defined(I_AM_COORDINATOR) || defined(I_AM_TRUST_CENTER))
                result |= NVMalloc( sizeof(LONG_ADDR), &trustCenterLongAddr );
            #endif
        #endif

        if (!result)
        {
            #ifdef ENABLE_DEBUG
                ConsolePutROMString((ROM char * const)"Initializing EE...\r\n");
            #endif
            // If the MAC Address is stored externally, then the user is responsible
            // for programming it.  They may choose to preprogram the EEPROM, or program
            // it based on other input.  It should be programmed with the PutMACAddress() macro.


            // Initialize the trust center address
            #if defined(I_SUPPORT_SECURITY) && (defined(I_AM_COORDINATOR) || defined(I_AM_TRUST_CENTER))
                if ((memBlock = SRAMalloc( 8 )) == NULL)
                {
                    result = 1;
                }
                else
                {
                    int i = 0;
    
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE0;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE1;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE2;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE3;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE4;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE5;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE6;
                    memBlock[i++] = TRUST_CENTER_LONG_ADDR_BYTE7;
    
                    NVMWrite( trustCenterLongAddr, memBlock, 8 );
                    SRAMfree( memBlock );
                }
            #endif

            // Initialize the descriptors using the ROM copy.
            if ((memBlock = SRAMalloc( sizeof(NODE_DESCRIPTOR) )) == NULL)
            {
                result = 1;
            }
            else
            {
                memcpypgm2ram( memBlock, (void *)&Config_Node_Descriptor, sizeof(NODE_DESCRIPTOR) );
                NVMWrite( configNodeDescriptor, memBlock, sizeof(NODE_DESCRIPTOR) );
                SRAMfree( memBlock );
            }

            if ((memBlock = SRAMalloc( sizeof(NODE_POWER_DESCRIPTOR) )) == NULL)
            {
                result = 1;
            }
            else
            {
                memcpypgm2ram( memBlock, (void *)&Config_Power_Descriptor, sizeof(NODE_POWER_DESCRIPTOR) );
                NVMWrite( configPowerDescriptor, memBlock, sizeof(NODE_POWER_DESCRIPTOR) );
                SRAMfree( memBlock );
            }

            if ((memBlock = SRAMalloc( sizeof(NODE_SIMPLE_DESCRIPTOR) )) == NULL)
            {
                result = 1;
            }
            else
            {
                // NOTE - Currently, a simple descriptor is needed for the ZDO endpoint.  When this requirement
                // goes away, take off the "+1".
                int     i;

                for (i=0; i<NUM_USER_ENDPOINTS+1; i++)
                {
                    memcpypgm2ram( memBlock, (void *)Config_Simple_Descriptors + i * sizeof(NODE_SIMPLE_DESCRIPTOR), sizeof(NODE_SIMPLE_DESCRIPTOR) );
                    NVMWrite( configSimpleDescriptors + (WORD)i * (WORD)sizeof(NODE_SIMPLE_DESCRIPTOR), memBlock, sizeof(NODE_SIMPLE_DESCRIPTOR) );
                }
                SRAMfree( memBlock );
            }
        }

        #ifdef ENABLE_DEBUG
            ConsolePutROMString((ROM char * const)"NVMInit complete.\r\n");
        #endif

        CLRWDT();

        return result;
    }
Ejemplo n.º 4
0
ZIGBEE_PRIMITIVE PHYTasks(ZIGBEE_PRIMITIVE inputPrimitive)
{
    
    if( RF_INT_PIN == 0 )
    {
        RFIE = 1;
        RFIF = 1;
    }
    
    MLME_SET_macPANId_hw();
    
    if(inputPrimitive == NO_PRIMITIVE)
    {
        /* manage background tasks here */
        if(ZigBeeTxUnblocked)   
        {

            if(PHYTasksPending.bits.PHY_RX)
            {
                BYTE packetSize;
                if(CurrentRxPacket != NULL)
                {
                    
                    return NO_PRIMITIVE;
                }

                packetSize = RxBuffer[RxRead];
                params.PD_DATA_indication.psdu = SRAMalloc(packetSize);

                if(params.PD_DATA_indication.psdu == NULL)
                {
                    phyError.failedToMallocRx = 1;
                    PHYTasksPending.bits.PHY_RX = 0;
                    
                    return NO_PRIMITIVE;
                }

                /* save the packet head somewhere so that it can be freed later */
                if(CurrentRxPacket == NULL)
                {
                    CurrentRxPacket = params.PD_DATA_indication.psdu;

                    params.PD_DATA_indication.psduLength = packetSize;
                    RxRead++;
                    if(RxRead == (BYTE)RX_BUFFER_SIZE)
                    {
                        RxRead = 0;
                    }

                    while(packetSize--)
                    {
                        *params.PD_DATA_indication.psdu++ = PHYGet();
                    }

                    /* reset the psdu to the head of the alloc-ed RAM, just happens to me CurrentRxPacket */
                    params.PD_DATA_indication.psdu = CurrentRxPacket;

				    #if !defined(__C30__)
                        /* disable interrupts before checking to see if this was the
                            last packet in the FIFO so that if we get a packet(interrupt) after the check,
                            but before the clearing of the bit then the new indication will not
                            get cleared */
    
                        savedBits.bGIEH = INTCONbits.GIEH;
                        INTCONbits.GIEH = 0;
    
				    #endif
                    if(RxRead == RxWrite)
                    {
                        PHYTasksPending.bits.PHY_RX = 0;
                    }

					#if !defined(__C30__)
                    	INTCONbits.GIEH = savedBits.bGIEH;
					#endif

                    return PD_DATA_indication;
                }
                else
                {
                    nfree(params.PD_DATA_indication.psdu);
                    return NO_PRIMITIVE;
                }
            }
        }
        else
        {
            return NO_PRIMITIVE;
        }

    }
    return NO_PRIMITIVE;
}
Ejemplo n.º 5
0
    BYTE NVMInit( void )
    {
        BYTE    *memBlock;
        BYTE    result = 0;
        WORD NodeDescriptorValiditykey;
        WORD validitykey;

        SPIUnselectEEPROM();

        CLRWDT();

        #if defined(I_SUPPORT_BINDINGS)
            result |= NVMalloc( sizeof(WORD), &bindingValidityKey );
            result |= NVMalloc( sizeof(BINDING_RECORD) * MAX_BINDINGS, &apsBindingTable );
            result |= NVMalloc( BINDING_USAGE_MAP_SIZE, &bindingTableUsageMap );
            result |= NVMalloc( BINDING_USAGE_MAP_SIZE, &bindingTableSourceNodeMap );
        #endif

        #if defined(USE_EXTERNAL_NVM) && defined(STORE_MAC_EXTERNAL)
            result |= NVMalloc( sizeof(WORD), &macLongAddrValidityKey );
            result |= NVMalloc( sizeof(LONG_ADDR), &macLongAddrEE );

            GetMACAddressValidityKey(&validitykey);
            if (validitykey != MAC_ADDRESS_VALID)
            {
                PutMACAddress(macLongAddrByte);
                MACEnable();
            }

        #endif
        #if defined(I_SUPPORT_GROUP_ADDRESSING)
            result |= NVMalloc( sizeof(APS_GROUP_RECORD) * MAX_GROUP, &apsGroupAddressTable);
        #endif

        result |= NVMalloc( sizeof(NEIGHBOR_TABLE_INFO), &neighborTableInfo );
        result |= NVMalloc( sizeof(NEIGHBOR_RECORD) * MAX_NEIGHBORS, &neighborTable );

        #if defined(I_SUPPORT_ROUTING) && !defined(USE_TREE_ROUTING_ONLY)
            result |= NVMalloc( sizeof(ROUTING_ENTRY) * ROUTING_TABLE_SIZE, &routingTable );
        #endif

        result |= NVMalloc( sizeof(WORD), &nodeDescriptorValidityKey);
        result |= NVMalloc( sizeof(NODE_DESCRIPTOR), &configNodeDescriptor );
        result |= NVMalloc( sizeof(NODE_POWER_DESCRIPTOR), &configPowerDescriptor );
        // NOTE - the simple descriptor for the ZDO has been removed in later specs, so the "+1" will go away.
        result |= NVMalloc( sizeof(NODE_SIMPLE_DESCRIPTOR) * (NUM_USER_ENDPOINTS+1), &configSimpleDescriptors );

        result |= NVMalloc(sizeof(PERSISTENCE_PIB), &persistencePIB);

        #if MAX_APS_ADDRESSES > 0
            result |= NVMalloc( sizeof(WORD), &apsAddressMapValidityKey );
            result |= NVMalloc( sizeof(APS_ADDRESS_MAP) * MAX_APS_ADDRESSES, &apsAddressMap );
        #endif

        #if defined(I_SUPPORT_SECURITY)
            result |= NVMalloc( sizeof(BYTE), &nwkActiveKeyNumber );
            result |= NVMalloc( sizeof(NETWORK_KEY_INFO) * NUM_NWK_KEYS, &networkKeyInfo );
            /* location for outgoing nwk frame counters */
			result |= NVMalloc(( sizeof(DWORD_VAL)*2), &outgoingFrameCounterIndex);

        #endif
        #if I_SUPPORT_LINK_KEY == 1
                result |= NVMalloc( sizeof(APS_KEY_PAIR_DESCRIPTOR) * MAX_APPLICATION_LINK_KEY_SUPPORTED, &appLinkKeyTable );
        #endif

        #if I_SUPPORT_LINK_KEY == 1
            #if I_SUPPORT_MULTIPLE_TC_LINK_KEY == 1
                result |= NVMalloc( sizeof(TC_LINK_KEY_TABLE) * MAX_TC_LINK_KEY_SUPPORTED, &TCLinkKeyTable );
            #endif
        #endif

        #if defined(I_SUPPORT_COMMISSIONING)
            result |= NVMalloc( sizeof(BYTE), &activeSASIndex );
            result |= NVMalloc( sizeof(STARTUP_ATTRIBUTE_SET), &default_SAS );
            result |= NVMalloc( (sizeof(STARTUP_ATTRIBUTE_SET) * 2), &Commissioned_SAS );
        #endif

        #if defined(I_SUPPORT_SECURITY)
			result |= NVMalloc(( sizeof(DWORD_VAL)*2), &outgoingFrameCounterIndex);
		#endif

        if (!result)
        {
            #ifdef ENABLE_DEBUG
                ConsolePutROMString((ROM char * const)"Initializing EE...\r\n");
            #endif
            #ifdef I_SUPPORT_COMMISSIONING
                BYTE index;
            #endif
            // If the MAC Address is stored externally, then the user is responsible
            // for programming it.  They may choose to preprogram the EEPROM, or program
            // it based on other input.  It should be programmed with the PutMACAddress() macro.


  /*          // Initialize the trust center address
            //below is code is comment #if defined(I_SUPPORT_SECURITY) && (defined(I_AM_COORDINATOR) || defined(I_AM_TRUST_CENTER))
                if ((memBlock = SRAMalloc( 8 )) == NULL)
                {
                    result = 1;
                }
                else
                {
                    int i = 0;

                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[0];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[1];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[2];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[3];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[4];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[5];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[6];
                    memBlock[i++] = current_SAS.spas.TrustCenterAddress.v[7];

                    NVMWrite( trustCenterLongAddr, memBlock, 8 );
                    SRAMfree( memBlock );
                }
            #endif*/
            GetNodeDescriptorValidity(&NodeDescriptorValiditykey);
            if (NodeDescriptorValiditykey != NODE_DESCRIPTOR_VALID)
            {
                // Initialize the descriptors using the ROM copy.
                if ((memBlock = SRAMalloc( sizeof(NODE_DESCRIPTOR) )) == NULL)
                {
                    result = 1;
                }
                else
                {
                    memcpy( memBlock, (void *)&Config_Node_Descriptor, sizeof(NODE_DESCRIPTOR) );
                    NVMWrite( configNodeDescriptor, memBlock, sizeof(NODE_DESCRIPTOR) );
                    SRAMfree( memBlock );
                    NodeDescriptorValiditykey = NODE_DESCRIPTOR_VALID;
                    PutNodeDescriptorValidity(&NodeDescriptorValiditykey);
                }
            }

            if ((memBlock = SRAMalloc( sizeof(NODE_POWER_DESCRIPTOR) )) == NULL)
            {
                result = 1;
            }
            else
            {
                memcpy( memBlock, (void *)&Config_Power_Descriptor, sizeof(NODE_POWER_DESCRIPTOR) );
                NVMWrite( configPowerDescriptor, memBlock, sizeof(NODE_POWER_DESCRIPTOR) );
                SRAMfree( memBlock );
            }

            if ((memBlock = SRAMalloc( sizeof(NODE_SIMPLE_DESCRIPTOR) )) == NULL)
            {
                result = 1;
            }
            else
            {
                // NOTE - Currently, a simple descriptor is needed for the ZDO endpoint.  When this requirement
                // goes away, take off the "+1".
                int     i;

                for (i=0; i<NUM_USER_ENDPOINTS+1; i++)
                {
					if(NOW_I_AM_A_ROUTER())
						memcpypgm2ram( memBlock, (void *)Config_Simple_Descriptors_MTR + i * sizeof(NODE_SIMPLE_DESCRIPTOR), sizeof(NODE_SIMPLE_DESCRIPTOR) );
					else if (NOW_I_AM_A_CORDINATOR())
						memcpypgm2ram( memBlock, (void *)Config_Simple_Descriptors_ESP + i * sizeof(NODE_SIMPLE_DESCRIPTOR), sizeof(NODE_SIMPLE_DESCRIPTOR) );
                    //memcpypgm2ram( memBlock, (void *)Config_Simple_Descriptors + i * sizeof(NODE_SIMPLE_DESCRIPTOR), sizeof(NODE_SIMPLE_DESCRIPTOR) );
                    NVMWrite( configSimpleDescriptors + (WORD)i * (WORD)sizeof(NODE_SIMPLE_DESCRIPTOR), memBlock, sizeof(NODE_SIMPLE_DESCRIPTOR) );
                }
                SRAMfree( memBlock );
            }
            #ifdef I_SUPPORT_COMMISSIONING
                GetSAS(&current_SAS,default_SAS);
		       if( MSDCL_Commission.ValidCleanStartUp == MSDCL_COMMISSION_DATA_VALID)
		       {
					memcpy(&current_SAS.spas.ExtendedPANId.v[0], &MSDCL_Commission.ExtendedPANId[0], sizeof(MSDCL_Commission.ExtendedPANId) );
			                       
				    current_SAS.spas.PreconfiguredLinkKey[15]= MSDCL_Commission.LinkKey[15];
				    current_SAS.spas.PreconfiguredLinkKey[14]= MSDCL_Commission.LinkKey[14];
				    current_SAS.spas.PreconfiguredLinkKey[13]= MSDCL_Commission.LinkKey[13];
				    current_SAS.spas.PreconfiguredLinkKey[12]= MSDCL_Commission.LinkKey[12];
				    current_SAS.spas.PreconfiguredLinkKey[11]= MSDCL_Commission.LinkKey[11];
				    current_SAS.spas.PreconfiguredLinkKey[10]= MSDCL_Commission.LinkKey[10];
				    current_SAS.spas.PreconfiguredLinkKey[9]= MSDCL_Commission.LinkKey[9];
				    current_SAS.spas.PreconfiguredLinkKey[8]= MSDCL_Commission.LinkKey[8];
				    current_SAS.spas.PreconfiguredLinkKey[7]= MSDCL_Commission.LinkKey[7];
				    current_SAS.spas.PreconfiguredLinkKey[6]= MSDCL_Commission.LinkKey[6];
				    current_SAS.spas.PreconfiguredLinkKey[5]= MSDCL_Commission.LinkKey[5];
				    current_SAS.spas.PreconfiguredLinkKey[4]= MSDCL_Commission.LinkKey[4];
				    current_SAS.spas.PreconfiguredLinkKey[3]= MSDCL_Commission.LinkKey[3];
				    current_SAS.spas.PreconfiguredLinkKey[2]= MSDCL_Commission.LinkKey[2];
				    current_SAS.spas.PreconfiguredLinkKey[1]= MSDCL_Commission.LinkKey[1];
				    current_SAS.spas.PreconfiguredLinkKey[0]= MSDCL_Commission.LinkKey[0];
			
				    current_SAS.spas.ChannelMask.Val = MSDCL_Commission.ChannelMask.Val & 0x07FFF800UL;
			
			   		current_SAS.spas.StartupControl = MSDCL_Commission.StartupStatus;
			    
			    	//PutNeighborTableInfo();
			    	//MSDCL_Commission.DoCleanStartUp = 0;
			    	//NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
				}

                if(current_SAS.validitykey != SAS_TABLE_VALID)
                {
                    Initdefault_SAS();
                    index = 0xFF;
                    PutActiveSASIndex(&index);
                }
            #endif
        }

        CLRWDT();

        return result;
    }
Ejemplo n.º 6
0
ZIGBEE_PRIMITIVE AILTasks(ZIGBEE_PRIMITIVE inputPrimitive)
{
    if (inputPrimitive == NO_PRIMITIVE)
    {
        APP_DATA_request    *dataReq;
        BYTE                length;

        dataReq = (APP_DATA_request *) AILDequeue( TransmitQueueID );
        if ( dataReq != NULL )
        {
            params.APSDE_DATA_request.DstAddrMode               = dataReq->DstAddrMode;
            params.APSDE_DATA_request.DstAddress.ShortAddr.Val  = dataReq->DstAddress.ShortAddr.Val;
            params.APSDE_DATA_request.DstEndpoint               = dataReq->DstEndpoint;
            params.APSDE_DATA_request.ProfileId.Val             = dataReq->ProfileId.Val;
            params.APSDE_DATA_request.ClusterId.Val             = dataReq->ClusterId.Val;
            params.APSDE_DATA_request.SrcEndpoint               = dataReq->SrcEndpoint;
            params.APSDE_DATA_request.TxOptions.Val             = dataReq->TxOptions.Val;
            params.APSDE_DATA_request.RadiusCounter             = dataReq->RadiusCounter;
            params.APSDE_DATA_request.asduLength                = dataReq->asduLength;
            params.APSDE_DATA_request.DiscoverRoute             = 1;
            if (dataReq->asduLength > 0)
            {
                for( length = 0; length < dataReq->asduLength; length++ )
                {
                    TxBuffer[TxData++] = *( dataReq->asdu + length );
                }
            }

            nfree(dataReq);
            return APSDE_DATA_request;
        }
        return NO_PRIMITIVE;
    }
    else
    {
        switch ( inputPrimitive )
        {
            case APSDE_DATA_indication:
            {
                APP_DATA_indication     *dataInd;
                BYTE                    length;

                dataInd = (APP_DATA_indication *)SRAMalloc( 126 );
                if ( dataInd != NULL )
                {
                    dataInd->MessageType                = MessageTypeAppDataIndication;
                    dataInd->DstAddrMode                = params.APSDE_DATA_indication.DstAddrMode;
                    dataInd->DstAddress.ShortAddr.Val   = params.APSDE_DATA_indication.DstAddress.ShortAddr.Val;
                    dataInd->DstEndpoint                = params.APSDE_DATA_indication.DstEndpoint;
                    dataInd->SrcAddrMode                = params.APSDE_DATA_indication.SrcAddrMode;
                    dataInd->SrcAddress.ShortAddr.Val   = params.APSDE_DATA_indication.SrcAddress.ShortAddr.Val;
                    dataInd->SrcEndpoint                = params.APSDE_DATA_indication.SrcEndpoint;
                    dataInd->ProfileId.Val              = params.APSDE_DATA_indication.ProfileId.Val;
                    dataInd->ClusterId.Val              = params.APSDE_DATA_indication.ClusterId.Val;
                    dataInd->Status                     = params.APSDE_DATA_indication.Status;
                    dataInd->SecurityStatus             = params.APSDE_DATA_indication.SecurityStatus;
                    dataInd->WasBroadcast               = params.APSDE_DATA_indication.WasBroadcast;
                    dataInd->LinkQuality                = params.APSDE_DATA_indication.LinkQuality;
                    dataInd->RxTime.Val                 = params.APSDE_DATA_indication.RxTime.Val;
                    dataInd->asduLength                 = params.APSDE_DATA_indication.asduLength;

                    if (params.APSDE_DATA_indication.asduLength > 0)
                    {
                        for( length = 0; length < params.APSDE_DATA_indication.asduLength; length++ )
                        {
                            *(dataInd->asdu + length) = *( params.APSDE_DATA_indication.asdu + length );
                        }
                    }

                    if (params.APSDE_DATA_indication.DstAddrMode != 0x01)
                    {
                        APLDiscardRx();
                    }

                    if (params.APSDE_DATA_indication.SrcEndpoint == 0x00)
                    {
                        ZDODiscardRx();
                    }

                    if ( AILEnqueue( (BYTE *)dataInd, ReceiveQueueID ) == AILQueueFailure )
                    {
                        nfree(dataInd);
                    }
                    return NO_PRIMITIVE;
                }
            }
            break;

            case APSDE_DATA_confirm:
            {
                APP_DATA_confirm    *dataConf;

                dataConf = (APP_DATA_confirm *)SRAMalloc(sizeof( APP_DATA_confirm ) );
                if ( dataConf != NULL )
                {
                    dataConf->MessageType               = MessageTypeAppDataConfirm;
                    dataConf->Status                    = params.APSDE_DATA_confirm.Status;
                    dataConf->DstAddrMode               = params.APSDE_DATA_confirm.DstAddrMode;
                    dataConf->DstAddress.ShortAddr.Val  = params.APSDE_DATA_confirm.DstAddress.ShortAddr.Val;
                    dataConf->DstEndpoint               = params.APSDE_DATA_confirm.DstEndpoint;
                    dataConf->SrcEndpoint               = params.APSDE_DATA_confirm.SrcEndpoint;
                    dataConf->TxTime.Val                = params.APSDE_DATA_confirm.TxTime.Val;

                    if ( AILEnqueue( (BYTE *)dataConf, ReceiveQueueID ) == AILQueueFailure )
                    {
                        nfree(dataConf);
                    }

                    return NO_PRIMITIVE;
                }
            }
            break;

            default:
            break;
        }
        return NO_PRIMITIVE;
    }
}