Esempio n. 1
0
void pubnub_task(void)
{
    static uint32_t s_tick_prev;

    if (0 == s_tick_prev) {
        s_tick_prev = SYS_TMR_TickCountGet();
    }
    
    if (m_watcher.apb_size > 0) {
        pubnub_t **ppbp;
        uint32_t tick_now = SYS_TMR_TickCountGet();
        int elapsed = elapsed_ms(s_tick_prev, tick_now);

        for (ppbp = m_watcher.apb; ppbp < m_watcher.apb + m_watcher.apb_size; ++ppbp) {
            pbnc_fsm(*ppbp);
        }
        if (elapsed > 0) {
            pubnub_t *expired = pubnub_timer_list_as_time_goes_by(&m_watcher.timer_head, elapsed);
            while (expired != NULL) {
                pubnub_t *next = expired->next;

                pbnc_stop(expired, PNR_TIMEOUT);

                expired->previous = NULL;
                expired->next = NULL;
                expired = next;
            }
            s_tick_prev = tick_now;
        }
    }
}
static void AppConfig_UI_Task(void)
{
    uint32 currentTickCount = 0;
    uint32 startTick = 0;
    uint32 lastUpTimeUpdate = 0;
    uint32 lastUpTime = SYS_TMR_TickCountGet();
    while (1)
    {
        currentTickCount = SYS_TMR_TickCountGet();

        if (currentTickCount - lastUpTimeUpdate >= SYS_TMR_TickCounterFrequencyGet())
        {
            _UptimeSecs++;
            lastUpTimeUpdate = currentTickCount;
        }

        if (currentTickCount - startTick >= SYS_TMR_TickCounterFrequencyGet() / 2)
        {
            startTick = currentTickCount;
            UIControl_UIStep();
        }

#ifdef SYS_UI_PRINT_UP_TIME
        if (currentTickCount - lastUpTime >= SYS_UI_PRINT_UP_TIME)
        {
            SYS_UPTIME uptime;
            AppConfig_Uptime(&uptime);
            lastUpTime = currentTickCount;
            CreatorConsole_Printf("\tSYS_UI Uptime = %d days, %d hours, %d min, %d seconds\r\n", uptime.Days, uptime.Hours, uptime.Minutes, uptime.Seconds);
        }
#endif
        CreatorThread_SleepMilliseconds(NULL, 100);
    }
}
/**
 * Start the next readout, depending on availability
 */
static void _changeState(STATE_t newState)
{

    SYS_PRINT("\r\nCNFG: Load online user config state change to %d\r\n", newState);
    switch(newState)
    {
        case STATE_ACTIVATING:
            APP_Activation_Initialize();
            SYS_PRINT("\r\nCNFG: Activating gateway\r\n");
            break;

        case STATE_ERASING_ACTIVATION_KEY:
            APP_SERIALFLASH_EraseActivationData();
            break;

        case STATE_STORING_ACTIVATION_KEY:
            APP_SERIALFLASH_SaveActivationData(
                (char*)&appGWActivationData.configuration.id, (char*)&appGWActivationData.configuration.key,
                (char*)&appGWActivationData.configuration.account_server_url,
                false); // Only lock it after first time successful downloading LoRa config
            break;

        case STATE_DOWNLOAD_LORA_CONFIG:
            APP_Configuration_Initialize();
            reconnectDelayStartTick = SYS_TMR_TickCountGet();
            break;

        case STATE_LOCK_ACTIVATION:
            appGWActivationData.locked = true;
            APP_SERIALFLASH_LockActivationData();
            break;

        case STATE_DOWNLOAD_FREQPLAN:
            APP_FreqPlan_Initialize();
            freqDelayStartTick = SYS_TMR_TickCountGet();
            break;

        case STATE_START_LORA_MODULE:
            SYS_PRINT("\r\nCNFG: Configuring LoRa module\r\n");
            APP_LORA_SetStartEvent();
            break;

        case STATE_COMMUNICATION_ERROR:
            SYS_PRINT("\r\nCNFG: Communication ERROR\r\n");
            break;

        default:
            break;
    }
    _state = newState;
}
Esempio n. 4
0
SNTP_RESULT TCPIP_SNTP_TimeStampGet(uint64_t* pTStamp, uint32_t* pLastUpdate)
{
    SNTP_RESULT res;

    if(ntpTimeStamp.llStamp == 0 || ntpLastStampTick == 0 || (SYS_TMR_TickCountGet() - ntpLastStampTick >  NTP_TIME_STAMP_TMO))
    {
        res = SNTP_RES_TSTAMP_STALE;
    }
    else
    {
        res = SNTP_RES_OK;
    }

    if(pTStamp)
    {
        *pTStamp = ntpTimeStamp.llStamp;
    }
    if(pLastUpdate)
    {
        *pLastUpdate = ntpLastStampTick;
    }

    return res;

}
int32_t BSP_SWITCH_DeviceDebounce(BSP_SWITCH_DEBOUNCE_T *handle, uint32_t curVal)
{
    if(handle->timerActive==false)
    {
       handle->timerActive = true;
       handle->prevValue   = curVal;
       handle->startTick   = SYS_TMR_TickCountGet();
    }

    if ((SYS_TMR_TickCountGet() - handle->startTick) >= (1250
                         / BSP_SWITCH_MS_ELLAPSED_TIME_TO_HZ(handle->duration)) )
    {
        handle->timerActive=false;
        if(handle->prevValue == curVal)
          return handle->prevValue;
        else
          return curVal; // Return the assert value
    }
    return BSP_SWITCH_BUSY;  // Busy
}
/**
 * Start the next readout, depending on availability
 */
