Example #1
0
File: main.c Project: oter/BSPTools
//*****************************************************************************
//
//! \brief     Starts Smart Configuration
//!
//! \param    none
//!
//! \return void
//! \note
//! \warning
//*****************************************************************************
void SmartConfigTask(void* pValue)
{
    long lRetVal = -1;
    DispatcherUartSendPacket((char*)pucUARTSmartConfigString, 
                             sizeof(pucUARTSmartConfigString));
    
    //Turn off the Network Status LED
    GPIO_IF_LedOff(MCU_IP_ALLOC_IND);
    
    LedTimerConfigNStart();
    
    //Reset the Network Status before Entering Smart Config
    Network_IF_UnsetMCUMachineState(STATUS_BIT_CONNECTION);
    Network_IF_UnsetMCUMachineState(STATUS_BIT_IP_AQUIRED);
    
    lRetVal = SmartConfigConnect();
    if(lRetVal < 0)
    {
        ERR_PRINT(lRetVal);
        LOOP_FOREVER();
    }
    //
    // Wait until IP is acquired
    //
    while (!(IS_CONNECTED(Network_IF_CurrentMCUState())) ||
           !(IS_IP_ACQUIRED(Network_IF_CurrentMCUState())));
    
    LedTimerDeinitStop();
    
    // Red LED on
    GPIO_IF_LedOn(MCU_IP_ALLOC_IND);
    
    //Enable GPIO Interrupt
    Button_IF_EnableInterrupt(SW2);
}
Example #2
0
File: main.c Project: oter/BSPTools
//*****************************************************************************
//
//!  \brief     Generates Random Message and Sends Email to the preconfigured
//!             Recipient Email Id
//!
//!  \param    pValue        -    pointer to Input Data
//!
//!  \return void
//!  \note
//!  \warning
//*****************************************************************************
void PushButtonMailSend(void* pValue)
{
    int iIndex;
    long lRetVal = -1;
    // reset Orange LED
    GPIO_IF_LedOff(MCU_SENDING_DATA_IND);

    if(!IS_CONNECTED(Network_IF_CurrentMCUState()))
    {
        LedTimerConfigNStart();
        lRetVal = Network_IF_ConnectAP(SSID_NAME,SecurityParams);
        if(lRetVal < 0)
        {
           UART_PRINT("Error: %d Connecting to an AP.\n\r",lRetVal);
           return;
        }
            
    }

    //
    // Disable the LED blinking Timer as Device is connected to AP
    //
    LedTimerDeinitStop();
    //
    // Switch ON RED LED to indicate that Device acquired an IP
    //
    GPIO_IF_LedOn(MCU_IP_ALLOC_IND);
    MAP_UtilsDelay(10000);

    GenerateRandomMessage();
    
    g_cConnectStatus = sl_NetAppEmailConnect();
    // If return -1, throw connect error
    if(g_cConnectStatus == -1)
    {
        DispatcherUartSendPacket((char*)pucUARTErrorSocketCreateString, \
                                 sizeof(pucUARTErrorSocketCreateString));
    }
    // If return -2, throw socket option error
    if(g_cConnectStatus == -2)
    {
        DispatcherUartSendPacket((char*)pucUARTErrorSocketOptionString, \
                                 sizeof(pucUARTErrorSocketOptionString));
    }
    if(g_cConnectStatus == 0)
    {
        SlNetAppServerError_t sEmailErrorInfo;
        long lRetCode = SL_EMAIL_ERROR_FAILED;
        if((lRetCode = sl_NetAppEmailSend(pcEmailto,pcEmailsubject,\
                                     pcEmailmessage, \
                                     &sEmailErrorInfo)) == SL_EMAIL_ERROR_NONE)
        {
            // Blink LED7 to indicate email has been sent
            for(iIndex=0 ;iIndex<5 ;iIndex++)
            { 
                MAP_UtilsDelay(6000000);
                GPIO_IF_LedOff(MCU_SENDING_DATA_IND);
                MAP_UtilsDelay(6000000);
                GPIO_IF_LedOn(MCU_SENDING_DATA_IND);
            }
            DispatcherUartSendPacket((char*)putUARTFinishString, \
                                     sizeof(putUARTFinishString));
        }
        else
        {
            lRetVal = EmailHandleERROR(lRetCode,(char*)sEmailErrorInfo.Value);
        }
        UART_PRINT("Cmd#");
    }      

    //Enable GPIO Interrupt
    Button_IF_EnableInterrupt(SW3);
    return;
}
Example #3
0
File: main.c Project: oter/BSPTools
//*****************************************************************************
//
//! UARTCommandHandler
//!
//!     @brief  The function handles commands arrived from CLI
//!
//!     @param  usBuffer is the receive buffer from the UART interface to PC
//!
//!     @return 0 on success or error code on failure
//!
//
//*****************************************************************************
long UARTCommandHandler(char *usBuffer)
{
    int iIndex = 0;
    int iParamcount = 0;
    long lRetVal = -1;
    signed char cStatus1 = 0;
    signed char cStatus2 = 0;

    if(usBuffer == NULL)
    {
        UART_PRINT("Null pointer\r\n");
        return -1;
    }

    switch(usBuffer[1])
    {
        //**********************************************
        // Case 01: Connect to default AP
        //**********************************************
        case UART_COMMAND_SIMPLE_CONFIG_START:

            if(!IS_CONNECTED(Network_IF_CurrentMCUState()))
            {
                LedTimerConfigNStart();

                // Setting Acess Point's security parameters
                SecurityParams.Key = (signed char *)SECURITY_KEY;
                SecurityParams.KeyLen = strlen(SECURITY_KEY);
                SecurityParams.Type = SECURITY_TYPE;

                lRetVal = Network_IF_ConnectAP(SSID_NAME,SecurityParams);
                if(lRetVal < 0)
                {
                    UART_PRINT("Error: %d Connecting to an AP.", lRetVal);
                    return lRetVal;
                }
            }

            //
            // Disable the LED blinking Timer as Device is connected to AP
            //
            LedTimerDeinitStop();
            
            //
            // Switch ON RED LED to indicate that Device acquired an IP
            //
            GPIO_IF_LedOn(MCU_IP_ALLOC_IND);
            DispatcherUartSendPacket((char*)pucUARTOKString, 
                                     sizeof(pucUARTOKString));
            break;
                
    //**********************************************
    // Case 02: Configure sender (source) email
    //**********************************************
        // TODO Phase 2: Include
        /*
    case UART_COMMAND_EMAIL_SOURCE:
          
        memset(serveruser,0,sizeof(serveruser));
                memset(pcServerpass,0,sizeof(pcServerpass));
        pcOfserveruser = &serveruser[0];
                ofpcServerpass = &pcServerpass[0];
                // '<' To maintain RFC 2821 format
                *pcOfserveruser++= '<';
                
        iIndex = 2;
        while ((int)usBuffer[iIndex] != 0x0D)
        {

            //look for comma ',' for separation of params
            if((int)usBuffer[iIndex] == 44)
                        {
                iParamcount++;
            }
            else
                        {
                if(iParamcount==1)
                                {
                                    //Enter smtp server username (email address)
                                    *pcOfserveruser++ = usBuffer[iIndex];

                }
                if(iParamcount==2)
                                {
                                    //Enter username's password
                                    *ofpcServerpass++ = usBuffer[iIndex];
                                }
                        }
            iIndex++;
        }
                // '>' To maintain RFC 2821 format
                *pcOfserveruser++= '>';
        *pcOfserveruser++= '\0';
        *ofpcServerpass++= '\0';
        
        //Set variables in smtp.c
        cStatus1 = smtpSetVariable(serveruser, USERNAME_VAR);
        cStatus2 = smtpSetVariable(pcServerpass, PASSWORD_VAR);
                //If error in return
        if(cStatus1 == 0 && cStatus2 == 0)
        {
                    DispatcherUartSendPacket((char*)pucUARTOKString, sizeof(pucUARTOKString));
        }
                else
                {
                    DispatcherUartSendPacket((char*)putUARTErrorInputString, \
                                        sizeof(putUARTErrorInputString));  
                }
        break;
                */
    //**********************************************
    // Case 03: Configure sender (source) email
    //**********************************************
        case UART_COMMAND_EMAIL_HEADER:
          
            memset(pcEmailto,0,sizeof(pcEmailto));
            pcOfemailto = &pcEmailto[0];
            pcOfemailsubject = &pcEmailsubject[0];
            // '<' To maintain RFC 2821 format
            *pcOfemailto++= '<';
            iIndex = 2;
            while ((int)usBuffer[iIndex] != 0x0D && usBuffer[iIndex] != '\0')
            {
                //look for comma ',' for separation of params
                if((int)usBuffer[iIndex] == 44)
                {
                    iParamcount++;
                }
                else
                {
                    if(iParamcount==1)
                    {
                        //Enter destination email address
                        *pcOfemailto++ = usBuffer[iIndex];

                    }
                    if(iParamcount==2)
                    {
                        //Enter email subject
                        *pcOfemailsubject++ = usBuffer[iIndex];
                    }
                }
                iIndex++;
            }
            
            // '>' To maintain RFC 2821 format
            *pcOfemailto++= '>';
            *pcOfemailto++= '\0';
            *pcOfemailsubject= '\0';

            SlNetAppDestination_t destEmailAdd;
            memcpy(destEmailAdd.Email,pcEmailto,strlen(pcEmailto)+1);
            cStatus1 = sl_NetAppEmailSet(SL_NET_APP_EMAIL_ID,NETAPP_DEST_EMAIL, \
                                         strlen(pcEmailto)+1, \
                                         (unsigned char *)&destEmailAdd);

            SlNetAppEmailSubject_t emailSubject;
            memcpy(emailSubject.Value,pcEmailsubject,strlen(pcEmailsubject)+1);
            cStatus2 = sl_NetAppEmailSet(SL_NET_APP_EMAIL_ID,NETAPP_SUBJECT, \
                                         strlen(pcEmailsubject)+1, \
                                         (unsigned char *)&emailSubject);
            
            // Check for Error in setting the variables
            if(cStatus1 == 0 && cStatus2 == 0)
            {
                DispatcherUartSendPacket((char*)pucUARTOKString, \
                                         sizeof(pucUARTOKString));
            }
            else
            {
                DispatcherUartSendPacket((char*)putUARTErrorInputString, \
                                         sizeof(putUARTErrorInputString));  
            }
            break;
                
        //**********************************************
        // Case 04: Record email message
        //**********************************************
        case UART_COMMAND_EMAIL_MESSAGE:

            pcOfemailmessage = &pcEmailmessage[0];

            //Enter "Message"
            iIndex =3;
            while ((int)usBuffer[iIndex] != 0x0D && usBuffer[iIndex] != '\0')
            {
                if((int)usBuffer[iIndex] == 62)
                {
                    iParamcount++;
                }
                else
                {
                    if(iParamcount==0)
                    {
                        *pcOfemailmessage++ = usBuffer[iIndex];
                    }
                }
                iIndex++;
            }
            *pcOfemailmessage= '\0';
            /* TODO here unsigned char is converting to char */
            DispatcherUartSendPacket((char*)pucUARTOKString, \
                                     sizeof(pucUARTOKString));

            break; 
        //**********************************************
        // Case 05: Send email message using configurations
        //**********************************************
        case UART_COMMAND_EMAIL_SEND:
        {

            // reset Orange LED state
            GPIO_IF_LedOff(MCU_SENDING_DATA_IND);
            // TODO: If no destination email given, default to hardcoded value
            SlNetAppEmailOpt_t eMailServerSetting;

            lRetVal = Network_IF_GetHostIP(GMAIL_HOST_NAME, &eMailServerSetting.Ip);
            if(lRetVal >= 0)
            {
                eMailServerSetting.Family = AF_INET;
                eMailServerSetting.Port = GMAIL_HOST_PORT;
                eMailServerSetting.SecurityMethod = SL_SO_SEC_METHOD_SSLV3;
                eMailServerSetting.SecurityCypher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_MD5;
                lRetVal = sl_NetAppEmailSet(SL_NET_APP_EMAIL_ID, \
                                        NETAPP_ADVANCED_OPT, \
                                        sizeof(SlNetAppEmailOpt_t), \
                                        (unsigned char*)&eMailServerSetting);
                ASSERT_ON_ERROR(lRetVal);
            }
            else
            {
                UART_PRINT("Error:%d GetHostIP.", lRetVal);
                return -1;
            }
            g_cConnectStatus = sl_NetAppEmailConnect();
            // If return -1, throw connect error
            if(g_cConnectStatus == -1)
            {
                DispatcherUartSendPacket((char*)pucUARTErrorSocketCreateString, \
                                         sizeof(pucUARTErrorSocketCreateString));
            }
            // If return -2, throw socket option error
            if(g_cConnectStatus == -2)
            {
                DispatcherUartSendPacket((char*)pucUARTErrorSocketOptionString, \
                                         sizeof(pucUARTErrorSocketOptionString));
            }

            if(g_cConnectStatus == 0)
            {
                SlNetAppServerError_t sEmailErrorInfo;
                long lRetCode = SL_EMAIL_ERROR_FAILED;
                if((lRetCode = sl_NetAppEmailSend(pcEmailto,pcEmailsubject, \
                                      pcEmailmessage, \
                                      &sEmailErrorInfo)) == SL_EMAIL_ERROR_NONE)
                {
                    // Blink LED7 to indicate email has been sent
                    for(iIndex=0 ;iIndex<5 ;iIndex++)
                    {
                          MAP_UtilsDelay(6000000);
                          GPIO_IF_LedOff(MCU_SENDING_DATA_IND);
                          MAP_UtilsDelay(6000000);
                          GPIO_IF_LedOn(MCU_SENDING_DATA_IND);

                    }
                    DispatcherUartSendPacket((char*)putUARTFinishString, \
                                             sizeof(putUARTFinishString));
                }
                else
                {
                    lRetVal = EmailHandleERROR(lRetCode,(char*)sEmailErrorInfo.Value);
                    ASSERT_ON_ERROR(lRetVal);
                }
            }
        }
        break;

        case UART_COMMAND_SMART_CONFIG:
            GPIO_IF_LedOff(MCU_IP_ALLOC_IND);
            DispatcherUartSendPacket((char*)pucUARTSmartConfigString, \
                                     sizeof(pucUARTSmartConfigString));
              
            // Start LED blinking Timer
            LedTimerConfigNStart();
            
            //Reset the Network Status before Entering Smart Config
            Network_IF_UnsetMCUMachineState(STATUS_BIT_CONNECTION);
            Network_IF_UnsetMCUMachineState(STATUS_BIT_IP_AQUIRED);
            
            // start smart config process
            lRetVal = SmartConfigConnect();
            ASSERT_ON_ERROR(lRetVal);
            while (!(IS_CONNECTED(Network_IF_CurrentMCUState())) || \
                   !(IS_IP_ACQUIRED(Network_IF_CurrentMCUState())))
            {
                MAP_UtilsDelay(100);
            }
            LedTimerDeinitStop();
            GPIO_IF_LedOn(MCU_IP_ALLOC_IND);
            break;
                      
        default:
            DispatcherUartSendPacket((char*)pucUARTErrorString, \
                                     sizeof(pucUARTErrorString));
            break;
  }

 return SUCCESS;
}
Example #4
0
//****************************************************************************
//
//! Task function implementing the TCP server and showcasing the  
//! deepsleep functionality
//!
//! \param none
//! 
//! This function  
//!    1. Creates a TCP socket and binds to it
//!    2. Listens on the socket
//!    3. Accepts a client connection
//!    4. Receives a packet on the socket
//!    5. Closes the socket
//!
//! \return None.
//
//****************************************************************************
void TCPServerTask(void *pvParameters)
{
    int iSocketDesc, iClientFD;
    struct sockaddr_in sClientAddr;
    int iRecvLen;
    unsigned int iClientAddrLen = sizeof(sClientAddr);
    unsigned char aucRecvBuffer[MAX_BUF];

    DisplayBanner(APPLICATION_NAME);

    DBG_PRINT("DEEPSLEEP: Test Begin\n\r");

    //
    // GPIO Configuration
    //
    GPIO_IF_LedConfigure(LED1|LED3);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);	

    //
    // Start the driver
    //
    Network_IF_InitDriver(ROLE_STA);

    GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);
    LedTimerConfigNStart();

    // Initialize AP security params
    SecurityParams.Key = SECURITY_KEY;
    SecurityParams.KeyLen = strlen(SECURITY_KEY);
    SecurityParams.Type = SECURITY_TYPE;

    //
    // Connect to the Access Point
    //
    Network_IF_ConnectAP(SSID_NAME,SecurityParams);

    LedTimerDeinitStop();

    //
    // Switch ON RED LED to indicate that Device acquired an IP
    //
    GPIO_IF_LedOn(MCU_IP_ALLOC_IND);

    //
    // Create and Bind TCP server socket
    //
    iSocketDesc = CreateTCPServerSocket(APP_TCP_PORT);
    if(iSocketDesc < 0)
    {
        DBG_PRINT("DEEPSLEEP: Socket create failed\n");
        goto end;
    }
    DBG_PRINT("DEEPSLEEP: Socket created\n\r");
    DBG_PRINT("DEEPSLEEP: Listening on Socket...\n\r");

    //
    // Start Listening on the socket
    //
    if( listen(iSocketDesc, 5) != 0)
    {
        DBG_PRINT("DEEPSLEEP: Listen failed\n\r");
        goto end;
    }

    while(FOREVER)
    {
        //
        // Accept new client connections (Here just one)
        //
        DBG_PRINT("DEEPSLEEP: Waiting for client.......\n\r");
        iClientFD = accept(iSocketDesc, 
                       (struct sockaddr*)&sClientAddr, 
                       &iClientAddrLen);
        DBG_PRINT("DEEPSLEEP: Connected to client [0x%x] \n\r", 
                           htonl(sClientAddr.sin_addr.s_addr));

        do
        {
            //
            // Receive on the socket
            //
            iRecvLen = recv(iClientFD,aucRecvBuffer,MAX_BUF,0);

            if(iRecvLen > 0)
            {
                DBG_PRINT("DEEPSLEEP: received %d bytes\n\r", iRecvLen);
                DBG_PRINT("DEEPSLEEP: received message : %s\n\r", aucRecvBuffer);
            }
        }while(iRecvLen > 0);

        //
        // Close the client descriptor
        //
        close(iClientFD);
    }

    //
    // Close the socket. Commented as not expected to reach here
    //
    //close(iSocketDesc);

