Esempio n. 1
0
void UserInterruptHandler(void)
{

    // *************************************************************************
    // Place any application-specific interrupt processing here
    // *************************************************************************

    // Is this a interrupt-on-change interrupt?
    if ( INTCONbits.RBIF == 1 )
    {
        // Record which button was pressed so the main() loop can
        // handle it
        if (LEVEL_SENSOR == 0)
		{
            myStatusFlags.bits.bLevelSensorButtonPressed = TRUE;
			ConsolePutROMString( (ROM char *)"O botao LEVEL_SENSOR foi pressionado!\r\n" );
		}

        if (MOVE_SENSOR == 0)
		{
            myStatusFlags.bits.bMoveSensorButtonPressed = TRUE;
			ConsolePutROMString( (ROM char *)"O botao MOVE_SENSOR foi pressionado!\r\n" );
		}

        // Disable further RBIF until we process it
        INTCONbits.RBIE = 0;

        // Clear mis-match condition and reset the interrupt flag
        LATB = PORTB;

        INTCONbits.RBIF = 0;
    }
}
Esempio n. 2
0
void StartWirelessConnection(void)
 {
    Read_MAC_Address();

    LED_1 = 0;
    LED_2 = 0;

                    //ConsolePutROMString((ROM char *)"\r\n<MAC Addr:");
                    //PrintChar(myLongAddress[3]);
                    //PrintChar(myLongAddress[2]);
                    //PrintChar(myLongAddress[1]);
                    //PrintChar(myLongAddress[0]);
                    //ConsolePutROMString((ROM char *)"\r>");

                    //ConsolePutROMString((ROM char *)"\r\n Board role: ");

  // if the node are Coordinator
  ConsolePutROMString((ROM char *)"COORDINATOR >> ");
  PrintChar(myNodeNumber);

  ConsolePutROMString((ROM char *)"\r\n<MAC Addr:");
  PrintChar(myLongAddress[3]);
  PrintChar(myLongAddress[2]);
  PrintChar(myLongAddress[1]);
  PrintChar(myLongAddress[0]);
  ConsolePutROMString((ROM char *)"\r>");

  MiApp_ProtocolInit(FALSE);

    // Force PANID & SHORT ADDRESS

  if( MiApp_SetChannel(myChannel) == FALSE )
  {
   return;
  }

  MiApp_ConnectionMode(ENABLE_ALL_CONN);

  myPANID.v[0] = 0x34;
  myPANID.v[1] = 0x12;

  myShortAddress.v[0] = 0x00;
  myShortAddress.v[1] = myNodeNumber;

  myChannel = PanCoordToCoordChan;
  //role = ROLE_COORDINATOR;

  if( MiApp_SetChannel(myChannel) == FALSE )
  {
   return;
  }

 
}
Esempio n. 3
0
/*********************************************************************
* Function:         void PrintDec(BYTE toPrint)
*
* PreCondition:     none
*
* Input:		    toPrint - character to be printed. Range is 0-99
*
* Output:		    none
*
* Side Effects:	    toPrint is printed to the console in decimal
*                   
*
* Overview:		    This function will print the inputed BYTE to 
*                   the console in decimal form
*
* Note:			    Do not power down the microcontroller until 
*                   the transmission is complete or the last 
*                   transmission of the string can be corrupted.  
********************************************************************/
void PrintDec(BYTE toPrint)
{
#if defined(ENABLE_CONSOLE)
	const char* temp = my_itoa(toPrint);
	ConsolePutROMString(temp);
#endif
}
Esempio n. 4
0
 //----------------------------------------------------------------------------//
 void Bypass(void)
 {
    if(SwTimer4 >= 50 ) 
    {
     SwTimer4 = 0;
     
     if(BypassCounter >= 5)      
     {
         RLY_1 = 1;
         
         
         EEPROMRead(&myDevicesRequiredStatus, 0, 1);
         if(myDevicesRequiredStatus[0] == 0xAA)      // estado relevador apagado
         {
             i = 0x55;
             EEPROMWRITE(&i,0,1); 
             EEPROMWRITE(&i,0,1); 
             EEPROMWRITE(&i,0,1); 
             EEPROMWRITE(&i,0,1); 
             EEPROMWRITE(&i,0,1);
         }
         
         
         
         ConsolePutROMString((ROM char *)"\r\nBypass");
     }
    }
 }
Esempio n. 5
0
 BYTE TemperatureRead(void)
 {
    double temp;
    BYTE tempHere;
    float tempAverage = 0;
    

    
    VBGResult = Read_VBGVoltage();
    
    
    ADCON0bits.CHS = 0x04;  // Temperature sensor channel select
    DelayMs(1);
    
    j=0;
    
    do
    {
    
      ADCON0bits.GO = 1;		    //Start A/D conversion
      while(ADCON0bits.DONE);
    
      SensorResult = ADRES;
      //ConsolePutROMString( (ROM char * const) "  \r\n TempResult:" );
      //PrintChar(ADRESH);
      //PrintChar(ADRESL);
    
    
      temp = (1200.0/VBGResult);
      temp = (temp * SensorResult);
      temp = (temp - 400.0)/19.5;
    
      tempArray[j] = (BYTE) temp;
      //tempIndex++;
    
      j++;
    }while(j < NUM_TEMP_SAMPLES);
    
    
    for(j = 0; j<NUM_TEMP_SAMPLES; j++)
    {
        tempAverage = (tempAverage + tempArray[j]);
    }
    tempAverage = (tempAverage/NUM_TEMP_SAMPLES);
    tempHere = (BYTE) tempAverage;
    tempAverage = (tempAverage - tempHere) * 10;
    
    if(tempAverage >= 5)
        tempHere = tempHere + 1;
        
    
    
    ConsolePutROMString( (ROM char * const) "  \r\n TempGrados:" );
    PrintDec((BYTE)tempHere);
    
    
    return (BYTE)tempHere;  


 }
Esempio n. 6
0
/*********************************************************************
* Function:         WORD Read_VBGVoltage(void)
*
* PreCondition:     none
*
* Input:		    none
*
* Output:		    ADRES
*
* Side Effects:	    none
*
* Overview:		    Reads the band gap voltage and compares with reference voltage
*					to arrive at the current voltage level
*
* Note:
**********************************************************************/
WORD Read_VBGVoltage(void)
{
   
    
    //ADCON0 = 0x3D;				// Configures the channel as VBG
    //ADCON1 = 0xBD;				// Program the acquisition time
    //ANCON1bits.VBGEN = 1;		// Enable Band gap reference voltage
    
    //Delay10us(100);			//Wait for the Band Gap Settling time
    ADCON0bits.CHS = 0x0F;  // VBG channel select
    DelayMs(1);
    
    //PIR1bits.ADIF = 0;
    //PIE1bits.ADIE = 0;			//Disable ADC interrupts
    							//This routine uses the polling based mechanism
    ADCON0bits.GO = 1;		    //Start A/D conversion
    while(ADCON0bits.DONE);

    //ADCON0bits.ADON = 0;	    // Turn ADC OFF
    //ANCON1bits.VBGEN = 0;	    // Disable Bandgap
    
    
    ConsolePutROMString( (ROM char * const) "  \r\n VBGResult:" );
    PrintChar(ADRESH);
    PrintChar(ADRESL);

    return ADRES;
}
Esempio n. 7
0
void RFDSendMessage(unsigned short attributeID, unsigned char value)
{
	// Send a light toggle message to the other node.
    ZigBeeBlockTx();

    TxBuffer[TxData++] = APL_FRAME_TYPE_KVP | 1;    // KVP, 1 transaction
    TxBuffer[TxData++] = APLGetTransId();
    TxBuffer[TxData++] = APL_FRAME_COMMAND_SET | (APL_FRAME_DATA_TYPE_UINT8 << 4);
    TxBuffer[TxData++] = ATTR_ID_LSB(attributeID);	// Attribute ID LSB
    TxBuffer[TxData++] = ATTR_ID_MSB(attributeID);  		// Attribute ID MSB
    TxBuffer[TxData++] = value;

    params.APSDE_DATA_request.DstAddrMode = APS_ADDRESS_16_BIT;
    params.APSDE_DATA_request.DstEndpoint = EP_LIGHT;
    params.APSDE_DATA_request.DstAddress.ShortAddr = destinationAddress;

    //params.APSDE_DATA_request.asduLength; TxData
    params.APSDE_DATA_request.ProfileId.Val = BABY_PROFILE_ID;
    params.APSDE_DATA_request.RadiusCounter = DEFAULT_RADIUS;
    params.APSDE_DATA_request.DiscoverRoute = ROUTE_DISCOVERY_ENABLE;
						    
	// Sem suporte a segurança                        
    params.APSDE_DATA_request.TxOptions.Val = 0; 
                          
    params.APSDE_DATA_request.SrcEndpoint = EP_LIGHT;
    params.APSDE_DATA_request.ClusterId = BabyControl_CLUSTER;

    ConsolePutROMString( (ROM char *)" Trying to send light switch message.\r\n" );

    currentPrimitive = APSDE_DATA_request;
}
Esempio n. 8
0
/*********************************************************************
* Function:         void PrintChar(BYTE toPrint)
*
* PreCondition:     none
*
* Input:		    toPrint - character to be printed
*
* Output:		    none
*
* Side Effects:	    toPrint is printed to the console
*
* Overview:		    This function will print the inputed BYTE to 
*                   the console in hexidecimal form
*
* Note:			    Do not power down the microcontroller until 
*                   the transmission is complete or the last 
*                   transmission of the string can be corrupted.  
********************************************************************/
void PrintChar(BYTE toPrint)
{
#if defined(ENABLE_CONSOLE)
	char temp[3];
	sprintf(temp,"%02x",toPrint);
	ConsolePutROMString(temp);
#endif
}
Esempio n. 9
0
    BYTE ComparePage( WORD dest,  BYTE *src, WORD count )
    {
        BYTE    oneByte;
        BYTE    result;

        result = 0;
        do
        {
            NVMRead( &oneByte, dest, 1 );
            #ifdef ENABLE_DEBUG
                ConsolePutROMString((ROM char * const)"Want ");
                PrintChar(*src);
                ConsolePutROMString((ROM char * const)"Got ");
                PrintChar(oneByte);
                ConsolePut( ' ' );
            #endif
            if (oneByte != *src)
            {
                #ifdef PRINT_MULTIPLE_WRITE_ATTEMPTS
                    if (flag)
                    {
                        ConsolePut('(');
                        PrintChar( (BYTE)(((WORD)dest>>8)&0xFF) );
                        PrintChar( (BYTE)((WORD)dest&0xFF) );
                        ConsolePut('-');
                        PrintChar( *src );
                        ConsolePut('-');
                        PrintChar( oneByte );
                        ConsolePut(')');
                    }
                #endif
                return 1;   // Mismatch
            }
            src++;
            dest++;
            count--;
        }
        while (count && (dest & (EEPROM_PAGE_SIZE-1)));

        return 0;   // Match
    }
Esempio n. 10
0
void DemoOutput_HandleMessage(BYTE TxNum, BYTE RxNum)
{
    BYTE i;
    
    if( rxMessage.flags.bits.secEn )
    {
        ConsolePutROMString((ROM char *)"Secured ");
    }

    if( rxMessage.flags.bits.broadcast )
    {
        ConsolePutROMString((ROM char *)"Broadcast Packet with RSSI ");
    }
    else
    {
        ConsolePutROMString((ROM char *)"Unicast Packet with RSSI ");
    }
    PrintChar(rxMessage.PacketRSSI);
    if( rxMessage.flags.bits.srcPrsnt )
    {
        ConsolePutROMString((ROM char *)" from ");
        if( rxMessage.flags.bits.altSrcAddr )
        {
            PrintChar( rxMessage.SourceAddress[1]);
            PrintChar( rxMessage.SourceAddress[0]);
        }
        else
        {    
            for(i = 0; i < MY_ADDRESS_LENGTH; i++)
            {
                PrintChar(rxMessage.SourceAddress[MY_ADDRESS_LENGTH-1-i]);
            }    
        }
    }
    ConsolePutROMString((ROM char *)": ");
    
    for(i = 0; i < rxMessage.PayloadSize; i++)
    {
        ConsolePut(rxMessage.Payload[i]);
    }       
}    
Esempio n. 11
0
 void WirelesStatus(void)
 {
     if( SwTimer3 >= 150)           // if lost connection ...
     {
      ConsolePutROMString( (ROM char * const) "  \r\n Timer - Link Lost... Restarting..." );
      
      ++BypassCounter;
    
      Reset();
      //StartWirelessConnection();   //  Try to restart connection
     }
     
     
     
     if(RestartCounter >= 3)
     {
         ConsolePutROMString( (ROM char * const) "  \r\n Counter - Link Lost... Restarting..." );
         Reset();
     }
     
 }
