Example #1
0
File: main.c Project: Mecabot/IoT
//*****************************************************************************
//
//! This function obtains the current time from a SNTP server if required due
//! to not having current time (when booting up) or periodically to update
//! the time
//!
//! \param None
//!
//! \return  0 on success else error code
//! \return  Error Number of failure
//
//*****************************************************************************
long GetCurrentTime()
{
    int iSocketDesc;
    long lRetVal = -1;

	//
	// Get the time and date currently stored in the RTC
	//
	getDeviceTimeDate();

	//
	// Calculate time difference between the last time we obtained time from a NTP server
	//
	timeDifference = dateTime.sl_tm_hour - hourSet; // This roughly works, it does however reset after midnight.

	//
	// Get the NTP time to use with the SSL process. Only call this every 6 hours to update the RTC
	// As we do not want to be calling the NTP server too often
	//
	if (timeDifference > 6 || timeDifference < 0)
	{
		//
		// Create UDP socket
		//
		iSocketDesc = sl_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
		if(iSocketDesc < 0)
		{
			CLI_Write("Could not create UDP socket.\n\r");
			close(iSocketDesc);
			return iSocketDesc;
		}
		else
		{
			CLI_Write("Socket successfully created\n\r");
		}
		g_sAppData.iSockID = iSocketDesc;

		//
		// Get the NTP server host IP address using the DNS lookup
		//
		lRetVal = getHostIP((char*)g_acSNTPserver, &g_sAppData.ulDestinationIP);
		if( lRetVal >= 0)
		{
			//
			// Configure the recieve timeout
			//
			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)
			{
			   CLI_Write("Could not configure socket option (receive timeout).\n\r");
			   close(iSocketDesc);
			   return lRetVal;
			}
		}
		else
		{
			CLI_Write("DNS lookup failed.");
		}

		//
		// Get current time from the SNTP server
		//
		CLI_Write("Fetching Time From SNTP Server\n\r");
		lRetVal = GetSNTPTime(GMT_DIFF_TIME_HRS, GMT_DIFF_TIME_MINS);
		if(lRetVal < 0)
		{
			CLI_Write("Server Get Time failed.\n\r");
			close(iSocketDesc);
			return lRetVal;
		}
		else
		{
			hourSet = dateTime.sl_tm_hour; // Set to current hour as we did get the time successfully
			CLI_Write("Server Get Time Successful\n\n\r");
		}

		//
		// Close the socket
		//
		close(iSocketDesc);
	}

	return 0;
}
Example #2
0
//****************************************************************************
//
//! 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 Returns \b TASK_RET_IN_PROG.
//
//****************************************************************************
int GetNTPTimeTask(void *pvParameters)
{
    SlSecParams_t SecurityParams;
    long lRetVal = -1;
    struct SlTimeval_t timeVal;
    static char cTaskOwnState = GET_TIME_TASK_STATE_INIT;
    static tGetTime sGetTime;
    long OptionLen;
    int SetCommitInt;
    unsigned char OptionVal;

    switch(cTaskOwnState)
    {

    case GET_TIME_TASK_STATE_INIT:
        //
        // Start networking service in default STA_MODE state
        //
        lRetVal = NetStartDefaultState();
        if(lRetVal < 0)
        {
          return TASK_RET_DONE;
        }

        //
        // Set the status as stated
        //
        sDisplayInfo.ucNetStat = NET_STAT_STARTED;

        //
        // Set the time zone
        //
        sGetTime.ucGmtDiffHr   = GMT_DIFF_TIME_HRS;
        sGetTime.ucGmtDiffMins = GMT_DIFF_TIME_MINS;

        //
        // Set conneting status
        //
        sDisplayInfo.ucNetStat = NET_STAT_CONN;

        //
        // Get the Version Info
        //
        NetFwInfoGet(&sDisplayInfo.sNwpVersion);

        //
        // Make the formated string for firmware version
        //
        sprintf(sDisplayInfo.ucNwpVersion,
                "%d.%d.%d.%d.31.%d.%d.%d.%d.%d.%d.%d.%d",
                sDisplayInfo.sNwpVersion.NwpVersion[0],
                sDisplayInfo.sNwpVersion.NwpVersion[1],
                sDisplayInfo.sNwpVersion.NwpVersion[2],
                sDisplayInfo.sNwpVersion.NwpVersion[3],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.FwVersion[0],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.FwVersion[1],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.FwVersion[2],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.FwVersion[3],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.PhyVersion[0],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.PhyVersion[1],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.PhyVersion[2],
                sDisplayInfo.sNwpVersion.ChipFwAndPhyVersion.PhyVersion[3]);

        //
        // Set next task state
        //
        cTaskOwnState = GET_TIME_TASK_STATE_CONN;

        //
        // Signal display refresh
        //
        DisplayRefresh();
        break;

    case GET_TIME_TASK_STATE_CONN:

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

        //
        // Connect to Access Point
        //
        lRetVal = NetWlanConnect(SSID_NAME,&SecurityParams);

        //
        // Failed to connect to AP, kill the task
        //
        if(lRetVal != 0)
        {
          return TASK_RET_DONE;
        }

        //
	// Check if this image is booted in test mode
	//
	sl_extLib_OtaGet(pvOtaApp,EXTLIB_OTA_GET_OPT_IS_PENDING_COMMIT,
                         &OptionLen,&OptionVal);

	if(OptionVal == true)
	{


            SetCommitInt = OTA_ACTION_IMAGE_COMMITED;
            sl_extLib_OtaSet(pvOtaApp, EXTLIB_OTA_SET_OPT_IMAGE_COMMIT,
                             sizeof(int), (_u8 *)&SetCommitInt);

            //
            // Set status
            //
            g_ulSysState = SYS_STATE_TEST_REBOOT;
            DisplayRefresh();

            //
            // Reboot the MCU
            //
            cTaskOwnState = GET_TIME_TASK_STATE_DONE;
            break;
	}

        //
        // Set the status
        //
        sDisplayInfo.ucNetStat = NET_STAT_CONNED;
        DisplayRefresh();

        //
        // Signal the network start
        //
        TaskSyncObjSignal(&g_NetStatSyncObj);

        //
        // Set next task state
        //
        cTaskOwnState = GET_TIME_TASK_STATE_OPEN_SOCK;

        break;

    case GET_TIME_TASK_STATE_OPEN_SOCK:

        //
        // Create UDP socket
        //
        sGetTime.iSocket = sl_Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

        //
        // Failed to create a socket, kill the task
        //
        while(sGetTime.iSocket < 0)
        {
          return TASK_RET_DONE;
        }

        //
        // Set socket time option
        //
        timeVal.tv_sec =  20;
        timeVal.tv_usec = 0;
        sl_SetSockOpt(sGetTime.iSocket,SOL_SOCKET,SL_SO_RCVTIMEO, &timeVal,
                      sizeof(timeVal));

        //
        // Initialize Server Index
        //
        sDisplayInfo.ucServerIndex = 0;
        DisplayRefresh();

        //
        // Set next task state
        //
        cTaskOwnState = GET_TIME_TASK_STATE_GET_IP;
        break;


    case GET_TIME_TASK_STATE_GET_IP:

        //
        // Get the NTP server host IP address using the DNS lookup
        //
        lRetVal = NetGetHostIP((char*)g_acSNTPserver[sDisplayInfo.ucServerIndex],
                         &sGetTime.ulNtpServerIP);

        sDisplayInfo.ulServerIP = sGetTime.ulNtpServerIP;
        DisplayRefresh();

        //
        // Set the net task state based on return value
        //
        if(lRetVal >= 0)
        {
          //
          // Go to get time
          //
          cTaskOwnState = GET_TIME_TASK_STATE_GET_TIME;
        }
        else
        {
          //
          // Go back and try a new NTP server
          //
          cTaskOwnState = GET_TIME_TASK_STATE_SET_SERVER;
        }
        break;

    case GET_TIME_TASK_STATE_GET_TIME:

        //
        // Get the NTP time and display the time
        //
        lRetVal = GetSNTPTime(&sGetTime);
        DisplayRefresh();

        //
        // On failure go back and try a new NTP server
        //
        if(lRetVal != 0)
        {
          //
          // Chech and wait if we are disconnected
          //
          while( !NetIsConnectedToAP() )
          {

          }

          cTaskOwnState = GET_TIME_TASK_STATE_SET_SERVER;
        }

        //
        // End the task if Reboot was requested
        //
        if(g_ulSysState == SYS_STATE_REBOOT)
        {
          cTaskOwnState = GET_TIME_TASK_STATE_DONE;
        }

        //
        // Set some sleep
        //
        TaskSleep(5*1000);
        break;

    case GET_TIME_TASK_STATE_SET_SERVER:

          strcpy((char *)sDisplayInfo.ucUTCTime,"NTP Server Error. Retrying...");
          sDisplayInfo.ucLocalTime[0]='-';
          sDisplayInfo.ucLocalTime[1]='\0';

          sDisplayInfo.ucServerIndex
            = ((sDisplayInfo.ucServerIndex + 1)%NOF_NTP_SERVER);

          cTaskOwnState = GET_TIME_TASK_STATE_GET_IP;
          DisplayRefresh();
          break;

    default:

        //
        // Disconnect and stop networking service
        //
        NetStop();

        sDisplayInfo.ucNetStat = NET_STAT_OFF;
        DisplayRefresh();

        //
        // Reboot nonw
        //
        RebootMCU();

        //
        // Return task done
        //
        return TASK_RET_DONE;
    }

    //
    // Return task in progress
    //
    return TASK_RET_IN_PROG;
}
Example #3
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();
}