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;
        }
    } 
}
/** Process characters typed in by the user. Normally this will fire off a menu command, unless
we are awaiting the user to enter a two-byte (four ascii character) short address or eight byte
(16 ascii character) long address.
@note: processCommand modifies variables shortAddressEntered and longAddressEntered
 @return the state to transition to next
 */
enum STATE processCommand(char cmd)
{
#define ESCAPE_KEY 0x1B
    if (cmd == ESCAPE_KEY)
    {
        printf("Resetting Command Line Interpreter\r\n");
        commandLineInterfaceMode = CLI_MODE_NORMAL;
        cliInputBufferIndex = 0;
        pendingState = STATE_IDLE;
        displayCommandLineInterfaceHelp();
        return STATE_IDLE;
    }

    if (cmd == '\r')
    {
        printf("\r\n");
        return STATE_IDLE;
    }

    if (commandLineInterfaceMode == CLI_MODE_NORMAL)
    {
        switch (cmd)
        {
        case '?':
            displayCommandLineInterfaceHelp();
            return STATE_IDLE;
        case 'n':
        case 'N':
            return STATE_DISPLAY_NETWORK_INFORMATION;
        case 'r':
        case 'R':
            return STATE_INIT;
        case 'S':
        case 's':
        {
            printf("Enter short address of destination, for example '2F6B' or Escape key to exit\r\n");
            commandLineInterfaceMode = CLI_MODE_ENTER_SHORT_ADDRESS;    // Next, get a short address typed by the user
            pendingState = STATE_SEND_MESSAGE_VIA_SHORT_ADDRESS;  // After a full short address has been entered
            return STATE_IDLE;
        }
        case 'L':
        case 'l':
        {
            printf("Enter long (MAC) address of destination, for example '00124B0012345678' or Escape key to exit\r\n");
            commandLineInterfaceMode = CLI_MODE_ENTER_LONG_ADDRESS;
            pendingState = STATE_SEND_MESSAGE_VIA_LONG_ADDRESS;  //when a full long address has been entered
            return STATE_IDLE;
        }
        case 'h':
        case 'H':
        {
            printf("Enter two byte short address to find, for example '2F6B' or press Escape key to exit\r\n");
            commandLineInterfaceMode = CLI_MODE_ENTER_SHORT_ADDRESS;
            pendingState = STATE_FIND_VIA_SHORT_ADDRESS;  //when a full short address has been entered
            return STATE_IDLE;
        }
        case 'j':
        case 'J':
        {
            printf("Enter eight byte long (MAC) address to find, for example '00124B0012345678' or press Escape key to exit\r\n");
            commandLineInterfaceMode = CLI_MODE_ENTER_LONG_ADDRESS;
            pendingState = STATE_FIND_VIA_LONG_ADDRESS;  //when a full long address has been entered
            return STATE_IDLE;
        }
        case 'v':
        case 'V':
        {
            printf("Module Version Information:\r\n");
            if (sysVersion() == MODULE_SUCCESS)                  //gets the version string
            {
                displaySysVersion();  // Display the contents of the received SYS_VERSION
            } else {
                printf("ERROR\r\n");
            }
            return STATE_IDLE;
        }

        /* Note: more commands can be added here */

        default:
            printf("Unknown command %c\r\n", cmd);
        }
        return STATE_IDLE;

    } else if (commandLineInterfaceMode == CLI_MODE_ENTER_SHORT_ADDRESS)    //accepts two hex numbers (4 ASCII characters)
    {
        if (IS_VALID_HEXADECIMAL_CHARACTER(cmd))
        {
            TO_UPPER_CASE(cmd);
            printf("%c", cmd);  //echo output
            cliInputBuffer[cliInputBufferIndex++] = (char) cmd;
            if (cliInputBufferIndex == 4)  
            {
                cliInputBuffer[4] = 0; //null terminate it so we can treat it as a string
                //now attempt to convert it:
                long val = 0;
                errno = 0;      // used in stdlib.h
                val = strtol(cliInputBuffer, NULL, 16);    // Interpret the string as a hex number
                if (errno != 0) // Should have already been error checked, but validate anyway
                {
                    printf("strtol parse error\r\n");
                } else { //no errors
                    shortAddressEntered = (uint16_t) val;
                    printf("Short Address = 0x%04X\r\n", shortAddressEntered);
                    //we're all done, so clear out buffers:
                    commandLineInterfaceMode = CLI_MODE_NORMAL;
                    cliInputBufferIndex = 0;
                    return STATE_VALID_SHORT_ADDRESS_ENTERED;
                }
                commandLineInterfaceMode = CLI_MODE_NORMAL;
                cliInputBufferIndex = 0;
                return STATE_IDLE;
            }
            /* Continue, since our buffer isn't full yet - leave settings alone */

        } else {
            /* not a hex number! */
            printf("\r\nNumber must be in hex: 0..9 or a..f inclusive\r\nAborting\r\n");
            displayCommandLineInterfaceHelp();
            commandLineInterfaceMode = CLI_MODE_NORMAL;
            cliInputBufferIndex = 0;
        }
        return STATE_IDLE;

    } else if (commandLineInterfaceMode == CLI_MODE_ENTER_LONG_ADDRESS)  //accepts eight hex numbers (16 ASCII characters)
    {

        if (IS_VALID_HEXADECIMAL_CHARACTER(cmd))
        {
            TO_UPPER_CASE(cmd);
            printf("%c", cmd);  //echo output

            cliInputBuffer[cliInputBufferIndex++] = (char) cmd;

            /* To used a tokenized substring splitter method, add a '-' at the end of each 2 characters. */
            if ((cliInputBufferIndex != 0) && ((cliInputBufferIndex+1) % 3 == 0) && (cliInputBufferIndex != 23))
            {
                cliInputBuffer[cliInputBufferIndex++] = '-';
                printf("-");
            }

            if (cliInputBufferIndex == 23)
            {
                printf("\r\nParsed '%s' into:", cliInputBuffer);

                /* now attempt to convert it: */
                char *substr = NULL;
                substr = strtok(cliInputBuffer,"-");    // Initialize string splitter

                /* Loops until there are no more substrings*/
                uint8_t parsedMacIndex = 0;
                while(substr!=NULL)
                {
                    /* Process the substring */
                    long val = 0;
                    /* errno is used in stdlib.h to indicate a parse error */
                    errno = 0;     
                    val = strtol(substr, NULL, 16);    // Interpret the string as a hex number
                    if (errno != 0) // Should have already been error checked, but validate anyway
                    {
                        printf("strtol parse error\r\n");
                        commandLineInterfaceMode = CLI_MODE_NORMAL;
                        cliInputBufferIndex = 0;
                        return STATE_IDLE;

                    } else { //no errors
                        longAddressEntered[parsedMacIndex] = (uint16_t) val;
                        printf("%02X ", longAddressEntered[parsedMacIndex]);
                    }
                    parsedMacIndex++;

                    substr = strtok(NULL,"-");  //Get the next substring
                }
                printf("\r\n");

                /* Now we have the mac address */
                if (!((longAddressEntered[0] == 0x00) &&
                        (longAddressEntered[1] == 0x12) &&
                        (longAddressEntered[2] == 0x4b)))
                    printf("Warning - MAC does not have 00-12-4B as first three bytes!\r\n");
                commandLineInterfaceMode = CLI_MODE_NORMAL;
                cliInputBufferIndex = 0;
                return STATE_VALID_LONG_ADDRESS_ENTERED;
            }

            /* continue, since our buffer isn't full yet - leave settings alone */
        } else {  //not a hex number!
            printf("Number must be in hex: 0..9 or a..f inclusive\r\nAborting\r\n");
            displayCommandLineInterfaceHelp();
            commandLineInterfaceMode = CLI_MODE_NORMAL;
            cliInputBufferIndex = 0;
        }  

        return STATE_IDLE;
    }