Esempio n. 12
0
BOOL MyMIWI_RxMsg(char *theMsg) {

    int i;

    /*******************************************************************/
    // Function MiApp_MessageAvailable returns a boolean to indicate if
    //  a packet has been received by the transceiver. If a packet has
    //  been received, all information will be stored in the rxFrame,
    //  structure of RECEIVED_MESSAGE.
    /*******************************************************************/
    if( !MiApp_MessageAvailable() )
        return FALSE;

    /*******************************************************************/
    // If a packet has been received, following code prints out some of
    // the information available in rxMessage.
    /*******************************************************************/
    if( rxMessage.flags.bits.secEn )
        ConsolePutROMString((ROM char *)"Secured ");

    if( rxMessage.flags.bits.broadcast )
        ConsolePutROMString((ROM char *)"Broadcast Packet with RSSI ");
    else
        ConsolePutROMString((ROM char *)"Unicast Packet with RSSI ");

    PrintChar(rxMessage.PacketRSSI);

    if( rxMessage.flags.bits.srcPrsnt ) {
        ConsolePutROMString((ROM char *)" from ");
         if( rxMessage.flags.bits.altSrcAddr ) {
            PrintChar(rxMessage.SourceAddress[1]);
            PrintChar(rxMessage.SourceAddress[0]);
         } else {
            for(i = 0; i < MY_ADDRESS_LENGTH; i++)
                PrintChar(rxMessage.SourceAddress[MY_ADDRESS_LENGTH-1-i]);
         }
    }

    ConsolePutROMString((ROM char *)" : ");
    for(i = 0; i < rxMessage.PayloadSize; i++) {
        ConsolePut(rxMessage.Payload[i]);
        *theMsg++ = rxMessage.Payload[i];
    }
    ConsolePutROMString((ROM char *)"\n");
    *theMsg = '\0';

    /*******************************************************************/
    // Function MiApp_DiscardMessage is used to release the current
    //  received packet.
    // After calling this function, the stack can start to process the
    //  next received frame
    /*******************************************************************/
    MiApp_DiscardMessage();

    return TRUE;
}
Esempio n. 13
0
    void NVMRead (BYTE *dest, WORD  src, BYTE count)
    {
        #if !defined(__C30__)
        BYTE oldGIEH;
        #endif
        
        #ifdef ENABLE_DEBUG
            ConsolePut('r');
            PrintChar( (BYTE)(((WORD)src>>8)&0xFF) );
            PrintChar( (BYTE)((WORD)src&0xFF) );
            ConsolePut('-');
            PrintChar( count );
        #endif
        #if !defined(__C30__)
            oldGIEH = 0;
            if ( INTCONbits.GIEH )
            {
                oldGIEH = 1;
            }
            INTCONbits.GIEH = 0;
        #endif

        SPISelectEEPROM();
        SPIPut( SPIREAD );
        SPIPut( (BYTE)(((WORD)src>>8) & 0xFF) );
        SPIPut( (BYTE)((WORD)src & 0xFF) );
        while( count )
        {
            *dest = SPIGet();
            #ifdef ENABLE_DEBUG
            #endif
            dest++;
            count--;
        }
        SPIUnselectEEPROM();

        #if !defined(__C30__)
            if (oldGIEH)
            {
                INTCONbits.GIEH = 1;
            }
        #endif

        #ifdef ENABLE_DEBUG
            ConsolePutROMString((ROM char * const)"\r\n");
        #endif
    }
Esempio n. 14
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;
    }
Esempio n. 15
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;
    }
Esempio n. 16
0
int main(void)
#endif
{   
    BYTE i, j;
    BYTE TxSynCount = 0;
    BOOL bReceivedMessage = FALSE;
    _U16  m;

    
     #define BAUDRG 77
    /*******************************************************************/
    // Initialize the system
    /*******************************************************************/

    ANCON0 = 0XFF;     /*desactiva entradas analogicas*/
    ANCON1 = 0XFF;     /*desactiva entradas analogicas*/

    PPSUnLock();
    PPSOutput(PPS_RP10, PPS_TX2CK2);    // TX2 RP17/RC6
    PPSInput(PPS_RX2DT2, PPS_RP9);     // RX2 RP18/RC7

    PPSOutput(PPS_RP23, PPS_SDO2);    // SDO2 RP23/RD6
    PPSInput(PPS_SDI2, PPS_RP24);     // SDI2 RP24/RD7
    PPSOutput(PPS_RP22, PPS_SCK2);    // SCK2 RP22/RD5

    PPSLock();

     System_PeripheralPinSelect( ExternalInterrupt3, 19);  /*external interrupt 3 B3*/

     BoardInit();
     ConsoleInit();

     Open2USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG);
     baud2USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF);

     Gpios_PinDirection(GPIOS_PORTD, 7, GPIOS_INPUT);  /*pin C0 como salida para SDI*/
     Gpios_PinDirection(GPIOS_PORTD, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/
     Gpios_PinDirection(GPIOS_PORTD, 5, GPIOS_OUTPUT); /*pin C2 como salida para SCK*/

     Spi_Init(SPI_PORT1, SPI_64DIV); /*Inicializamos SPI2*/
     Spi_Init(SPI_PORT2, SPI_64DIV); /*Inicializamos SPI2*/
     //Spi_SetMode(SPI_PORT1, 1);
     //Spi_SetMode(SPI_PORT1, 1);


    LED_1 = 1;
    LED_2 = 1;

    Read_MAC_Address();

    LED_1 = 0;
    LED_2 = 0;

                    ConsolePutROMString((ROM char *)"\r\n<MAC Addr:");
                 
                    PrintChar(myLongAddress[3]);
                    PrintChar(myLongAddress[2]);
                    PrintChar(myLongAddress[1]);
                    PrintChar(myLongAddress[0]);

                    ConsolePutROMString((ROM char *)"\r>");

        
    Printf("\r\nStarting Testing Interface for MiWi(TM) PRO Stack ...");
    #if defined(MRF24J40)
    Printf("\r\n     RF Transceiver: MRF24J40");
    #elif defined(MRF49XA)
    Printf("\r\n     RF Transceiver: MRF49XA");
    #elif defined(MRF89XA)
    Printf("\r\n     RF Transceiver: MRF89XA");
    #endif
    Printf("\r\n   Demo Instruction:");
    Printf("\r\n                     Press Enter to bring up the menu.");
    Printf("\r\n                     Type in hyper terminal to choose");
    Printf("\r\n                     menu item. ");
    Printf("\r\n\r\n");
   
    /*******************************************************************/
    // Following block display demo information on LCD of Explore 16 or 
    // PIC18 Explorer demo board.
    /*******************************************************************/
    #if defined(MRF49XA)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF49XA", 0, TRUE); 
    #elif defined(MRF24J40)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF24J40", 0, TRUE);
    #elif defined(MRF89XA)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF89XA", 0, TRUE); 
    #endif
    
    //if( (PUSH_BUTTON_1 == 0) || ( MiApp_ProtocolInit(TRUE) == FALSE ) )
    if (PUSH_BUTTON_1 == 1)
    {  

        MiApp_ProtocolInit(FALSE);


        LED_1 = 0;
        LED_2 = 0;

        #ifdef ENABLE_ACTIVE_SCAN
        
            myChannel = 0xFF;
            ConsolePutROMString((ROM char *)"\r\nStarting Active Scan...");
            
            LCDDisplay((char *)"Active Scanning", 0, FALSE);
    
            /*******************************************************************/
            // Function MiApp_SearchConnection will return the number of 
            // existing connections in all channels. It will help to decide 
            // which channel to operate on and which connection to add.
            // The return value is the number of connections. The connection 
            //     data are stored in global variable ActiveScanResults. 
            //     Maximum active scan result is defined as 
            //     ACTIVE_SCAN_RESULT_SIZE
            // The first parameter is the scan duration, which has the same 
            //     definition in Energy Scan. 10 is roughly 1 second. 9 is a 
            //     half second and 11 is 2 seconds. Maximum scan duration is 14, 
            //     or roughly 16 seconds.
            // The second parameter is the channel map. Bit 0 of the 
            //     double word parameter represents channel 0. For the 2.4GHz 
            //     frequency band, all possible channels are channel 11 to 
            //     channel 26. As the result, the bit map is 0x07FFF800. Stack 
            //     will filter out all invalid channels, so the application 
            //     only needs to pay attention to the channels that are not 
            //     preferred.
            /*******************************************************************/
            i = MiApp_SearchConnection(10, 0x02000000);
            
            if( i > 0 )
            {
                // now print out the scan result.
                Printf("\r\nActive Scan Results: \r\n");
                for(j = 0; j < i; j++)
                {
                    Printf("Channel: ");
                    PrintDec(ActiveScanResults[j].Channel );
                    Printf("   RSSI: ");
                    PrintChar(ActiveScanResults[j].RSSIValue);
                    Printf("\r\n");
                    myChannel = ActiveScanResults[j].Channel;
                    Printf("PeerInfo: ");
                    PrintChar( ActiveScanResults[j].PeerInfo[0]);
                }
            }
        #endif

    

        /*******************************************************************/
        // Function MiApp_ConnectionMode sets the connection mode for the 
        // protocol stack. Possible connection modes are:
        //  - ENABLE_ALL_CONN       accept all connection request
        //  - ENABLE_PREV_CONN      accept only known device to connect
        //  - ENABL_ACTIVE_SCAN_RSP do not accept connection request, but 
        //                          allow response to active scan
        //  - DISABLE_ALL_CONN      disable all connection request, including
        //                          active scan request
        /*******************************************************************/
        MiApp_ConnectionMode(ENABLE_ALL_CONN);
    
    
        if( i > 0 )
        {
            /*******************************************************************/
            // Function MiApp_EstablishConnection try to establish a new 
            // connection with peer device. 
            // The first parameter is the index to the active scan result, which 
            //      is acquired by discovery process (active scan). If the value
            //      of the index is 0xFF, try to establish a connection with any 
            //      peer.
            // The second parameter is the mode to establish connection, either 
            //      direct or indirect. Direct mode means connection within the 
            //      radio range; Indirect mode means connection may or may not 
            //      in the radio range. 
            /*******************************************************************/
            if( MiApp_EstablishConnection(0, CONN_MODE_DIRECT) == 0xFF )
            {
                Printf("\r\nJoin Fail");
            }
        }    
        else
        {
            /*******************************************************************/
            // Function MiApp_StartConnection tries to start a new network 
            //
            // The first parameter is the mode of start connection. There are 
            // two valid connection modes:
            //   - START_CONN_DIRECT        start the connection on current 
            //                              channel
            //   - START_CONN_ENERGY_SCN    perform an energy scan first, 
            //                              before starting the connection on 
            //                              the channel with least noise
            //   - START_CONN_CS_SCN        perform a carrier sense scan 
            //                              first, before starting the 
            //                              connection on the channel with 
            //                              least carrier sense noise. Not 
            //                              supported on currrent radios
            //
            // The second parameter is the scan duration, which has the same 
            //     definition in Energy Scan. 10 is roughly 1 second. 9 is a 
            //     half second and 11 is 2 seconds. Maximum scan duration is 
            //     14, or roughly 16 seconds.
            //
            // The third parameter is the channel map. Bit 0 of the 
            //     double word parameter represents channel 0. For the 2.4GHz 
            //     frequency band, all possible channels are channel 11 to 
            //     channel 26. As the result, the bit map is 0x07FFF800. Stack 
            //     will filter out all invalid channels, so the application 
            //     only needs to pay attention to the channels that are not 
            //     preferred.
            /*******************************************************************/
            #ifdef ENABLE_ED_SCAN
                //LCDDisplay((char *)"Active Scanning Energy Scanning", 0, FALSE);
                ConsolePutROMString((ROM char *)"\r\nActive Scanning Energy Scanning");
                MiApp_StartConnection(START_CONN_ENERGY_SCN, 10, 0x02000000);
            #endif
        }
        
        // Turn on LED 1 to indicate ready to accept new connections
        LED_1 = 1;
    }
    else
    {
        //LCDDisplay((char *)" Network Freezer    ENABLED", 0, TRUE);
        Printf("\r\nNetwork Freezer Feature is enabled. There will be no hand-shake process.\r\n");
        LED_1 = 1;
        DumpConnection(0xFF);
    }
                   
    LCDDisplay((char *)"Start Connection on Channel %d", currentChannel, TRUE);
    LCDDisplay((char *)"Testing Menu on  Hyper Terminal", 0, FALSE);

    while(1)
    {
        /*******************************************************************/
        // Function MiApp_MessageAvailable will return a boolean to indicate 
        // if a message for application layer has been received by the 
        // transceiver. If a message has been received, all information will 
        // be stored in the rxMessage, structure of RECEIVED_MESSAGE.
        /*******************************************************************/
        if( MiApp_MessageAvailable() )
        {
            /*******************************************************************/
            // If a packet has been received, following code prints out some of
            // the information available in rxFrame.
            /*******************************************************************/
            if( rxMessage.flags.bits.secEn )
            {
                ConsolePutROMString((ROM char *)"Secured ");
            }

            if( rxMessage.flags.bits.broadcast )
            {
                ConsolePutROMString((ROM char *)"Broadcast Packet with RSSI ");
            }
            else
            {
                ConsolePutROMString((ROM char *)"Unicast Packet with RSSI ");
            }
            PrintChar(rxMessage.PacketRSSI);
            if( rxMessage.flags.bits.srcPrsnt )
            {
                ConsolePutROMString((ROM char *)" from ");
                if( rxMessage.flags.bits.altSrcAddr )
                {
                    PrintChar(rxMessage.SourceAddress[1]);
                    PrintChar(rxMessage.SourceAddress[0]);
                }
                else
                {    
                    for(i = 0; i < MY_ADDRESS_LENGTH; i++)
                    {
                        PrintChar(rxMessage.SourceAddress[MY_ADDRESS_LENGTH-1-i]);
                    }
                }    
            }

            ConsolePutROMString((ROM char *)": ");
            
            
            for(i = 0; i < rxMessage.PayloadSize; i++)
            {
                ConsolePut(rxMessage.Payload[i]);
            }
            
            // Toggle LED2 to indicate receiving a packet.
            LED_2 ^= 1;
            
            /*******************************************************************/
            // Function MiApp_DiscardMessage is used to release the current 
            // received message. After calling this function, the stack can 
            // start to process the next received message.
            /*******************************************************************/          
            MiApp_DiscardMessage();
            
            bReceivedMessage = TRUE;
            
            /*******************************************************************/
            // Following block update the total received and transmitted messages
            // on the LCD of the demo board. 
            /*******************************************************************/
            LCDTRXCount(TxNum, ++RxNum);
        }
        else
        {
         ++m;

         if(m > 8000)
         {
             m=0;
             //LED_1 ^= 1;
             
                MiApp_FlushTx();
    	        MiApp_WriteData('H');
    	        MiApp_WriteData('o');
    	        MiApp_WriteData('l');
    	        MiApp_WriteData('a');
                MiApp_WriteData('a');
                MiApp_WriteData('a');
    	        MiApp_WriteData(0x0D);
    	        MiApp_WriteData(0x0A);
               MiApp_BroadcastPacket(FALSE);

         }



            if ( ConsoleIsGetReady() )
            {
                //ProcessMenu();
            } 
        }
    }
}
Esempio n. 17
0
void ProcessMenu( void )
{

    BYTE        c;
    BYTE        i;

    // Get the key value.
    c = ConsoleGet();
    ConsolePut( c );
    switch (c)
    {
        case '1':
            ConsolePutROMString((ROM char * const)"\r\n1=ENABLE_ALL 2=ENABLE PREV 3=ENABLE SCAN 4=DISABLE: ");
            while( !ConsoleIsGetReady());
        	c = ConsoleGet();
        	ConsolePut(c);
        	switch(c)
        	{
        		case '1':
        		    MiApp_ConnectionMode(ENABLE_ALL_CONN);
        		    break;
        		
        		case '2':
        		    MiApp_ConnectionMode(ENABLE_PREV_CONN);
        		    break;
        		    
        		case '3':
        		    MiApp_ConnectionMode(ENABLE_ACTIVE_SCAN_RSP);
        		    break;
        		    
        		case '4':
        		    MiApp_ConnectionMode(DISABLE_ALL_CONN);
        		    break;
        		
        	    default:
        	        break;	
            }
            break;
            
        case '2':
            Printf("\r\nFamily Tree: ");
            for(i = 0; i < NUM_COORDINATOR; i++)
            {
                PrintChar(FamilyTree[i]);
                Printf(" ");
            }
            break;
            
        case '3':
            Printf("\r\nMy Routing Table: ");
            for(i = 0; i < NUM_COORDINATOR/8; i++)
            {
                PrintChar(RoutingTable[i]);
            }
            Printf("\r\nNeighbor Routing Table: ");
            for(i = 0; i < NUM_COORDINATOR; i++)
            {
                BYTE j;
                for(j = 0; j < NUM_COORDINATOR/8; j++)
                {
                    PrintChar(NeighborRoutingTable[i][j]);
                }
                Printf(" ");
            }
            break;
            
        case '4':
            {   
                WORD_VAL tempShortAddr;
                Printf("\r\n1=Broadcast 2=Unicast Connection 3=Unicast Addr: ");
                while( !ConsoleIsGetReady());
            	c = ConsoleGet();
            	ConsolePut(c);
            	
    	        MiApp_FlushTx();
    	        MiApp_WriteData('T');
    	        MiApp_WriteData('e');
    	        MiApp_WriteData('s');
    	        MiApp_WriteData('t');
    	        MiApp_WriteData(0x0D);
    	        MiApp_WriteData(0x0A);
        	    switch(c)
        	    {
            	    case '1':
            	        MiApp_BroadcastPacket(FALSE);
            	        TxNum++;
            	        break;
            	        
            	    case '2':
            	        Printf("\r\nConnection Index: ");
            	        while( !ConsoleIsGetReady());
            	        c = GetHexDigit();
                        MiApp_UnicastConnection(c, FALSE);
                        TxNum++;
                        break;
                        
                    case '3':
                        Printf("\r\n1=Long Address 2=Short Address: ");
                        while( !ConsoleIsGetReady());
                    	c = ConsoleGet();
                    	ConsolePut(c);
                    	switch(c)
                    	{
                        	case '1':
                        	    Printf("\r\nDestination Long Address: ");
                        	    for(i = 0; i < MY_ADDRESS_LENGTH; i++)
                        	    {
                            	    tempLongAddress[MY_ADDRESS_LENGTH-1-i] = GetMACByte();
                            	}
                            	MiApp_UnicastAddress(tempLongAddress, TRUE, FALSE);
                            	TxNum++;
                            	break;
                        	
                        	case '2':
                        	    Printf("\r\nDestination Short Address: ");
                        	    tempLongAddress[1] = GetMACByte();
                        	    tempLongAddress[0] = GetMACByte();
                        	    MiApp_UnicastAddress(tempLongAddress, FALSE, FALSE);
                        	    TxNum++;
                        	    break;
                        	
                        	default:
                        	    break;
                        }
                        break;
                        
                    default:
                        break;
            	}
            }
            LCDTRXCount(TxNum, RxNum);
            break;
            
        case '5':
            {
                Printf("\r\nMSB of the Coordinator: ");
                i = GetMACByte();
                Printf("\r\nSet MSB of this Node's Parent: ");
                FamilyTree[i] = GetMACByte();
            }
            break;
            
        case '6':
            {
                Printf("\r\nSet my Routing Table: ");
                for(i = 0; i < NUM_COORDINATOR/8; i++)
                {
                    RoutingTable[i] = GetMACByte();
                    Printf(" ");
                }
            }
            break;
            
        case '7':
            {
                BYTE j;
                
                Printf("\r\nNode Number: ");
                i = GetMACByte();
                Printf("\r\nContent of Neighbor Routing Table: ");
                for(j = 0; j < NUM_COORDINATOR/8; j++)
                {
                    NeighborRoutingTable[i][j] = GetMACByte();
                    Printf(" ");
                }
            }
            break;
        
        case '8':
            {
                MiApp_InitChannelHopping(0xFFFFFFFF);
            }
            break;    
        
        
        case '9':
            {
                Printf("\r\nSocket: ");
                PrintChar(MiApp_EstablishConnection(0xFF, CONN_MODE_INDIRECT));
            }
            break;
        
        
        case 'z':
        case 'Z':
            {
                DumpConnection(0xFF);
            }    
        
        default:
            break;
    }
    PrintMenu();
}
Esempio n. 18
0
void PrintMenu( void )
{
    ConsolePutROMString(menu);
    ConsolePutROMString( (ROM char * const) "\r\nEnter a menu choice: " );
}
Esempio n. 19
0
void Repeater(void)
 {
     if( MiApp_MessageAvailable())
     {
            Printf("\r\n  ");
            if( rxMessage.flags.bits.secEn )
            {
                ConsolePutROMString((ROM char *)"Secured ");
            }

            if( rxMessage.flags.bits.broadcast )
            {
             ConsolePutROMString((ROM char *)"Broadcast Packet with RSSI ");
            }
            else
            {
             ConsolePutROMString((ROM char *)"Unicast Packet with RSSI ");
            }
            PrintChar(rxMessage.PacketRSSI);


           if( rxMessage.flags.bits.srcPrsnt )
            {
                ConsolePutROMString((ROM char *)" from ");
                if( rxMessage.flags.bits.altSrcAddr )
                {
                    PrintChar(rxMessage.SourceAddress[1]);
                    PrintChar(rxMessage.SourceAddress[0]);
                }
                else
                {
                    for(i = 0; i < MY_ADDRESS_LENGTH; i++)
                    {
                      PrintChar(rxMessage.SourceAddress[MY_ADDRESS_LENGTH-1-i]);

                    }
                }
            }

            ConsolePutROMString((ROM char *)": ");


            for(i = 0; i < rxMessage.PayloadSize; i++)
            {
              PrintChar(rxMessage.Payload[i]);
            }
         
       ClrWdt();  
       SwTimer3 = 0;  
         
       LED_2 ^= 1;
       MiApp_DiscardMessage();
       
     }
     
     
     if(SwTimer3 >= 500)           // if lost connection ... JL:Anteriormente 100, se cambio para
     {                              //lugares donde los mensajes llegan con mucho retardo entre uno y otro (area de pozo))
         Reset();
     }
 }