end:
    DBG_PRINT("DEEPSLEEP: Test Complete\n\r");
    //
    // Loop here
    //
    while(1);
}
Example #5
0
//*****************************************************************************
//
//! Task implementing MQTT client communication to other web client through
//!    a broker
//!
//! \param  none
//!
//! This function
//!    1. Initializes network driver and connects to the default AP
//!    2. Initializes the mqtt library and set up MQTT connection configurations
//!    3. set up the button events and their callbacks(for publishing)
//!    4. handles the callback signals
//!
//! \return None
//!
//*****************************************************************************
void MqttClient(void *pvParameters)
{
    
    long lRetVal = -1;
    int iCount = 0;
    int iNumBroker = 0;
    int iConnBroker = 0;
    event_msg RecvQue;
    unsigned char policyVal;
    
    connect_config *local_con_conf = (connect_config *)app_hndl;

    //
    // Configure LED
    //
    GPIO_IF_LedConfigure(LED1|LED2|LED3);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);

    //
    // Reset The state of the machine
    //
    Network_IF_ResetMCUStateMachine();

    //
    // Start the driver
    //
    lRetVal = Network_IF_InitDriver(ROLE_STA);
    if(lRetVal < 0)
    {
       UART_PRINT("Failed to start SimpleLink Device\n\r",lRetVal);
       LOOP_FOREVER();
    }

    // switch on Green LED to indicate Simplelink is properly up
    GPIO_IF_LedOn(MCU_ON_IND);

    // Start Timer to blink Red LED till AP connection
    LedTimerConfigNStart();

    // Initialize AP security params
    SecurityParams.Key = (signed char *)SECURITY_KEY;
    SecurityParams.KeyLen = strlen(SECURITY_KEY);
    SecurityParams.Type = SECURITY_TYPE;

    //
    // Connect to the Access Point
    //
    lRetVal = Network_IF_ConnectAP(SSID_NAME, SecurityParams);
    if(lRetVal < 0)
    {
       UART_PRINT("Connection to an AP failed\n\r");
       LOOP_FOREVER();
    }

    lRetVal = sl_WlanProfileAdd(SSID_NAME,strlen(SSID_NAME),0,&SecurityParams,0,1,0);

    //set AUTO policy
    lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION,
                      SL_CONNECTION_POLICY(1,0,0,0,0),
                      &policyVal, 1 /*PolicyValLen*/);    
    
    //
    // Disable the LED blinking Timer as Device is connected to AP
    //
    LedTimerDeinitStop();

    //
    // Switch ON RED LED to indicate that Device acquired an IP
    //
    GPIO_IF_LedOn(MCU_IP_ALLOC_IND);

    UtilsDelay(20000000);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOff(MCU_ORANGE_LED_GPIO);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);
   
    //
    // Register Push Button Handlers
    //
    Button_IF_Init(pushButtonInterruptHandler2,pushButtonInterruptHandler3);
    
    //
    // Initialze MQTT client lib
    //
    lRetVal = sl_ExtLib_MqttClientInit(&Mqtt_Client);
    if(lRetVal != 0)
    {
        // lib initialization failed
        UART_PRINT("MQTT Client lib initialization failed\n\r");
        LOOP_FOREVER();
    }
    
    /******************* connection to the broker ***************************/
    iNumBroker = sizeof(usr_connect_config)/sizeof(connect_config);
    if(iNumBroker > MAX_BROKER_CONN)
    {
        UART_PRINT("Num of brokers are more then max num of brokers\n\r");
        LOOP_FOREVER();
    }