    return STATE_IDLE;
}
示例#3
0
void sendcmd(unsigned char * req, unsigned char cmdtype){
	switch (cmdtype)
	{
	case 0:
		sysPing();
		break;
	case 1:
		sysSetExtAddr((SetExtAddrFormat_t*) req);
		break;
	case 2:
		sysGetExtAddr();
		break;
	case 3:
		sysRamRead((RamReadFormat_t*) req);
		break;
	case 4:
		sysRamWrite((RamWriteFormat_t*) req);
		break;
	case 5:
		sysResetReq((ResetReqFormat_t*) req);
		break;
	case 6:
		sysVersion();
		break;
	case 7:
		sysOsalNvRead((OsalNvReadFormat_t*) req);
		break;
	case 8:
		sysOsalNvWrite((OsalNvWriteFormat_t*) req);
		break;
	case 9:
		sysOsalNvItemInit((OsalNvItemInitFormat_t*) req);
		break;
	case 10:
		sysOsalNvDelete((OsalNvDeleteFormat_t*) req);
		break;
	case 11:
		sysOsalNvLength((OsalNvLengthFormat_t*) req);
		break;
	case 12:
		sysOsalStartTimer((OsalStartTimerFormat_t*) req);
		break;
	case 13:
		sysOsalStopTimer((OsalStopTimerFormat_t*) req);
		break;
	case 14:
		sysStackTune((StackTuneFormat_t*) req);
		break;
	case 15:
		sysAdcRead((AdcReadFormat_t*) req);
		break;
	case 16:
		sysGpio((GpioFormat_t*) req);
		break;
	case 17:
		sysRandom();
		break;
	case 18:
		sysSetTime((SetTimeFormat_t*) req);
		break;
	case 19:
		sysGetTime();
		break;
	case 20:
		sysSetTxPower((SetTxPowerFormat_t*) req);
		break;
	case 21:
		afRegister((RegisterFormat_t*) req);
		break;
	case 22:
		afDataRequest((DataRequestFormat_t*) req);
		break;
	case 23:
		afDataRequestExt((DataRequestExtFormat_t*) req);
		break;
	case 24:
		afDataRequestSrcRtg((DataRequestSrcRtgFormat_t*) req);
		break;
	case 25:
		afInterPanCtl((InterPanCtlFormat_t*) req);
		break;
	case 26:
		afDataStore((DataStoreFormat_t*) req);
		break;
	case 27:
		afDataRetrieve((DataRetrieveFormat_t*) req);
		break;
	case 28:
		afApsfConfigSet((ApsfConfigSetFormat_t*) req);
		break;
	case 29:
		zdoNwkAddrReq((NwkAddrReqFormat_t*) req);
		break;
	case 30:
		zdoIeeeAddrReq((IeeeAddrReqFormat_t*) req);
		break;
	case 31:
		zdoNodeDescReq((NodeDescReqFormat_t*) req);
		break;
	case 32:
		zdoPowerDescReq((PowerDescReqFormat_t*) req);
		break;
	case 33:
		zdoSimpleDescReq((SimpleDescReqFormat_t*) req);
		break;
	case 34:
		zdoActiveEpReq((ActiveEpReqFormat_t*) req);
		break;
	case 35:
		zdoMatchDescReq((MatchDescReqFormat_t*) req);
		break;
	case 36:
		zdoComplexDescReq((ComplexDescReqFormat_t*) req);
		break;
	case 37:
		zdoUserDescReq((UserDescReqFormat_t*) req);
		break;
	case 38:
		zdoDeviceAnnce((DeviceAnnceFormat_t*) req);
		break;
	case 39:
		zdoUserDescSet((UserDescSetFormat_t*) req);
		break;
	case 40:
		zdoServerDiscReq((ServerDiscReqFormat_t*) req);
		break;
	case 41:
		zdoEndDeviceBindReq((EndDeviceBindReqFormat_t*) req);
		break;
	case 42:
		zdoBindReq((BindReqFormat_t*) req);
		break;
	case 43:
		zdoUnbindReq((UnbindReqFormat_t*) req);
		break;
	case 44:
		zdoMgmtNwkDiscReq((MgmtNwkDiscReqFormat_t*) req);
		break;
	case 45:
		zdoMgmtLqiReq((MgmtLqiReqFormat_t*) req);
		break;
	case 46:
		zdoMgmtRtgReq((MgmtRtgReqFormat_t*) req);
		break;
	case 47:
		zdoMgmtBindReq((MgmtBindReqFormat_t*) req);
		break;
	case 48:
		zdoMgmtLeaveReq((MgmtLeaveReqFormat_t*) req);
		break;
	case 49:
		zdoMgmtDirectJoinReq((MgmtDirectJoinReqFormat_t*) req);
		break;
	case 50:
		zdoMgmtPermitJoinReq((MgmtPermitJoinReqFormat_t*) req);
		break;
	case 51:
		zdoMgmtNwkUpdateReq((MgmtNwkUpdateReqFormat_t*) req);
		break;
	case 52:
		zdoStartupFromApp((StartupFromAppFormat_t*) req);
		break;
	case 53:
		zdoAutoFindDestination((AutoFindDestinationFormat_t*) req);
		break;
	case 54:
		zdoSetLinkKey((SetLinkKeyFormat_t*) req);
		break;
	case 55:
		zdoRemoveLinkKey((RemoveLinkKeyFormat_t*) req);
		break;
	case 56:
		zdoGetLinkKey((GetLinkKeyFormat_t*) req);
		break;
	case 57:
		zdoNwkDiscoveryReq((NwkDiscoveryReqFormat_t*) req);
		break;
	case 58:
		zdoJoinReq((JoinReqFormat_t*) req);
		break;
	case 59:
		zdoMsgCbRegister((MsgCbRegisterFormat_t*) req);
		break;
	case 60:
		zdoMsgCbRemove((MsgCbRemoveFormat_t*) req);
		break;
	case 61:
		zbSystemReset();
		break;
	case 62:
		zbAppRegisterReq((AppRegisterReqFormat_t*) req);
		break;
	case 63:
		zbStartReq();
		break;
	case 64:
		zbPermitJoiningReq((PermitJoiningReqFormat_t*) req);
		break;
	case 65:
		zbBindDevice((BindDeviceFormat_t*) req);
		break;
	case 66:
		zbAllowBind((AllowBindFormat_t*) req);
		break;
	case 67:
		zbSendDataReq((SendDataReqFormat_t*) req);
		break;
	case 68:
		zbFindDeviceReq((FindDeviceReqFormat_t*) req);
		break;
	case 69:
		zbWriteConfiguration((WriteConfigurationFormat_t*) req);
		break;
	case 70:
		zbGetDeviceInfo((GetDeviceInfoFormat_t*) req);
		break;
	case 71:
		zbReadConfiguration((ReadConfigurationFormat_t*) req);
		break;

	}

}