Esempio n. 20
0
void main(void)
{
     #define BAUDRG 77

    BYTE SecNum = 0;

   BOOL Tx_Success = FALSE;
   BYTE Tx_Trials = 0, scanresult = 0;
    /*******************************************************************/
    // Initialize the system
    /*******************************************************************/

    ANCON0 = 0XFF;     /*desactiva entradas analogicas*/
    ANCON1 = 0XFF;     /*desactiva entradas analogicas*/



    PPSUnLock();

    PPSOutput(PPS_RP10, PPS_TX2CK2);    // TX2 RP17/RC6     icsp
    PPSInput(PPS_RX2DT2, PPS_RP9);     // RX2 RP18/RC7

    PPSOutput(PPS_RP23, PPS_SDO2);    // SDO2 RP23/RD6
    PPSInput(PPS_SDI2, PPS_RP24);     // SDI2 RP24/RD7
    PPSOutput(PPS_RP22, PPS_SCK2);    // SCK2 RP22/RD5

    PPSLock();

     System_PeripheralPinSelect( ExternalInterrupt3, 19);  /*external interrupt 3 B3*/

     BoardInit();
     ConsoleInit();

     Gpios_PinDirection(GPIOS_PORTC, 7, GPIOS_INPUT);  /*pin C0 como salida para SDI*/
     Gpios_PinDirection(GPIOS_PORTC, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/
     
     //Gpios_PinDirection(GPIOS_PORTD, 4, GPIOS_OUTPUT);  /*pin D4 como salida */

     Open1USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG);
     baud1USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF);


     Open2USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG);
     baud2USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF);


     OpenTimer1( TIMER_INT_OFF &T1_16BIT_RW &T1_SOURCE_FOSC_4 & T1_PS_1_8 &T1_OSC1EN_OFF &T1_SYNC_EXT_OFF, TIMER_GATE_OFF  & TIMER_GATE_INT_OFF);



     Gpios_PinDirection(GPIOS_PORTD, 7, GPIOS_INPUT);  /*pin C0 como salida para SDI*/
     Gpios_PinDirection(GPIOS_PORTD, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/
     Gpios_PinDirection(GPIOS_PORTD, 5, GPIOS_OUTPUT); /*pin C2 como salida para SCK*/

     Spi_Init(SPI_PORT1, SPI_64DIV); /*Inicializamos SPI2*/
     Spi_Init(SPI_PORT2, SPI_64DIV); /*Inicializamos SPI2*/

     //Adc_Init(ADC_10BITS);

     LED_1 = 1;
     LED_2 = 0;
     //RLY_1 = 0;
     RLY_2 = 0;

     ON_RADIO = 1;
     ON_MAC = 1;
     ON_TEMP = 1;
     
     StartWirelessConnection();
     
     
     
     //myDevicesRequiredStatus[0] = 0x55;
     
     
     EEPROMRead(&myDevicesRequiredStatus, 0, 1);
     
     if(myDevicesRequiredStatus[0] == 0x55)
     {
         RLY_1 = 1;
         EEPROMCHG = 1;
         ConsolePutROMString((ROM char *)"RELAY ON ");
     }
     
     if(myDevicesRequiredStatus[0] == 0xAA)
     {
         RLY_1 = 0;
         EEPROMCHG = 0;
         ConsolePutROMString((ROM char *)"RELAY OFF ");
     }
     
     
     
     
     

     for(j=0;j<10;j++)
     {
         DelayMs(50);

         LED_1 ^= 1;
         LED_2 ^= 1;
     }
     
     

     LED_1 = 0;
     LED_2 = 0;
     //RLY_1 = 0;
     RLY_2 = 0;
     
    
     
     TickScaler = 4;
     EndDevStateMachine =0;



/*
                                

                                while(!Tx_Success)
                                {
                                    if(myChannel < 8)
                                        scanresult = MiApp_SearchConnection(10, (0x00000001 << myChannel));
                                    else if(myChannel < 16)
                    				    scanresult = MiApp_SearchConnection(10, (0x00000100 << (myChannel-8)));
                                    else if(myChannel < 24)
                    				    scanresult = MiApp_SearchConnection(10, (0x00010000 << (myChannel-16)));
                                    else
                    				    scanresult = MiApp_SearchConnection(10, (0x01000000 << (myChannel-24)));
                                    if(scanresult == 0)
                                    {
                                        Tx_Trials++;
                                        if(Tx_Trials > 2) break;

                                    }
                                    else Tx_Success = TRUE;

                                }
                                if(Tx_Success)
                                {
                                    ConsolePutROMString((ROM char *)"RADIO OK ");
                                }
                                else
                                {
                                    ConsolePutROMString((ROM char *)"RADIO FAIL ");
                                }

*/


     //.VBGOE = 0;
     //ANCON1bits.VBGEN = 1;		// Enable Band gap reference voltage
     //DelayMs(10);
     //VBGResult = Adc_u16Read(15);
     //ANCON1bits.VBGEN = 0;	    // Disable Bandgap

      //Adc_Init(ADC_10BITS);
     
     
     ANCON0 = 0xFF;
     ANCON1 = 0x9F;
     ANCON1bits.VBGEN = 1;		// Enable Band gap reference voltage
     
     
     ADCON0bits.VCFG = 0;    // vreff VDD-VSS
     ADCON0bits.CHS = 0x0F;  // VBG channel select
     
     ADCON1 = 0xBE;
     ADCON0bits.ADON = 1;
     
     //for(j=0;j<16;j++)
     //{
        //myDevicesOutputStatus[j] = j;
     //}
    
     
     //EEPROMWRITE(myDevicesOutputStatus,0,16);
     
     
     //for(j=0;j<16;j++)
     //{
        //myDevicesOutputStatus[j] = 0;
     //}
     
     //DelayMs(500);
     
     EEPROMRead(&myDevicesOutputStatus, 0, 16);
     ConsolePutROMString((ROM char *)"EEPROM READ: ");
     //PrintChar(TemperatureCalibrationValue);
     
     
     for(j=0;j<1;j++)
     {
         PrintChar(myDevicesOutputStatus[j]);
     }
	

     SwTimer3 = 0;
     SwTimer4 = 0;
     
     TRISB&=0xEF;   //JL: Configuro el pin B4 como salida si modificar el estado de los demas pines
     
     while(1)
     {
     /*
         WirelessTxRx();
         WirelesStatus();
         Bypass();
         */
         
         
         //No se utilizaron
         //Menu();
         //Timer1Tick();
         //WirelessTxRxPANCOORD();
         //TaskScheduler();
         
         //JLEstas funciones deben habilitarse para trabajar como repetidora
         
         Timer1Tick();
         Repeater();
        
     }

}
Esempio n. 21
0
void main(void)
{
    CLRWDT();
    ENABLE_WDT();

    currentPrimitive = NO_PRIMITIVE;
    NetworkDescriptor = NULL;
    orphanTries = 3;

    // If you are going to send data to a terminal, initialize the UART.
    ConsoleInit();

	ConsolePutROMString( (ROM char *)"Universidade Paulista - UNIP\r\n" );
	ConsolePutROMString( (ROM char *)"Daniel Gonçalves\r\n" );
	ConsolePutROMString( (ROM char *)"Projeto: Baba Eletronica\r\n\r\n" );
    ConsolePutROMString( (ROM char *)"\r\n\r\n\r\n*************************************\r\n" );
    ConsolePutROMString( (ROM char *)"Microchip ZigBee(TM) Stack - v1.0-3.8\r\n\r\n" );
    ConsolePutROMString( (ROM char *)"ZigBee RFD\r\n\r\n" );
    ConsolePutROMString( (ROM char *)"Transceiver-MRF24J40\r\n\r\n" );

    // Inicializa o Hardware
    HardwareInit();

    // Inicializa a pilha ZigBee
    ZigBeeInit();

    // *************************************************************************
    // Outras Inicializações
    // *************************************************************************

    myStatusFlags.Val = STATUS_FLAGS_INIT;

    // Endereço padrão do Coordenador
    destinationAddress.Val = 0x0000;

    // Inicializa os LEDS
    MOVE_SENSOR_LED = ON;
    LEVEL_SENSOR_LED = ON;

    // Habilita as interrupções 
    RCONbits.IPEN = 1;
    INTCONbits.GIEH = 1;

    while (1)
    {
        CLRWDT();
        ZigBeeTasks( &currentPrimitive );

        switch (currentPrimitive)
        {
            case NLME_NETWORK_DISCOVERY_confirm:
                currentPrimitive = NO_PRIMITIVE;
                if (!params.NLME_NETWORK_DISCOVERY_confirm.Status)
                {
                    if (!params.NLME_NETWORK_DISCOVERY_confirm.NetworkCount)
                    {
                        ConsolePutROMString( (ROM char *)"No networks found.  Trying again...\r\n" );
                    }
                    else
                    {
                        // Save the descriptor list pointer so we can destroy it later.
                        NetworkDescriptor = params.NLME_NETWORK_DISCOVERY_confirm.NetworkDescriptor;

                        // Select a network to try to join.  We're not going to be picky right now...
                        currentNetworkDescriptor = NetworkDescriptor;

SubmitJoinRequest:
                        // not needed for new join params.NLME_JOIN_request.ScanDuration = ;
                        // not needed for new join params.NLME_JOIN_request.ScanChannels = ;
                        params.NLME_JOIN_request.PANId          = currentNetworkDescriptor->PanID;
                        ConsolePutROMString( (ROM char *)"Network(s) found. Trying to join " );
                        PrintChar( params.NLME_JOIN_request.PANId.byte.MSB );
                        PrintChar( params.NLME_JOIN_request.PANId.byte.LSB );
                        ConsolePutROMString( (ROM char *)".\r\n" );
                        params.NLME_JOIN_request.JoinAsRouter   = FALSE;
                        params.NLME_JOIN_request.RejoinNetwork  = FALSE;
                        params.NLME_JOIN_request.PowerSource    = NOT_MAINS_POWERED;
                        params.NLME_JOIN_request.RxOnWhenIdle   = FALSE;
                        params.NLME_JOIN_request.MACSecurity    = FALSE;
                        currentPrimitive = NLME_JOIN_request;
                    }
                }
                else
                {
                    PrintChar( params.NLME_NETWORK_DISCOVERY_confirm.Status );
                    ConsolePutROMString( (ROM char *)" Error finding network.  Trying again...\r\n" );
                }
                break;

            case NLME_JOIN_confirm:
                currentPrimitive = NO_PRIMITIVE;
                if (!params.NLME_JOIN_confirm.Status)
                {
                    ConsolePutROMString( (ROM char *)"Join successful!\r\n" );

                    // Free the network descriptor list, if it exists. If we joined as an orphan, it will be NULL.
                    while (NetworkDescriptor)
                    {
                        currentNetworkDescriptor = NetworkDescriptor->next;
                        free( NetworkDescriptor );
                        NetworkDescriptor = currentNetworkDescriptor;
                    }
                }
                else
                {
                    PrintChar( params.NLME_JOIN_confirm.Status );

                    // If we were trying as an orphan, see if we have some more orphan attempts.
                    if (ZigBeeStatus.flags.bits.bTryOrphanJoin)
                    {
                        // If we tried to join as an orphan, we do not have NetworkDescriptor, so we do
                        // not have to free it.

                        ConsolePutROMString( (ROM char *)" Could not join as orphan. " );
                        orphanTries--;
                        if (orphanTries == 0)
                        {
                            ConsolePutROMString( (ROM char *)"Must try as new node...\r\n" );
                            ZigBeeStatus.flags.bits.bTryOrphanJoin = 0;
                        }
                        else
                        {
                            ConsolePutROMString( (ROM char *)"Trying again...\r\n" );
                        }
                    }
                    else
                    {
                        ConsolePutROMString( (ROM char *)" Could not join selected network. " );
                        currentNetworkDescriptor = currentNetworkDescriptor->next;
                        if (currentNetworkDescriptor)
                        {
                            ConsolePutROMString( (ROM char *)"Trying next discovered network...\r\n" );
                            goto SubmitJoinRequest;
                        }
                        else
                        {
                            // We ran out of descriptors.  Free the network descriptor list, and fall
                            // through to try discovery again.
                            ConsolePutROMString( (ROM char *)"Cleaning up and retrying discovery...\r\n" );
                            while (NetworkDescriptor)
                            {
                                currentNetworkDescriptor = NetworkDescriptor->next;
                                free( NetworkDescriptor );
                                NetworkDescriptor = currentNetworkDescriptor;
                            }
                        }
                    }
                }
                break;

            case NLME_LEAVE_indication:
                if (!memcmppgm2ram( &params.NLME_LEAVE_indication.DeviceAddress, (ROM void *)&macLongAddr, 8 ))
                {
                    ConsolePutROMString( (ROM char *)"We have left the network.\r\n" );
                }
                else
                {
                    ConsolePutROMString( (ROM char *)"Another node has left the network.\r\n" );
                }
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NLME_RESET_confirm:
                ConsolePutROMString( (ROM char *)"ZigBee Stack has been reset.\r\n" );
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NLME_SYNC_confirm:
                switch (params.NLME_SYNC_confirm.Status)
                {
                    case SUCCESS:
                        // I have heard from my parent, but it has no data for me.  Note that
                        // if my parent has data for me, I will get an APSDE_DATA_indication.
                        ConsolePutROMString( (ROM char *)"No data available.\r\n" );
                        break;

                    case NWK_SYNC_FAILURE:
                        // I cannot communicate with my parent.
                        ConsolePutROMString( (ROM char *)"I cannot communicate with my parent.\r\n" );
                        break;

                    case NWK_INVALID_PARAMETER:
                        // If we call NLME_SYNC_request correctly, this doesn't occur.
                        ConsolePutROMString( (ROM char *)"Invalid sync parameter.\r\n" );
                        break;
                }
                currentPrimitive = NO_PRIMITIVE;
                break;

            case APSDE_DATA_indication:
                {
                    WORD_VAL    attributeId;
                    BYTE        command;
                    BYTE        data;
                    BYTE        dataLength;
                    //BYTE        dataType;
                    BYTE        frameHeader;
                    BYTE        sequenceNumber;
                    BYTE        transaction;
                    BYTE        transByte;

                    currentPrimitive = NO_PRIMITIVE;
                    frameHeader = APLGet();

                    switch (params.APSDE_DATA_indication.DstEndpoint)
                    {
                        case EP_ZDO:
                            ConsolePutROMString( (ROM char *)"  Receiving ZDO cluster " );
                            PrintChar( params.APSDE_DATA_indication.ClusterId );
                            ConsolePutROMString( (ROM char *)"\r\n" );

                            // Put code here to handle any ZDO responses that we requested
                            if ((frameHeader & APL_FRAME_TYPE_MASK) == APL_FRAME_TYPE_MSG)
                            {
                                frameHeader &= APL_FRAME_COUNT_MASK;
                                for (transaction=0; transaction<frameHeader; transaction++)
                                {
                                    sequenceNumber          = APLGet();
                                    dataLength              = APLGet();
                                    transByte               = 1;    // Account for status byte

                                    switch( params.APSDE_DATA_indication.ClusterId )
                                    {

                                        // ********************************************************
                                        // Put a case here to handle each ZDO response that we requested.
                                        // ********************************************************

                                        case NWK_ADDR_rsp:
                                            if (APLGet() == SUCCESS)
                                            {
                                                ConsolePutROMString( (ROM char *)"  Receiving NWK_ADDR_rsp.\r\n" );

                                                // Skip over the IEEE address of the responder.
                                                for (data=0; data<8; data++)
                                                {
                                                    APLGet();
                                                    transByte++;
                                                }
                                                destinationAddress.byte.LSB = APLGet();
                                                destinationAddress.byte.MSB = APLGet();
                                                transByte += 2;
                                                myStatusFlags.bits.bDestinationAddressKnown = 1;
                                            }
                                            break;
                                        default:
                                            break;
                                    }

                                    // Read out the rest of the MSG in case there is another transaction.
                                    for (; transByte<dataLength; transByte++)
                                    {
                                        APLGet();
                                    }
                                }
                            }
                            break;

                        // ************************************************************************
                        // Place a case for each user defined endpoint.
                        // ************************************************************************
                        case EP_LIGHT:
                            if ((frameHeader & APL_FRAME_TYPE_MASK) == APL_FRAME_TYPE_KVP)
                            {
                                frameHeader &= APL_FRAME_COUNT_MASK;
                                for (transaction=0; transaction<frameHeader; transaction++)
                                {
                                    sequenceNumber          = APLGet();
                                    command                 = APLGet();
                                    attributeId.byte.LSB    = APLGet();
                                    attributeId.byte.MSB    = APLGet();

                                    //dataType = command & APL_FRAME_DATA_TYPE_MASK;
                                    command &= APL_FRAME_COMMAND_MASK;

                                    if ((params.APSDE_DATA_indication.ClusterId == OnOffSRC_CLUSTER) &&
                                        (attributeId.Val == OnOffSRC_OnOff))
                                    {
                                        if ((command == APL_FRAME_COMMAND_SET) ||
                                            (command == APL_FRAME_COMMAND_SETACK))
                                        {
                                            // Prepare a response in case it is needed.
                                            TxBuffer[TxData++] = APL_FRAME_TYPE_KVP | 1;    // KVP, 1 transaction
                                            TxBuffer[TxData++] = sequenceNumber;
                                            TxBuffer[TxData++] = APL_FRAME_COMMAND_SET_RES | (APL_FRAME_DATA_TYPE_UINT8 << 4);
                                            TxBuffer[TxData++] = attributeId.byte.LSB;
                                            TxBuffer[TxData++] = attributeId.byte.MSB;

                                            // Data type for this attibute must be APL_FRAME_DATA_TYPE_UINT8
                                            data = APLGet();
                                            switch (data)
                                            {
                                                case LIGHT_OFF:
                                                    ConsolePutROMString( (ROM char *)" Turning light off.\r\n" );
                                                    LEVEL_SENSOR_LED = 0;
                                                    TxBuffer[TxData++] = SUCCESS;
                                                    break;
                                                case LIGHT_ON:
                                                    ConsolePutROMString( (ROM char *)" Turning light on.\r\n" );
                                                    LEVEL_SENSOR_LED = 1;
                                                    TxBuffer[TxData++] = SUCCESS;
                                                    break;
                                                case LIGHT_TOGGLE:
                                                    ConsolePutROMString( (ROM char *)" Toggling light.\r\n" );
                                                    LEVEL_SENSOR_LED ^= 1;
                                                    TxBuffer[TxData++] = SUCCESS;
                                                    break;
                                                default:
                                                    PrintChar( data );
                                                    ConsolePutROMString( (ROM char *)" Invalid light message.\r\n" );
                                                    TxBuffer[TxData++] = KVP_INVALID_ATTRIBUTE_DATA;
                                                    break;
                                            }
                                        }
                                        if (command == APL_FRAME_COMMAND_SETACK)
                                        {
                                            // Send back an application level acknowledge.
                                            ZigBeeBlockTx();

                                            // Take care here that parameters are not overwritten before they are used.
                                            // We can use the data byte as a temporary variable.
                                            params.APSDE_DATA_request.DstAddrMode = params.APSDE_DATA_indication.SrcAddrMode;
                                            params.APSDE_DATA_request.DstEndpoint = params.APSDE_DATA_indication.SrcEndpoint;
                                            params.APSDE_DATA_request.DstAddress.ShortAddr = params.APSDE_DATA_indication.SrcAddress.ShortAddr;

                                            //params.APSDE_DATA_request.asduLength; TxData
                                            //params.APSDE_DATA_request.ProfileId; unchanged
                                            params.APSDE_DATA_request.RadiusCounter = DEFAULT_RADIUS;
                                            params.APSDE_DATA_request.DiscoverRoute = ROUTE_DISCOVERY_ENABLE;
											#ifdef I_SUPPORT_SECURITY
												params.APSDE_DATA_request.TxOptions.Val = 1;
											#else											                                            
                                            	params.APSDE_DATA_request.TxOptions.Val = 0;
											#endif                                            
                                            params.APSDE_DATA_request.SrcEndpoint = EP_LIGHT;
                                            //params.APSDE_DATA_request.ClusterId; unchanged

                                            currentPrimitive = APSDE_DATA_request;
                                        }
                                        else
                                        {
                                            // We are not sending an acknowledge, so reset the transmit message pointer.
                                            TxData = TX_DATA_START;
                                        }
                                    }
                                    // TODO read to the end of the transaction.
                                } // each transaction
                            } // frame type
                            break;
                          
                        default:               
                			break;
                	}

                    APLDiscardRx();
                }
                break;

            case APSDE_DATA_confirm:
                if (params.APSDE_DATA_confirm.Status)
                {
                    ConsolePutROMString( (ROM char *)"Error " );
                    PrintChar( params.APSDE_DATA_confirm.Status );
                    ConsolePutROMString( (ROM char *)" sending message.\r\n" );
                }
                else
                {
                    ConsolePutROMString( (ROM char *)" Message sent successfully.\r\n" );
                }
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NO_PRIMITIVE:
                if (!ZigBeeStatus.flags.bits.bNetworkJoined)
                {
                    if (!ZigBeeStatus.flags.bits.bTryingToJoinNetwork)
                    {
                        if (ZigBeeStatus.flags.bits.bTryOrphanJoin)
                        {
                            ConsolePutROMString( (ROM char *)"Trying to join network as an orphan...\r\n" );
                            params.NLME_JOIN_request.JoinAsRouter           = FALSE;
                            params.NLME_JOIN_request.RejoinNetwork          = TRUE;
                            params.NLME_JOIN_request.PowerSource            = NOT_MAINS_POWERED;
                            params.NLME_JOIN_request.RxOnWhenIdle           = FALSE;
                            params.NLME_JOIN_request.MACSecurity            = FALSE;
                            params.NLME_JOIN_request.ScanDuration           = 8;
                            params.NLME_JOIN_request.ScanChannels.Val       = ALLOWED_CHANNELS;
                            currentPrimitive = NLME_JOIN_request;
                        }
                        else
                        {
                            ConsolePutROMString( (ROM char *)"Trying to join network as a new device...\r\n" );
                            params.NLME_NETWORK_DISCOVERY_request.ScanDuration          = 6;
                            params.NLME_NETWORK_DISCOVERY_request.ScanChannels.Val      = ALLOWED_CHANNELS;
                            currentPrimitive = NLME_NETWORK_DISCOVERY_request;
                        }
                    }
                }
                else
                {
                    // See if I can do my own internal tasks.  We don't want to try to send a message
                    // if we just asked for one.
                    if (ZigBeeStatus.flags.bits.bDataRequestComplete && ZigBeeReady())
                    {

                        // ************************************************************************
                        // Place all processes that can send messages here.  Be sure to call
                        // ZigBeeBlockTx() when currentPrimitive is set to APSDE_DATA_request.
                        // ************************************************************************
                        if ( myStatusFlags.bits.bMoveSensorButtonPressed)
                        {
                            // Send a light toggle message to the other node.
                            myStatusFlags.bits.bMoveSensorButtonPressed = FALSE;

							BLINK_LED(MOVE_SENSOR_LED);							

							// envia a mensagem para ligar/desligar o led
							RFDSendMessage(MoveSensor_Activated, 0x00);                
                        }
                        else if (myStatusFlags.bits.bLevelSensorButtonPressed)
                        {
                        	// Envia mensagem indicando que o sensor de nível foi acionado

                            myStatusFlags.bits.bLevelSensorButtonPressed = FALSE;

							BLINK_LED(LEVEL_SENSOR_LED);

							RFDSendMessage(LevelSensor_Activated, 0x00);                                
                        }

                        // We've processed any key press, so re-enable interrupts.
                        INTCONbits.RBIE = 1;
                    }

                    // If we don't have to execute a primitive, see if we need to request data from
                    // our parent, or if we can go to sleep.
                    if (currentPrimitive == NO_PRIMITIVE)
                    {
                        if (!ZigBeeStatus.flags.bits.bDataRequestComplete)
                        {
                            // We have not received all data from our parent.  If we are not waiting
                            // for an answer from a data request, send a data request.
                            if (!ZigBeeStatus.flags.bits.bRequestingData)
                            {
                                if (ZigBeeReady())
                                {
                                    // Our parent still may have data for us.
                                    params.NLME_SYNC_request.Track = FALSE;
                                    currentPrimitive = NLME_SYNC_request;
                                    ConsolePutROMString( (ROM char *)"Requesting data...\r\n" );
                                }
                            }
                        }
                        else
                        {
                            if (!ZigBeeStatus.flags.bits.bHasBackgroundTasks && myProcessesAreDone())
                            {
                                // We do not have a primitive to execute, we've extracted all messages
                                // that our parent has for us, the stack has no background tasks,
                                // and all application-specific processes are complete.  Now we can
                                // go to sleep.  Make sure that the UART is finished, turn off the transceiver,
                                // and make sure that we wakeup from key press.
                                if(APLDisable() == TRUE)
                                {
	                                ConsolePutROMString( (ROM char *)"Going to sleep...\r\n" );
    	                            while (!ConsoleIsPutReady());
                                	APLDisable();
    	                            INTCONbits.RBIE = 1;
	                                SLEEP();
        	                        NOP();

	                                // We just woke up from sleep. Turn on the transceiver and
	                                // request data from our parent.
	                                APLEnable();
	                                params.NLME_SYNC_request.Track = FALSE;
	                                currentPrimitive = NLME_SYNC_request;
	                                ConsolePutROMString( (ROM char *)"Requesting data...\r\n" );
								}
                            }
                        }
                    }
                }
                break;

            default:
                PrintChar( currentPrimitive );
                ConsolePutROMString( (ROM char *)" Unhandled primitive.\r\n" );
                currentPrimitive = NO_PRIMITIVE;
        }

        // *********************************************************************
        // Place any non-ZigBee related processing here.  Be sure that the code
        // will loop back and execute ZigBeeTasks() in a timely manner.
        // *********************************************************************

    }
}
Esempio n. 22
0
 void WirelessTxRx(void)
 {
     Timer1Tick();

     switch(EndDevStateMachine)
     {
         case 0:                      // recibe estado para relevadores y latencia de comunicacion
         {
             if( MiApp_MessageAvailable())
             {
                if((rxMessage.Payload[1] == 0x00)&&((rxMessage.Payload[3] == OutputStat)))
                {
                    BypassCounter = 0;
                    if(rxMessage.Payload[4] <= 16)
                    {
                        //BaseTimeToTx = rxMessage.Payload[4];
                        TickScaler = rxMessage.Payload[4];
                    }


                    j = (myNodeNumber-1)/8;
                    j += 5;

                    i = rxMessage.Payload[j];

                    j =  (myNodeNumber-1)%8;

                    if(QUERY_8BIT(i,j))
                    {

                        RLY_STATUS = 1;
                    }
                    else
                    {

                        RLY_STATUS = 0;
                    }


                    ConsolePutROMString((ROM char *)"\r\n Req Stat:");

                    for(i=0;i<rxMessage.PayloadSize;i++)
                    {
                        PrintChar(rxMessage.Payload[i]);
                    }
                    

                    SwTimer0 = 0;
                    WriteTimer1(56161);           
                    Tick = 0;
                    
                    LED_2 ^= 1;
                    EndDevStateMachine = 1;
                    SwTimer3 = 0;     // clear MIWIPRO STATUS TIMER


                }
                else
                {
                    if((rxMessage.Payload[1] == 0x00)&&((rxMessage.Payload[3] == ListenDevices)))
                    {
                        ConsolePutROMString((ROM char *)"\r\n Listen Devices:");

                        for(i=0;i<rxMessage.PayloadSize;i++)
                        {
                         PrintChar(rxMessage.Payload[i]);
                        }
                        
                        j = (myNodeNumber-1)/8;
                        j += 4;

                        i = rxMessage.Payload[j];

                        j =  (myNodeNumber-1)%8;
                        
                        
                        if(QUERY_8BIT(i,j))
                        {
                         ConsolePutROMString((ROM char *)"\r\n Link stablished correctly");
                         RestartCounter = 0;
                        }
                        else
                        {
                         ConsolePutROMString((ROM char *)"\r\n NO Link stablished!!");
                         ++RestartCounter;
                        }
                        
                        
                        
                    }
                    else
                    {
                        if((rxMessage.Payload[1] == 0x00)&&((rxMessage.Payload[3] == CalibrationProcedure)))
                        {
                            
                            ConsolePutROMString((ROM char *)"\r\n Temperature sensor calibration:");
                            
                            //TemperatureCalibrationValue = rxMessage.Payload[5];
                            
                            
                            if((rxMessage.Payload[5] == MyTemp)||(rxMessage.Payload[5] == 0))
                            {
                                TemperatureCalibrationValue = 0;
                            }
                            else
                            {
                                if(rxMessage.Payload[5] > MyTemp)              // la temp de referencia es mayor a la leida
                                {
                                    //TemperatureCalibrationValue = (rxMessage.Payload[5] - MyTemp) & 0x0F;
                                    
                                }
                                else                                           // la temperatura leida es mayor a la temp de referencia
                                {
                                    //TemperatureCalibrationValue = (MyTemp - rxMessage.Payload[5]) & 0x0F;
                                    //SET_8BIT(TemperatureCalibrationValue,7);
                                }
                            }
                            
                            //EEPROMWRITE(TemperatureCalibrationValue,0,1);
                        }
                    }
                    
                }
                

                 MiApp_DiscardMessage();
             }
         }
         break;

//-----------------------------------------------------------------------------//

         case 1:                // envia estado y temperatura
         {
             if(SwTimer0 >= (_U08)myNodeNumber)
             {

              MyTemp = TemperatureRead();
                                                       
              MiApp_FlushTx();
              MiApp_WriteData(' ');
              MiApp_WriteData(myNodeNumber);
              MiApp_WriteData(MyTrackingNumber);
              MiApp_WriteData(OutputStat);
              MiApp_WriteData(RLY_STATUS);
              MiApp_WriteData(MyTemp);

              MiApp_BroadcastPacket(FALSE);
              

             /*              
              if(RLY_STATUS == 1)
              {
                  RLY_1 = 1;
              }
              else
              {
                  RLY_1 = 0;
              }
              */
              
              
              //SDW_RLY_STATUS
              
              if(RLY_STATUS == 1)
              {
                  if(SDW_RLY_STATUS == 1)
                  {
                      RLY_1 = 1;
                      
                      if(EEPROMCHG == 0)
                      {
                        i = 0x55;
                        EEPROMWRITE(&i,0,1); 
                        EEPROMWRITE(&i,0,1); 
                        EEPROMWRITE(&i,0,1); 
                        EEPROMWRITE(&i,0,1); 
                        EEPROMWRITE(&i,0,1); 
                          
                          
                       //for(j=0;j<16;j++)
                       //{
                        //myDevicesOutputStatus[j] = 0x55;
                       //}
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                        
                        ConsolePutROMString((ROM char *)"\r\n Relay status updated in eeprom 55");
                      }
                      
                      EEPROMCHG = 1;
                  }
                  else
                  {
                      SDW_RLY_STATUS = 1;
                  }
              }
              else
              {
                  if(SDW_RLY_STATUS == 0)
                  {
                      RLY_1 = 0;
                      
                      if(EEPROMCHG == 1)
                      {
                       i = 0xAA;
                       EEPROMWRITE(&i,0,1); 
                       EEPROMWRITE(&i,0,1); 
                       EEPROMWRITE(&i,0,1); 
                       EEPROMWRITE(&i,0,1); 
                       EEPROMWRITE(&i,0,1); 
                          
                       //for(j=0;j<16;j++)
                       //{
                        //myDevicesOutputStatus[j] = 0xAA;
                       //}
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);   
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                       //EEPROMWRITE(&myDevicesOutputStatus,0,16);
                          
                          
                       ConsolePutROMString((ROM char *)"\r\n Relay status updated in eeprom AA");
                      }
                      
                      EEPROMCHG = 0;
                      
                  }
                  else
                  {
                      SDW_RLY_STATUS = 0;
                  }
              }
              
              
              
              
              
              
              IRControl();
              

              EndDevStateMachine = 2;
             }
         }
         break;

//-----------------------------------------------------------------------------//

         case 2:
         {
             LED_1 ^= 1;
             EndDevStateMachine = 0;
         }
         break;

//-----------------------------------------------------------------------------//

         default:
         {
             EndDevStateMachine = 0;
         }
         break;


     }
 }