connect_to_broker:
    while(iCount < iNumBroker)
    {
        //create client context
        local_con_conf[iCount].clt_ctx =
        sl_ExtLib_MqttClientCtxCreate(&local_con_conf[iCount].broker_config,
                                      &local_con_conf[iCount].CallBAcks,
                                      &(local_con_conf[iCount]));

        //
        // Set Client ID
        //
        sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx,
                            SL_MQTT_PARAM_CLIENT_ID,
                            local_con_conf[iCount].client_id,
                            strlen((char*)(local_con_conf[iCount].client_id)));

        //
        // Set will Params
        //
        if(local_con_conf[iCount].will_params.will_topic != NULL)
        {
            sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx,
                                    SL_MQTT_PARAM_WILL_PARAM,
                                    &(local_con_conf[iCount].will_params),
                                    sizeof(SlMqttWill_t));
        }

        //
        // setting username and password
        //
        if(local_con_conf[iCount].usr_name != NULL)
        {
            sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx,
                                SL_MQTT_PARAM_USER_NAME,
                                local_con_conf[iCount].usr_name,
                                strlen((char*)local_con_conf[iCount].usr_name));

            if(local_con_conf[iCount].usr_pwd != NULL)
            {
                sl_ExtLib_MqttClientSet((void*)local_con_conf[iCount].clt_ctx,
                                SL_MQTT_PARAM_PASS_WORD,
                                local_con_conf[iCount].usr_pwd,
                                strlen((char*)local_con_conf[iCount].usr_pwd));
            }
        }

        //
        // connectin to the broker
        //
        if((sl_ExtLib_MqttClientConnect((void*)local_con_conf[iCount].clt_ctx,
                            local_con_conf[iCount].is_clean,
                            local_con_conf[iCount].keep_alive_time) & 0xFF) != 0)
        {
            UART_PRINT("\n\rBroker connect fail for conn no. %d \n\r",iCount+1);
            
            //delete the context for this connection
            sl_ExtLib_MqttClientCtxDelete(local_con_conf[iCount].clt_ctx);
            
            break;
        }
        else
        {
            UART_PRINT("\n\rSuccess: conn to Broker no. %d\n\r ", iCount+1);
            local_con_conf[iCount].is_connected = true;
            iConnBroker++;
        }

        //
        // Subscribe to topics
        //

        if(sl_ExtLib_MqttClientSub((void*)local_con_conf[iCount].clt_ctx,
                                   local_con_conf[iCount].topic,
                                   local_con_conf[iCount].qos, TOPIC_COUNT) < 0)
        {
            UART_PRINT("\n\r Subscription Error for conn no. %d\n\r", iCount+1);
            UART_PRINT("Disconnecting from the broker\r\n");
            sl_ExtLib_MqttClientDisconnect(local_con_conf[iCount].clt_ctx);
            local_con_conf[iCount].is_connected = false;
            
            //delete the context for this connection
            sl_ExtLib_MqttClientCtxDelete(local_con_conf[iCount].clt_ctx);
            iConnBroker--;
            break;
        }
        else
        {
            int iSub;
            UART_PRINT("Client subscribed on following topics:\n\r");
            for(iSub = 0; iSub < local_con_conf[iCount].num_topics; iSub++)
            {
                UART_PRINT("%s\n\r", local_con_conf[iCount].topic[iSub]);
            }
        }
        iCount++;
    }

    if(iConnBroker < 1)
    {
        //
        // no succesful connection to broker
        //
        goto end;
    }

    iCount = 0;

    for(;;)
    {
        osi_MsgQRead( &g_PBQueue, &RecvQue, OSI_WAIT_FOREVER);
        
        if(PUSH_BUTTON_SW2_PRESSED == RecvQue.event)
        {
            Button_IF_EnableInterrupt(SW2);
            //
            // send publish message
            //
            sl_ExtLib_MqttClientSend((void*)local_con_conf[iCount].clt_ctx,
                    pub_topic_sw2,data_sw2,strlen((char*)data_sw2),QOS2,RETAIN);
            UART_PRINT("\n\r CC3200 Publishes the following message \n\r");
            UART_PRINT("Topic: %s\n\r",pub_topic_sw2);
            UART_PRINT("Data: %s\n\r",data_sw2);
        }
        else if(PUSH_BUTTON_SW3_PRESSED == RecvQue.event)
        {
            Button_IF_EnableInterrupt(SW3);
            //
            // send publish message
            //
            sl_ExtLib_MqttClientSend((void*)local_con_conf[iCount].clt_ctx,
                    pub_topic_sw3,data_sw3,strlen((char*)data_sw3),QOS2,RETAIN);
            UART_PRINT("\n\r CC3200 Publishes the following message \n\r");
            UART_PRINT("Topic: %s\n\r",pub_topic_sw3);
            UART_PRINT("Data: %s\n\r",data_sw3);
        }
        else if(BROKER_DISCONNECTION == RecvQue.event)
        {
            iConnBroker--;
            /* Derive the value of the local_con_conf or clt_ctx from the message */
			sl_ExtLib_MqttClientCtxDelete(((connect_config*)(RecvQue.hndl))->clt_ctx);
            
            if(!IS_CONNECTED(g_ulStatus))
            {
                UART_PRINT("device has disconnected from AP \n\r");
                
                UART_PRINT("retry connection to the AP\n\r");
                
                while(!(IS_CONNECTED(g_ulStatus)) || !(IS_IP_ACQUIRED(g_ulStatus)))
                {
                    osi_Sleep(10);
                }
                goto connect_to_broker;
                
            }
            if(iConnBroker < 1)
            {
                //
                // device not connected to any broker
                //
                goto end;
            }
        }
    }
