void SendAddMeterCommandResponce(unsigned char success)
{
	unsigned char Tp;
	unsigned char SenUart2Buffer[20];
	unsigned char dataSize;

	memcpy( (void*)SenUart2Buffer, (void*)AddMeterCommandResponce, sizeof(AddMeterCommandResponce));
	dataSize = sizeof(AddMeterCommandResponce);
	if(success == 1)
	{
		SenUart2Buffer[dataSize++] = 0x00;
		SenUart2Buffer[dataSize++] = MACAddMeter.NumberMeter;
	}
	else
		SenUart2Buffer[dataSize++] = 0x01;
	SenUart2Buffer[1] = dataSize-1;
	//xprintf("\n\r I Send Data = ");
		DelayMs(100);
	for(Tp=0;Tp<dataSize;Tp++)
	{
		PrintChar(SenUart2Buffer[Tp]); 
		ConsolePut(' '); 
		x2putc(SenUart2Buffer[Tp]); 
	}
}
Esempio n. 2
0
    void ClearNVM( WORD dest, WORD count )
    {
        BYTE    dummy = 0;
        WORD    i;
        BYTE    oldByte;

        #ifdef ENABLE_DEBUG
            ConsolePut('c');
        #endif

        for (i=0; i<count; i++)
        {

    #if defined(VERIFY_WRITE)
            NVMRead( &oldByte, dest, 1 );
            while (oldByte)
    #elif defined(CHECK_BEFORE_WRITE)
            NVMRead( &oldByte, dest, 1 );
            if (oldByte)
    #endif
            {
                NVMWrite( dest, &dummy, 1 );
    #if defined(VERIFY_WRITE)
                NVMRead( &oldByte, dest, 1 );
    #endif
            }
            dest++;
            CLRWDT();
        }
    }
Esempio n. 3
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. 4
0
    BYTE NVMalloc( WORD size, WORD *location )
    {
        static WORD nextEEPosition = 0;
        if ((nextEEPosition + size) > EXTERNAL_NVM_BYTES)
        {
            return 1;
        }

        *location = nextEEPosition;
        nextEEPosition += size;
        #ifdef ENABLE_DEBUG
            ConsolePut('(');
            PrintChar((unsigned int)nextEEPosition >> 8);
            PrintChar((unsigned int)nextEEPosition & 0xFF);
            ConsolePut(')');
        #endif
        return 0;
    }
Esempio n. 5
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. 6
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
    }