Esempio n. 23
0
/*********************************************************************
 * Function:        CIPHER_STATUS PHYCipher(INPUT CIPHER_MODE CipherMode, INPUT SECURITY_INPUT SecurityInput, OUTPUT BYTE *OutData, OUTPUT BYTE *OutDataLen)
 *
 * PreCondition:    Called by DataEncrypt or DataDecrypt
 *
 * Input:           CIPHER_MODE CipherMode       - Either MODE_ENCRYPTION or MODE_DECRYPTION
 *                  SECURITY_INPUT SecurityInput - Cipher operation input. Filled by DataEncryption or DataDecryption
 *
 * Output:          BYTE *OutData                - Encrypted or decrypted data, including MIC
 *                  BYTE *OutDataLen             - Data length after cipher operation, including MIC bytes
 *                  CIPHER_STATUS                - Cipher operation result
 *
 * Side Effects:    Input data get encrypted or decrypted and put into output buffer
 *
 * Overview:        This is the function that invoke the hardware cipher to do encryption and decryption
 ********************************************************************/
CIPHER_STATUS PHYCipher(INPUT CIPHER_MODE CipherMode, INPUT SECURITY_INPUT SecurityInput, OUTPUT BYTE *OutData, OUTPUT BYTE *OutDataLen)
{
    BYTE CipherRetry = CIPHER_RETRY;
    BYTE i;
    WORD loc;

    // make sure that we are not in the process of sending out a packet
    loc = 0;
    while( !TxStat.finished )
    {
        loc++;
        if( loc > 0xfff )
        {
            PHY_RESETn = 0;
            MACEnable();
            TxStat.finished = 1;
        }
#if defined(__C30__)
        if(RF_INT_PIN == 0)
        {
            RFIF = 1;
        }
#else
        if( PORTBbits.RB0 == 0 )
        {
            INTCONbits.INT0IF = 1;
        }
#endif

        Nop();
    }

CipherOperationStart:

    // step 1, set the normal FIFO
    // step 1a, fill the length of the header
    if( SecurityInput.cipherMode > 0x04 )
    {
        PHYSetLongRAMAddr(0x000, SecurityInput.HeaderLen+SecurityInput.TextLen+14);
    } else {
        PHYSetLongRAMAddr(0x000, SecurityInput.HeaderLen+14);
    }

    // step 1b, fill the length of the packet
    if( CipherMode == MODE_ENCRYPTION )
    {
        PHYSetLongRAMAddr(0x001, SecurityInput.TextLen+SecurityInput.HeaderLen+14);
    } else {
        PHYSetLongRAMAddr(0x001, SecurityInput.TextLen+SecurityInput.HeaderLen+16);// two additional bytes FCS
    }

    // step 1c, fill the header
    loc = 0x002;
    for(i = 0; i < SecurityInput.HeaderLen; i++)
    {
        PHYSetLongRAMAddr(loc++, SecurityInput.Header[i]);
    }

    // step 1d, fill the auxilary header
    PHYSetLongRAMAddr(loc++, SecurityInput.SecurityControl.Val | nwkSecurityLevel);
    for(i = 0; i < 4; i++)
    {
        PHYSetLongRAMAddr(loc++, SecurityInput.FrameCounter.v[i]);
    }
    for(i = 0; i < 8; i++)
    {
        PHYSetLongRAMAddr(loc++, SecurityInput.SourceAddress->v[i]);
    }
    PHYSetLongRAMAddr(loc++, SecurityInput.KeySeq);

    // step 1e, fill the data to be encrypted or decrypted
    for(i = 0; i < SecurityInput.TextLen; i++)
    {
        PHYSetLongRAMAddr(loc++, SecurityInput.InputText[i]);
    }

    // step 2, set nounce
    SetNonce(SecurityInput.SourceAddress, &(SecurityInput.FrameCounter), SecurityInput.SecurityControl);

    // step 3, set TXNFIFO security key
    loc = 0x280;
    for(i = 0; i < 16; i++)
    {
        PHYSetLongRAMAddr(loc++, SecurityInput.SecurityKey[i]);
    }

    // step 4, set cipher mode either encryption or decryption
    if( CipherMode == MODE_ENCRYPTION )
    {
        PHYSetShortRAMAddr(SECCR2, 0x40);
    } else {
        PHYSetShortRAMAddr(SECCR2, 0x80);
    }

    // step 5, fill the encryption mode
    PHYSetShortRAMAddr(SECCR0, SecurityInput.cipherMode);

    TxStat.cipher = 1;
    // step 6, trigger
    PHYSetShortRAMAddr(TXNMTRIG, 0x03);

    i = 0;
    while( TxStat.cipher )
    {
#if defined(__C30__)
        if(RF_INT_PIN == 0)
        {
            RFIF = 1;
        }
#else
        if( PORTBbits.RB0 == 0 )
        {
            INTCONbits.INT0IF = 1;
        }
#endif
        i++;
#if 1
        // in rare condition, the hardware cipher will stall. Handle such condition
        // here
        if(i > 0x1f)
        {
            // in certain rare cases, the RX and Upper Cipher will block each other
            // in case that happens, reset the RF chip to avoid total disfunction
            ConsolePutROMString((ROM char*)"X");
            PHYTasksPending.Val = 0;
            PHY_RESETn = 0;
            MACEnable();
            break;
        }
#endif
    }
    //PHYSetShortRAMAddr(0x0d, 0x01);

    // if MIC is generated, check MIC here
    if( (CipherMode == MODE_DECRYPTION) && (SecurityInput.cipherMode != 0x01))
    {
        BYTE MIC_check = PHYGetShortRAMAddr(0x30);
        if( MIC_check & 0x40 )
        {
            PHYSetShortRAMAddr(0x30, 0x40);
            // there is a small chance that the hardware cipher will not
            // decrypt for the first time, retry to solve this problem.
            // details documented in errata
            if( CipherRetry )
            {
                CipherRetry--;
                for(loc = 0; loc < 0x255; loc++);
                goto CipherOperationStart;
            }
            PHY_RESETn = 0;
            MACEnable();
            ConsolePutROMString((ROM char *)"MIC error");
            return CIPHER_MIC_ERROR;
        }
    }

    if( TxStat.success )
    {
        // get output data length
        *OutDataLen = PHYGetLongRAMAddr(0x001) - SecurityInput.HeaderLen - 14;
        // get the index of data encrypted or decrypted
        loc = 0x002 + SecurityInput.HeaderLen + 14;

        // if this is a decryption operation, get rid of the useless MIC and two bytes of FCS
        if( CipherMode == MODE_DECRYPTION )
        {
            switch( SecurityInput.cipherMode )
            {
            case 0x02:
            case 0x05:
                *OutDataLen -= 18;
                break;
            case 0x03:
            case 0x06:
                *OutDataLen -= 10;
                break;
            case 0x04:
            case 0x07:
                *OutDataLen -= 6;
                break;
            case 0x01:
                *OutDataLen-= 2;
                break;
            }
        }

        // copy the output data
        for(i = 0; i < *OutDataLen; i++)
        {
            OutData[i] = PHYGetLongRAMAddr(loc++);
        }
        return CIPHER_SUCCESS;
    }

    return CIPHER_ERROR;
}
Esempio n. 24
0
    void NVMWrite( WORD dest, BYTE *src, BYTE count )
    {
        BYTE    bytesOnPage;
        BYTE    bytesOnPageCounter;
    	#if !defined(__C30__)
        	BYTE    oldGIEH;
    	#endif
        BYTE    *srcCounter;
        BYTE    status;
        WORD    writeStart;

        if (!count)
        {
            return;
        }

        #if !defined(__C30__)
            oldGIEH = 0;
            if ( INTCONbits.GIEH )
            {
                oldGIEH = 1;
            }
            INTCONbits.GIEH = 0;
        #endif


        // Make sure the chip is unlocked.
        SPISelectEEPROM();                  // Enable chip select
        SPIPut( SPIWRSR );                  // Send WRSR - Write Status Register opcode
        SPIPut( 0x00 );                     // Write the status register
        SPIUnselectEEPROM();                // Disable Chip Select

        #ifdef ENABLE_DEBUG
            ConsolePut('w');
            PrintChar( (BYTE)(((WORD)dest>>8)&0xFF) );
            PrintChar( (BYTE)((WORD)dest&0xFF) );
            ConsolePut('-');
            PrintChar( count );
        #endif

        writeStart = dest;
        while (count)
        {
            bytesOnPage = EEPROM_PAGE_SIZE - (writeStart & (EEPROM_PAGE_SIZE-1));
            if (bytesOnPage > count)
            {
                bytesOnPage = count;
            }

            #ifdef PRINT_MULTIPLE_WRITE_ATTEMPTS
                flag = 0;
            #endif
            CLRWDT();

            #if defined(VERIFY_WRITE)
                while (ComparePage( writeStart, src, bytesOnPage ))
            #elif defined(CHECK_BEFORE_WRITE)
                if (ComparePage( writeStart, src, bytesOnPage ))
            #endif
            {
                #ifdef PRINT_MULTIPLE_WRITE_ATTEMPTS
                    flag = 1;
                #endif
                SPISelectEEPROM();                          // Enable chip select
                SPIPut( SPIWREN );                          // Transmit the write enable instruction
                SPIUnselectEEPROM();                        // Disable Chip Select to enable Write Enable Latch

                SPISelectEEPROM();                          // Enable chip select
                SPIPut( SPIWRITE );                         // Transmit write instruction
                SPIPut( (BYTE)((writeStart>>8) & 0xFF) );   // Transmit address high byte
                SPIPut( (BYTE)((writeStart) & 0xFF) );      // Trabsmit address low byte

                // Loop until the required number of bytes have been written or
                // until the maximum number of bytes per write cycle have been written
                bytesOnPageCounter = bytesOnPage;
                srcCounter = src;
                do
                {
                    SPIPut (*srcCounter++);                    // Write the source byte
                    bytesOnPageCounter--;
                }
                while (bytesOnPageCounter);

                // Disable chip select to start write cycle.  We'll let it finish in the background if we can.
                SPIUnselectEEPROM();

                // Wait for the write to complete.  We have to wait here, because we can't
                // do a read of the memory while the write is in progress.
                do
                {
                    SPISelectEEPROM();                  // Enable chip select
                    SPIPut( SPIRDSR );                  // Send RDSR - Read Status Register opcode
                    status = SPIGet();;                 // Read the status register
                    SPIUnselectEEPROM();                // Disable Chip Select
                }
                while (status & WIP_MASK);
            }

            count -= bytesOnPage;
            writeStart += bytesOnPage;
            src = &src[bytesOnPage];
        }

        #if !defined(__C30__)
            if (oldGIEH)        // If interrupts were enabled before this function
            {
                INTCONbits.GIEH = 1;       // re-enable them
            }
        #endif

        #ifdef ENABLE_DEBUG
            ConsolePut('.');
            ConsolePutROMString((ROM char * const)"\r\n");
        #endif
    }
