int main( void )
{
    halInit();
    moduleInit();    
    printf("\r\n****************************************************\r\n");    
    printf("Fragmentation Example - ROUTER - using AFZDO\r\n");
    buttonIsr = &handleButtonPress;    

#define MODULE_START_DELAY_IF_FAIL_MS 5000

    /* See basic communications examples for more information about module startup. */
    struct moduleConfiguration defaultConfiguration = DEFAULT_MODULE_CONFIGURATION_ROUTER;
    start: 
    while ((result = startModule(&defaultConfiguration, GENERIC_APPLICATION_CONFIGURATION)) != MODULE_SUCCESS)
    {
        printf("Module start unsuccessful. Error Code 0x%02X. Retrying...\r\n", result);
        delayMs(MODULE_START_DELAY_IF_FAIL_MS);
    }
    printf("On Network!\r\n");
    setLed(0);
    /* On network, display info about this network */ 
#ifdef DISPLAY_NETWORK_INFORMATION    //excluded to reduce code size
    displayNetworkConfigurationParameters();   
    displayDeviceInformation();
#endif 
    HAL_ENABLE_INTERRUPTS();

    /* Now the network is running - send a message to the coordinator every few seconds.*/
#define TEST_CLUSTER 0x77    

    /* Fill test message buffer with an incrementing counter */
    int i = 0;
    for (i=0; i<MESSAGE_LENGTH; i++)
    {
    	testMessage[i] = i;
    }
    printf("Sending the following message:\r\n");

    uint8_t counter = 0;
    while (1)
    {       
        printf("Sending Message #%u L%u to Short Address 0x0000 (Coordinator) ", counter++, MESSAGE_LENGTH);
        /* Send an extended length message to a short address */
        moduleResult_t result = afSendDataExtendedShort(DEFAULT_ENDPOINT, DEFAULT_ENDPOINT, 0, TEST_CLUSTER, testMessage, MESSAGE_LENGTH);  //a short message - coordinator will receive an AF_INCOMING_MSG_EXT
        if (result == MODULE_SUCCESS)
        {
            printf("Success\r\n");
        } else {
            printf("ERROR %i ", result);
#ifdef RESTART_AFTER_ZM_FAILURE
            printf("\r\nRestarting\r\n");
            goto start;
#else        
            printf("stopping\r\n");
            while(1);
#endif
        }
        delayMs(2000);  
    }   
}
/** When a button is pressed, display device information */
void handleButtonPress(int8_t whichButton)
{
#ifdef DISPLAY_NETWORK_INFORMATION     
    displayNetworkConfigurationParameters();                
    displayDeviceInformation();
#else
    displayBasicDeviceInformation();
#endif
}
int main( void )
{
    halInit();
    moduleInit();    
    printf("\r\n****************************************************\r\n");    
    printf("Secure Communications Example - ROUTER - using AFZDO\r\n");
    HAL_ENABLE_INTERRUPTS();

#define MODULE_START_DELAY_IF_FAIL_MS 5000

    struct moduleConfiguration defaultConfiguration = DEFAULT_MODULE_CONFIGURATION_ROUTER;
    defaultConfiguration.securityMode = SECURITY_MODE_PRECONFIGURED_KEYS;
    defaultConfiguration.securityKey = key;
    start:
    while ((result = startModule(&defaultConfiguration, GENERIC_APPLICATION_CONFIGURATION)) != MODULE_SUCCESS)
    {
        printf("Module start unsuccessful. Error Code 0x%02X. Retrying...\r\n", result);
        delayMs(MODULE_START_DELAY_IF_FAIL_MS);
    }

    printf("On Network!\r\n");
    setLed(0);

    /* On network, display info about this network */
#ifdef DISPLAY_NETWORK_INFORMATION     
    displayNetworkConfigurationParameters();
    displayDeviceInformation();
#endif  

    /* Now the network is running - send a message to the coordinator every few seconds.*/
#define TEST_CLUSTER 0x77    

    while (1)
    {
        printf("Sending Message %u  ", counter++);
        result = afSendData(DEFAULT_ENDPOINT,DEFAULT_ENDPOINT,0, TEST_CLUSTER, testMessage, 5);
        if (result == MODULE_SUCCESS)
        {
            printf("Success\r\n");
        } else {
            printf("ERROR %02X ", result);
#ifdef RESTART_AFTER_ZM_FAILURE
            printf("\r\nRestarting\r\n");
            goto start;
#else        
            printf("stopping\r\n");
            while(1);
#endif
        }
        toggleLed(1);
        delayMs(2000);
    }
}
int main( void )
{
    halInit();
    moduleInit();
    printf("\r\n****************************************************\r\n");
    printf("Packet Error Rate Tester - ROUTER\r\n");
    buttonIsr = &handleButtonPress;
    
#define MODULE_START_DELAY_IF_FAIL_MS 5000
    
    /* Use the default module configuration */
    struct moduleConfiguration defaultConfiguration = DEFAULT_MODULE_CONFIGURATION_ROUTER;
    
    /* Turn Off nwk status LED if on */
    clearLed(ON_NETWORK_LED);
    
    /* Loop until module starts */
    while ((result = expressStartModule(&defaultConfiguration, GENERIC_APPLICATION_CONFIGURATION, MODULE_REGION_NORTH_AMERICA)) != MODULE_SUCCESS)
    {
        /* Module startup failed; display error and blink LED */
        setLed(NETWORK_FAILURE_LED);                    
        printf("Module start unsuccessful. Error Code 0x%02X. Retrying...\r\n", result);
        delayMs(MODULE_START_DELAY_IF_FAIL_MS/2);                    
        clearLed(NETWORK_FAILURE_LED);
        delayMs(MODULE_START_DELAY_IF_FAIL_MS/2);
    }
    printf("On Network!\r\n");
    
    /* Indicate we got on the network */
    setLed(ON_NETWORK_LED); 
    
    /* On network, display info about this network */
#ifdef DISPLAY_NETWORK_INFORMATION     
    displayNetworkConfigurationParameters();                
    displayDeviceInformation();
#else
    displayBasicDeviceInformation();
#endif
    
    HAL_ENABLE_INTERRUPTS();
    
    /* Now the network is running - send messages to the Coordinator.*/    
#define TEST_CLUSTER 0x77
    
#define MESSAGE_HEADER_LENGTH    13
#define MESSAGE_LENGTH  (TEST_MESSAGE_PAYLOAD_LENGTH + MESSAGE_HEADER_LENGTH)
    /* Here we precompute zmBuf contents so that we don't have to do it in the loop. This is faster.
    This is the equivalent of afSendData(DEFAULT_ENDPOINT,DEFAULT_ENDPOINT,0, TEST_CLUSTER, testMessage, 10); */
    uint8_t testBuf[MESSAGE_LENGTH];
    testBuf[0] = MESSAGE_LENGTH;
    testBuf[1] = MSB(AF_DATA_REQUEST);
    testBuf[2] = LSB(AF_DATA_REQUEST);      
    
    testBuf[3] = 0; 
    testBuf[4] = 0;
    testBuf[5] = DEFAULT_ENDPOINT;
    testBuf[6] = DEFAULT_ENDPOINT;
    testBuf[7] = LSB(TEST_CLUSTER); 
    testBuf[8] = MSB(TEST_CLUSTER); 
    testBuf[9] = 0xFF;  // Sequence: we don't care
    testBuf[10] = AF_MAC_ACK; //Could also use AF_APS_ACK;
    testBuf[11] = DEFAULT_RADIUS;
    testBuf[12] = TEST_MESSAGE_PAYLOAD_LENGTH; // Datalength
    //memcpy(testBuf+MESSAGE_HEADER_LENGTH, testMessage, TEST_MESSAGE_PAYLOAD_LENGTH);
    //testBuf is now loaded with our test message.        
    
    printf("!!  Sending %u messages  !!\r\n", NUMBER_OF_PACKETS_TO_SEND);    
    
    while (1)
    {
    	uint16_t packetCounter;
        for (packetCounter = 0; packetCounter<NUMBER_OF_PACKETS_TO_SEND; packetCounter++)
        {
            /* Copy our message over to zmBuf because zmBuf gets overwritten when the AF_DATA_CONFIRM is received */
            memcpy(zmBuf, testBuf, MESSAGE_LENGTH);
            
            /* Now initialize the payload */
            int index;
            for (index = MESSAGE_HEADER_LENGTH; index < (TEST_MESSAGE_PAYLOAD_LENGTH + MESSAGE_HEADER_LENGTH); index++)
            {
                testBuf[index] = index;
            }

            /* Send the message to the Coordinator */
            result = sendMessage();       
            if (result != MODULE_SUCCESS)
            {
                printf("afSendData Error %02X; stopping\r\n", result);
                while (1);
            }        
            
            /* Now, wait for the AF_DATA_CONFIRM to verify that the message was successfully sent*/
            while (!(MODULE_HAS_MESSAGE_WAITING()));
            
            /* Retrieve the AF_DATA_CONFIRM message */
            getMessage();
            
            if (!(IS_AF_DATA_CONFIRM())) 
            {
                /* Stop if we receive a different message */
                printf("Error; stopped after packet %u", packetCounter);
            }        
            
            toggleLed(1); 
            /* If you want to slow down the rate of sending packets then add:
            delayMs(1);
            which will add a one mSec delay after each packet is sent. */
            
            if (((packetCounter % 100) == 0) && (packetCounter != 0))
            {
                printf("%u\r\n", packetCounter);
            }
        }
        printf("Done! Sent %u packets!\r\nPress button to start again\r\n", NUMBER_OF_PACKETS_TO_SEND);        
        
        /* Wait until a button is pressed, then send another 1000 */
        while (!(buttonIsPressed(ANY_BUTTON)));
    }
}
static void stateMachine()
{
    while (1)
    {
        if (zigbeeNetworkStatus == NWK_ONLINE)
        {
            if(moduleHasMessageWaiting())      //wait until SRDY goes low indicating a message has been received.   
                displayMessages();
        }

        switch (state)
        {
        case STATE_IDLE:
        {
            /* process command line commands only if not doing anything else: */
            if (command != NO_CHARACTER_RECEIVED)
            {
                /* parse the command entered, and go to the required state */
                state = processCommand(command);

                command = NO_CHARACTER_RECEIVED;
            }
            /* note: other flags (for different messages or events) can be added here */
            break;
        }
        case STATE_INIT:
        {
            printf("Starting State Machine\r\n");
            state = STATE_GET_DEVICE_TYPE;
            break;
        }
        /* A button press during startup will cause the application to prompt for device type */
        case STATE_GET_DEVICE_TYPE: 
        {
            //printf("Current Configured DeviceType: %s\r\n", getDeviceTypeName());
            set_type:                
            /* if saving device type to flash memory:
                printf("Any other key to exit. Timeout in 5 seconds.\r\n");
                / long wait = 0;
                long timeout = TICKS_IN_ONE_MS * 5000l;
                while ((command == NO_CHARACTER_RECEIVED) && (wait != timeout))
                wait++;
             */
            while (command == NO_CHARACTER_RECEIVED)
            {
                printf("Setting Device Type: Press C for Coordinator, R for Router, or E for End Device.\r\n");
                delayMs(2000);
            }

            switch (command)
            {
            case 'C':
            case 'c':
                printf("Coordinator it is...\r\n");
                zigbeeDeviceType = COORDINATOR;
                break;
            case 'R':
            case 'r':
                printf("Router it is...\r\n");
                zigbeeDeviceType = ROUTER;
                break;

            case 'E':
            case 'e':
                printf("End Device it is...\r\n");
                zigbeeDeviceType = END_DEVICE;
                break;
            default:
                command = NO_CHARACTER_RECEIVED;
                goto set_type;

            }
            command = NO_CHARACTER_RECEIVED;
            state = STATE_MODULE_STARTUP;
            break;
        }
        case STATE_MODULE_STARTUP:
        {
#define MODULE_START_DELAY_IF_FAIL_MS 5000
            moduleResult_t result;
            /* Start with the default module configuration */
            struct moduleConfiguration defaultConfiguration = DEFAULT_MODULE_CONFIGURATION_COORDINATOR;
            /* Make any changes needed here (channel list, PAN ID, etc.)
                   We Configure the Zigbee Device Type (Router, Coordinator, End Device) based on what user selected */
            defaultConfiguration.deviceType = zigbeeDeviceType;
            while ((result = startModule(&defaultConfiguration, GENERIC_APPLICATION_CONFIGURATION)) != MODULE_SUCCESS)
            {
                printf("Module start unsuccessful. Error Code 0x%02X. Retrying...\r\n", result);
                delayMs(MODULE_START_DELAY_IF_FAIL_MS);
            }
            printf("Success\r\n");
            state = STATE_DISPLAY_NETWORK_INFORMATION;
            zigbeeNetworkStatus = NWK_ONLINE;
            break;
        }
        case STATE_DISPLAY_NETWORK_INFORMATION:                 
        {
            printf("Module Information:\r\n");
            /* On network, display info about this network */
            displayNetworkConfigurationParameters();
            displayDeviceInformation();
            displayCommandLineInterfaceHelp();
            state = STATE_IDLE;   //startup is done!
            break;
        }
        case STATE_VALID_SHORT_ADDRESS_ENTERED:  //command line processor has a valid shortAddressEntered
        {
            printf("Valid Short Address Entered\r\n");
            state = pendingState;
            break;
        }
        case STATE_VALID_LONG_ADDRESS_ENTERED:
        {
            /* flip byte order */
            int8_t temp[8];
            int i;
            for (i=0; i<8; i++)
                temp[7-i] = longAddressEntered[i];

            memcpy(longAddressEntered, temp, 8);  //Store LSB first since that is how it will be sent:
            state = pendingState;
            break;
        }
        case STATE_SEND_MESSAGE_VIA_SHORT_ADDRESS:
        {
            printf("Send via short address to %04X\r\n", shortAddressEntered);
            moduleResult_t result = afSendData(DEFAULT_ENDPOINT,DEFAULT_ENDPOINT,shortAddressEntered, TEST_CLUSTER, testMessage, 5);
            if (result == MODULE_SUCCESS)
            {
                printf("Success\r\n");
            } else {
                printf("Could not send to that device (Error Code 0x%02X)\r\n", result);

#ifdef RESTART_AFTER_ZM_FAILURE
                printf("\r\nRestarting\r\n");
                state = STATE_MODULE_STARTUP;
                continue;
#endif
            }
            state = STATE_IDLE;
            break;
        }
        case STATE_SEND_MESSAGE_VIA_LONG_ADDRESS:
        {
            printf("Send via long address to (LSB first)");
            printHexBytes(longAddressEntered, 8);
            moduleResult_t result = afSendDataExtended(DEFAULT_ENDPOINT, DEFAULT_ENDPOINT, longAddressEntered,
                    DESTINATION_ADDRESS_MODE_LONG, TEST_CLUSTER, testMessage, 5);
            if (result == MODULE_SUCCESS)
            {
                printf("Success\r\n");
            } else {
                printf("Could not send to that device (Error Code 0x%02X)\r\n", result);
#ifdef RESTART_AFTER_ZM_FAILURE
                printf("\r\nRestarting\r\n");
                state = STATE_MODULE_STARTUP;
                continue;
#endif
            }
            state = STATE_IDLE;
            break;
        }
        case STATE_FIND_VIA_SHORT_ADDRESS:
        {
            printf("Looking for that device...\r\n");
            moduleResult_t result = zdoRequestIeeeAddress(shortAddressEntered, SINGLE_DEVICE_RESPONSE, 0);
            if (result == MODULE_SUCCESS)
            {
#ifndef ZDO_NWK_ADDR_RSP_HANDLED_BY_APPLICATION
                displayZdoAddressResponse(zmBuf + SRSP_PAYLOAD_START);
#endif
            } else {
                printf("Could not locate that device (Error Code 0x%02X)\r\n", result);
            }
            state = STATE_IDLE;
            break;
        }
        case STATE_FIND_VIA_LONG_ADDRESS:
        {
            printf("Looking for that device...\r\n");
            moduleResult_t result = zdoNetworkAddressRequest(longAddressEntered, SINGLE_DEVICE_RESPONSE, 0);
            if (result == MODULE_SUCCESS)
            {
#ifndef ZDO_NWK_ADDR_RSP_HANDLED_BY_APPLICATION
                displayZdoAddressResponse(zmBuf + SRSP_PAYLOAD_START);
#endif
            } else {
                printf("Could not locate that device (Error Code 0x%02X)\r\n", result);
            }
            state = STATE_IDLE;
            break;
        }
        default:     //should never happen
        {
            printf("UNKNOWN STATE (%u)\r\n", state);
            state = STATE_IDLE;
        }
        break;
        }
    }
}
void stateMachine()
{
    while (1)
    {
        if (zigbeeNetworkStatus == NWK_ONLINE)
        {  
            if(moduleHasMessageWaiting())      //wait until SRDY goes low indicating a message has been received.
            {
                getMessage();                      
                displayMessage();
            }   
        }
        
        switch (state)
        {
        case STATE_IDLE:
            {
                if (stateFlags & STATE_FLAG_SEND_INFO_MESSAGE)  //if there is a pending info message to be sent
                {
                    state = STATE_SEND_INFO_MESSAGE;            //then send the message and clear the flag
                    stateFlags &= ~STATE_FLAG_SEND_INFO_MESSAGE;
                }
                /* Other flags (for different messages or events) can be added here */
                break;
            }
            
        case STATE_MODULE_STARTUP:
            {
#define MODULE_START_DELAY_IF_FAIL_MS   5000    // Must be greater than MODULE_START_FAIL_LED_ONTIME
                moduleResult_t result;
                struct moduleConfiguration defaultConfiguration = DEFAULT_MODULE_CONFIGURATION_END_DEVICE;
                
                /* Uncomment below to restrict the device to a specific PANID
                defaultConfiguration.panId = 0x1234;
                */
                
                struct applicationConfiguration endDeviceConf;
                endDeviceConf.endPoint = 1;
                endDeviceConf.latencyRequested = LATENCY_NORMAL;
                endDeviceConf.profileId = 0xcc00; // the clock profile is 0xCC00
                endDeviceConf.deviceId = 0x8866;
                endDeviceConf.deviceVersion = 0x01;
                endDeviceConf.numberOfBindingInputClusters = 4; // number of binding input cluster
                endDeviceConf.bindingInputClusters[0] = 0x0000; // basic cluster
                endDeviceConf.bindingInputClusters[1] = 0x0003; // identify cluster
                endDeviceConf.bindingInputClusters[2] = 0xfc01; // synchronise clock cluster
                endDeviceConf.bindingInputClusters[3] = 0xfc02; // send string message cluster
                endDeviceConf.numberOfBindingOutputClusters = 4; // number of binding output cluster
                endDeviceConf.bindingOutputClusters[0] = 0x0000;
                endDeviceConf.bindingOutputClusters[1] = 0x0003;
                endDeviceConf.bindingOutputClusters[2] = 0xfc01;
                endDeviceConf.bindingOutputClusters[3] = 0xfc02;
                
                struct applicationConfiguration ac;
                ac.endPoint = 1;
                ac.deviceVersion = 0x10;
                ac.profileId = 0xfafa;
                ac.latencyRequested = LATENCY_NORMAL;
                
                ac.numberOfBindingInputClusters = 2;
                ac.bindingInputClusters[0] =        0x0000;    
                ac.bindingInputClusters[1] =        0x0900;    
                ac.numberOfBindingOutputClusters = 2;
                ac.bindingOutputClusters[0] =        0x0000;
                ac.bindingOutputClusters[1] =        0x0900;
                
                /* Below is an example of how to restrict the device to only one channel:
                defaultConfiguration.channelMask = CHANNEL_MASK_17;
                printf("DEMO - USING CUSTOM CHANNEL 17\r\n");
                */
                
                //while ((result = startModule(&defaultConfiguration, GENERIC_APPLICATION_CONFIGURATION)) != MODULE_SUCCESS)
                while ((result = startModule(&defaultConfiguration, &ac)) != MODULE_SUCCESS)
                {
                    SET_NETWORK_FAILURE_LED_ON();          // Turn on the LED to show failure
                    printf("FAILED. Error Code 0x%02X. Retrying...\r\n", result);
                    delayMs(MODULE_START_DELAY_IF_FAIL_MS/2);                    
                    SET_NETWORK_FAILURE_LED_OFF();
                    delayMs(MODULE_START_DELAY_IF_FAIL_MS/2);
                }
                
                INIT_BOOSTER_PACK_LEDS();                
                SET_NETWORK_LED_ON();
                SET_NETWORK_FAILURE_LED_OFF();
                printf("Success\r\n"); 
                /* Module is now initialized so store MAC Address */
                zbGetDeviceInfo(DIP_MAC_ADDRESS);
                memcpy(hdr.mac, zmBuf+SRSP_DIP_VALUE_FIELD, 8);
#define MESSAGE_PERIOD_SECONDS  4
                int16_t timerResult = initTimer(MESSAGE_PERIOD_SECONDS);
                if (timerResult != 0)
                {
                    printf("timerResult Error %d, STOPPING\r\n", timerResult);
                    while (1);   
                }
                
                state = STATE_DISPLAY_NETWORK_INFORMATION;
                break;
            }
        case STATE_DISPLAY_NETWORK_INFORMATION:
            {
                printf("~ni~");
                /* On network, display info about this network */              
                displayNetworkConfigurationParameters();                
                displayDeviceInformation();
                /* Set module GPIOs as output and turn them off */
                if ((sysGpio(GPIO_SET_DIRECTION, ALL_GPIO_PINS) != MODULE_SUCCESS) || (sysGpio(GPIO_CLEAR, ALL_GPIO_PINS) != MODULE_SUCCESS))
                {
                    printf("ERROR\r\n");
                }
                state = STATE_SEND_INFO_MESSAGE;
                break;   
            }
        case STATE_SEND_INFO_MESSAGE:
            {
                printf("~im~");
                
                struct infoMessage im;
                /* See infoMessage.h for description of these info message fields.*/
                im.header = hdr;
                im.deviceType = DEVICETYPE_TESLA_CONTROLS_END_DEVICE_DEMO;
                im.header.sequence = sequenceNumber++;
                im.numParameters = getSensorValues(im.kvps);    // Does two things: Loads infoMessage with sensor value KVPs and gets the number of them
                                
                // now, add status message interval
                im.kvps[im.numParameters].oid = OID_STATUS_MESSAGE_INTERVAL;
                im.kvps[im.numParameters].value = MESSAGE_PERIOD_SECONDS;
                im.numParameters++;
                
                // add zigbee module information:
                if (sysVersion() != MODULE_SUCCESS)
                {
                    printf("ERROR retriving module information\r\n");
                } else {                
                displaySysVersion();
                
                // Product ID
                im.kvps[im.numParameters].oid = OID_MODULE_PRODUCT_ID;
                im.kvps[im.numParameters].value = zmBuf[SYS_VERSION_RESULT_PRODUCTID_FIELD];
                im.numParameters++;
                
                // FW - Major
                im.kvps[im.numParameters].oid = OID_MODULE_FIRMWARE_MAJOR;
                im.kvps[im.numParameters].value = zmBuf[SYS_VERSION_RESULT_FW_MAJOR_FIELD];
                im.numParameters++;    
                
                // FW - Minor
                im.kvps[im.numParameters].oid = OID_MODULE_FIRMWARE_MINOR;
                im.kvps[im.numParameters].value = zmBuf[SYS_VERSION_RESULT_FW_MINOR_FIELD];
                im.numParameters++;  

                // FW - Build
                im.kvps[im.numParameters].oid = OID_MODULE_FIRMWARE_BUILD;
                im.kvps[im.numParameters].value = zmBuf[SYS_VERSION_RESULT_FW_BUILD_FIELD];
                im.numParameters++;
                }
                
                printInfoMessage(&im);
#define RESTART_DELAY_IF_MESSAGE_FAIL_MS 5000
                uint8_t messageBuffer[MAX_INFO_MESSAGE_SIZE];
                serializeInfoMessage(&im, messageBuffer);
                setLed(SEND_MESSAGE_LED); //indicate that we are sending a message
                moduleResult_t result = afSendData(DEFAULT_ENDPOINT, DEFAULT_ENDPOINT, 0, INFO_MESSAGE_CLUSTER, messageBuffer, getSizeOfInfoMessage(&im)); // and send it
                clearLed(SEND_MESSAGE_LED);                
                if (result != MODULE_SUCCESS)
                {
                    zigbeeNetworkStatus = NWK_OFFLINE;
                    printf("afSendData error %02X; restarting...\r\n", result);
                    delayMs(RESTART_DELAY_IF_MESSAGE_FAIL_MS);  //allow enough time for coordinator to fully restart, if that caused our problem
                    state = STATE_MODULE_STARTUP;
                } else {   
                    printf("Success\r\n");
                    state = STATE_IDLE;
                }
                break;   
            }
        default:     //should never happen
            {
                printf("UNKNOWN STATE\r\n");
                state = STATE_MODULE_STARTUP;
            }
            break;
        }
    } 
}
/** 
The main state machine for the application.
Never exits.
*/
void stateMachine()
{
 //   while (1)
  //  {
        if (zigbeeNetworkStatus == NWK_ONLINE)
        {
            if(moduleHasMessageWaiting())      //wait until SRDY goes low indicating a message has been received. 
                stateFlags |= STATE_FLAG_MESSAGE_WAITING;
        }
        
        switch (state)
        {
        case STATE_IDLE:
            {
                if (stateFlags & STATE_FLAG_MESSAGE_WAITING & coordinator_on)    // If there is a message waiting...
                {
                    parseMessages();                            // ... then display it
                    trackingStateMachine(current_router_index);
                    stateFlags &= ~STATE_FLAG_MESSAGE_WAITING;
                }
                
                if (stateFlags & STATE_FLAG_BUTTON_PRESSED)     // If ISR set this flag...
                {
                    if (debounceButton(ANY_BUTTON))             // ...then debounce it
                    {
                        processButtonPress();                   // ...and process it
                    }
                    if (debounceButtonHold(ANY_BUTTON))
                    {
                        processButtonHold();
                    }
                    stateFlags &= ~STATE_FLAG_BUTTON_PRESSED;
                }
                
                /* Other flags (for different messages or events) can be added here */
                break;
            }
            
        case STATE_MODULE_STARTUP:              // Start the Zigbee Module on the network
            {
#define MODULE_START_DELAY_IF_FAIL_MS 5000
                moduleResult_t result;
                struct moduleConfiguration defaultConfiguration = DEFAULT_MODULE_CONFIGURATION_COORDINATOR;
                
                /* Uncomment below to restrict the device to a specific PANID
                defaultConfiguration.panId = 0x1234;
                */
                
                /* Below is an example of how to restrict the device to only one channel:
                defaultConfiguration.channelMask = CHANNEL_MASK_17;
                printf("DEMO - USING CUSTOM CHANNEL 17\r\n");
                */
                
                while ((result = startModule(&defaultConfiguration, GENERIC_APPLICATION_CONFIGURATION)) != MODULE_SUCCESS)
                {
                    printf("FAILED. Error Code 0x%02X. Retrying...\r\n", result);
                    delayMs(MODULE_START_DELAY_IF_FAIL_MS);
                }
                //printf("Success\r\n");
                zigbeeNetworkStatus = NWK_ONLINE;
                
                state = STATE_DISPLAY_NETWORK_INFORMATION;
                break;
            }
        case STATE_DISPLAY_NETWORK_INFORMATION:
            {
                printf("~ni~");
                /* On network, display info about this network */
                displayNetworkConfigurationParameters();
                displayDeviceInformation();
                if (sysGpio(GPIO_SET_DIRECTION, ALL_GPIO_PINS) != MODULE_SUCCESS)   //Set module GPIOs as output
                {
                    printf("ERROR\r\n");
                }
                /*
                printf("Press button to change which received value is displayed on RGB LED. D6 & D5 will indicate mode:\r\n");
                printf("    None = None\r\n");
                printf("    Yellow (D9) = IR Temp Sensor\r\n");
                printf("    Red (D8) = Color Sensor\r\n");
                */
                printf("Displaying Messages Received\r\n");
                setModuleLeds(RGB_LED_DISPLAY_MODE_NONE);
                
                /* Now the network is running - wait for any received messages from the ZM */
#ifdef VERBOSE_MESSAGE_DISPLAY    
                printAfIncomingMsgHeaderNames();
#endif                
                state = STATE_IDLE;
                break;
            }
            
        default:     //should never happen
            {
                printf("UNKNOWN STATE\r\n");
                state = STATE_MODULE_STARTUP;
            }
            break;
        }
 //   } 
}    
/** 
The main state machine for the application.
Never exits.
*/
void stateMachine()
{
    while (1)
    {
        if (zigbeeNetworkStatus == NWK_ONLINE)
        {
            if(moduleHasMessageWaiting())      //wait until SRDY goes low indicating a message has been received. 
                stateFlags |= STATE_FLAG_MESSAGE_WAITING;
        }
        
        switch (state)
        {
        case STATE_IDLE:
            {
                if (stateFlags & STATE_FLAG_MESSAGE_WAITING)    // If there is a message waiting...
                {
                    parseMessages();                            // ... then display it
                    stateFlags &= ~STATE_FLAG_MESSAGE_WAITING;
                }
                
                if (stateFlags & STATE_FLAG_BUTTON_PRESSED)     // If ISR set this flag...
                {
                    state = STATE_BUTTON_PRESSED;
                    stateFlags &= ~STATE_FLAG_BUTTON_PRESSED;
                }                
                /* Other flags (for different messages or events) can be added here */
            }
            break;            
            
        case STATE_BUTTON_PRESSED:
            {
                rgbLedColor++;
                if (rgbLedColor > RGB_LED_COLOR_MAX)
                {
                    rgbLedColor = 0; 
                }
                printf("Setting Color to %s (%u)\r\n", getRgbLedColorName(rgbLedColor), rgbLedColor);
                switch (rgbLedColor)
                {
                case RGB_LED_COLOR_WHITE: red=RGB_LED_MAX; blue=RGB_LED_MAX; green=RGB_LED_MAX; break;
                case RGB_LED_COLOR_RED: red=RGB_LED_MAX; blue=0; green=0; break;
                case RGB_LED_COLOR_VIOLET: red=RGB_LED_MAX; blue=RGB_LED_MAX; green=0; break;
                case RGB_LED_COLOR_BLUE: red=0; blue=RGB_LED_MAX; green=0; break;        
                case RGB_LED_COLOR_CYAN: red=0; blue=RGB_LED_MAX; green=RGB_LED_MAX; break;
                case RGB_LED_COLOR_GREEN: red=0; blue=0; green=RGB_LED_MAX; break;
                case RGB_LED_COLOR_YELLOW: red=RGB_LED_MAX; blue=0; green=RGB_LED_MAX; break;
                default: red=RGB_LED_MAX; blue=RGB_LED_MAX; green=RGB_LED_MAX; break;
                }
                halRgbSetLeds(red, blue, green);
                state = STATE_IDLE;                
            }
            break;
            
        case STATE_MODULE_STARTUP:              // Start the Zigbee Module on the network
            {
#define MODULE_START_DELAY_IF_FAIL_MS 5000
                moduleResult_t result;
                struct moduleConfiguration defaultConfiguration = DEFAULT_MODULE_CONFIGURATION_COORDINATOR;
                
                /* Change this if you wish to use a custom PAN */
                defaultConfiguration.panId = ANY_PAN;
                
                /*Example of how to use a custom channel:
                printf("DEMO - USING CUSTOM CHANNEL 25\r\n");
                defaultConfiguration.channelMask = CHANNEL_MASK_25; */
                
                /* Change this below to be your operating region - MODULE_REGION_NORTH_AMERICA or MODULE_REGION_EUROPE */
#define OPERATING_REGION    (MODULE_REGION_NORTH_AMERICA) // or MODULE_REGION_EUROPE
                
                while ((result = expressStartModule(&defaultConfiguration, GENERIC_APPLICATION_CONFIGURATION, OPERATING_REGION)) != MODULE_SUCCESS)
                {
                    SET_NETWORK_FAILURE_LED_ON();          // Turn on the LED to show failure
                    printf("FAILED. Error Code 0x%02X. Retrying...\r\n", result);
                    delayMs(MODULE_START_DELAY_IF_FAIL_MS/2);                    
                    SET_NETWORK_FAILURE_LED_OFF();
                    delayMs(MODULE_START_DELAY_IF_FAIL_MS/2);
                }                
                INIT_BOOSTER_PACK_LEDS();                
                SET_NETWORK_LED_ON();
                SET_NETWORK_FAILURE_LED_OFF();
                halRgbSetLeds(RGB_LED_MAX, RGB_LED_MAX, RGB_LED_MAX);
                printf("Module Start Complete\r\n"); 
                SET_NETWORK_STATUS_ONLINE();
                
                state = STATE_DISPLAY_NETWORK_INFORMATION;
            }
            break;            
            
        case STATE_DISPLAY_NETWORK_INFORMATION:
            {
                printf("~ni~");
                /* On network, display info about this network */
                displayNetworkConfigurationParameters();
                displayDeviceInformation();
                
                printf("Press button to change color configuration\r\n");                
                printf("Displaying Messages Received\r\n");
                
                /* Now the network is running - wait for any received messages from the ZM */
#ifdef VERBOSE_MESSAGE_DISPLAY    
                printAfIncomingMsgHeaderNames();
#endif                
                state = STATE_IDLE;
            }
            break;            
            
        default:     //should never happen
            {
                printf("UNKNOWN STATE\r\n");
                state = STATE_MODULE_STARTUP;
            }
            break;
        }
    } 
}    
static void stateMachine()
{
    while (1)
    {
        if (zigbeeNetworkStatus == NWK_ONLINE)
        {
            if(moduleHasMessageWaiting())      //wait until SRDY goes low indicating a message has been received.
            {
                getMessage();                 
                displayMessage();          
            }   
        }
        
        switch (state)
        {
        case STATE_IDLE:
            {
                /* process command line commands only if not doing anything else: */
                if (command != NO_CHARACTER_RECEIVED)
                {
                    /* parse the command entered, and go to the required state */
                    state = processCommand(command);                    
                    command = NO_CHARACTER_RECEIVED;
                }
                /* note: other flags (for different messages or events) can be added here */
                break;
            }
        case STATE_INIT:
            {
                printf("Starting State Machine\r\n");
                state = STATE_GET_DEVICE_TYPE;
                break;
            }
            /* A button press during startup will cause the application to prompt for device type */
        case STATE_GET_DEVICE_TYPE: 
            {
            set_type:                
                while (command == NO_CHARACTER_RECEIVED)
                {
                    printf("Setting Device Type: Press C for Coordinator, R for Router, or E for End Device.\r\n");
#define DEVICE_TYPE_DELAY_MS    2000
#define DEVICE_TYPE_DELAY_PER_CYCLE_MS  100
                    uint16_t delayCycles = DEVICE_TYPE_DELAY_MS / DEVICE_TYPE_DELAY_PER_CYCLE_MS;
                    while ((command == NO_CHARACTER_RECEIVED) && (delayCycles--) > 0)
                        delayMs(DEVICE_TYPE_DELAY_PER_CYCLE_MS);
                }
                
                switch (command)
                {
                case 'C':
                case 'c':
                    printf("Coordinator it is...\r\n");
                    zigbeeDeviceType = COORDINATOR;
                    break;
                case 'R':
                case 'r':
                    printf("Router it is...\r\n");
                    zigbeeDeviceType = ROUTER;
                    break;
                    
                case 'E':
                case 'e':
                    printf("End Device it is...\r\n");
                    zigbeeDeviceType = END_DEVICE;
                    break;
                default:
                    command = NO_CHARACTER_RECEIVED;
                    goto set_type;
                    
                }
                command = NO_CHARACTER_RECEIVED;
                state = STATE_MODULE_STARTUP;
                break;
            }
        case STATE_MODULE_STARTUP:
            {
#define MODULE_START_DELAY_IF_FAIL_MS 5000
                moduleResult_t result;
                /* Start with the default module configuration */
                struct moduleConfiguration defaultConfiguration = DEFAULT_MODULE_CONFIGURATION_COORDINATOR;
                /* Make any changes needed here (channel list, PAN ID, etc.)
                We Configure the Zigbee Device Type (Router, Coordinator, End Device) based on what user selected */
                defaultConfiguration.deviceType = zigbeeDeviceType;
                
                /* Change this below to be your operating region - MODULE_REGION_NORTH_AMERICA or MODULE_REGION_EUROPE */
#define OPERATING_REGION    (MODULE_REGION_NORTH_AMERICA) // or MODULE_REGION_EUROPE
                
                while ((result = expressStartModule(&defaultConfiguration, GENERIC_APPLICATION_CONFIGURATION, OPERATING_REGION)) != MODULE_SUCCESS)
                {
                    SET_NETWORK_FAILURE_LED_ON();          // Turn on the LED to show failure
                    handleModuleError(result);
                    printf("Retrying...\r\n");
                    delayMs(MODULE_START_DELAY_IF_FAIL_MS/2);                    
                    SET_NETWORK_FAILURE_LED_OFF();
                    delayMs(MODULE_START_DELAY_IF_FAIL_MS/2);
                }                
                printf("Success\r\n");
                state = STATE_DISPLAY_NETWORK_INFORMATION;
                zigbeeNetworkStatus = NWK_ONLINE;
                break;
            }
        case STATE_DISPLAY_NETWORK_INFORMATION:                 
            {
                printf("Module Information:\r\n");
                /* On network, display info about this network */
                displayNetworkConfigurationParameters();
                displayDeviceInformation();
                displayCommandLineInterfaceHelp();
                state = STATE_IDLE;   //startup is done!
                break;
            }
        case STATE_VALID_SHORT_ADDRESS_ENTERED:  //command line processor has a valid shortAddressEntered
            {
                state = pendingState;
                break;
            }
        case STATE_VALID_LONG_ADDRESS_ENTERED:
            {
                /* Flip byte order because we need to send it LSB first */
                int8_t temp[8];
                int i;
                for (i=0; i<8; i++)
                    temp[7-i] = longAddressEntered[i];
                
                memcpy(longAddressEntered, temp, 8);  //Store LSB first since that is how it will be sent:
                state = pendingState;
                break;
            }
        case STATE_SEND_MESSAGE_VIA_SHORT_ADDRESS:
            {
                printf("Send to 0x%04X\r\n", shortAddressEntered);
                moduleResult_t result = afSendData(DEFAULT_ENDPOINT,DEFAULT_ENDPOINT,shortAddressEntered, TEST_CLUSTER, testMessage, 5);
                if (result == MODULE_SUCCESS)
                {
                    printf("Success\r\n");
                } else {
                    handleModuleError(result);                    
#ifdef RESTART_AFTER_ZM_FAILURE
                    printf("\r\nRestarting\r\n");
                    state = STATE_MODULE_STARTUP;
                    continue;
#endif
                }
                state = STATE_IDLE;
                break;
            }
        case STATE_SEND_MESSAGE_VIA_LONG_ADDRESS:
            {
                printf("Send to (LSB first)");
                printHexBytes(longAddressEntered, 8);
                moduleResult_t result = afSendDataExtended(DEFAULT_ENDPOINT, DEFAULT_ENDPOINT, longAddressEntered,
                                                           DESTINATION_ADDRESS_MODE_LONG, TEST_CLUSTER, testMessage, 5);
                if (result == MODULE_SUCCESS)
                {
                    printf("Success\r\n");
                } else {
                    handleModuleError(result);
#ifdef RESTART_AFTER_ZM_FAILURE
                    printf("\r\nRestarting\r\n");
                    state = STATE_MODULE_STARTUP;
                    continue;
#endif
                }
                state = STATE_IDLE;
                break;
            }
            
#ifdef LEAVE_REQUEST            
        case STATE_MANAGEMENT_LEAVE_REQUEST:
            {
                printf("Sending Leave Request for MAC (LSB first)");
                printHexBytes(longAddressEntered, 8);
                moduleResult_t result = zdoManagementLeaveRequest(longAddressEntered, 0);
                
                if (result == MODULE_SUCCESS)
                {
                    printf("Success\r\n");
                } else {
                    handleModuleError(result);
                }
                state = STATE_IDLE;
                break;
            }
#endif
            
        case STATE_FIND_VIA_SHORT_ADDRESS:
            {
                printf("Looking for that device...\r\n");
                moduleResult_t result = zdoRequestIeeeAddress(shortAddressEntered, INCLUDE_ASSOCIATED_DEVICES, 0);
                if (result == MODULE_SUCCESS)
                {
#ifndef ZDO_NWK_ADDR_RSP_HANDLED_BY_APPLICATION
                    displayZdoAddressResponse(zmBuf + SRSP_PAYLOAD_START);
#endif
                } else {
                    handleModuleError(result);
                }
                state = STATE_IDLE;
                break;
            }
            
        case STATE_FIND_VIA_LONG_ADDRESS:
            {
                printf("Looking for that device...\r\n");
                moduleResult_t result = zdoNetworkAddressRequest(longAddressEntered, INCLUDE_ASSOCIATED_DEVICES, 0);
                if (result == MODULE_SUCCESS)
                {
#ifndef ZDO_NWK_ADDR_RSP_HANDLED_BY_APPLICATION
                    displayZdoAddressResponse(zmBuf + SRSP_PAYLOAD_START);
#endif
                } else {
                    handleModuleError(result);
                }
                state = STATE_IDLE;
                break;
            }
            
#ifdef INCLUDE_PERMIT_JOIN        
        case STATE_SET_PERMIT_JOIN_ON:
            {
                printf("Turning joining ON...\r\n");
                moduleResult_t result = zdoManagementPermitJoinRequest(shortAddressEntered, PERMIT_JOIN_ON_INDEFINITELY, 0);
                if (result == MODULE_SUCCESS)
                {
                    printf("Success\r\n");
                } else {
                    handleModuleError(result);
                }
                state = STATE_IDLE;
                break; 
            }
            
        case STATE_SET_PERMIT_JOIN_OFF:
            {
                printf("Turning joining OFF...\r\n");
                moduleResult_t result = zdoManagementPermitJoinRequest(shortAddressEntered, PERMIT_JOIN_OFF, 0);
                if (result == MODULE_SUCCESS)
                {
                    printf("Success\r\n");
                } else {
                    handleModuleError(result);
                }
                state = STATE_IDLE;
                break; 
            }   
#endif
            
#ifdef DISCOVER_NETWORKS             
        case STATE_NETWORK_DISCOVERY_REQUEST:
            {
                printf("Scanning...\r\n");
                moduleResult_t result = zdoNetworkDiscoveryRequest(ANY_CHANNEL_MASK, BEACON_ORDER_480_MSEC);
                if (result == MODULE_SUCCESS)
                {
                    printf("Success\r\n");
                } else {
                    handleModuleError(result);
                }
                state = STATE_IDLE;
                break; 
            }
#endif
            
#ifdef INCLUDE_NETWORK_TOPOLOGY
        case STATE_GET_NETWORK_TOPOLOGY:
            {
                printf("Displaying NWK Topology...........\r\n");                
                initSet(&searchedSet);
                // Start the recursive search for all children of the short address
                //removeAllFromSet();
                int8_t numChildren = displayChildren(shortAddressEntered);
                state = STATE_IDLE;
                break;
            }
#endif
            
        default:     //should never happen
            {
                printf("UNKNOWN STATE (%u)\r\n", state);
                state = STATE_IDLE;
            }
            break;
        }
    }
}