static void _changeState(STATE_t newState)
{
    SYS_PRINT("INET: State change to %d\r\n", newState);

    // onEnter
    switch(newState)
    {
        case STATE_WAIT_FOR_NETWORK:
            if(appWifiData.valid)
            {
                APP_WIFI_INFRA_MODE();
            }
            break;

        case STATE_AP_ONLY:
            wifiRetryStartTick = SYS_TMR_TickCountGet();
            APP_WIFI_AP_MODE();
            firstTimeAPReconnectTimeout = true;
            break;

        case STATE_SETTLE:
            SYS_PRINT("INET: Connected to a network, waiting for DHCP lease, checking validity with ping\r\n");
            settleStartTick = SYS_TMR_TickCountGet();
            break;

        case STATE_PING_PROBE:
            ping_probe_reply_received = false;
            ping_probe_sent           = false;
            ping_retry                = 0;
            pingStartTick             = SYS_TMR_TickCountGet();
            break;

        case STATE_WAIT_FOR_NTP:
            ntpStartTick = SYS_TMR_TickCountGet();
            break;

        default:
            break;
    }
    _state = newState;
}
Esempio n. 7
0
/*****************************************************************************
  Function:
    bool RawSetIndex(uint16_t rawId, uint16_t index)

  Summary:
    Sets the index within the specified RAW window.

  Description:
    Sets the index within the specified RAW window.    If attempt to set RAW index 
    outside boundaries of RAW window (past the end) this function will time out.  
    It's legal to set the index past the end of the raw window so long as there 
    is no attempt to read or write at that index.

  Precondition:
    None

  Parameters:
    rawId -- RAW window ID
    index -- desired index within RAW window
                 
  Returns:
    True if successful, False if caller tried to set raw index past end of 
    window
      
  Remarks:
    None
*****************************************************************************/
bool RawSetIndex(uint16_t rawId, uint16_t index)
{
    uint8_t regId;
    uint16_t regValue;
    uint32_t startTickCount;
    uint32_t maxAllowedTicks;

    /* get the index register associated with the raw ID and write to it */
    regId = g_RawIndexReg[rawId];
    Write16BitWFRegister(regId, index);

    /* Get the raw status register address associated with the raw ID.  This will be polled to         */
    /* determine that:                                                                                 */
    /*  1) raw set index completed successfully  OR                                                    */
    /*  2) raw set index failed, implying that the raw index was set past the end of the raw window    */
    regId = g_RawStatusReg[rawId];

    maxAllowedTicks = SYS_TMR_TickPerSecond() / 200;   /* 5ms */
    startTickCount = SYS_TMR_TickCountGet();
        
    /* read the status register until set index operation completes or times out */
    while (1)
    {
        regValue = Read16BitWFRegister(regId);
        if ((regValue & WF_RAW_STATUS_REG_BUSY_MASK) == 0)
        {
            ClearIndexOutOfBoundsFlag(rawId);
            return true;
        }
        
        /* if timed out then trying to set index past end of raw window, which is OK so long as the app */
        /* doesn't try to access it                                                                     */
        if (SYS_TMR_TickCountGet() - startTickCount >= maxAllowedTicks)
        {
            SetIndexOutOfBoundsFlag(rawId);
            return false;  /* timed out waiting for Raw set index to complete */
        }    
    }
}
Esempio n. 8
0
// sntp.h
uint32_t TCPIP_SNTP_UTCSecondsGet(void)
{

    uint32_t dwTickDelta;
    uint32_t dwTick;

    // Update the dwSNTPSeconds variable with the number of seconds
    // that has elapsed
    dwTick = SYS_TMR_TickCountGet();
    dwTickDelta = dwTick - dwLastUpdateTick;
    while(dwTickDelta > SYS_TMR_TickPerSecond())
    {
        dwSNTPSeconds++;
        dwTickDelta -= SYS_TMR_TickPerSecond();
    }


    // Save the tick and residual fractional seconds for the next call
    dwLastUpdateTick = dwTick - dwTickDelta;

    return dwSNTPSeconds;

}//TCPIP_SNTP_UTCSecondsGet
void SSMWaitForInternet_Tasks(void)
{
    switch(_state)
    {
        case STATE_WAIT_FOR_NETWORK:
            if(APP_ETH_Has_Link())
            {
                SYS_PRINT("INET: Gateway has Ethernet\r\n");
                _changeState(STATE_SETTLE);
            }
            else if(!appWifiData.valid)
            {
                SYS_PRINT("INET: No Ethernet and no WiFi config\r\n");
                _changeState(STATE_AP_ONLY);
            }
            if(APP_WIFI_Has_LinkINFRA())
            {
                SYS_PRINT("INET: Gateway has WiFi\r\n");
                _changeState(STATE_SETTLE);
            }
            break;

        case STATE_AP_ONLY:
            if(APP_ETH_Has_Link())
            {
                _changeState(STATE_WAIT_FOR_NETWORK);
            }
            else if(appWifiData.valid && ((SYS_TMR_TickCountGet() - wifiRetryStartTick) >=
                                          (SYS_TMR_TickCounterFrequencyGet() * WIFI_RETRY_TIMEOUT)))
            { // REVIEW: Use isElapsed kind of function
                if(APP_WIFI_Has_LinkAP())
                {
                    if(firstTimeAPReconnectTimeout)
                    {
                        SYS_PRINT("INET: Not trying to connect to WiFi router again because client is connected (after "
                                  "%d seconds)\r\n",
                                  (SYS_TMR_TickCountGet() - wifiRetryStartTick) / SYS_TMR_TickCounterFrequencyGet());
                        firstTimeAPReconnectTimeout = false;
                    }
                }
                else
                {
                    SYS_PRINT("INET: Trying to connect to WiFi router again (after %d seconds)\r\n",
                              (SYS_TMR_TickCountGet() - wifiRetryStartTick) / SYS_TMR_TickCounterFrequencyGet());
                    _changeState(STATE_WAIT_FOR_NETWORK);
                }
            }
            break;

        case STATE_SETTLE:
            if((SYS_TMR_TickCountGet() - settleStartTick) >= (SYS_TMR_TickCounterFrequencyGet() * 5))
            {
                _changeState(STATE_PING_PROBE);
            }
            break;

        case STATE_PING_PROBE:
            if(!ping_probe_sent)
            {
                IPV4_ADDR googledns = {0};
                googledns.v[0]      = 8;
                googledns.v[1]      = 8;
                googledns.v[2]      = 4;
                googledns.v[3]      = 4;

                ping_probe_reply_received = false;

                SYS_PRINT("INET: Ping probe\r\n");
                if(TCPIP_ICMP_EchoRequestSend(TCPIP_STACK_IndexToNet(WIFI_INTERFACE_NUM), &googledns, 0, 0x1234) !=
                   ICMP_ECHO_OK)
                {
                    SYS_PRINT("INET: Error sending probe on WiFi\r\n");
                }
                if(TCPIP_ICMP_EchoRequestSend(TCPIP_STACK_IndexToNet(ETH_INTERFACE_NUM), &googledns, 0, 0x1234) !=
                   ICMP_ECHO_OK)
                {
                    SYS_PRINT("INET: Error sending probe on Eth\r\n");
                }
                ping_probe_sent = true;
            }
            else if(ping_probe_reply_received)
            {
                SYS_PRINT("INET: Ping response from %s, set as default\r\n",
                          TCPIP_STACK_NetNameGet(TCPIP_STACK_NetDefaultGet()));
                if(ntpEverSynchronized)
                {
                    _changeState(STATE_DONE);
                }
                else
                {
                    _changeState(STATE_WAIT_FOR_NTP);
                }
                break;
            }
            else
            {
                if((SYS_TMR_TickCountGet() - pingStartTick) >=
                   (SYS_TMR_TickCounterFrequencyGet() * PING_TIMEOUT)) // REVIEW: Use isElapsed kind of function
                {
                    SYS_PRINT("INET: Ping Timeout of :%d seconds\r\n", PING_TIMEOUT);
                    pingStartTick             = SYS_TMR_TickCountGet();
                    ping_probe_sent           = false;
                    ping_probe_reply_received = false;
                    if(ping_retry >= PING_RETRIES)
                    {
                        // TODO: find a proper recovery -> _changeState(STATE_WAIT_FOR_NETWORK);
                        RebootWithMessage("Ping timeout %d retries, rebooting", PING_RETRIES);    
                        
                    }
                    ping_retry++;
                }
            }
            break;

        case STATE_WAIT_FOR_NTP:
        {
            uint32_t lastUpdate = 0;
            TCPIP_SNTP_TimeStampGet(NULL, &lastUpdate);
            if(lastUpdate != 0)
            { // If at least once NTP succeeded
                ntpEverSynchronized = true;
                _changeState(STATE_DONE);
            }
            else
            {
                if((SYS_TMR_TickCountGet() - ntpStartTick) >= (SYS_TMR_TickCounterFrequencyGet() * NTP_TIMEOUT))
                { // REVIEW: Use isElapsed kind of function
                    SYS_PRINT("INET: Not received any NTP response. Wait for network again (after %d seconds).\r\n",
                              (SYS_TMR_TickCountGet() - ntpStartTick) / SYS_TMR_TickCounterFrequencyGet());
                    _changeState(STATE_WAIT_FOR_NETWORK);
                }
                else if(TCPIP_SNTP_ConnectionInitiate() == SNTP_RES_OK)
                {
                    SYS_PRINT("INET: Initiated NTP request.\r\n");
                }
            }
            break;
        }

        case STATE_DONE:
            break;
    }
}
Esempio n. 10
0
static uint32_t _zcll_rand(void)
{
   return SYS_TMR_TickCountGet();
}
uint32_t platform_get_time_ms(void)
{
    return SYS_TMR_TickCountGet();
}
Esempio n. 12
0
static void TCPIP_SMTP_ClientProcess(void)
{
    uint8_t			    i;
    uint16_t			w;
    uint8_t			    vBase64Buffer[4];
    static uint32_t	    SMTPTimer;

    static uint8_t		RXBuffer[4];
    static const uint8_t *ROMStrPtr, *ROMStrPtr2;
    static const uint8_t *RAMStrPtr;
    static uint16_t		wAddressLength;
    TCPIP_DNS_RESULT    dnsRes;
    DNS_RESOLVE_TYPE    dnsType;

    switch(TransportState)
    {
        case TRANSPORT_HOME:
            // TCPIP_SMTP_UsageBegin() is the only function which will kick
            // the state machine into the next state
            break;

        case TRANSPORT_BEGIN:
            // Wait for the user to program all the pointers and then
            // call TCPIP_SMTP_MailSend()
            if(!SMTPFlags.bits.ReadyToStart)
            {
                break;
            }

            SMTPClient.Server = FindEmailServer(&SMTPClient, &dnsType);
            // See if we found a hostname anywhere which we could resolve
            if(!(SMTPClient.Server))
            {
                ResponseCode = SMTP_RESOLVE_ERROR;
                TransportState = TRANSPORT_HOME;
                break;
            }

            // check for a plain IP address
            if(TCPIP_Helper_StringToIPAddress(SMTPClient.Server, &SMTPServer))
            {
                TransportState = TRANSPORT_OBTAIN_SOCKET;
                break;
            }

            // use DNS to resolve the name
            TCPIP_DNS_Resolve(SMTPClient.Server, dnsType);
            SMTPTimer = SYS_TMR_TickCountGet();

            TransportState++;
            break;

        case TRANSPORT_NAME_RESOLVE:
            // Wait for the DNS server to return the requested IP address
            dnsRes = TCPIP_DNS_IsResolved((const char*)SMTPClient.Server,&SMTPServer);
            if(dnsRes == DNS_RES_PENDING)
            {
                break;
            }
            if(dnsRes < 0)
            {   // some error occurred
                ResponseCode = SMTP_RESOLVE_ERROR;
                TransportState = TRANSPORT_HOME;
                break;
            }
            
            // DNS_RES_OK
            TransportState++;
            // No need to break here

        case TRANSPORT_OBTAIN_SOCKET:
            // Connect a TCP socket to the remote SMTP server
            MySocket = TCPIP_TCP_ClientOpen(IP_ADDRESS_TYPE_IPV4, SMTPClient.ServerPort, (IP_MULTI_ADDRESS*)&SMTPServer.Val);

            // Abort operation if no TCP socket could be opened.
            // If this ever happens, you need to update your tcp_config.h
            if(MySocket == INVALID_SOCKET)
                break;

            TCPIP_TCP_SignalHandlerRegister(MySocket, TCPIP_TCP_SIGNAL_RX_DATA, _SMTPSocketRxSignalHandler, 0);

            TransportState++;
            SMTPTimer = SYS_TMR_TickCountGet();

            // No break; fall into TRANSPORT_SOCKET_OBTAINED
			
        case TRANSPORT_SOCKET_OBTAINED:
            if(!TCPIP_TCP_IsConnected(MySocket))
            {
                // Don't stick around in the wrong state if the
                // server was connected, but then disconnected us.
                // Also time out if we can't establish the connection
                // to the SMTP server
                if(SMTPFlags.bits.ConnectedOnce || ((SYS_TMR_TickCountGet()-SMTPTimer) > (TCPIP_SMTP_SERVER_REPLY_TIMEOUT * SYS_TMR_TickCounterFrequencyGet())))
                {
                    ResponseCode = SMTP_CONNECT_ERROR;
                    TransportState = TRANSPORT_CLOSE;
                }

                break;
            }
            SMTPFlags.bits.ConnectedOnce = true;

            // See if the server sent us anything
            while(TCPIP_TCP_GetIsReady(MySocket))
            {
                TCPIP_TCP_Get(MySocket, &i);
                switch(RXParserState)
                {
                    case RX_BYTE_0:
                    case RX_BYTE_1:
                    case RX_BYTE_2:
                        RXBuffer[RXParserState] = i;
                        RXParserState++;
                        break;
	
                    case RX_BYTE_3:
                        switch(i)
                        {
                            case ' ':
                                SMTPFlags.bits.RXSkipResponse = false;
                                RXParserState++;
                                break;
                            case '-':
                                SMTPFlags.bits.RXSkipResponse = true;
                                RXParserState++;
                                break;
                            case '\r':
                                RXParserState = RX_SEEK_LF;
                                break;
                        }
                        break;
	
					case RX_SEEK_CR:
                                            if(i == '\r')
                                                    RXParserState++;
                                            break;
	
					case RX_SEEK_LF:
						// If we received the whole command
						if(i == '\n')
						{
							RXParserState = RX_BYTE_0;

							if(!SMTPFlags.bits.RXSkipResponse)
							{
								// The server sent us a response code
								// Null terminate the ASCII reponse code so we can convert it to an integer
								RXBuffer[3] = 0;
								ResponseCode = atoi((char*)RXBuffer);

								// Handle the response
								switch(SMTPState)
								{
									case SMTP_HELO_ACK:
										if(ResponseCode >= 200u && ResponseCode <= 299u)
										{
											if(SMTPClient.Username)
												SMTPState = SMTP_AUTH_LOGIN;
											else
												SMTPState = SMTP_MAILFROM;
										}
										else
											SMTPState = SMTP_QUIT_INIT;
										break;


									case SMTP_AUTH_LOGIN_ACK:
									case SMTP_AUTH_USERNAME_ACK:
										if(ResponseCode == 334u)
											SMTPState++;
										else
											SMTPState = SMTP_QUIT_INIT;
										break;

									case SMTP_AUTH_PASSWORD_ACK:
										if(ResponseCode == 235u)
											SMTPState++;
										else
											SMTPState = SMTP_QUIT_INIT;
										break;

									case SMTP_HOME:
									case SMTP_MAILFROM_ACK:
									case SMTP_RCPTTO_ACK:
									case SMTP_RCPTTOCC_ACK:
									case SMTP_RCPTTOBCC_ACK:
										if(ResponseCode >= 200u && ResponseCode <= 299u)
											SMTPState++;
										else
											SMTPState = SMTP_QUIT_INIT;
										break;
							
									case SMTP_DATA_ACK:
										if(ResponseCode == 354u)
											SMTPState++;
										else
											SMTPState = SMTP_QUIT_INIT;
										break;
							
									case SMTP_DATA_BODY_ACK:
										if(ResponseCode >= 200u && ResponseCode <= 299u)
											SMTPFlags.bits.SentSuccessfully = true;
							
										SMTPState = SMTP_QUIT_INIT;
										break;

									// Default case needed to supress compiler diagnostics
									default:
										break;
								}
							}
						}
						else if(i != '\r')
							RXParserState--;
	
						break;
				}
			}

			// Generate new data in the TX buffer, as needed, if possible
			if(TCPIP_TCP_PutIsReady(MySocket) < 64u)
				break;

			switch(SMTPState)
			{
				case SMTP_HELO:
					if(SMTPClient.Username == NULL)
						TCPIP_TCP_StringPut(MySocket, (uint8_t*)"HELO MCHPBOARD\r\n");
					else    
						TCPIP_TCP_StringPut(MySocket, (uint8_t*)"EHLO MCHPBOARD\r\n");
					TCPIP_TCP_Flush(MySocket);
					SMTPState++;
					break;

				case SMTP_AUTH_LOGIN:
					// Note: This state is only entered from SMTP_HELO_ACK if the application 
					// has specified a Username to use (SMTPClient.Username is non-NULL)
					TCPIP_TCP_StringPut(MySocket, (uint8_t*)"AUTH LOGIN\r\n");
					TCPIP_TCP_Flush(MySocket);
					SMTPState++;
					break;

				case SMTP_AUTH_USERNAME:
					// Base 64 encode and transmit the username.
                    RAMStrPtr = (uint8_t*)SMTPClient.Username;
                    w = strlen((char*)RAMStrPtr);

					while(w)
					{
						i = 0;
						while((i < w) && (i < sizeof(vBase64Buffer)*3/4))
						{
                            vBase64Buffer[i] = *RAMStrPtr++;
							i++;
						}
						w -= i;					
						TCPIP_Helper_Base64Encode(vBase64Buffer, i, vBase64Buffer, sizeof(vBase64Buffer));
						TCPIP_TCP_ArrayPut(MySocket, vBase64Buffer, sizeof(vBase64Buffer));
					}
					TCPIP_TCP_StringPut(MySocket, (uint8_t*)"\r\n");
					TCPIP_TCP_Flush(MySocket);
					SMTPState++;
					break;

				case SMTP_AUTH_PASSWORD:
					// Base 64 encode and transmit the password
                    RAMStrPtr = (uint8_t*)SMTPClient.Password;
                    w = strlen((char*)RAMStrPtr);

					while(w)
					{
						i = 0;
						while((i < w) && (i < sizeof(vBase64Buffer)*3/4))
						{
                            vBase64Buffer[i] = *RAMStrPtr++;
							i++;
						}
						w -= i;					
						TCPIP_Helper_Base64Encode(vBase64Buffer, i, vBase64Buffer, sizeof(vBase64Buffer));
						TCPIP_TCP_ArrayPut(MySocket, vBase64Buffer, sizeof(vBase64Buffer));
					}
					TCPIP_TCP_StringPut(MySocket, (uint8_t*)"\r\n");
					TCPIP_TCP_Flush(MySocket);
					SMTPState++;
					break;

				case SMTP_MAILFROM:
					// Send MAIL FROM header.  Note that this is for the SMTP server validation, 
					// not what actually will be displayed in the recipients mail client as a 
					// return address.
					TCPIP_TCP_StringPut(MySocket, (uint8_t*)"MAIL FROM:<");
                    RAMStrPtr = FindEmailAddress((uint8_t*)SMTPClient.From, &wAddressLength);
                    TCPIP_TCP_ArrayPut(MySocket, RAMStrPtr, wAddressLength);
					TCPIP_TCP_StringPut(MySocket, (uint8_t*)">\r\n");
					TCPIP_TCP_Flush(MySocket);
					SMTPState++;
					break;

				case SMTP_RCPTTO_INIT:
					// See if there are any (To) recipients to process
					if(SMTPClient.To)
					{
						RAMStrPtr = FindEmailAddress((uint8_t*)SMTPClient.To, &wAddressLength);
						if(wAddressLength)
						{
							SMTPState = SMTP_RCPTTO;
							break;
						}
					}
					
					SMTPState = SMTP_RCPTTOCC_INIT;
					break;

				case SMTP_RCPTTO:
				case SMTP_RCPTTOCC:
				case SMTP_RCPTTOBCC:
					TCPIP_TCP_StringPut(MySocket, (uint8_t*)"RCPT TO:<");
                    TCPIP_TCP_ArrayPut(MySocket, RAMStrPtr, wAddressLength);
					TCPIP_TCP_StringPut(MySocket, (uint8_t*)">\r\n");
					TCPIP_TCP_Flush(MySocket);
					SMTPState++;
					break;

				case SMTP_RCPTTO_ISDONE:
					// See if we have any more (To) recipients to process
					// If we do, we must roll back a couple of states
                    RAMStrPtr = FindEmailAddress(RAMStrPtr+wAddressLength, &wAddressLength);
	
					if(wAddressLength)
					{
						SMTPState = SMTP_RCPTTO;
						break;
					}

					// All done with To field
					SMTPState++;
					//No break

				case SMTP_RCPTTOCC_INIT:
					// See if there are any Carbon Copy (CC) recipients to process
					if(SMTPClient.CC)
					{
						RAMStrPtr = FindEmailAddress((uint8_t*)SMTPClient.CC, &wAddressLength);
						if(wAddressLength)
						{
							SMTPState = SMTP_RCPTTOCC;
							break;
						}
					}
					
					SMTPState = SMTP_RCPTTOBCC_INIT;
					break;

				case SMTP_RCPTTOCC_ISDONE:
					// See if we have any more Carbon Copy (CC) recipients to process
					// If we do, we must roll back a couple of states
                    RAMStrPtr = FindEmailAddress(RAMStrPtr+wAddressLength, &wAddressLength);

					if(wAddressLength)
					{
						SMTPState = SMTP_RCPTTOCC;
						break;
					}

					// All done with CC field
					SMTPState++;
					//No break

				case SMTP_RCPTTOBCC_INIT:
					// See if there are any Blind Carbon Copy (BCC) recipients to process
					if(SMTPClient.BCC)
					{
						RAMStrPtr = FindEmailAddress((uint8_t*)SMTPClient.BCC, &wAddressLength);
						if(wAddressLength)
						{
							SMTPState = SMTP_RCPTTOBCC;
							break;
						}
					}

					// All done with BCC field
					SMTPState = SMTP_DATA;
					break;

				case SMTP_RCPTTOBCC_ISDONE:
					// See if we have any more Blind Carbon Copy (CC) recipients to process
					// If we do, we must roll back a couple of states
                    RAMStrPtr = FindEmailAddress(RAMStrPtr+wAddressLength, &wAddressLength);

					if(wAddressLength)
					{
						SMTPState = SMTP_RCPTTOBCC;
						break;
					}

					// All done with BCC field
					SMTPState++;
					//No break

				case SMTP_DATA:
					TCPIP_TCP_StringPut(MySocket, (uint8_t*)"DATA\r\n");
					SMTPState++;
					PutHeadersState = PUTHEADERS_FROM_INIT;
					TCPIP_TCP_Flush(MySocket);
					break;

				case SMTP_DATA_HEADER:
					while((PutHeadersState != PUTHEADERS_DONE) && (TCPIP_TCP_PutIsReady(MySocket) > 64u))
					{
						switch(PutHeadersState)
						{
							case PUTHEADERS_FROM_INIT:
								if(SMTPClient.From)
								{
									PutHeadersState = PUTHEADERS_FROM;
									TCPIP_TCP_StringPut(MySocket, (uint8_t*)"From: ");
								}
								else
								{
									PutHeadersState = PUTHEADERS_TO_INIT;
								}
								break;
								
							case PUTHEADERS_FROM:
                                SMTPClient.From = (char*)TCPIP_TCP_StringPut(MySocket, (uint8_t*)SMTPClient.From);
                                if(*SMTPClient.From == 0u)
                                    PutHeadersState = PUTHEADERS_TO_INIT;
								break;

							case PUTHEADERS_TO_INIT:
								if(SMTPClient.To)
								{
									PutHeadersState = PUTHEADERS_TO;
									TCPIP_TCP_StringPut(MySocket, (uint8_t*)"\r\nTo: ");
								}
								else
								{
									PutHeadersState = PUTHEADERS_CC_INIT;
								}
								break;
								
							case PUTHEADERS_TO:
                                SMTPClient.To = (char*)TCPIP_TCP_StringPut(MySocket, (uint8_t*)SMTPClient.To);
                                if(*SMTPClient.To == 0u)
                                    PutHeadersState = PUTHEADERS_CC_INIT;
								break;

							case PUTHEADERS_CC_INIT:
								if(SMTPClient.CC)
								{
									PutHeadersState = PUTHEADERS_CC;
									TCPIP_TCP_StringPut(MySocket, (uint8_t*)"\r\nCC: ");
								}
								else
								{
									PutHeadersState = PUTHEADERS_SUBJECT_INIT;
								}
								break;
								
							case PUTHEADERS_CC:
                                SMTPClient.CC = (char*)TCPIP_TCP_StringPut(MySocket, (uint8_t*)SMTPClient.CC);
                                if(*SMTPClient.CC == 0u)
                                    PutHeadersState = PUTHEADERS_SUBJECT_INIT;
								break;

							case PUTHEADERS_SUBJECT_INIT:
								if(SMTPClient.Subject)
								{
									PutHeadersState = PUTHEADERS_SUBJECT;
									TCPIP_TCP_StringPut(MySocket, (uint8_t*)"\r\nSubject: ");
								}
								else
								{
									PutHeadersState = PUTHEADERS_OTHER_INIT;
								}
								break;
								
							case PUTHEADERS_SUBJECT:
                                SMTPClient.Subject = (char*)TCPIP_TCP_StringPut(MySocket, (uint8_t*)SMTPClient.Subject);
                                if(*SMTPClient.Subject == 0u)
                                    PutHeadersState = PUTHEADERS_OTHER_INIT;
								break;

							case PUTHEADERS_OTHER_INIT:
								TCPIP_TCP_ArrayPut(MySocket, (uint8_t*)"\r\n", 2);
								if(SMTPClient.OtherHeaders)
								{
									PutHeadersState = PUTHEADERS_OTHER;
								}
								else
								{
									TCPIP_TCP_ArrayPut(MySocket, (uint8_t*)"\r\n", 2);
									PutHeadersState = PUTHEADERS_DONE;
									SMTPState++;
								}
								break;
								
							case PUTHEADERS_OTHER:
                                SMTPClient.OtherHeaders = (char*)TCPIP_TCP_StringPut(MySocket, (uint8_t*)SMTPClient.OtherHeaders);
                                if(*SMTPClient.OtherHeaders == 0u)
                                {
                                    TCPIP_TCP_ArrayPut(MySocket, (uint8_t*)"\r\n", 2);
                                    PutHeadersState = PUTHEADERS_DONE;
                                    SMTPState++;
                                }
								break;
							
							// Default case needed to supress compiler diagnostics
							default:
								break;
						}
					}
					TCPIP_TCP_Flush(MySocket);
					break;
		
				case SMTP_DATA_BODY_INIT:
					SMTPState++;
					RAMStrPtr = (uint8_t*)SMTPClient.Body;
					ROMStrPtr2 = (const uint8_t*)"\r\n.\r\n";
					CRPeriod.Pos = NULL;
					if(RAMStrPtr)
						CRPeriod.Pos = (uint8_t*)strstr((char*)RAMStrPtr, (const char*)"\r\n.");
					// No break here
		
				case SMTP_DATA_BODY:
					if(SMTPClient.Body)
					{
						if(*ROMStrPtr2)
						{
							// Put the application data, doing the transparancy replacement of "\r\n." with "\r\n.."
							while(CRPeriod.Pos)
							{
								CRPeriod.Pos += 3;
								RAMStrPtr += TCPIP_TCP_ArrayPut(MySocket, RAMStrPtr, CRPeriod.Pos-RAMStrPtr);
								if(RAMStrPtr == CRPeriod.Pos)
								{
									if(!TCPIP_TCP_Put(MySocket, '.'))
									{
										CRPeriod.Pos -= 3;
										break;
									}
								}
								else
								{
									CRPeriod.Pos -= 3;
									break;
								}
								CRPeriod.Pos = (uint8_t*)strstr((char*)RAMStrPtr, (const char*)"\r\n.");
							}
							
							// If we get down here, either all replacements have been made or there is no remaining space in the TCP output buffer
							RAMStrPtr = TCPIP_TCP_StringPut(MySocket, RAMStrPtr);
							ROMStrPtr2 = TCPIP_TCP_StringPut(MySocket, (uint8_t*)ROMStrPtr2);
							TCPIP_TCP_Flush(MySocket);
						}
					}
					else
					{
						if(SMTPFlags.bits.ReadyToFinish)
						{
							if(*ROMStrPtr2)
							{
								ROMStrPtr2 = TCPIP_TCP_StringPut(MySocket, (uint8_t*)ROMStrPtr2);
								TCPIP_TCP_Flush(MySocket);
							}
		
						}
					}

					if(*ROMStrPtr2 == 0u)
					{
						SMTPState++;
					}
					break;
		
				case SMTP_QUIT_INIT:
					SMTPState++;
					ROMStrPtr = (const uint8_t*)"QUIT\r\n";
					// No break here

				case SMTP_QUIT:
					if(*ROMStrPtr)
					{
						ROMStrPtr = TCPIP_TCP_StringPut(MySocket, (uint8_t*)ROMStrPtr);
						TCPIP_TCP_Flush(MySocket);
					}

					if(*ROMStrPtr == 0u)
					{
						TransportState = TRANSPORT_CLOSE;
					}
					break;
				
				// Default case needed to supress compiler diagnostics
				default:
					break;
			}
			break;

		case TRANSPORT_CLOSE:
			// Close the socket so it can be used by other modules
			TCPIP_TCP_Close(MySocket);
			MySocket = INVALID_SOCKET;

			// Go back to doing nothing
			TransportState = TRANSPORT_HOME;
			break;
	}
}
Esempio n. 13
0
// sntp_manager.h
bool TCPIP_SNTP_Client(TCPIP_NET_IF* pNetIf)
{
    NTP_PACKET          pkt;
    uint16_t            w;
    TCPIP_DNS_RESULT          dnsRes;
    static uint32_t     SNTPTimer;


    if(pSntpIf != 0 && pNetIf != pSntpIf)
    {   // not our job
        return false;
    }

    switch(sntpState)
    {
        case SM_HOME:
            sntpSocket = INVALID_UDP_SOCKET;
            pSntpIf = pSntpDefIf;
            if(!TCPIP_STACK_NetworkIsLinked(pSntpIf))
            {
                pSntpIf = _TCPIPStackAnyNetLinked(true);
            }

            TCPIP_DNS_Resolve(NTP_SERVER, ntpConnection ==IP_ADDRESS_TYPE_IPV6 ? DNS_TYPE_AAAA : DNS_TYPE_A);
            sntpState++;
            break;

        case SM_WAIT_DNS:
            dnsRes = TCPIP_DNS_IsResolved(NTP_SERVER, &serverIP);
            if(dnsRes == DNS_RES_PENDING)
            {   // ongoing operation;
                break;
            }
            else if(dnsRes < 0)
            {   // some DNS error occurred; retry after waiting a while
                SNTPTimer = SYS_TMR_TickCountGet();
                sntpState = SM_SHORT_WAIT;
                ntpLastError = SNTP_RES_NTP_DNS_ERR;
            }
            else
            {
                sntpState++;
            }
            break;

        case SM_DNS_RESOLVED:
	    sntpSocket = TCPIP_UDP_ClientOpen(ntpConnection, TCPIP_NTP_SERVER_REMOTE_PORT, (IP_MULTI_ADDRESS*)&serverIP);
            if(sntpSocket != INVALID_UDP_SOCKET)
            {
                TCPIP_UDP_SocketNetSet(sntpSocket, pSntpIf);
                sntpState++;
                SNTPTimer = SYS_TMR_TickCountGet();
            }
            else
            {
                ntpLastError = SNTP_RES_SKT_ERR; 
            }
            break;

        case SM_UDP_IS_OPENED:
            if(TCPIP_UDP_IsOpened(sntpSocket) == true)
            {
                SNTPTimer = SYS_TMR_TickCountGet();
                sntpState = SM_UDP_SEND;
            }
            else if((SYS_TMR_TickCountGet() - SNTPTimer > 1*SYS_TMR_TickPerSecond()))
            {   // failed to open
                TCPIP_UDP_Close(sntpSocket);
                sntpState = SM_DNS_RESOLVED;
                sntpSocket = INVALID_UDP_SOCKET;
                ntpLastError = SNTP_RES_SKT_ERR; 
            }
            break;

        case SM_UDP_SEND:
            // Open up the sending UDP socket
            // Make certain the socket can be written to
            if(!TCPIP_UDP_TxPutIsReady(sntpSocket, sizeof(pkt)))
            {   // Wait no more than 1 sec
                if((SYS_TMR_TickCountGet() - SNTPTimer > 1*SYS_TMR_TickPerSecond()))
                {
                    TCPIP_UDP_Close(sntpSocket);
                    sntpState = SM_DNS_RESOLVED;
                    sntpSocket = INVALID_UDP_SOCKET;
                    ntpLastError = SNTP_RES_SKT_ERR; 
                    break;
                }
            }

            // Success
            // Transmit a time request packet
            memset(&pkt, 0, sizeof(pkt));
            pkt.flags.versionNumber = NTP_VERSION;
            pkt.flags.mode = 3;             // NTP Client
            pkt.orig_ts_secs = TCPIP_Helper_htonl(NTP_EPOCH);
            TCPIP_UDP_ArrayPut(sntpSocket, (uint8_t*) &pkt, sizeof(pkt));
            TCPIP_UDP_Flush(sntpSocket);

            SNTPTimer = SYS_TMR_TickCountGet();
            sntpState = SM_UDP_RECV;
            break;

        case SM_UDP_RECV:
            // Look for a response time packet
            if(!TCPIP_UDP_GetIsReady(sntpSocket))
            {
                if((SYS_TMR_TickCountGet()) - SNTPTimer > NTP_REPLY_TIMEOUT * SYS_TMR_TickPerSecond())
                {
                    // Abort the request and resume
                    TCPIP_UDP_Close(sntpSocket);
                    //SNTPTimer = SYS_TMR_TickCountGet();
                    //sntpState = SM_SHORT_WAIT;
                    sntpState = SM_HOME;
                    sntpSocket = INVALID_UDP_SOCKET;
                    ntpLastError = SNTP_RES_NTP_SERVER_TMO; 
                }
                break;
            }

            // Get the response time packet
            w = TCPIP_UDP_ArrayGet(sntpSocket, (uint8_t*) &pkt, sizeof(pkt));
            TCPIP_UDP_Close(sntpSocket);
            SNTPTimer = SYS_TMR_TickCountGet();

            sntpState = SM_WAIT;
            sntpSocket = INVALID_UDP_SOCKET;

            // sanity packet check
            if(w != sizeof(pkt) || pkt.flags.versionNumber != NTP_VERSION )
            {
                ntpLastError = SNTP_RES_NTP_VERSION_ERR; 
                break;
            }
            if((pkt.tx_ts_secs == 0 && pkt.tx_ts_fraq == 0))
            {
                ntpLastError = SNTP_RES_NTP_TSTAMP_ERR; 
                break;
            }
            if(pkt.stratum == 0 )
            {
                ntpLastError = SNTP_RES_NTP_KOD_ERR; 
                break;
            }
            if(pkt.stratum >= NTP_MAX_STRATUM || pkt.flags.leapIndicator == 3 )
            {
                ntpLastError = SNTP_RES_NTP_SYNC_ERR; 
                break;
            }

            // get the last timestamp
            ntpTimeStamp.tStampSeconds = pkt.tx_ts_secs;
            ntpTimeStamp.tStampFraction = pkt.tx_ts_fraq;
            ntpLastStampTick = SYS_TMR_TickCountGet();

            
            // Set out local time to match the returned time
            dwLastUpdateTick = ntpLastStampTick;
            dwSNTPSeconds = TCPIP_Helper_ntohl(pkt.tx_ts_secs) - NTP_EPOCH;
            // Do rounding.  If the partial seconds is > 0.5 then add 1 to the seconds count.
            if(((uint8_t*)&pkt.tx_ts_fraq)[0] & 0x80)
                dwSNTPSeconds++;

            break;

        case SM_SHORT_WAIT:
            // Attempt to requery the NTP server after a specified NTP_FAST_QUERY_INTERVAL time (ex: 8 seconds) has elapsed.
            if(SYS_TMR_TickCountGet() - SNTPTimer > (NTP_FAST_QUERY_INTERVAL * SYS_TMR_TickPerSecond()))
            {
                sntpState = SM_HOME;
                sntpSocket = INVALID_UDP_SOCKET;
            }
            break;

        case SM_WAIT:
            // Requery the NTP server after a specified NTP_QUERY_INTERVAL time (ex: 10 minutes) has elapsed.
            if(SYS_TMR_TickCountGet() - SNTPTimer > (NTP_QUERY_INTERVAL * SYS_TMR_TickPerSecond()))
            {
                sntpState = SM_HOME;
                sntpSocket = INVALID_UDP_SOCKET;
            }

            break;
    }

    return true;

}//TCPIP_SNTP_Client
void BSP_LED_LightShow(BSP_LED_LIGHT_SHOW lightShow)
{
    static uint32_t ledTick = 0;
    static uint8_t count = 0;
    static uint8_t count2 = 0;
    static uint32_t connectionTimeout = 0;

    switch (lightShow)
    {
        case     BSP_LED_EASY_CONFIGURATION:
            if(SYS_TMR_TickCountGet() - ledTick >= 625)
            {
                ledTick = SYS_TMR_TickCountGet();
                BSP_LEDToggle(BSP_LED_5_CHANNEL, BSP_LED_5_PORT);
                BSP_LEDOff(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);
                BSP_LEDOff(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
                BSP_LEDOff(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
                BSP_LEDOff(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
                BSP_LEDOff(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
            }
            break;

        case     BSP_LED_CONNECTING_TO_AP:
            if(SYS_TMR_TickCountGet() - connectionTimeout >= (1250 * 10))
            {
                connectionTimeout = SYS_TMR_TickCountGet();
                BSP_LED_LightShowSet(BSP_LED_CONNECTION_FAILED);
            }
            if (SYS_TMR_TickCountGet() - ledTick >= 150)
            {
                ledTick = SYS_TMR_TickCountGet();
                BSP_LEDOff(BSP_LED_5_CHANNEL, BSP_LED_5_PORT);
                BSP_LEDOn(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);
                switch (count)
                {
                    case (0):
                        BSP_LEDOn(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
                        BSP_LEDOff(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
                        BSP_LEDOff(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
                        BSP_LEDOff(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
                        count++;
                        break;
                    case (1):
                        BSP_LEDOff(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
                        BSP_LEDOn(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
                        BSP_LEDOff(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
                        BSP_LEDOff(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
                        count++;
                        break;
                    case (2):
                        BSP_LEDOff(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
                        BSP_LEDOff(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
                        BSP_LEDOff(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
                        BSP_LEDOn(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
                        count++;
                        break;
                    case (3):
                        BSP_LEDOff(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
                        BSP_LEDOff(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
                        BSP_LEDOn(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
                        BSP_LEDOff(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
                        count = 0;
                        break;
                    default:
                        count = 0;
                        break;
                }

            }
            break;
            //Not implemented
        case     BSP_LED_CONNECTION_FAILED:
                BSP_LEDOff(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
                BSP_LEDOn(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
                BSP_LEDOff(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
                BSP_LEDOff(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
                BSP_LEDOn(BSP_LED_5_CHANNEL, BSP_LED_5_PORT);
                BSP_LEDOn(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);

            if(SYS_TMR_TickCountGet() - connectionTimeout >= 4750)
            {
                connectionTimeout = SYS_TMR_TickCountGet();
                ledTick = SYS_TMR_TickCountGet();
                BSP_LED_LightShowSet(BSP_LED_CONNECTING_TO_AP);
            }
            break;
        case    BSP_LED_AP_CONNECTED:
                if(SYS_TMR_TickCountGet() - ledTick >= 625)
                {
                    count2++;
                    ledTick = SYS_TMR_TickCountGet();
                    BSP_LEDStateSet(BSP_LED_5_CHANNEL, BSP_LED_5_PORT, BSP_LEDStateGet(BSP_LED_6_CHANNEL, BSP_LED_6_PORT));
                    BSP_LEDToggle(BSP_LED_5_CHANNEL, BSP_LED_6_PORT);
                    BSP_LEDToggle(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);
                    BSP_LEDOff(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
                    BSP_LEDOff(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
                    BSP_LEDOff(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
                    BSP_LEDOff(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
                }
            break;

        case    BSP_LED_SERVER_CONNECT_FAILED:
                BSP_LEDOn(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
                BSP_LEDOff(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
                BSP_LEDOff(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
                BSP_LEDOff(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
                BSP_LEDOn(BSP_LED_5_CHANNEL, BSP_LED_5_PORT);
                BSP_LEDOn(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);
            break;

        case    BSP_LED_ALL_GOOD:
                BSP_LEDOff(BSP_LED_5_CHANNEL, BSP_LED_5_PORT);
                BSP_LEDOff(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);
                ledTick = SYS_TMR_TickCountGet();
            // Idle state
            break;
            
        case    BSP_LED_TX:
            BSP_LEDOn(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);
            if(SYS_TMR_TickCountGet() - ledTick >= 30)
                BSP_LED_LightShowSet(BSP_LED_ALL_GOOD);
            break;
            
        case    BSP_LED_RX:
            BSP_LEDOn(BSP_LED_5_CHANNEL, BSP_LED_5_PORT);
            if(SYS_TMR_TickCountGet() - ledTick >= 30)
                BSP_LED_LightShowSet(BSP_LED_ALL_GOOD);
            break; 

        case    BSP_LED_DNS_FAILED:
            BSP_LEDOn(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
            BSP_LEDOff(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
            BSP_LEDOn(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
            BSP_LEDOff(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
            BSP_LEDOn(BSP_LED_5_CHANNEL, BSP_LED_5_PORT);
            BSP_LEDOn(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);
        break;
        
        case    BSP_LED_TCPIP_STACK_INIT_FAILURE:
            BSP_LEDOff(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
            BSP_LEDOn(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
            BSP_LEDOn(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
            BSP_LEDOff(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
            BSP_LEDOn(BSP_LED_5_CHANNEL, BSP_LED_5_PORT);
            BSP_LEDOn(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);
        break;
        
        case BSP_LED_NVM_FAILED_MOUNT:
            BSP_LEDOff(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
            BSP_LEDOff(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
            BSP_LEDOn(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
            BSP_LEDOff(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
            BSP_LEDOn(BSP_LED_5_CHANNEL, BSP_LED_5_PORT);
            BSP_LEDOn(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);
        break;  
        
        case BSP_LED_INTIAL_CONNECT:
            BSP_LEDOn(BSP_LED_1_CHANNEL, BSP_LED_1_PORT);
            BSP_LEDOn(BSP_LED_2_CHANNEL, BSP_LED_2_PORT);
            BSP_LEDOn(BSP_LED_3_CHANNEL, BSP_LED_3_PORT);
            BSP_LEDOn(BSP_LED_4_CHANNEL, BSP_LED_4_PORT);
            BSP_LEDOn(BSP_LED_5_CHANNEL, BSP_LED_5_PORT);
            BSP_LEDOn(BSP_LED_6_CHANNEL, BSP_LED_6_PORT);
            
        default:
            break;
    }
}
void APP1_Tasks ( void )
{
    /* Check the application's current state. */
    switch ( app1Data.state )
    {
        /* Application's initial state. */
        case APP1_STATE_INIT:
        {
            bool appInitialized = true;
       
        
            if (appInitialized)
            {
                // Open the ADC drivers
                DRV_ADC0_Open();
               // DRV_ADC1_Open();
                DRV_ADC_DigitalFilter0_Open();
               // DRV_ADC_DigitalFilter1_Open();
                DRV_ADC_Start();
                app1Data.state = APP1_STATE_SERVICE_TASKS;
            }
            break;
        }

        case APP1_STATE_SERVICE_TASKS:
        {
            // BSP tasks that control switch and led functions
            BSP_SYS_Tasks();
            
            // Check if switches are pressed and send a message to the queue
            if(BSP_SWITCH_SwitchGetState(BSP_SWITCH_1_PORT) != bspData.previousStateS1){
                BSP_SWITCH_SwitchSetPreviousState(BSP_SWITCH_1_PORT, BSP_SWITCH_SwitchGetState(BSP_SWITCH_1_PORT));
                mySwitchMessage.switchNum = BSP_SWITCH_1;
                mySwitchMessage.switchVal = bspData.previousStateS1;
                xQueueSendToBack( app1Data.switchQueue, &mySwitchMessage, 1 );
            }
            if(BSP_SWITCH_SwitchGetState(BSP_SWITCH_2_PORT) != bspData.previousStateS2){
                BSP_SWITCH_SwitchSetPreviousState(BSP_SWITCH_2_PORT, BSP_SWITCH_SwitchGetState(BSP_SWITCH_2_PORT));
                mySwitchMessage.switchNum = BSP_SWITCH_2;
                mySwitchMessage.switchVal = bspData.previousStateS2;
                xQueueSendToBack( app1Data.switchQueue, &mySwitchMessage, 1 );
            }
            if(BSP_SWITCH_SwitchGetState(BSP_SWITCH_3_PORT) != bspData.previousStateS3){
                BSP_SWITCH_SwitchSetPreviousState(BSP_SWITCH_3_PORT, BSP_SWITCH_SwitchGetState(BSP_SWITCH_3_PORT));
                mySwitchMessage.switchNum = BSP_SWITCH_3;
                mySwitchMessage.switchVal = bspData.previousStateS3;
                xQueueSendToBack( app1Data.switchQueue, &mySwitchMessage, 1 );
            }
            if(BSP_SWITCH_SwitchGetState(BSP_SWITCH_4_PORT) != bspData.previousStateS4){
                BSP_SWITCH_SwitchSetPreviousState(BSP_SWITCH_4_PORT, BSP_SWITCH_SwitchGetState(BSP_SWITCH_4_PORT));
                mySwitchMessage.switchNum = BSP_SWITCH_4;
                mySwitchMessage.switchVal = bspData.previousStateS4;
                xQueueSendToBack( app1Data.switchQueue, &mySwitchMessage, 1 );
            }
            
            // Trigger an ADC reading every one second for the pot
            if((SYS_TMR_TickCountGet() - app1Data.potTimer) > (1000)){
                app1Data.potTimer = SYS_TMR_TickCountGet();
                DRV_ADC_Start();
            }
            
            // If the ADC reading is ready, see if value changed and send a message to queue
            if(DRV_ADC_DigitalFilter0_DataIsReady()) {
                app1Data.newPotSamp = (uint16_t)DRV_ADC_DigitalFilter0_DataRead();
                uint32_t adcVal;
                adcVal = app1Data.newPotSamp >> 6;
                if(adcVal != app1Data.potValue) {
                    app1Data.potValue = adcVal;
                    app1Data.potChanged = true;
                }
                
                if(app1Data.potChanged){
                    xQueueSendToBack( app1Data.potentiometerQueue, &app1Data.potValue, 1 );
                    app1Data.potChanged = false;
                }
            }
            
            // Check light show queue for a state, if exists, set state
            if( uxQueueMessagesWaiting( app1Data.lightShowQueue ) > 0 ){
                uint32_t lightShowVar;
                xQueueReceive( app1Data.lightShowQueue, &lightShowVar, 1 );
                BSP_LED_LightShowSet(lightShowVar);
            }
            
            break;
        }
        
        /* The default state should never be executed. */
        default:
        {
            /* TODO: Handle error in application's state machine. */
            break;
        }
    }
}
Esempio n. 16
0
void SSMLoadOnlineConfig_Tasks(void)
{
    switch(_state)
    {
        case STATE_NEEDS_MORE_CONFIG:
            // TODO: what do we do then? Display on status page?
            break;

        case STATE_ACTIVATING:
        {
            if(APP_SERIALFLASH_IsReady())
            {
                APP_Activation_Tasks();

                switch(APP_Activation_State())
                { // REVIEW: don't check internal state, but via test function
                    case APP_ACTIVATION_BARE_DONE:
                        if(strcmp(appGWActivationData.configuration.key, "") == 0)
                        {
                            FATAL("Activation done, but key not filled");
                        }

                        SYS_PRINT("\r\nCNFG: Valid key, proceeding\r\n");
                        _changeState(STATE_ERASING_ACTIVATION_KEY);
                        break;

                    case APP_ACTIVATION_BARE_WAS_ACTIVATED:
                        // invalid gateway id, wipe id, start over.
                        SYS_PRINT("\r\nCNFG: Was already activated, wait for a key to be configured\r\n");
                        _changeState(STATE_NEEDS_MORE_CONFIG);
                        break;

                    case APP_ACTIVATION_BARE_NON_EXISTING_ID:
                        SYS_PRINT("\r\nCNFG: Non existing ID, please register this ID with The Things Network\r\n");
                        _changeState(STATE_NEEDS_MORE_CONFIG);
                        break;

                    case APP_ACTIVATION_BARE_ERROR:
                        SYS_PRINT("\r\nCNFG: Activation failed\r\n");
                        ErrorMessageWarning_Set(ERROR_MESSAGE_WARNING_HTTP_COMMUNICATION_FAILURE_ACTIVATION);
                        _changeState(STATE_COMMUNICATION_ERROR);
                        break;
                }
            }
            break;
        }

        case STATE_ERASING_ACTIVATION_KEY:
            if(APP_SERIALFLASH_IsReady())
            {
                _changeState(STATE_STORING_ACTIVATION_KEY);
            }
            break;

        case STATE_STORING_ACTIVATION_KEY:
            if(APP_SERIALFLASH_IsReady())
            {
                SYS_PRINT("\r\nCNFG: Gateway Activated\r\n");
                _changeState(STATE_DOWNLOAD_LORA_CONFIG);
            }
            break;

        case STATE_DOWNLOAD_LORA_CONFIG:
            APP_Configuration_Tasks();

            switch(APP_Configuration_State())
            { // REVIEW: don't check internal state, but via test function
                case APP_CONFIGURATION_DONE:
                    if(appGWActivationData.locked)
                    {
                        _changeState(STATE_DOWNLOAD_FREQPLAN);
                    }
                    else
                    {
                        _changeState(STATE_LOCK_ACTIVATION);
                    }
                    break;

                case APP_CONFIGURATION_INCOMPLETE:
                    _changeState(STATE_NEEDS_MORE_CONFIG);
                    break;

                case APP_CONFIGURATION_NON_EXISTING_ID:
                    // invalid gateway id, wipe id, start over.
                    SYS_PRINT("\r\nCNFG: Non existing gateway ID, wiping and starting over\r\n");
                    appGWActivationData.configuration.id[0]  = '\0';
                    appGWActivationData.configuration.key[0] = '\0';
                    _changeState(STATE_NEEDS_MORE_CONFIG);
                    break;

                case APP_CONFIGURATION_KEY_FAILURE:
                    // invalid gateway key, wipe key start over.
                    SYS_PRINT("\r\nCNFG: Invalid gateway key, wiping and starting over\r\n");
                    appGWActivationData.configuration.key[0] = '\0';
                    _changeState(STATE_ACTIVATING);
                    break;

                case APP_CONFIGURATION_SERVER_BUSY:
                    if(SYS_TMR_TickCountGet() - reconnectDelayStartTick >=
                       SYS_TMR_TickCounterFrequencyGet() *
                           RECONNECT_DELAY_TIMEOUT) // REVIEW: use something like isElapsed function
                    {
                        SYS_PRINT("\r\nCNFG: Server busy, retry\r\n");
                        _changeState(STATE_DOWNLOAD_LORA_CONFIG);
                    }
                    break;

                case APP_CONFIGURATION_ERROR:
                    SYS_PRINT("\r\nCNFG: Downloading gateway configuration failed\r\n");
                    _changeState(STATE_COMMUNICATION_ERROR);
                    ErrorMessageWarning_Set(ERROR_MESSAGE_WARNING_HTTP_COMMUNICATION_FAILURE_CONFIGURATION);
                    break;

                default:
                    break;
            }
            break;

        case STATE_LOCK_ACTIVATION:
            if(APP_SERIALFLASH_IsReady())
            {
                SYS_PRINT("\r\nCNFG: Gateway activation locked\r\n");
                _changeState(STATE_DOWNLOAD_FREQPLAN);
            }
            break;

        case STATE_DOWNLOAD_FREQPLAN:
            // Fetch lora module configuration
            if(SYS_TMR_TickCountGet() - freqDelayStartTick <= SYS_TMR_TickCounterFrequencyGet() * 2)
            {
                break; // take a little break after the settings fetch to be nice on the TTN server
            }

            APP_FreqPlan_Tasks();

            switch(APP_FreqPlan_State())
            { // REVIEW: don't check internal state, but via test function
                case APP_FREQPLAN_DONE:
                    _changeState(STATE_START_LORA_MODULE);
                    break;

                case APP_FREQPLAN_FAILURE:
                case APP_FREQPLAN_SERVER_BUSY:
                    SYS_PRINT("\r\nCNFG: Server busy/failure, retry\r\n");
                    _changeState(STATE_DOWNLOAD_FREQPLAN);
                    break;

                case APP_FREQPLAN_ERROR:
                    SYS_PRINT("\r\nCNFG: Downloading frequency plan failed\r\n");
                    ErrorMessageWarning_Set(ERROR_MESSAGE_WARNING_HTTP_COMMUNICATION_FAILURE_FREQPLAN);
                    _changeState(STATE_COMMUNICATION_ERROR);
                    break;
            }
            break;

        case STATE_START_LORA_MODULE:
            if(APP_LORA_GET_APP_STATE() ==
               APP_LORA_POLL_UART) // REVIEW: don't check internal state, but via test function
            {
                _changeState(STATE_DONE);
            }

        case STATE_COMMUNICATION_ERROR:
            break;

        case STATE_DONE:
            break;
    }
}