Esempio n. 25
0
 //----------------------------------------------------------------------------//
 void Menu(void)
 {
      ReadButtons();
      
      
     if( Button1Pressed && Button2Pressed)   // si se han presionado ambos botones 
     {
      ++MenuIn;
     }
     else
     {
         MenuIn = 0;
     }
     
      if(MenuIn >=250)
      {
          MenuIndex = 1;
          MenuIn = 0;
      }
      else
      {
          MenuIndex = 0;
      }
     
      if(MenuIndex != 0)
      {
       switch(MenuIndex)
       {
         case 0:
         {
             
         }
         break;
         
         case 1:
         {
             LED_1 = 1;
             LED_2 = 1;
             
             ConsolePutROMString((ROM char *)"\r\n      MENU : Temperature Calibration ");
             
             
             while((Button1Pressed)&&(Button2Pressed))
             {
                 if( MiApp_MessageAvailable())
                 {
                     MiApp_DiscardMessage();
                 }
                 
                 ReadButtons();
                 ClrWdt();
             }
             
             ConsolePutROMString((ROM char *)"\r\n SW1: Increase offset value  || SW2 Decrease offset value");
             
             
             
             Button1Released = 1;
             Button2Released = 1;
             
             Exit = 0xff;
             OffsetValue = 100;
             
             while(Exit)
             {
                 ReadButtons();
                 
                 
                 
                 
                 
                 if( Button1Pressed && Button2Pressed)   // si se han presionado ambos botones
                 {
                     Exit = 0;
                     ConsolePutROMString((ROM char *)"\r\nExit");       
                 }
                 else
                 {
                     if( Button1Pressed && Button1Released)   // 
                   {
                     Button1Released = 0;
                     ++OffsetValue;
                     LED_1 ^= 1;
                     LED_2 ^= 1;
                     ConsolePutROMString((ROM char *)"\r\nIncreased offset value");
                   }
                 
                   if( Button2Pressed && Button2Released)   // 
                   {   
                     Button2Released = 0;
                     --OffsetValue;
                     LED_1 ^= 1;
                     LED_2 ^= 1;
                     ConsolePutROMString((ROM char *)"\r\nDecreased offset value");
                   }
                 }
                 
           
                 
                 
                 
                 if( MiApp_MessageAvailable())
                 {
                     MiApp_DiscardMessage();
                 }
                 
                 ClrWdt();
             }
             
             while((Button1Pressed)&&(Button2Pressed))
             {
              if( MiApp_MessageAvailable())
              {
                MiApp_DiscardMessage();
              }
                 
              ReadButtons();
              ClrWdt();
             }
             
             
             
             
         }
         break;
         
         case 2:
         {
             
         }
         break;
         
         case 3:
         {
             
         }
         break;
         
         
         default: break;
         
       }
 }
     
     
     
 }