end:
    //
    // Deinitializating the client library
    //
    sl_ExtLib_MqttClientExit();
    UART_PRINT("\n\r Exiting the Application\n\r");
    
    LOOP_FOREVER();
}
Example #6
0
File: main.c Project: dlugaz/All
//****************************************************************************
//
//! Task function implementing the UDP client and showcasing the hibernate 
//! functionality
//!
//! \param none
//! 
//! This function  
//!    1. Creates a UDP socket
//!    2. Broadcasts a packet on the socket
//!    3. Closes the socket
//!    4. Enters the HIBernate mode
//!
//! \return None.
//
//****************************************************************************
void HIBUDPBroadcastTask(void *pvParameters)
{
    int iSocketDesc;
    long lRetVal;
    struct sockaddr_in sBroadcastAddr;
    char pcBroadcastMessage[]="32xx HIB example application";

    //
    // Check the wakeup source. If first itme entry or wakeup from HIB
    //
    if(MAP_PRCMSysResetCauseGet() == 0)
    {
        DisplayBanner(APPNAME);
        DBG_PRINT("HIB: Wake up on Power ON\n\r");
    }
    else if(MAP_PRCMSysResetCauseGet() == PRCM_HIB_EXIT)
    {
        DBG_PRINT("HIB: Woken up from Hibernate\n\r");
    }
    else
    {

    }
    GPIO_IF_LedConfigure(LED1);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);


    //
    // Configure Timer for blinking the LED for IP acquisition
    //
    LedTimerConfigNStart();

    //
    //
    // Reset The state of the machine
    //
    Network_IF_ResetMCUStateMachine();

    //
    // Start the driver
    //
    lRetVal = Network_IF_InitDriver(ROLE_STA);
    if(lRetVal < 0)
    {
       UART_PRINT("Failed to start SimpleLink Device\n\r");
       LOOP_FOREVER();
    }

    // Initialize AP security params
    SecurityParams.Key = (signed char*)SECURITY_KEY;
    SecurityParams.KeyLen = strlen(SECURITY_KEY);
    SecurityParams.Type = SECURITY_TYPE;

    //
    // Connect to the Access Point
    //
    lRetVal = Network_IF_ConnectAP(SSID_NAME, SecurityParams);
    if(lRetVal < 0)
    {
       UART_PRINT("Connection to AP failed\n\r",lRetVal);
       LOOP_FOREVER();
    }

    //
    // Disable the LED blinking Timer as Device is connected to AP
    //
    LedTimerDeinitStop();

    //
    // Switch ON RED LED to indicate that Device acquired an IP
    //
    GPIO_IF_LedOn(MCU_IP_ALLOC_IND);

    //
    // Create UDP socket
    //
    iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, 0);
    if(iSocketDesc < 0)
    {
        DBG_PRINT("HIB: Socket create failed\n\r");
        goto end;
    }
    DBG_PRINT("HIB: Socket created\n\r");

    //
    // Assign socket structure values for a braodcast message
    //
    sBroadcastAddr.sin_family = AF_INET;
    sBroadcastAddr.sin_addr.s_addr= sl_Htonl(0xFFFFFFFF);
    sBroadcastAddr.sin_port= sl_Htons(APP_UDP_PORT);

    //
    // Broadcast message
    //
    lRetVal = sendto(iSocketDesc, (char *)&pcBroadcastMessage[0],
                        sizeof(pcBroadcastMessage), 0,
                     (struct sockaddr *)&sBroadcastAddr,sizeof(sBroadcastAddr));
    if(lRetVal < 0)
    {
        ERR_PRINT(lRetVal);
        LOOP_FOREVER();
    }

    UNUSED(lRetVal);
    DBG_PRINT("HIB: sent message\n\r");

    //
    // Close the socket
    //
    close(iSocketDesc);
    DBG_PRINT("HIB: Socket closed\n\r");

    //
    // Stop the driver
    //
    lRetVal = Network_IF_DeInitDriver();
    if(lRetVal < 0)
    {
       UART_PRINT("Failed to stop SimpleLink Device\n\r");
       LOOP_FOREVER();
    }

    //
    // Switch Off RED & Green LEDs to indicate that Device is
    // disconnected from AP and Simplelink is shutdown
    //
    GPIO_IF_LedOff(MCU_IP_ALLOC_IND);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);

    //
    // Enter HIB here configuring the wakeup-timer
    //
    EnterHIBernate();