BYTE GetHexDigit( void )
{
    BYTE    c;

    while (!ConsoleIsGetReady());
    c = ConsoleGet();
    ConsolePut(c);

    if (('0' <= c) && (c <= '9'))
        c -= '0';
    else if (('a' <= c) && (c <= 'f'))
        c = c - 'a' + 10;
    else if (('A' <= c) && (c <= 'F'))
        c = c - 'A' + 10;
    else
        c = 0;

    return c;
}
Esempio n. 8
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]);
    }       
}    
void CheckDataAndSend(void)
{
	LONG_ADDR IeeAddress;
	int Tp;

	WORD_VAL ZDODstAddr;
	BYTE addr1[2];
	BYTE i = 0;

	int LogAddrPos;
	unsigned int SenLen;
	WORD_VAL MSDCL_ClusterID;
	
	unsigned char SenUart2Buffer[800];
	
	//Check for start Network command from HHU
	if( memcmp( (void*)Uart2Buffer, (void*)NetworkStartCommand, sizeof(NetworkStartCommand) ) == 0 )
	{
		StartNetworkFlag = TRUE;	//This will trigger the start of network from the main function. Till this function is sent, it will wait
		SendModuleNetworkSetCommandResponse( (const unsigned char*) NetworkStartCommandResponse, sizeof(NetworkStartCommandResponse) );
	}
	else if( memcmp( (void*)Uart2Buffer, (void*)NetworkStatusCommand, sizeof(NetworkStatusCommand) ) == 0 )
	{
		NetworkStatusCommandResponse[sizeof(NetworkStatusCommandResponse) - 1] = StartNetworkFlag;	//StartNetworkFlag;	//This will trigger the start of network from the main function. Till this function is sent, it will wait
		SendModuleNetworkSetCommandResponse( (unsigned char*) NetworkStatusCommandResponse, sizeof(NetworkStatusCommandResponse) );
	}
	else if( memcmp( (void*)Uart2Buffer, (void*)NetworkStopCommand, sizeof(NetworkStopCommand) ) == 0 )
	{
		SendModuleNetworkSetCommandResponse( (const unsigned char*) NetworkStopCommandResponse, sizeof(NetworkStopCommandResponse) );
		DelayMs(1000);
		Reset();		//Simple reset the device on reception of this command
	}
	else if( memcmp( (void*)Uart2Buffer, (void*)SetNetworkExtendedPANIdCommand, sizeof(SetNetworkExtendedPANIdCommand) ) == 0 )
	{
		NVMRead ( (BYTE*)&MSDCL_Commission, MSDCL_Commission_Locations, sizeof(MSDCL_Commission));
		//Set the Network Extended PAN Id sent from the HHU
		memcpy( (void*)MSDCL_Commission.ExtendedPANId, (void*)&Uart2Buffer[sizeof(SetNetworkExtendedPANIdCommand)], sizeof(MSDCL_Commission.ExtendedPANId) );
		NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
		SendModuleNetworkSetCommandResponse( (const unsigned char*) SetNetworkExtendedPANIdCommandResponse, sizeof(SetNetworkExtendedPANIdCommandResponse) );
	}
	else if( memcmp( (void*)Uart2Buffer, (void*)SetNetworkLinkKeyCommand, sizeof(SetNetworkLinkKeyCommand) ) == 0 )
	{
		NVMRead ( (BYTE*)&MSDCL_Commission, MSDCL_Commission_Locations, sizeof(MSDCL_Commission));
		//Set the Network Link Key sent from the HHU
		memcpy( (void*)MSDCL_Commission.LinkKey, (void*)&Uart2Buffer[sizeof(SetNetworkLinkKeyCommand)], sizeof(MSDCL_Commission.LinkKey) );
		NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
		SendModuleNetworkSetCommandResponse( (const unsigned char*) SetNetworkLinkKeyCommandResponse, sizeof(SetNetworkLinkKeyCommandResponse) );
	}
	else if( memcmp( (void*)Uart2Buffer, (void*)SetNetworkDeviceTypeCommand, sizeof(SetNetworkDeviceTypeCommand) ) == 0 )
	{
		NVMRead ( (BYTE*)&MSDCL_Commission, MSDCL_Commission_Locations, sizeof(MSDCL_Commission));
		//Set the Network StartUp Status sent from the HHU
		if( Uart2Buffer[sizeof(SetNetworkDeviceTypeCommand)] == SET_NETWORK_DEVICE_TYPE_ESP )
		{
			MSDCL_Commission.StartupStatus = STARTUP_CONTROL_FORM_NEW_NETWORK;
		}
		else if( Uart2Buffer[sizeof(SetNetworkDeviceTypeCommand)] == SET_NETWORK_DEVICE_TYPE_MTR )
		{
			MSDCL_Commission.StartupStatus = STARTUP_CONTROL_JOIN_NEW_NETWORK;
		}
		NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
		SendModuleNetworkSetCommandResponse( (const unsigned char*) SetNetworkDeviceTypeCommandResponse, sizeof(SetNetworkDeviceTypeCommandResponse) );
	}
	else if( memcmp( (void*)Uart2Buffer, (void*)SetNetworkResetCommand, sizeof(SetNetworkResetCommand) ) == 0 )
	{
		NVMRead ( (BYTE*)&MSDCL_Commission, MSDCL_Commission_Locations, sizeof(MSDCL_Commission));
		//Set the Network Reset sent from the HHU
		MSDCL_Commission.ChannelMask.Val = ALLOWED_CHANNELS;	//0b00000000000000001000000000000000;	//Channel 15 as default
		MSDCL_Commission.ValidCleanStartUp = MSDCL_COMMISSION_DATA_VALID;
		NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
		SendModuleNetworkSetCommandResponse( (const unsigned char*) SetNetworkResetCommandResponse, sizeof(SetNetworkResetCommandResponse) );
		DelayMs(1000);
		Reset();
	}
	else if( memcmp( (void*)Uart2Buffer, (void*)SetNetworkChannelMaskCommand, sizeof(SetNetworkChannelMaskCommand) ) == 0 )
	{
		SendModuleNetworkSetCommandResponse( (const unsigned char*) SetNetworkChannelMaskResponce, sizeof(SetNetworkChannelMaskResponce) );
		
	}
	else if( memcmp( (void*)Uart2Buffer, (void*)SetNetworkDefaultESPCommand, sizeof(SetNetworkDefaultESPCommand) ) == 0 )
	{
		NVMRead ( (BYTE*)&MSDCL_Commission, MSDCL_Commission_Locations, sizeof(MSDCL_Commission));
		//Set the Network Extended Pan Id Status sent from the HHU
		MSDCL_Commission.ExtendedPANId[0] = NWK_EXTENDED_PAN_ID_BYTE0;
		MSDCL_Commission.ExtendedPANId[1] = NWK_EXTENDED_PAN_ID_BYTE1;
		MSDCL_Commission.ExtendedPANId[2] = NWK_EXTENDED_PAN_ID_BYTE2;
		MSDCL_Commission.ExtendedPANId[3] = NWK_EXTENDED_PAN_ID_BYTE3;
		MSDCL_Commission.ExtendedPANId[4] = NWK_EXTENDED_PAN_ID_BYTE4;
		MSDCL_Commission.ExtendedPANId[5] = NWK_EXTENDED_PAN_ID_BYTE5;
		MSDCL_Commission.ExtendedPANId[6] = NWK_EXTENDED_PAN_ID_BYTE6;
		MSDCL_Commission.ExtendedPANId[7] = NWK_EXTENDED_PAN_ID_BYTE7;
		
		//Set Channel Mask
		MSDCL_Commission.ChannelMask.Val = ALLOWED_CHANNELS_PRE_CONFIG;// ALLOWED_CHANNELS;
		
		//Set Link Key
		MSDCL_Commission.LinkKey[0] = PRECONFIGURED_LINK_KEY00;
		MSDCL_Commission.LinkKey[1] = PRECONFIGURED_LINK_KEY01;
		MSDCL_Commission.LinkKey[2] = PRECONFIGURED_LINK_KEY02;
		MSDCL_Commission.LinkKey[3] = PRECONFIGURED_LINK_KEY03;
		MSDCL_Commission.LinkKey[4] = PRECONFIGURED_LINK_KEY04;
		MSDCL_Commission.LinkKey[5] = PRECONFIGURED_LINK_KEY05;
		MSDCL_Commission.LinkKey[6] = PRECONFIGURED_LINK_KEY06;
		MSDCL_Commission.LinkKey[7] = PRECONFIGURED_LINK_KEY07;
		MSDCL_Commission.LinkKey[8] = PRECONFIGURED_LINK_KEY08;
		MSDCL_Commission.LinkKey[9] = PRECONFIGURED_LINK_KEY09;
		MSDCL_Commission.LinkKey[10] = PRECONFIGURED_LINK_KEY10;
		MSDCL_Commission.LinkKey[11] = PRECONFIGURED_LINK_KEY11;
		MSDCL_Commission.LinkKey[12] = PRECONFIGURED_LINK_KEY12;
		MSDCL_Commission.LinkKey[13] = PRECONFIGURED_LINK_KEY13;
		MSDCL_Commission.LinkKey[14] = PRECONFIGURED_LINK_KEY14;
		MSDCL_Commission.LinkKey[15] = PRECONFIGURED_LINK_KEY15;
		
		//Set Startup Status
		MSDCL_Commission.StartupStatus = STARTUP_CONTROL_FORM_NEW_NETWORK;
		
		MSDCL_Commission.ValidCleanStartUp = MSDCL_COMMISSION_DATA_VALID;
		
		NVMWrite( MSDCL_Commission_Locations, (BYTE*)&MSDCL_Commission, sizeof(MSDCL_Commission) );
		SendModuleNetworkSetCommandResponse( (const unsigned char*) SetNetworkDefaultESPCommandResponse, sizeof(SetNetworkDefaultESPCommandResponse) );
	}
	else if(memcmp( (void*)Uart2Buffer, (void*)NumberOfAddedMetersCommand, sizeof(NumberOfAddedMetersCommand) ) == 0 )
	{
		FindNumberofAddedMetersResponce();
	}	
	else if(memcmp( (void*)Uart2Buffer, (void*)MyRouteRequest, sizeof(MyRouteRequest) ) == 0 )
	{
		
	}
	else if(memcmp( (void*)Uart2Buffer, (void*)MyChannelNumberCommand, sizeof(MyChannelNumberCommand) ) == 0 )
	{
		FindMyChannel();
	}
	else if(memcmp( (void*)Uart2Buffer, (void*)AddMeterCommand, sizeof(AddMeterCommand) ) == 0 )
	{
		unsigned char Tp2 = 0;
		char TpStr3[20];
		unsigned char success =0;
		if(MACAddMeter.NumberMeter<MAX_NEIGHBORS)
		{
			success = 1;
			Tp2 = 10;
			for(Tp=0;Tp<=7;Tp++)
			{				
					MACAddMeter.AddMeter[MACAddMeter.NumberMeter].v[Tp] = Uart2Buffer[Tp2];
					Tp2++;
			}
			MACAddMeter.NumberMeter++;
		}
		SendAddMeterCommandResponce(success);
	}
	else if( (Uart2Buffer[2] == 0x02) && (Uart2Buffer[4] == 0x72) )
	{

		SenLen = 0;

		SenUart2Buffer[SenLen++] = 0x2D;	
		SenUart2Buffer[SenLen++] = 0x01;	
		SenUart2Buffer[SenLen++] = 0x82;	
		SenUart2Buffer[SenLen++] = 0x72;	
		SenUart2Buffer[SenLen++] = 0x74;	
		SenUart2Buffer[SenLen++] = 0x00;	
		SenUart2Buffer[SenLen++] = EndDeviceAnounceTable.Counter;	

		if(EndDeviceAnounceTable.Counter>0)
		{
			for(Tp=0;Tp<EndDeviceAnounceTable.Counter;Tp++)
			{
				int Tp2;
				for(Tp2=7;Tp2>=0;Tp2--)
				{
					SenUart2Buffer[SenLen++] = EndDeviceAnounceTable.EndDevAddr[Tp].longaddress.v[Tp2];
				}
			
				SenUart2Buffer[SenLen++] = EndDeviceAnounceTable.EndDevAddr[Tp].shortaddress.v[1];
				SenUart2Buffer[SenLen++] = EndDeviceAnounceTable.EndDevAddr[Tp].shortaddress.v[0];
			}
		}
	
		
		SenUart2Buffer[1] = SenLen-1;
		
		//xprintf("\n\r I Send Data = ");
		for(Tp=0;Tp<SenLen;Tp++)
		{
			//PrintChar(SenUart2Buffer[Tp]); 
			//ConsolePut(' '); 
			x2putc(SenUart2Buffer[Tp]);
			//Delay10us(1);
		}
		
	}
	else if( (Uart2Buffer[2] == 0x02) && (Uart2Buffer[4] == 0x73) )
	{
		//AckReceived = 1;
		SendExtPANIdResponse();
	}
	else if((Uart2Buffer[2] == 0x04))
	{
	
		i = 0;
		{
			unsigned char cntr;
			
			for( cntr = 15; cntr <=Uart2Datalen; cntr++ )
			{
				asduData[i++] = Uart2Buffer[cntr];
				PrintChar(Uart2Buffer[cntr]); 
				ConsolePut(' '); 
			}
			MSDCL_ClusterID.byte.HB = Uart2Buffer[13];
			MSDCL_ClusterID.byte.LB = Uart2Buffer[14];
		}
		ZDODstAddr.Val =  0xFFFD; 
			
		//xprintf("\n\raddr1[0] = %02x \n\r",addr1[0]);
		//xprintf("\n\raddr1[1] = %02x \n\r",addr1[1]);
		//xprintf("\n\rZDODstAddr.Val = %04X \n\r",ZDODstAddr.Val);
		
		SendAPPLRequest( ZDODstAddr, MSDCL_ClusterID.Val , asduData, i);
	
/*		for(Tp=0;Tp<NumberOfDevicesConnected;Tp++)
		{
			i = 0;
			{
				unsigned char cntr;
				
				for( cntr = 15; cntr <=Uart2Datalen; cntr++ )
				{
					asduData[i++] = Uart2Buffer[cntr];
					PrintChar(Uart2Buffer[cntr]); 
					ConsolePut(' '); 
				}
				MSDCL_ClusterID.byte.HB = Uart2Buffer[13];
				MSDCL_ClusterID.byte.LB = Uart2Buffer[14];
			}
		
			addr1[0] = CurrentDeviceConnectedInfo[Tp].shortAddr.v[0];
			addr1[1] = CurrentDeviceConnectedInfo[Tp].shortAddr.v[1];  
			
			ZDODstAddr.Val =  ( (addr1[1] << 8) | addr1[0] ); 
			
			//xprintf("\n\raddr1[0] = %02x \n\r",addr1[0]);
			//xprintf("\n\raddr1[1] = %02x \n\r",addr1[1]);
			//xprintf("\n\rZDODstAddr.Val = %04X \n\r",ZDODstAddr.Val);
			SendAPPLRequest( ZDODstAddr, MSDCL_ClusterID.Val , asduData, i);
			
			SendModuleNetworkSetCommandResponse( (const unsigned char*) SetNetworkResetCommandResponse, sizeof(SetNetworkResetCommandResponse) );
			
		}*/
	}
	else
	{

		IeeAddress.v[7] = Uart2Buffer[10];
		IeeAddress.v[6] = Uart2Buffer[9];
		IeeAddress.v[5] = Uart2Buffer[8];
		IeeAddress.v[4] = Uart2Buffer[7];
		IeeAddress.v[3] = Uart2Buffer[6];
		IeeAddress.v[2] = Uart2Buffer[5];
		IeeAddress.v[1] = Uart2Buffer[4];
		IeeAddress.v[0] = Uart2Buffer[3];
	
		//xprintf("\n\r IeeAddress Received =");
		//PrintChar(IeeAddress.v[7]);
		//PrintChar(IeeAddress.v[6]);
		//PrintChar(IeeAddress.v[5]);
		//PrintChar(IeeAddress.v[4]);
		//PrintChar(IeeAddress.v[3]);
		//PrintChar(IeeAddress.v[2]);
		//PrintChar(IeeAddress.v[1]);
		//PrintChar(IeeAddress.v[0]);
	
		//xprintf("\n\rNow Going to send Data = ");
	
		{
			unsigned char cntr;
			
			for( cntr = 15; cntr <=Uart2Datalen; cntr++ )
			{
				asduData[i++] = Uart2Buffer[cntr];
				//PrintChar(Uart2Buffer[cntr]); 
				//ConsolePut(' '); 
			}
			MSDCL_ClusterID.byte.HB = Uart2Buffer[13];
			MSDCL_ClusterID.byte.LB = Uart2Buffer[14];
		}
		

		{
			LogAddrPos = -1;
			if(EndDeviceAnounceTable.Counter>0)
			{
				for(Tp=0;Tp<EndDeviceAnounceTable.Counter;Tp++)
				{
					//xprintf("\n\r IeeAddress Received =");
					//PrintChar(IeeAddress.v[7]);
					//PrintChar(IeeAddress.v[6]);
					//PrintChar(IeeAddress.v[5]);
					//PrintChar(IeeAddress.v[4]);
					//PrintChar(IeeAddress.v[3]);
					//PrintChar(IeeAddress.v[2]);
					//PrintChar(IeeAddress.v[1]);
					//PrintChar(IeeAddress.v[0]);
	
					//xprintf("\n\r Cur Device Log Addr =");
					//PrintChar(CurrentDeviceConnectedInfo[Tp].longAddr.v[7]);
					//PrintChar(CurrentDeviceConnectedInfo[Tp].longAddr.v[6]);
					//PrintChar(CurrentDeviceConnectedInfo[Tp].longAddr.v[5]);
					//PrintChar(CurrentDeviceConnectedInfo[Tp].longAddr.v[4]);
					//PrintChar(CurrentDeviceConnectedInfo[Tp].longAddr.v[3]);
					//PrintChar(CurrentDeviceConnectedInfo[Tp].longAddr.v[2]);
					//PrintChar(CurrentDeviceConnectedInfo[Tp].longAddr.v[1]);
					//PrintChar(CurrentDeviceConnectedInfo[Tp].longAddr.v[0]);
	
					if(	IeeAddress.v[7] == EndDeviceAnounceTable.EndDevAddr[Tp].longaddress.v[7] &&
						IeeAddress.v[6] == EndDeviceAnounceTable.EndDevAddr[Tp].longaddress.v[6] &&
						IeeAddress.v[5] == EndDeviceAnounceTable.EndDevAddr[Tp].longaddress.v[5] &&
						IeeAddress.v[4] == EndDeviceAnounceTable.EndDevAddr[Tp].longaddress.v[4] &&
						IeeAddress.v[3] == EndDeviceAnounceTable.EndDevAddr[Tp].longaddress.v[3] &&
						IeeAddress.v[2] == EndDeviceAnounceTable.EndDevAddr[Tp].longaddress.v[2] &&
						IeeAddress.v[1] == EndDeviceAnounceTable.EndDevAddr[Tp].longaddress.v[1] &&
						IeeAddress.v[0] == EndDeviceAnounceTable.EndDevAddr[Tp].longaddress.v[0])
					{
						LogAddrPos = Tp;
						break;
		
					}
				}	
		
			}
	
			//xprintf("\n\r LogAddrPos = %u\n\r",LogAddrPos);
			if(LogAddrPos != -1)
			{
				addr1[0] =  EndDeviceAnounceTable.EndDevAddr[LogAddrPos].shortaddress.v[0];
				addr1[1] =  EndDeviceAnounceTable.EndDevAddr[LogAddrPos].shortaddress.v[1];  
				
				ZDODstAddr.Val =  ( (addr1[1] << 8) | addr1[0] ); 
				
				xprintf("\n\raddr1[0] = %02x \n\r",addr1[0]);
				xprintf("\n\raddr1[1] = %02x \n\r",addr1[1]);
				xprintf("\n\rZDODstAddr.Val = %04X \n\r",ZDODstAddr.Val);
				SendAPPLRequest( ZDODstAddr, MSDCL_ClusterID.Val , asduData, i);
			}
			else
			{
				MyAskForDeviceAddress(FALSE,IeeAddress);
			}
		}
	}	

}
void HanddleUART2Request(int Seq,int Cmd,unsigned char RW,APP_DATA_indication* p_dataInd)
{
	int len;
	int Tp;
	int SenLen;
	unsigned char SenUart2Buffer[40];
	int LogAddrPos;
	unsigned char SendData[100];
	int sendLen;
	


	ScanResponceReceived = 1;

	len =  p_dataInd->asduLength;
	//xprintf("\n\rSeq = %u, Cmd = %u, Rw = %d",Seq,Cmd,RW);
	//xprintf("\n\rData len = %u\n\r",len);
	for(Tp=0;Tp<len;Tp++)
	{
		SendData[Tp] = p_dataInd->asdu[Tp];
		//xprintf("\n\r Tp= %d  Data = ",Tp);
		//PrintChar(SendData[Tp]); 

	}
	sendLen = Tp;
	

	LogAddrPos = -1;
	
	xprintf("\n\r Number of Deveices Connected = %u\n\r",EndDeviceAnounceTable.Counter);

	
	
	
	
	if(EndDeviceAnounceTable.Counter>0)
	{
		for(Tp=0;Tp<=EndDeviceAnounceTable.Counter;Tp++)
		{
			//xprintf("\n\r Rec Short Address =");
			//PrintChar(p_dataInd->SrcAddress.v[1]);
			//PrintChar(p_dataInd->SrcAddress.v[0]);
			
			//xprintf("\n\r Act Short Address =");
			//PrintChar(EndDeviceAnounceTable.EndDevAddr[Tp].shortaddress.v[1]);
			//PrintChar(EndDeviceAnounceTable.EndDevAddr[Tp].shortaddress.v[0]);

			if(	p_dataInd->SrcAddress.v[0] == EndDeviceAnounceTable.EndDevAddr[Tp].shortaddress.v[0] &&
				p_dataInd->SrcAddress.v[1] == EndDeviceAnounceTable.EndDevAddr[Tp].shortaddress.v[1] )
			{
				
				LogAddrPos = Tp;
				break;

			}
		}	
	
	}

	if(LogAddrPos!= -1)
	{
		SenLen = 0;
		SenUart2Buffer[0] = 0x2d;	
		SenUart2Buffer[1] = 0x01;	
		SenUart2Buffer[2] = 0x01;		
		SenUart2Buffer[3] = EndDeviceAnounceTable.EndDevAddr[LogAddrPos].longaddress.v[7];
		SenUart2Buffer[4] = EndDeviceAnounceTable.EndDevAddr[LogAddrPos].longaddress.v[6];
		SenUart2Buffer[5] = EndDeviceAnounceTable.EndDevAddr[LogAddrPos].longaddress.v[5];
		SenUart2Buffer[6] = EndDeviceAnounceTable.EndDevAddr[LogAddrPos].longaddress.v[4];
		SenUart2Buffer[7] = EndDeviceAnounceTable.EndDevAddr[LogAddrPos].longaddress.v[3];
		SenUart2Buffer[8] = EndDeviceAnounceTable.EndDevAddr[LogAddrPos].longaddress.v[2];
		SenUart2Buffer[9] = EndDeviceAnounceTable.EndDevAddr[LogAddrPos].longaddress.v[1];
		SenUart2Buffer[10] = EndDeviceAnounceTable.EndDevAddr[LogAddrPos].longaddress.v[0];

		SenUart2Buffer[11] = EndDeviceAnounceTable.EndDevAddr[LogAddrPos].shortaddress.v[0];
		SenUart2Buffer[12] = EndDeviceAnounceTable.EndDevAddr[LogAddrPos].shortaddress.v[1];
	
		SenUart2Buffer[13] = p_dataInd->ClusterId.v[1];
		SenUart2Buffer[14] = p_dataInd->ClusterId.v[0];

		for(Tp=0,SenLen=15;Tp<sendLen;Tp++,SenLen++)
		{
			SenUart2Buffer[SenLen] =SendData[Tp];
		}
		SenUart2Buffer[1] = SenLen-1;
		
		xprintf("\n\r I Send Data = ");
		for(Tp=0;Tp<SenLen;Tp++)
		{
			PrintChar(SenUart2Buffer[Tp]); 
			ConsolePut(' '); 
			x2putc(SenUart2Buffer[Tp]); 
		}

	}


}
Esempio n. 11
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. 12
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. 13
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. 14
0
void sendBuffer(BYTE const *buffer, WORD len){
    int i = 0;
    for(i = 0; i<len; i++){
        ConsolePut(buffer[i]);
    }
}
Esempio n. 15
0
void sendByte(BYTE byte){
    ConsolePut(byte);
}
Esempio n. 16
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();
		}
	}
}