Esempio n. 26
0
unsigned char * NEAR SRAMalloc(NEAR unsigned char nBytes)
{
	#if defined(__C30__)
		return (unsigned char *)malloc((size_t)nBytes);
	#else
	
    	SALLOC * NEAR       pHeap;
		#ifdef MAKE_INTERRUPT_SAFE
		    BYTE                saveGIEH;
		#endif
	    NEAR SALLOC         segHeader;
    	NEAR unsigned char  segLen;
	    SALLOC * NEAR       temp;


    	#ifdef MAKE_INTERRUPT_SAFE
        	saveGIEH = 0;
	        if (INTCONbits.GIEH)
    	        saveGIEH = 1;
        	INTCONbits.GIEH = 0;
	    #endif


    	#ifdef ENABLE_DEBUG
        	ConsolePutROMString( (ROM char * const)"Alloc " );
	        PrintChar(nBytes);
			printf("\r\n");
    	#endif

	    // Do not allow allocation above the max minus one bytes.  Also, do
    	// not allow a zero length packet.  Could cause problems.
	    if ((nBytes > (_MAX_SEGMENT_SIZE - 1))  ||
    	    (nBytes == 0))
    	{
        	#ifdef MAKE_INTERRUPT_SAFE
            	INTCONbits.GIEH = saveGIEH;
	        #endif
    	    return (0);
	    }

    	// Init the pointer to the heap
	    pHeap = (SALLOC *)_uDynamicHeap;

    	while (1)
	    {
    	    #ifdef ENABLE_DEBUG
        	    ConsolePutROMString( (ROM char * const)" check " );
            	PrintChar( (BYTE)((WORD)pHeap>>8) );
	            PrintChar( (BYTE)((WORD)pHeap&0xff) );
    	    #endif

        	// Get the header of the segment
	        segHeader = *pHeap;

    	    // Extract the segment length from the segment
        	segLen = segHeader.bits.count - 1;

	        // A null segment indicates the end of the table
    	    if (segHeader.byte == 0)
        	{
            	#ifdef ENABLE_DEBUG
                	ConsolePutROMString( (ROM char * const)" TableEnd\r\n" );
	            #endif
    	        #ifdef MAKE_INTERRUPT_SAFE
        	        INTCONbits.GIEH = saveGIEH;
            	#endif
	            return (0);
    	    }

        	// If this segment is not allocated then attempt to allocate it
	        if (!(segHeader.bits.alloc))
    	    {
        	    // If the free segment is too small then attempt to merge
            	if (nBytes > segLen)
	            {
    	            #ifdef ENABLE_DEBUG
        	            ConsolePutROMString( (ROM char * const)" merge" );
            	    #endif
                	// If the merge fails them move on to the next segment
	                if (!(_SRAMmerge(pHeap)))
    	            {
        	            pHeap +=(WORD)(segHeader.bits.count);
            	    }
                	// Fall through so we can check the newly created segment.
	            }
    	        else

        	    // If the segment length matches the request then allocate the
            	// header and return the pointer
	            if (nBytes == segLen)
    	        {
        	        // Allocate the segment
            	    (*pHeap).bits.alloc = 1;

                	// Return the pointer to the caller
	                #ifdef MAKE_INTERRUPT_SAFE
    	                INTCONbits.GIEH = saveGIEH;
        	        #endif
            	    #ifdef ENABLE_DEBUG
                	    ConsolePutROMString( (ROM char * const)" Found\r\n" );
	                #endif
    	            return ((unsigned char *)(pHeap + 1));
        	    }

            	// Else create a new segment
	            else
    	        {
        	        // Reset the header to point to a new segment
            	    (*pHeap).byte = nBytes + 0x81;

                	// Remember the pointer to the first segment
	                temp = pHeap + 1;

    	            // Point to the new segment
        	        pHeap += (WORD)(nBytes + 1);

            	    // Insert the header for the new segment
                	(*pHeap).byte = segLen - nBytes;

	                // Return the pointer to the user
    	            #ifdef MAKE_INTERRUPT_SAFE
        	            INTCONbits.GIEH = saveGIEH;
            	    #endif
                	#ifdef ENABLE_DEBUG
                    	ConsolePutROMString( (ROM char * const)" Found\r\n" );
	                #endif
    	            return ((unsigned char *) temp);
        	    }
	        }

    	    // else set the pointer to the next segment header in the heap
        	else
	        {
    	        pHeap += (WORD)segHeader.bits.count;
        	}
	    }

    	#ifdef MAKE_INTERRUPT_SAFE
        	INTCONbits.GIEH = saveGIEH;
	    #endif
    	#ifdef ENABLE_DEBUG
        	ConsolePutROMString( (ROM char * const)" ???\r\n" );
	    #endif
    	return (0);
	#endif    
}
Esempio n. 27
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 );
        }
    }