end:
    DBG_PRINT("HIB: Test Complete\n\r");

    //
    // Loop here
    //
    LOOP_FOREVER();
}
Example #7
0
File: main.c Project: nqd/cc3200
//****************************************************************************
//
//! Task function implementing the gettime functionality using an NTP server
//!
//! \param none
//!
//! This function
//!    1. Initializes the required peripherals
//!    2. Initializes network driver and connects to the default AP
//!    3. Creates a UDP socket, gets the NTP server IP address using DNS
//!    4. Periodically gets the NTP time and displays the time
//!
//! \return None.
//
//****************************************************************************
void GetNTPTimeTask(void *pvParameters)
{
    int iSocketDesc;
    long lRetVal = -1;

    UART_PRINT("GET_TIME: Test Begin\n\r");

    //
    // Configure LED
    //
    GPIO_IF_LedConfigure(LED1|LED3);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);    


    //
    // Reset The state of the machine
    //
    Network_IF_ResetMCUStateMachine();

    //
    // Start the driver
    //
    lRetVal = Network_IF_InitDriver(ROLE_STA);
    if(lRetVal < 0)
    {
       UART_PRINT("Failed to start SimpleLink Device\n\r",lRetVal);
       LOOP_FOREVER();
    }

    // switch on Green LED to indicate Simplelink is properly up
    GPIO_IF_LedOn(MCU_ON_IND);

    // Start Timer to blink Red LED till AP connection
    LedTimerConfigNStart();

    // Initialize AP security params
    SecurityParams.Key = (signed char *)SECURITY_KEY;
    SecurityParams.KeyLen = strlen(SECURITY_KEY);
    SecurityParams.Type = SECURITY_TYPE;

    //
    // Connect to the Access Point
    //
    lRetVal = Network_IF_ConnectAP(SSID_NAME, SecurityParams);
    if(lRetVal < 0)
    {
       UART_PRINT("Connection to an AP failed\n\r");
       LOOP_FOREVER();
    }

    //
    // Disable the LED blinking Timer as Device is connected to AP
    //
    LedTimerDeinitStop();

    //
    // Switch ON RED LED to indicate that Device acquired an IP
    //
    GPIO_IF_LedOn(MCU_IP_ALLOC_IND);

    //
    // Create UDP socket
    //
    iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(iSocketDesc < 0)
    {
        ERR_PRINT(iSocketDesc);
        goto end;
    }
    g_sAppData.iSockID = iSocketDesc;

    UART_PRINT("Socket created\n\r");

    //
    // Get the NTP server host IP address using the DNS lookup
    //
    lRetVal = Network_IF_GetHostIP((char*)g_acSNTPserver, \
                                    &g_sAppData.ulDestinationIP);
    
    if( lRetVal >= 0)
    {
    
        struct SlTimeval_t timeVal;
        timeVal.tv_sec =  SERVER_RESPONSE_TIMEOUT;    // Seconds
        timeVal.tv_usec = 0;     // Microseconds. 10000 microseconds resolution
        lRetVal = sl_SetSockOpt(g_sAppData.iSockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO,\
                        (unsigned char*)&timeVal, sizeof(timeVal)); 
        if(lRetVal < 0)
        {
           ERR_PRINT(lRetVal);
           LOOP_FOREVER();
        }
        
        while(1)
        {
            //
            // Get the NTP time and display the time
            //
            lRetVal = GetSNTPTime(GMT_DIFF_TIME_HRS, GMT_DIFF_TIME_MINS);
            if(lRetVal < 0)
            {
                UART_PRINT("Server Get Time failed\n\r");
                break;                
            }

            //
            // Wait a while before resuming
            //
            MAP_UtilsDelay(SLEEP_TIME);
        }
    }
    else
    {
        UART_PRINT("DNS lookup failed. \n\r");
    }

    //
    // Close the socket
    //
    close(iSocketDesc);
    UART_PRINT("Socket closed\n\r");

end:
    //
    // Stop the driver
    //
    lRetVal = Network_IF_DeInitDriver();
    if(lRetVal < 0)
    {
       UART_PRINT("Failed to stop SimpleLink Device\n\r");
       LOOP_FOREVER();
    }

    //
    // Switch Off RED & Green LEDs to indicate that Device is
    // disconnected from AP and Simplelink is shutdown
    //
    GPIO_IF_LedOff(MCU_IP_ALLOC_IND);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);

    UART_PRINT("GET_TIME: Test Complete\n\r");

    //
    // Loop here
    //
    LOOP_FOREVER();
}