void main(void)
{
    CLRWDT();
    ENABLE_WDT();

    currentPrimitive = NO_PRIMITIVE;
    NetworkDescriptor = NULL;

    // If you are going to send data to a terminal, initialize the UART.
    ConsoleInit();

    // Initialize the hardware - must be done before initializing ZigBee.
    HardwareInit();

    // Initialize the ZigBee Stack.
    ZigBeeInit();


    // *************************************************************************
    // Perform any other initialization here
    // *************************************************************************


    // Enable interrupts to get everything going.
    IPEN = 1;
    GIEH = 1;

    while (1)
    {
        CLRWDT();
        ZigBeeTasks( &currentPrimitive );

        switch (currentPrimitive)
        {
            case NLME_NETWORK_DISCOVERY_confirm:
                currentPrimitive = NO_PRIMITIVE;
                if (!params.NLME_NETWORK_DISCOVERY_confirm.Status)
                {
                    if (!params.NLME_NETWORK_DISCOVERY_confirm.NetworkCount)
                    {
                        ConsolePutROMString( (ROM char *)"No networks found.  Trying again...\r\n" );
                    }
                    else
                    {
                        // Save the descriptor list pointer so we can destroy it later.
                        NetworkDescriptor = params.NLME_NETWORK_DISCOVERY_confirm.NetworkDescriptor;

                        // Select a network to try to join.  We're not going to be picky right now...
                        currentNetworkDescriptor = NetworkDescriptor;

                        // not needed for new join params.NLME_JOIN_request.ScanDuration = ;
                        // not needed for new join params.NLME_JOIN_request.ScanChannels = ;
                        params.NLME_JOIN_request.PANId          = currentNetworkDescriptor->PanID;
                        params.NLME_JOIN_request.JoinAsRouter   = FALSE;
                        params.NLME_JOIN_request.RejoinNetwork  = FALSE;
                        params.NLME_JOIN_request.PowerSource    = NOT_MAINS_POWERED;
                        params.NLME_JOIN_request.RxOnWhenIdle   = FALSE;
                        params.NLME_JOIN_request.MACSecurity    = FALSE;
                        currentPrimitive = NLME_JOIN_request;

                        ConsolePutROMString( (ROM char *)"Network(s) found. Trying to join " );
                        PrintChar( params.NLME_JOIN_request.PANId.byte.MSB );
                        PrintChar( params.NLME_JOIN_request.PANId.byte.LSB );
                        ConsolePutROMString( (ROM char *)".\r\n" );
                    }
                }
                else
                {
                    PrintChar( params.NLME_NETWORK_DISCOVERY_confirm.Status );
                    ConsolePutROMString( (ROM char *)" Error finding network.  Trying again...\r\n" );
                }
                break;

            case NLME_JOIN_confirm:
                currentPrimitive = NO_PRIMITIVE;
                if (!params.NLME_JOIN_confirm.Status)
                {
                    ConsolePutROMString( (ROM char *)"Join successful!\r\n" );
                    if (NetworkDescriptor)
                    {
                        // If we joined as an orphan, this will be NULL.
                        free( NetworkDescriptor );
                    }

                    // We are now on the network.  Enable routing.
                    params.NLME_START_ROUTER_request.BeaconOrder = MAC_PIB_macBeaconOrder;
                    params.NLME_START_ROUTER_request.SuperframeOrder = MAC_PIB_macSuperframeOrder;
                    params.NLME_START_ROUTER_request.BatteryLifeExtension = FALSE;
                    currentPrimitive = NLME_START_ROUTER_request;
                }
                else
                {
                    PrintChar( params.NLME_JOIN_confirm.Status );
                    ConsolePutROMString( (ROM char *)" Could not join. Trying again as new device..." );
                }
                break;

            case NLME_LEAVE_indication:
                if (!memcmppgm2ram( &params.NLME_LEAVE_indication.DeviceAddress, (ROM void *)&macLongAddr, 8 ))
                {
                    ConsolePutROMString( (ROM char *)"We have left the network.\r\n" );
                }
                else
                {
                    ConsolePutROMString( (ROM char *)"Another node has left the network.\r\n" );
                }
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NLME_RESET_confirm:
                ConsolePutROMString( (ROM char *)"ZigBee Stack has been reset.\r\n" );
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NLME_START_ROUTER_confirm:
                if (!params.NLME_START_ROUTER_confirm.Status)
                {
                    ConsolePutROMString( (ROM char *)"Router Started!\r\n" );
                }
                else
                {
                    PrintChar( params.NLME_JOIN_confirm.Status );
                    ConsolePutROMString( (ROM char *)" Router start unsuccessful. We cannot route frames.\r\n" );
                }

                // We are now ready to do ZigBee related tasks.
                currentPrimitive = NO_PRIMITIVE;
                break;

            case APSDE_DATA_indication:
                {
                    WORD_VAL    attributeId;
                    BYTE        command;
                    BYTE        data;
                    BYTE        dataLength;
                    //BYTE        dataType;
                    BYTE        frameHeader;
                    BYTE        sequenceNumber;
                    BYTE        transaction;
                    BYTE        transByte;

                    currentPrimitive = NO_PRIMITIVE;
                    frameHeader = APLGet();

                    switch (params.APSDE_DATA_indication.DstEndpoint)
                    {
                        case EP_ZDO:
                            if ((frameHeader & APL_FRAME_TYPE_MASK) == APL_FRAME_TYPE_MSG)
                            {
                                frameHeader &= APL_FRAME_COUNT_MASK;
                                for (transaction=0; transaction<frameHeader; transaction++)
                                {
                                    sequenceNumber          = APLGet();
                                    dataLength              = APLGet();
                                    transByte               = 0;

                                    switch( params.APSDE_DATA_indication.ClusterId )
                                    {

                                        // ********************************************************
                                        // Put a case here to handle each ZDO response that we requested.
                                        // Be sure to increment transByte for each APLGet().
                                        // ********************************************************

                                        default:
                                            break;
                                    }

                                    // Read out the rest of the MSG in case there is another transaction.
                                    for (; transByte<dataLength; transByte++)
                                    {
                                        APLGet();
                                    }
                                }
                            }
                            break;

                        // ************************************************************************
                        // Place a case for each user defined endpoint.
                        // ************************************************************************

                        default:
                            // If the command type was something that requested an acknowledge, we could send back
                            // KVP_INVALID_ENDPOINT here.
                            break;
                    }
                    APLDiscardRx();
                }
                break;

            case APSDE_DATA_confirm:
                if (params.APSDE_DATA_confirm.Status)
                {
                    ConsolePutROMString( (ROM char *)"Error " );
                    PrintChar( params.APSDE_DATA_confirm.Status );
                    ConsolePutROMString( (ROM char *)" sending message.\r\n" );
                }
                else
                {
                    ConsolePutROMString( (ROM char *)" Message sent successfully.\r\n" );
                }
                currentPrimitive = NO_PRIMITIVE;
                break;

            case NO_PRIMITIVE:
                if (!ZigBeeStatus.flags.bits.bNetworkJoined)
                {
                    if (!ZigBeeStatus.flags.bits.bTryingToJoinNetwork)
                    {
                        if (ZigBeeStatus.flags.bits.bTryOrphanJoin)
                        {
                            ConsolePutROMString( (ROM char *)"Trying to join network as an orphan...\r\n" );
                            params.NLME_JOIN_request.ScanDuration       = 8;
                            params.NLME_JOIN_request.ScanChannels.Val   = ALLOWED_CHANNELS;
                            // not needed for orphan join - params.NLME_JOIN_request.PANId
                            params.NLME_JOIN_request.JoinAsRouter       = FALSE;
                            params.NLME_JOIN_request.RejoinNetwork      = TRUE;
                            params.NLME_JOIN_request.PowerSource        = NOT_MAINS_POWERED;
                            params.NLME_JOIN_request.RxOnWhenIdle       = FALSE;
                            params.NLME_JOIN_request.MACSecurity        = FALSE;
                            currentPrimitive = NLME_JOIN_request;
                        }
                        else
                        {
                            ConsolePutROMString( (ROM char *)"Trying to join network as a new device...\r\n" );
                            params.NLME_NETWORK_DISCOVERY_request.ScanDuration          = 8;
                            params.NLME_NETWORK_DISCOVERY_request.ScanChannels.Val      = ALLOWED_CHANNELS;
                            currentPrimitive = NLME_NETWORK_DISCOVERY_request;
                        }
                    }
                }
                else
                {
                    // See if we can do our own internal tasks.
                    if (ZigBeeReady())
                    {

                        // ************************************************************************
                        // Place all processes that can send messages here.  Be sure to call
                        // ZigBeeBlockTx() when currentPrimitive is set to APSDE_DATA_request.
                        // ************************************************************************

                    }
                }
                break;

            default:
                PrintChar( currentPrimitive );
                ConsolePutROMString( (ROM char *)" Unhandled primitive.\r\n" );
                currentPrimitive = NO_PRIMITIVE;
                break;
        }

        // *********************************************************************
        // Place any non-ZigBee related processing here.  Be sure that the code
        // will loop back and execute ZigBeeTasks() in a timely manner.
        // *********************************************************************

    }
}
Esempio n. 29
0
/*********************************************************************
 * Function:        BOOL DataDecrypt(IOPUT BYTE *Input, IOPUT BYTE *DataLen, INPUT BYTE *Header, INPUT BYTE HeaderLen, INPUT KEY_IDENTIFIER KeyIdentifier, INPUT LONG_ADDR *longAddr)
 *
 * 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
 *                  LONG_ADDRESS *longAddress       - Extended source address if not use extended nonce
 *
 * Output:          BOOL           - If data encryption successful
 *
 * Input/Output:    BYTE *Input    - Pointer to the data to be decrypted. The decrypted data will be write back to the pointer
 *                  BYTE *DataLen  - Input as the length of the data to be decrypted. The encrypted data length (excluding MICs) will be written back
 *
 * Side Effects:    Input data get decrypted and written back to the input pointer
 *
 * Overview:        This is the function that call the hardware cipher to decrypt input data
 ********************************************************************/
BOOL DataDecrypt(IOPUT BYTE *Input, IOPUT BYTE *DataLen, INPUT BYTE *Header, INPUT BYTE HeaderLen, INPUT KEY_IDENTIFIER KeyIdentifier, INPUT LONG_ADDR *longAddr)
{
    SECURITY_INPUT SecurityInput;
    SECURITY_CONTROL SecurityControl;
    BYTE i;
    BYTE Counter;
    DWORD_VAL   FrameCounter;
    LONG_ADDR mySourceAddress;
    BYTE KeySeq;
    BYTE ActiveKeyIndex;

    // retrieve information from auxilary header
    SecurityControl.Val = Input[0];
    Counter = 1;
    for(i = 0; i < 4; i++)
    {
        FrameCounter.v[i] = Input[Counter++];
    }
    if( SecurityControl.bits.ExtendedNonce )
    {
        for(i = 0; i < 8; i++)
        {
            mySourceAddress.v[i] = Input[Counter++];
        }
    } else {
        mySourceAddress = *longAddr;
    }

    if( SecurityControl.bits.KeyIdentifier == ID_NetworkKey )
    {
        KeySeq = Input[Counter++];
        // get security key based on the key sequence number
        for(i = 0; i < 2; i++)
        {
#ifdef USE_EXTERNAL_NVM
            currentNetworkKeyInfo = plainSecurityKey[i];
#else
            GetNwkKeyInfo(&currentNetworkKeyInfo, &networkKeyInfo[i]);
#endif
            if( KeySeq == currentNetworkKeyInfo.SeqNumber.v[0] && currentNetworkKeyInfo.SeqNumber.v[1] == nwkMAGICResSeq )
            {
                ActiveKeyIndex = i;
                break;
            }
        }
        if( i == 2 )
        {
            ConsolePutROMString( (ROM char *)"No Valid Key.\r\n" );
            return FALSE;
        }
    }

    // fill the security input
    SecurityInput.cipherMode = SecurityLevel_ZIGBEE_2_IEEE(nwkSecurityLevel);
    SecurityInput.FrameCounter = FrameCounter;
    SecurityInput.InputText = &(Input[Counter]);
    SecurityInput.SecurityControl = SecurityControl;
    SecurityInput.SecurityKey = currentNetworkKeyInfo.NetKey.v;
    SecurityInput.KeySeq = KeySeq;
    SecurityInput.SourceAddress = &mySourceAddress;
    SecurityInput.TextLen = *DataLen - Counter;
    SecurityInput.Header = Header;
    SecurityInput.HeaderLen = HeaderLen;

    // call hardware cipher
    if( PHYCipher(MODE_DECRYPTION, SecurityInput, Input, DataLen) != 0 )
    {
//      ConsolePutROMString((ROM char *)"decrpt wrong");
        return FALSE;
    }

    // check the frame counter. make sure that the frame counter increase always
    // we only check family members, because only family members know if a node
    // join or leave the network to reset the frame counter
    if( securityStatus.flags.bits.nwkAllFresh )
    {
        if( INVALID_NEIGHBOR_KEY != (i = NWKLookupNodeByLongAddr(&mySourceAddress)) )
        {
            if( (currentNeighborRecord.deviceInfo.bits.Relationship == NEIGHBOR_IS_CHILD ||
                    currentNeighborRecord.deviceInfo.bits.Relationship == NEIGHBOR_IS_PARENT ) &&
                    FrameCounter.Val < IncomingFrameCount[ActiveKeyIndex][i].Val )
            {
                ConsolePutROMString((ROM char *)"frame counter");
                PrintChar(FrameCounter.v[3]);
                PrintChar(FrameCounter.v[2]);
                PrintChar(FrameCounter.v[1]);
                PrintChar(FrameCounter.v[0]);
                ConsolePutROMString((ROM char *)" vs ");
                PrintChar(IncomingFrameCount[ActiveKeyIndex][i].v[3]);
                PrintChar(IncomingFrameCount[ActiveKeyIndex][i].v[2]);
                PrintChar(IncomingFrameCount[ActiveKeyIndex][i].v[1]);
                PrintChar(IncomingFrameCount[ActiveKeyIndex][i].v[0]);
                return FALSE;
            }
            IncomingFrameCount[ActiveKeyIndex][i].Val = FrameCounter.Val;
        }
    }
    return TRUE;
}
Esempio n. 30
0
int main ()
{
	

	unsigned char zigbee_mode = 0;

	HardwareInit();
	ConsoleInit();
	InitSymbolTimer();
	uart_init();
	initMSDCLTimers();
	IFS1bits.U2RXIF = 0;
	

	ConsolePutROMString( (ROM char *)"\r\nW to exit");

	SendModuleStartData();
	while( StartNetworkFlag == FALSE )
	{
		HanddleUART2();	
		if(IFS1bits.U2RXIF)
		{
			zigbee_mode = U2RXREG;
			if(zigbee_mode == 'W')
				break;
		}
	}
	StartNetworkFlag = FALSE;
	zigbee_mode = 0;
	
    ConsolePutROMString( (ROM char *)"\r\n*********************************" );
	ConsolePutROMString( (ROM char *)"\r\nMicrochip SE Profile 1.0.version.0.5.3" );
	ConsolePutROMString( (ROM char *)"\r\n*********************************" );
	ConsolePutROMString( (ROM char *)"\r\nE:Comission device as ESP\r\n" );
	ConsolePutROMString( (ROM char *)"\r\nM:Comission device as MTR\r\n" );
	
	{
		
		TICK startTime = TickGet();
		
		do
		{
			IFS1bits.U2RXIF = 0;
			do
			{
				if( TickGetDiff(TickGet(),startTime) > (2 * ONE_SECOND))
				{
					break;
				}
			}
			while( !IFS1bits.U2RXIF );
			if( TickGetDiff(TickGet(),startTime) > (2 * ONE_SECOND))
			{
				break;
			}
			zigbee_mode = U2RXREG;
			ConsolePut(zigbee_mode);
		}while( (zigbee_mode != 'M') && (zigbee_mode != 'm') && (zigbee_mode != 'E') && (zigbee_mode != 'e') );
		
		NVMRead ( (BYTE*)&MSDCL_Commission, MSDCL_Commission_Locations, sizeof(MSDCL_Commission));

		if( ( MSDCL_Commission.ValidCleanStartUp != MSDCL_COMMISSION_DATA_VALID )
			 && (MSDCL_Commission.ValidCleanStartUp != MSDCL_DEFAULT_MTR) && 
			 (MSDCL_Commission.ValidCleanStartUp != MSDCL_DEFAULT_ESP) &&  (zigbee_mode != 'E') && (zigbee_mode != 'e') )
		{
			zigbee_mode = 'M';
	 	}   
	 			
		if( ((zigbee_mode == 'M') || (zigbee_mode == 'm') || (MSDCL_Commission.ValidCleanStartUp == MSDCL_DEFAULT_MTR))
			&& (zigbee_mode != 'E') && (zigbee_mode != 'e') )
		{
			NowIam = 0;
 			NowIam = A_ROUTER | A_FFD; // These variables are exported in Zigbee.def
			I_AM_TRUST_CENTER = 0; 		//Trust center enabled Enabled
			USE_COMMON_TC_LINK_KEY = 1;
			MAX_ENERGY_THRESHOLD = 112;
			DEFAULT_STARTUP_CONTROL = DEFAULT_STARTUP_CONTROL_MTR;
			MSDCL_Commission.StartupStatus = STARTUP_CONTROL_JOIN_NEW_NETWORK;
			ALLOWED_CHANNELS = ALLOWED_CHANNELS_PRE_CONFIG;
			if(MSDCL_Commission.ValidCleanStartUp != MSDCL_DEFAULT_MTR)
			{
				MSDCL_Commission.ValidCleanStartUp = MSDCL_DEFAULT_MTR;
				NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
			}
		}
		else if( (zigbee_mode == 'E') || (zigbee_mode == 'e') || (MSDCL_Commission.ValidCleanStartUp == MSDCL_DEFAULT_ESP)  )
		{
			NowIam = 0;
 			NowIam = A_CORDINATOR | A_FFD; // These variables are exported in Zigbee.def
			I_AM_TRUST_CENTER = 1; 		//Trust center enabled Enabled
			USE_COMMON_TC_LINK_KEY = 1;
			MAX_ENERGY_THRESHOLD = 241;
			DEFAULT_STARTUP_CONTROL = DEFAULT_STARTUP_CONTROL_ESP;
			MSDCL_Commission.StartupStatus = STARTUP_CONTROL_FORM_NEW_NETWORK;
			ALLOWED_CHANNELS = ALLOWED_CHANNELS_PRE_CONFIG;
			if(MSDCL_Commission.ValidCleanStartUp != MSDCL_DEFAULT_ESP)
			{
				MSDCL_Commission.ValidCleanStartUp = MSDCL_DEFAULT_ESP;
				NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
			}
		}


	if((MSDCL_Commission.ValidCleanStartUp == MSDCL_COMMISSION_DATA_VALID) )
	{
	 	switch( MSDCL_Commission.StartupStatus )
	 	{
		 	case STARTUP_CONTROL_FORM_NEW_NETWORK:
		 		ConsolePutROMString( (ROM char *)"\r\nStarting as ESP\r\n" );
				NowIam = 0;
	 			NowIam = A_CORDINATOR | A_FFD; // These variables are exported in Zigbee.def
				I_AM_TRUST_CENTER = 1; 		//Trust center enabled Enabled
				USE_COMMON_TC_LINK_KEY = 1;
				MAX_ENERGY_THRESHOLD = 241;
				ALLOWED_CHANNELS = MSDCL_Commission.ChannelMask.Val ;
				DEFAULT_STARTUP_CONTROL = DEFAULT_STARTUP_CONTROL_ESP;
		 	break;
		 	
		 	case STARTUP_CONTROL_PART_OF_NETWORK_NO_EXPLICIT_ACTION:
		 	case STARTUP_CONTROL_JOIN_NEW_NETWORK:
		 	case STARTUP_CONTROL_START_FROM_SCRATCH_AS_ROUTER:
		 	default:
		 		ConsolePutROMString( (ROM char *)"\r\nStarting as MTR\r\n" );
				NowIam = 0;
	 			NowIam = A_ROUTER | A_FFD; // These variables are exported in Zigbee.def
				I_AM_TRUST_CENTER = 1; 		//Trust center enabled Enabled
				USE_COMMON_TC_LINK_KEY = 0;
				MAX_ENERGY_THRESHOLD = 112;
				ALLOWED_CHANNELS = MSDCL_Commission.ChannelMask.Val ;
				DEFAULT_STARTUP_CONTROL = DEFAULT_STARTUP_CONTROL_MTR;
		 	break;
		}
	}
	
	}
	
//	if (NOW_I_AM_A_CORDINATOR())
//		USE_COMMON_TC_LINK_KEY = 1;
//	else
//		USE_COMMON_TC_LINK_KEY = 0;
		
	if(NOW_I_AM_A_ROUTER())
		I_AM_TRUST_CENTER = 0;

	
	if(NOW_I_AM_A_ROUTER())
		appNextSeqNum_PTR = &appNextSeqNum_MTR;
	else if (NOW_I_AM_A_CORDINATOR())
		appNextSeqNum_PTR = &appNextSeqNum_ESP;
	
	if(NOW_I_AM_A_ROUTER())
		App_AttributeStorageTable = App_AttributeStorageTable_MTR;
	else if (NOW_I_AM_A_CORDINATOR())
		App_AttributeStorageTable = App_AttributeStorageTable_ESP;
		
	if(NOW_I_AM_A_ROUTER())
		Config_Node_Descriptor.NodeLogicalType = 0x01;
	else if (NOW_I_AM_A_CORDINATOR())
		Config_Node_Descriptor.NodeLogicalType = 0x00;
		
	if( NOW_I_AM_A_ROUTER() )
		pAppListOfDeviceServerInfo[0] = &Meter_DeviceServerinfo;
	else if( NOW_I_AM_A_CORDINATOR() )
		pAppListOfDeviceServerInfo[0] = &ESP_DeviceServerinfo;
		
	if( NOW_I_AM_A_ROUTER() )
		pAppListOfDeviceClientInfo[0] = &Meter_DeviceClientinfo;
	else if( NOW_I_AM_A_CORDINATOR() )
		pAppListOfDeviceClientInfo[0] = &ESP_DeviceClientinfo;
		
	if( NOW_I_AM_A_ROUTER() )
		Config_Simple_Descriptors = Config_Simple_Descriptors_MTR;
	else if( NOW_I_AM_A_CORDINATOR() )
		Config_Simple_Descriptors = Config_Simple_Descriptors_ESP;

	if( MSDCL_Commission.ValidCleanStartUp == MSDCL_COMMISSION_DATA_VALID)
	{
		if( ChannelsToBeScanned.Val == 0 )
		{
			ChannelsToBeScanned.Val = MSDCL_Commission.ChannelMask.Val & 0x03FFF800UL;
		}
	}
	else
	{
		if( ChannelsToBeScanned.Val == 0 )
		{
			ChannelsToBeScanned.Val = ALLOWED_CHANNELS_PRE_CONFIG & 0x03FFF800UL;
		}
	}
	{
		unsigned long channelMaskToScan = 0x00000800UL;
		
		if( ( ChannelsToBeScanned.Val & 0x03FFF800UL ) == 0 )
		{
			ChannelsToBeScanned.Val = ALLOWED_CHANNELS_PRE_CONFIG & 0x03FFF800UL;
		}
		
		ChannelsToBeScanned.Val &= 0x03FFF800UL;
	
		while( !(ChannelsToBeScanned.Val & channelMaskToScan) )
		{
			channelMaskToScan <<= 1;	
		}
		ALLOWED_CHANNELS = channelMaskToScan;
		ChannelsToBeScanned.Val &= channelMaskToScan ^ 0xFFFFFFFFUL;
		
		//ALLOWED_CHANNELS = 0x3FFFC00UL;
	}
	

	//ALLOWED_CHANNELS = 0b000000000111111111101111100000000000;
	ALLOWED_CHANNELS = 0b0000000000010000000000000000000000;

	while(1)
	{	
		if (NOW_I_AM_A_CORDINATOR())
			main_ESP(); 
		else
		{
			
			main_MTR();
		}
	}
}