Example #1
0
long FTPStreamWrite(char strWrite[], long toWrite)
{
	long len = 0;
	DWORD tick1, tick2;
	if ( (FTPisConn(dataSocket)) && (streamStat == FTP_STREAM_WRITING) )
	{
		tick1 = TickGetDiv64K();
		while (len < toWrite)
		{ 
			len += FTPWrite(dataSocket, (BYTE*)&strWrite[len], toWrite - len);
			//	Checking timeout on writing operation
			tick2 = TickGetDiv64K();
			if ((tick2 - tick1) > 5)
			{
				//	Timeout occured during writing, a check on data connection is required
				if (!FTPisConn(dataSocket))
				{
					debug("FTPStreamWrite: timeout by server disconnection\n");
					errHandling(&dataSocket);
					streamStat = FTP_STREAM_NOT_CONN;
					return len;
				}
				else
				{
					debug("FTPStreamWrite: timeout\n");
					return len;
				}
			}
		}
		return len;
	}
	else if (!FTPisConn(dataSocket))
		return FTP_DATA_NO_CONNECTED;
	else 
		return FTP_STREAM_INVALID_OP;
}
Example #2
0
/*********************************************************************
  Function:
  	static DWORD SNMPGetTimeStamp(void)
                                   
  Summary:
	Obtains the current Tick value for the SNMP time stamp.

  Description:
	This function retrieves the absolute time measurements for 
	SNMP time stamp.Use TickGet and TickGetDiv64K to collect all 48bits
	of the internal Tick Timer.

  PreCondition:
  	None
 
  parameters:
  	None
 
  Return Values:
  	timeStamp - DWORD timevalue
 
  Remarks:
 	None.
 ********************************************************************/
static DWORD SNMPGetTimeStamp(void)
{

	DWORD_VAL dwvHigh, dwvLow;
    DWORD dw;
    DWORD timeStamp;
	
	//TimeStamp
	// Get all 48 bits of the internal Tick timer
    do
   	{
	   	dwvHigh.Val = TickGetDiv64K();
	   	dwvLow.Val = TickGet();
	} while(dwvHigh.w[0] != dwvLow.w[1]);
    dwvHigh.Val = dwvHigh.w[1];
    
	// Find total contribution from lower DWORD
    dw = dwvLow.Val/(DWORD)TICK_SECOND;
    timeStamp = dw*100ul;
    dw = (dwvLow.Val - dw*(DWORD)TICK_SECOND)*100ul;		// Find fractional seconds and convert to 10ms ticks
    timeStamp += (dw+((DWORD)TICK_SECOND/2ul))/(DWORD)TICK_SECOND;

	// Itteratively add in the contribution from upper WORD
	while(dwvHigh.Val >= 0x1000ul)
	{
		timeStamp += (0x100000000000ull*100ull+(TICK_SECOND/2ull))/TICK_SECOND;
		dwvHigh.Val -= 0x1000;
	}	
	while(dwvHigh.Val >= 0x100ul)
	{
		timeStamp += (0x010000000000ull*100ull+(TICK_SECOND/2ull))/TICK_SECOND;
		dwvHigh.Val -= 0x100;
	}	
	while(dwvHigh.Val >= 0x10ul)
	{
		timeStamp += (0x001000000000ull*100ull+(TICK_SECOND/2ull))/TICK_SECOND;
		dwvHigh.Val -= 0x10;
	}	
	while(dwvHigh.Val)
	{
		timeStamp += (0x000100000000ull*100ull+(TICK_SECOND/2ull))/TICK_SECOND;
		dwvHigh.Val--;
	}
    
    return timeStamp;
}
Example #3
0
/// @cond debug
int  cSMTPEmailSend()
{
    char cmdReply[200];
    char msg2send[200];
    int resCheck = 0;
    DWORD tick;
    int countData;
    int chars2read;

    switch(smInternal)
    {
    case 0:
        // Check if Buffer is free
        if(GSMBufferSize() > 0)
        {
            // Parse Unsol Message
            mainGSMStateMachine = SM_GSM_CMD_PENDING;
            return -1;
        }
        else
            smInternal++;

    case 1:
        // AT+KSMTPSUBJECT
        sprintf(msg2send, "AT+KSMTPSUBJECT=\"");

        GSMWrite(msg2send);
        GSMWrite(smtpsubject);
        GSMWrite("\"\r");

        // Start timeout count
        tick = TickGetDiv64K(); // 1 tick every seconds
        maxtimeout = 2;
        smInternal++;

    case 2:
        vTaskDelay(20);
        // Check ECHO
        countData = 0;

        resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }
        else
        {
            int flushNum = strlen(smtpsubject) + 2;
            while(flushNum > 0)
            {
                GSMRead(cmdReply, 1);
                flushNum--;
            }
            cmdReply[0] = '\0';
        }

    case 3:
        // Get reply (\r\nOK\r\n)
        vTaskDelay(1);
        // Get OK
        sprintf(msg2send, "OK");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 4:
        maxtimeout = 60; //just to prevent hardware lock... it should be less since depends on data size
        // AT+KSMTPUL=1,<size> -> with "1,<size>" it is specified to use normal mode
        int smtpmsglen = strlen(smtpmsg);
        sprintf(msg2send, "AT+KSMTPUL=1,%d\r",smtpmsglen);

        GSMWrite(msg2send);
        // Start timeout count
        tick = TickGetDiv64K(); // 1 tick every seconds

        smInternal++;

    case 5:
        vTaskDelay(20);
        // Check ECHO
        countData = 0;

        resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 6:
        // Get reply "+KSMTPUL: <session_id>"
        vTaskDelay(20);
        sprintf(msg2send, "+KSMTPUL");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>+KSMTPUL: <session_id><CR><LF>

        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }
        else
        {
            // Get SMPT last session_id:
            char temp[25];
            int res = getfield(':', '\r', 5, 1, cmdReply, temp, 500);
            if(res != 1)
            {
                // Execute Error Handler
                gsmDebugPrint("Error in getfield for +KSMTPUL socket\r\n");
                break;
            }
            else
            {
                smtpLastSessionId = atoi(temp);
            }
        }

    case 7:
        // Get reply "\r\nCONNECT\r\n"
        vTaskDelay(2);
        sprintf(msg2send, "CONNECT\r\n");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>CONNECT<CR><LF>

        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }
        else
        {
            GSMWrite(smtpmsg);
        }

    case 8:
        // Get reply (\r\nOK\r\n)
        vTaskDelay(20);
        // Get OK
        sprintf(msg2send, "\r\nOK");
        chars2read = 2;
        countData = 0; // GSM buffer should be: <CR><LF>OK<CR><LF>
        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }


    default:
        break;
    }

    smInternal = 0;
    // Cmd = 0 only if the last command successfully executed
    mainOpStatus.ExecStat = OP_SUCCESS;
    mainOpStatus.Function = 0;
    mainOpStatus.ErrorCode = 0;
    mainGSMStateMachine = SM_GSM_IDLE;
    return -1;
}
Example #4
0
/// @cond debug
int  cSMTPEmailTo()
{
    char cmdReply[350];
    char msg2send[350];
    int resCheck = 0;
    DWORD tick;
    int countData;
    int chars2read;

    switch(smInternal)
    {
    case 0:
        // Check if Buffer is free
        if(GSMBufferSize() > 0)
        {
            // Parse Unsol Message
            mainGSMStateMachine = SM_GSM_CMD_PENDING;
            return -1;
        }
        else
            smInternal++;

    case 1:
        // AT+KSMTPTO
        sprintf(msg2send, "AT+KSMTPTO=\"%s\",",smtpTo1);
        GSMWrite(msg2send);
        GSMWrite("\"");
        GSMWrite(smtpTo2);
        GSMWrite("\",\"");
        GSMWrite(smtpCc1);
        GSMWrite("\",\"");
        GSMWrite(smtpCc2);
        GSMWrite("\"");
        GSMWrite("\r");

        // Start timeout count
        tick = TickGetDiv64K(); // 1 tick every seconds
        maxtimeout = 2;
        smInternal++;

    case 2:
        vTaskDelay(1);
        // Check ECHO
        countData = 0;

        resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }
        else
        {
            int flushNum = 	strlen(smtpTo2) +
                            strlen(smtpCc1) +
                            strlen(smtpCc2) + 10;
            while(flushNum > 0)
            {
                GSMRead(cmdReply, 1);
                flushNum--;
            }
            cmdReply[0] = '\0';
        }

    case 3:
        // Get reply (\r\nOK\r\n)
        vTaskDelay(1);
        // Get OK
        sprintf(msg2send, "OK");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    default:
        break;
    }

    smInternal = 0;
    // Cmd = 0 only if the last command successfully executed
    mainOpStatus.ExecStat = OP_SUCCESS;
    mainOpStatus.Function = 0;
    mainOpStatus.ErrorCode = 0;
    mainGSMStateMachine = SM_GSM_IDLE;
    return -1;
}
Example #5
0
/// @cond debug
int  cSMTPParamsSet()
{
    char cmdReply[200];
    char msg2send[200];
    int resCheck = 0;
    DWORD tick;
    int countData;
    int chars2read;

    switch(smInternal)
    {
    case 0:
        // Check if Buffer is free
        if(GSMBufferSize() > 0)
        {
            // Parse Unsol Message
            mainGSMStateMachine = SM_GSM_CMD_PENDING;
            return -1;
        }
        else
            smInternal++;

    case 1:
        // Send first AT command
        // AT&K3
        sprintf(msg2send, "AT&K3\r");

        GSMWrite(msg2send);
        // Start timeout count
        tick = TickGetDiv64K(); // 1 tick every seconds
        maxtimeout = 2;
        smInternal++;

    case 2:
        vTaskDelay(20);
        // Check ECHO
        countData = 0;

        resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 3:
        // Get reply (\r\nOK\r\n)
        vTaskDelay(1);
        // Get OK
        sprintf(msg2send, "OK");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 4:
        // AT+KCNXTIMER
        sprintf(msg2send, "AT+KCNXTIMER=0,60,2,70\r");

        GSMWrite(msg2send);
        // Start timeout count
        tick = TickGetDiv64K(); // 1 tick every seconds
        maxtimeout = 2;
        smInternal++;

    case 5:
        vTaskDelay(1);
        // Check ECHO
        countData = 0;

        resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 6:
        // Get reply (\r\nOK\r\n)
        vTaskDelay(1);
        // Get OK
        sprintf(msg2send, "OK");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 7:
        // AT+CGATT=1
        sprintf(msg2send, "AT+CGATT=1\r");

        GSMWrite(msg2send);
        // Start timeout count
        tick = TickGetDiv64K(); // 1 tick every seconds
        maxtimeout = 60;
        smInternal++;

    case 8:
        vTaskDelay(1);
        // Check ECHO
        countData = 0;

        resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 9:
        // Get reply (\r\nOK\r\n)
        vTaskDelay(1);
        // Get OK
        sprintf(msg2send, "OK");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 10:
        // ----------	SMTP Parameter Configuration	----------
        sprintf(msg2send, "AT+KSMTPPARAM=\"%s\",%d,\"%s\"\r",smtpdomain, smtpport, smtpsender);

        GSMWrite(msg2send);
        // Start timeout count
        tick = TickGetDiv64K(); // 1 tick every seconds
        maxtimeout = 2;
        smInternal++;

    case 11:
        vTaskDelay(20);
        // Check ECHO
        countData = 0;

        resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 12:
        /*
        // Get reply "+KSMTPPARAM: <socket>"
        vTaskDelay(2);
        sprintf(msg2send, "+KSMTPPARAM");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>+KSMTPPARAM: <socket><CR><LF>

        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
        	return mainOpStatus.ErrorCode;
        }
        */
        smInternal++;

    case 13:
        // Get reply (\r\nOK\r\n)
        vTaskDelay(1);
        // Get OK
        sprintf(msg2send, "OK");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 14:
        // ----------	SMTP Login Configuration	----------
        sprintf(msg2send, "AT+KSMTPPWD=\"%s\",\"%s\"\r",smtplogin, smtppassw);

        GSMWrite(msg2send);
        // Start timeout count
        tick = TickGetDiv64K(); // 1 tick every seconds
        maxtimeout = 2;
        smInternal++;

    case 15:
        vTaskDelay(1);
        // Check ECHO
        countData = 0;

        resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 16:
        /*
        // Get reply "+KSMTPPWD: <socket>"
        vTaskDelay(2);
        sprintf(msg2send, "+KSMTPPWD");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>+KSMTPPARAM: <socket><CR><LF>

        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
        	return mainOpStatus.ErrorCode;
        }
        else
        {

        }
        */
        smInternal++;

    case 17:
        // Get reply (\r\nOK\r\n)
        vTaskDelay(1);
        // Get OK
        sprintf(msg2send, "OK");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    default:
        break;
    }

    smInternal = 0;
    // Cmd = 0 only if the last command successfully executed
    mainOpStatus.ExecStat = OP_SUCCESS;
    mainOpStatus.Function = 0;
    mainOpStatus.ErrorCode = 0;
    mainGSMStateMachine = SM_GSM_IDLE;
    return -1;
}
Example #6
0
long FTPStreamRead(char dest[], int len, BYTE timeout)
{
	long count = 0;
	int toRead;
	DWORD tick1, tick2;
	if ( (FTPisConn(dataSocket)) && (streamStat == FTP_STREAM_READING) )
	{
		tick1 = TickGetDiv64K();
		while (count < len)
		{
			toRead = FTPRxLen(dataSocket);
			//	Resizing bytes to read according to buffer size
			if (toRead > (len - count))
				toRead = len - count;
			FTPRead(dataSocket, &dest[count], toRead);
			count += toRead;
			streamRBytes += toRead;
			
			//	No data to read, checking timeout and chars read
			if (toRead == 0)
			{
				//	check on file ending, if file is not finished, checking timeout
				if (streamRBytes == streamLen)
				{
					debug("FTPStreamRead: EOF reached\n");
					streamStat = FTP_STREAM_EOF;
					return count;
				}
				tick2 = TickGetDiv64K();
				IOPut(o4, toggle);
				if ( (tick2 -tick1) > timeout)
				{	
					//	Timeout occured during reading, a check on data connection is required
					if (!FTPisConn(dataSocket))
					{
						debug("FTPStreamRead: timeout by server disconnection\n");
						errHandling(&dataSocket);
						streamStat = FTP_STREAM_NOT_CONN;
						return count;
					}
					else
					{
						debug("FTPStreamRead: timeout\n");
						return count;
					}
				}
			}
			/*
			else
			{
				sprintf(dbg, "count:%d\n", count);
				UARTWrite(1, dbg);
				sprintf(dbg, "toRead:%d\n", toRead);
				UARTWrite(1, dbg);
			}
			*/
		}
		return count;
	} 
	else if (!FTPisConn(dataSocket))
		return FTP_DATA_NO_CONNECTED;
	else 
		return FTP_STREAM_INVALID_OP;
	
}
Example #7
0
/*****************************************************************************
 FUNCTION 	TCPIPTask
			Main function to handle the TCPIP stack
 
 RETURNS  	None
 
 PARAMS		None
*****************************************************************************/
void TCPIPTask()
{
	WFConnection = WF_CUSTOM;
	ConnectionProfileID = 0;
	static DWORD dwLastIP = 0;
	_WFStat = NOT_CONNECTED;
        
	dwLastIP = 0;
	//	Function pointers for the callback function of the TCP/IP and WiFi stack 

#if defined (FLYPORT_WF)
	FP[1] = cWFConnect;
	FP[2] = cWFDisconnect;
	FP[3] = cWFScan;
	FP[5] = cWFPsPollDisable;
	FP[6] = cWFPsPollEnable;
	FP[7] = cWFScanList;
#if defined (FLYPORT_G)
	FP[8] = cRSSIUpdate;
	FP[9] = cWFGetPSK;
#endif
	FP[10] = cWFStopConnecting;
	
#endif
#if defined (FLYPORT_ETH)
	FP[1] = cETHRestart;
#endif
#if defined (STACK_USE_SSL_CLIENT)
	FP[14] = cTCPSSLStatus;
	FP[15] = cTCPSSLStart;
#endif
	FP[16] = cTCPRxFlush;
	FP[17] = cTCPpRead;
	FP[18] = cTCPRemote;
	FP[19] = cTCPServerDetach;
	FP[20] = cTCPGenericOpen;
	FP[21] = cTCPRead;
	FP[22] = cTCPWrite;
	FP[23] = cTCPGenericClose;
	FP[24] = cTCPisConn;
	FP[25] = cTCPRxLen;


	#if defined(STACK_USE_SMTP_CLIENT)
	FP[26] = cSMTPStart;
	FP[27] = cSMTPSetServer;
	FP[28] = cSMTPSetMsg;
	FP[29] = cSMTPSend;
	FP[30] = cSMTPBusy;
	FP[31] = cSMTPStop;
	FP[32] = cSMTPReport;
	#endif
	
	FP[ARP_RESOLVE] = cARPResolveMAC;
	#if MAX_UDP_SOCKETS_FREERTOS>0	
	FP[35] = cUDPGenericOpen;
	FP[36] = cUDPWrite;
	FP[37] = cUDPGenericClose;
    FP[38] = cUDPMultiOn;
	#endif
	
	// Initialize stack-related hardware components that may be 
	// required by the UART configuration routines
	
	// Initialization of tick and of DHCPs SM only at the startup of the device
	if (hFlyTask == NULL)
	{
	    TickInit();
	    #if defined STACK_USE_DHCP_SERVER
	    DHCPServerSMInit();
	    #endif
	}  
	#if defined(STACK_USE_MPFS) || defined(STACK_USE_MPFS2)
	MPFSInit();
	#endif

	// Initialize Stack and application related NV variables into AppConfig.
	InitAppConfig();

	// Initialize core stack layers (MAC, ARP, TCP, UDP) and application modules (HTTP, SNMP, etc.)
    StackInit();

	if (hFlyTask == NULL)
	{
		NETConf[0] = AppConfig;
		NETConf[1] = AppConfig;
	}
	
	#if defined(WF_CS_TRIS)
	//	On startup no connection profile should be present inside WiFi module, so a new one is created
	UINT8 listIds = 0;
	WF_CPGetIds(&listIds);
	if (listIds == 0)
	{
		WF_CPCreate(&ConnectionProfileID);
	}
	//	Logical connection state initialization
	SetLogicalConnectionState(FALSE);
    #endif



	#if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
    ZeroconfLLInitialize();
	#endif

	
	#if defined(STACK_USE_ZEROCONF_MDNS_SD)
	mDNSInitialize(MY_DEFAULT_HOST_NAME);
	mDNSServiceRegister(
		(const char *) "DemoWebServer",		// base name of the service
		"_http._tcp.local",			    	// type of the service
		80,				                	// TCP or UDP port, at which this service is available
		((const BYTE *)"path=/index.htm"),	// TXT info
		1,								    // auto rename the service when if needed
		NULL,							    // no callback function
		NULL							    // no application context
		);

    mDNSMulticastFilterRegister();			
	#endif

	//	INITIALIZING UDP
	#if MAX_UDP_SOCKETS_FREERTOS>0
	_dbgwrite("Initializing UDP...\r\n");
	UDPInit();
	activeUdpSocket=0;
	while (activeUdpSocket < MAX_UDP_SOCKETS_FREERTOS) 
	{
		tmp_len[activeUdpSocket]=0;
		if (activeUdpSocket == 0) 
		{
			BUFFER_UDP_LEN[0] = BUFFER1_UDP_LEN;
			udpBuffer[activeUdpSocket] = udpBuffer1;
			udpSocket[0] = INVALID_UDP_SOCKET;
		}
		#if MAX_UDP_SOCKETS_FREERTOS>1
		if (activeUdpSocket == 1)
		{
			BUFFER_UDP_LEN[1] = BUFFER2_UDP_LEN;
			udpBuffer[activeUdpSocket] = udpBuffer2;
			udpSocket[1] = INVALID_UDP_SOCKET;
		}
		#endif
		#if MAX_UDP_SOCKETS_FREERTOS>2
		if (activeUdpSocket == 2)
		{
			BUFFER_UDP_LEN[2] = BUFFER3_UDP_LEN;
			udpBuffer[activeUdpSocket] = udpBuffer3;
			udpSocket[2] = INVALID_UDP_SOCKET;
		}
		#endif
		#if MAX_UDP_SOCKETS_FREERTOS>3
		if (activeUdpSocket == 3)
		{
			BUFFER_UDP_LEN[3] = BUFFER4_UDP_LEN;
			udpBuffer[activeUdpSocket] = udpBuffer4;
			udpSocket[3] = INVALID_UDP_SOCKET;
		}
		#endif
		p_udp_wifiram[activeUdpSocket] = udpBuffer[activeUdpSocket];
		p_udp_data[activeUdpSocket] = udpBuffer[activeUdpSocket];
		activeUdpSocket++;
	}
	#endif
	if (hFlyTask == NULL)
	{
		//	Creates the task dedicated to user code
		xTaskCreate(FlyportTask,(signed char*) "FLY" , (configMINIMAL_STACK_SIZE * 4), 
		NULL, tskIDLE_PRIORITY + 1, &hFlyTask);	
	}

	//	DEBUG code - Firmware version on UART 1
	#ifdef FW_VER_ON_U1
	char fwVerString[30];
	tWFDeviceInfo deviceInfo;
	WF_GetDeviceInfo(&deviceInfo); 
	sprintf(fwVerString,"ver.%02x%02x\n", deviceInfo.romVersion , deviceInfo.patchVersion);
	_dbgwrite(fwVerString);
	#endif
//-------------------------------------------------------------------------------------------
//|							--- COOPERATIVE MULTITASKING LOOP ---							|
//-------------------------------------------------------------------------------------------
    while(1)
    {
        #if defined (FLYPORT_WF)
        if (_WFStat != TURNED_OFF)
        #endif
        {
				
	        // This task performs normal stack task including checking
	        // for incoming packet, type of packet and calling
	        // appropriate stack entity to process it.
			vTaskSuspendAll();
			StackTask();
			xTaskResumeAll();
			#if defined(STACK_USE_HTTP_SERVER) || defined(STACK_USE_HTTP2_SERVER)
			vTaskSuspendAll();
			HTTPServer();
			xTaskResumeAll();
			#endif
			// This tasks invokes each of the core stack application tasks
	        StackApplications();
	
	        #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
			ZeroconfLLProcess();
	        #endif
	
	        #if defined(STACK_USE_ZEROCONF_MDNS_SD)
	        mDNSProcess();
			// Use this function to exercise service update function
			// HTTPUpdateRecord();
	        #endif
	
			#if defined(STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED)
			//User should use one of the following SNMP demo
			// This routine demonstrates V1 or V2 trap formats with one variable binding.
			SNMPTrapDemo();
			#if defined(SNMP_STACK_USE_V2_TRAP)
			//This routine provides V2 format notifications with multiple (3) variable bindings
			//User should modify this routine to send v2 trap format notifications with the required varbinds.
			//SNMPV2TrapDemo();
			#endif 
			if(gSendTrapFlag)
				SNMPSendTrap();
			#endif
			
			#if defined(STACK_USE_BERKELEY_API)
			BerkeleyTCPClientDemo();
			BerkeleyTCPServerDemo();
			BerkeleyUDPClientDemo();
			#endif


			// Check on the queue to verify if other task have requested some stack function
			xStatus = xQueueReceive(xQueue,&Cmd,0);
			CmdCheck();
			#if defined (FLYPORT_WF)
			//	Check to verify the connection. If it's lost or failed, the device tries to reconnect
			switch(_WFStat)
			{
				case CONNECTION_LOST:
				case CONNECTION_FAILED:
					tick01 = TickGetDiv64K();
					_WFStat = RECONNECTING;		
					break;
				case RECONNECTING:
					tick02 = TickGetDiv64K();
					if ((tick02 - tick01) >= 3)
					{
						_WFStat = CONNECTING;
						WF_Connect(WFConnection);
					}	
					break;
			}
			//	RSSI management
			if (myRSSI.stat == RSSI_TO_READ)
			{
				tWFScanResult rssiScan;
				WF_ScanGetResult(0, &rssiScan);
				myRSSI.value = rssiScan.rssi;
				myRSSI.stat = RSSI_VALID;
			}
			#endif
	        // If the local IP address has changed (ex: due to DHCP lease change)
	        // write the new IP address to the LCD display, UART, and Announce 
	        // service
			if(dwLastIP != AppConfig.MyIPAddr.Val)
			{
				dwLastIP = AppConfig.MyIPAddr.Val;
				
				_dbgwrite("\r\nNew IP Address: ");

				DisplayIPValue(AppConfig.MyIPAddr);
	
				_dbgwrite("\r\n");
	
				#if defined(STACK_USE_ANNOUNCE)
					AnnounceIP();
				#endif
	
	            #if defined(STACK_USE_ZEROCONF_MDNS_SD)
					mDNSFillHostRecord();
				#endif
			}
		} //end check turnoff	
	}
}
Example #8
0
/// @cond debug
//****************************************************************************
//	Only internal use:
//	cAPNConfig callback function
//****************************************************************************
int cAPNConfig()
{
    char cmdReply[200];
    char msg2send[200];
    int resCheck = 0;
    DWORD tick;
    int countData;
    int chars2read;

    switch(smInternal)
    {
    case 0:
        // Check if Buffer is free
        if(GSMBufferSize() > 0)
        {
            // Parse Unsol Message
            mainGSMStateMachine = SM_GSM_CMD_PENDING;
            return -1;
        }
        else
            smInternal++;

    case 1:
        // Send first AT command
        // ----------	APN Configuration	----------
        sprintf(msg2send, 	"AT+KCNXCFG=0,\"GPRS\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\r",
                xApn, xLogin, xPassw, xIp, xDns1, xDns2);

        GSMWrite(msg2send);
        // Start timeout count
        tick = TickGetDiv64K(); // 1 tick every seconds
        maxtimeout = 2 + 3;
        smInternal++;

    case 2:
        vTaskDelay(20);
        // Check ECHO
        countData = 0;

        resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 3:
        // Get reply (\r\nOK\r\n)
        vTaskDelay(1);
        // Get OK
        sprintf(msg2send, "OK");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }
        else
        {
            vTaskDelay(200); // To prevent too fast TCP connection attempt
        }

    default:
        break;

    }

    smInternal = 0;
    // Cmd = 0 only if the last command successfully executed
    mainOpStatus.ExecStat = OP_SUCCESS;
    mainOpStatus.Function = 0;
    mainOpStatus.ErrorCode = 0;
    mainGSMStateMachine = SM_GSM_IDLE;
    return -1;
}
/*****************************************************************************
  Function:
	void BerkeleyUDPClientDemo(void)

  Summary:
	Periodically checks the current time from a pool of servers.

  Description:
	This function periodically checks a pool of time servers to obtain the
	current date/time.

  Precondition:
	UDP is initialized.

  Parameters:
	None

  Returns:
  	None

  Remarks:
	This function requires once available UDP socket while processing, but
	frees that socket when the SNTP module is idle.
  ***************************************************************************/
void BerkeleyUDPClientDemo(void)
{
#if defined(STACK_USE_DNS)
    NTP_PACKET			pkt;
    int			 		i;
    static NODE_INFO	Server;
    static DWORD		dwTimer;
    static SOCKET		bsdUdpClient = INVALID_SOCKET;
    int 				addrlen = sizeof(struct sockaddr_in);
    static struct sockaddr_in	udpaddr;
    static enum
    {
        SM_HOME = 0,
        SM_NAME_RESOLVE,
        SM_UDP_SEND,
        SM_UDP_RECV,
        SM_SHORT_WAIT,
        SM_WAIT
    } SNTPState = SM_HOME;

    switch(SNTPState)
    {
    case SM_HOME:
        // Obtain ownership of the DNS resolution module
        if(!DNSBeginUsage())
            break;

        // Obtain the IP address associated with the server name
        DNSResolveROM((ROM BYTE*)NTP_SERVER, DNS_TYPE_A);
        dwTimer = TickGet();
        SNTPState = SM_NAME_RESOLVE;
        break;

    case SM_NAME_RESOLVE:
        // Wait for DNS resolution to complete
        if(!DNSIsResolved(&Server.IPAddr))
        {
            if((TickGet() - dwTimer) > (5 * TICK_SECOND))
            {
                DNSEndUsage();
                dwTimer = TickGetDiv64K();
                SNTPState = SM_SHORT_WAIT;
            }
            break;
        }

        // Obtain DNS resolution result
        if(!DNSEndUsage())
        {
            // No valid IP address was returned from the DNS
            // server.  Quit and fail for a while if host is not valid.
            dwTimer = TickGetDiv64K();
            SNTPState = SM_SHORT_WAIT;
            break;
        }

        bsdUdpClient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        udpaddr.sin_port = 0;
        udpaddr.sin_addr.S_un.S_addr = IP_ADDR_ANY;
        if( bind(bsdUdpClient, (struct sockaddr*)&udpaddr, addrlen) == SOCKET_ERROR )
            break;
        SNTPState = SM_UDP_SEND;

    case SM_UDP_SEND:
        // Transmit a time request packet
        memset(&pkt, 0, sizeof(pkt));
        pkt.flags.versionNumber = 3;	// NTP Version 3
        pkt.flags.mode = 3;				// NTP Client
        pkt.orig_ts_secs = swapl(NTP_EPOCH);
        udpaddr.sin_port = NTP_SERVER_PORT;
        udpaddr.sin_addr.S_un.S_addr = Server.IPAddr.Val;
        if(sendto(bsdUdpClient, (const char*)&pkt, sizeof(pkt), 0, (struct sockaddr*)&udpaddr, addrlen)>0)
        {
            dwTimer = TickGet();
            SNTPState = SM_UDP_RECV;
        }
        break;

    case SM_UDP_RECV:
        // Look for a response time packet
        i = recvfrom(bsdUdpClient, (char*)&pkt, sizeof(pkt), 0, (struct sockaddr*)&udpaddr, &addrlen);
        if(i < (int)sizeof(pkt))
        {
            if((TickGet()) - dwTimer > NTP_REPLY_TIMEOUT)
            {
                // Abort the request and wait until the next timeout period
                closesocket(bsdUdpClient);
                dwTimer = TickGetDiv64K();
                SNTPState = SM_SHORT_WAIT;
                break;
            }
            break;
        }
        closesocket(bsdUdpClient);
        dwTimer = TickGetDiv64K();
        SNTPState = SM_WAIT;

        // Set out local time to match the returned time
        dwLastUpdateTick = TickGet();
        dwSNTPSeconds = swapl(pkt.tx_ts_secs) - NTP_EPOCH;
        // Do rounding.  If the partial seconds is > 0.5 then add 1 to the seconds count.
        if(((BYTE*)&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(TickGetDiv64K() - dwTimer > (NTP_FAST_QUERY_INTERVAL/65536ull))
            SNTPState = SM_HOME;
        break;

    case SM_WAIT:
        // Requery the NTP server after a specified NTP_QUERY_INTERVAL time (ex: 10 minutes) has elapsed.
        if(TickGetDiv64K() - dwTimer > (NTP_QUERY_INTERVAL/65536ull))
            SNTPState = SM_HOME;

        break;
    }

    //#if defined(STACK_USE_DNS)
#else
#warning You must define STACK_USE_DNS for BerkeleyUDPClientDemo to work
#endif
}
long FTPStreamRead(char dest[], int len, BYTE timeout)
{
	long count = 0, count2 = 0;
	int toRead;
	DWORD tick1, tick2;
	if (streamStat == FTP_STREAM_READING)
	{
		tick1 = TickGetDiv64K();
		while (count < len)
		{
			count2 = 0;
			toRead = FTPRxLen(dataSocket);
			while ((toRead < len) && (toRead + streamRBytes < streamLen))
			{
				toRead = FTPRxLen(dataSocket);
				count2++;
				if (count2 == 3)
					break;
			}	
			//	Resizing bytes to read according to buffer size
			if (toRead > (len - count))
				toRead = len - count;
			FTPRead(dataSocket, &dest[count], toRead);
			count += toRead;
			streamRBytes += toRead;
			
			//	No data to read, checking timeout and chars read
			if (toRead == 0)
			{
				//	check on file ending, if file is not finished, checking timeout
				if (streamRBytes == streamLen)
				{
					_dbgwrite("FTPStreamRead: EOF reached\r\n");
					streamStat = FTP_STREAM_EOF;
					return count;
				}
				tick2 = TickGetDiv64K();
				
				if ( (tick2 -tick1) > timeout)
				{	
					//	Timeout occured during reading, a check on data connection is required
					if (!FTPisConn(dataSocket))
					{
						_dbgwrite("FTPStreamRead: timeout by server disconnection\r\n");
						errHandling(&dataSocket);
						streamStat = FTP_STREAM_NOT_CONN;
						return count;
					}
					else
					{
						_dbgwrite("FTPStreamRead: timeout\r\n");
						return count;
					}
				}
			}
		}
		return count;
	} 
	else if (!FTPisConn(dataSocket))
	{
		errHandling(&dataSocket);
		return FTP_DATA_NO_CONNECTED;
	}
	else 
		return FTP_STREAM_INVALID_OP;
	
}
/// @cond debug
//****************************************************************************
//	Only internal use:
//	cTCPStatus callback function
//****************************************************************************
int cTCPStatus()
{
	char cmdReply[200];
	char msg2send[200];
	int resCheck = 0;
	DWORD tick;
	int countData;
	int chars2read;
	
	switch(smInternal)
	{
		case 0:
			// Check if Buffer is free
			if(GSMBufferSize() > 0)
			{
				// Parse Unsol Message
				mainGSMStateMachine = SM_GSM_CMD_PENDING;
				return -1;
			}
			else
				smInternal++;
		case 1:	
			// Send first AT command
			// ----------	TCP Status Update ----------
			sprintf(msg2send, "AT+KTCPSTAT=%d\r",xSocket->number);
			
			GSMWrite(msg2send);
			// Start timeout count
			tick = TickGetDiv64K(); // 1 tick every seconds
			maxtimeout = 60;
			smInternal++;
			
		case 2:
			vTaskDelay(20);
			// Check ECHO 
			countData = 0;
			
			resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);
						
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		case 3:
			// Get reply "\r\n+KTCPSTAT: <status>,<tcp_notif>,<rem_data>,<rcv_data>\r\n"
			vTaskDelay(20);
			sprintf(msg2send, "+KTCPSTAT");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>+KTCPSTAT: <status>,<tcp_notif>,<rem_data>,<rcv_data><CR><LF>
			
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			else
			{
				// Get status
				char temp[25];
				int res = getfield(':', ',', 5, 1, cmdReply, temp, 500);
				if(res != 1)
				{
					// Execute Error Handler
					gsmDebugPrint( "Error in getfield for +KTCP_DATA socket\r\n");
					break;
				}
				else
				{
					xSocket->status = atoi(temp);
				}
				
				// Get tcp_notif
				res = getfield(',', ',', 5, 1, cmdReply, temp, 500);
				if(res != 1)
				{
					// Execute Error Handler
					gsmDebugPrint( "Error in getfield for +KTCP_DATA socket\r\n");
					break;
				}
				else
				{
					xSocket->notif = atoi(temp);
				}
				
				// Get rcv_data
				res = getfield(',', '\r', 6, 3, cmdReply, temp, 500);
				if(res != 1)
				{
					// Execute Error Handler
					gsmDebugPrint( "Error in getfield for +KTCP_DATA socket\r\n");
					break;
				}
				else
				{
					xSocket->rxLen = atoi(temp);
				}
			}	
			
		case 4:
			// Get reply (\r\nOK\r\n)
			vTaskDelay(1);
			// Get OK
			sprintf(msg2send, "OK");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		default:
			break;
	
	}
	
	smInternal = 0;
	// Cmd = 0 only if the last command successfully executed
	mainOpStatus.ExecStat = OP_SUCCESS;
	mainOpStatus.Function = 0;
	mainOpStatus.ErrorCode = 0;
	mainGSMStateMachine = SM_GSM_IDLE;
	return -1;
}
/// @cond debug
//****************************************************************************
//	Only internal use:
//	cTCPWrite callback function
//****************************************************************************
int cTCPWrite()
{
	char cmdReply[200];
	char msg2send[200];
	int resCheck = 0;
	DWORD tick;
	int countData;
	int chars2read;
	
	switch(smInternal)
	{
		case 0:
			// Check if Buffer is free
			if(GSMBufferSize() > 0)
			{
				// Parse Unsol Message
				mainGSMStateMachine = SM_GSM_CMD_PENDING;
				return -1;
			}
			else
				smInternal++;
				
		case 1:	
			// Send first AT command
			// ----------	TCP Write Command ----------
			sprintf(msg2send, "AT+KTCPSND=%d,%d\r",xSocket->number, tcpWriteBufferCount);
			
			GSMWrite(msg2send);
			// Start timeout count
			tick = TickGetDiv64K(); // 1 tick every seconds
			maxtimeout = 120;
			smInternal++;
			
		case 2:
			vTaskDelay(20);
			// Check ECHO 
			countData = 0;
			
			resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);
						
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		case 3:
			// Get reply "\r\nCONNECT\r\n"
			vTaskDelay(20);
			sprintf(msg2send, "\r\nCONNECT");
			chars2read = 2;
			countData = 4; // GSM buffer should be: <CR><LF>CONNECT<CR><LF>
			
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			else
			{
				int counterLen = 0;
				
				while(counterLen < tcpWriteBufferCount) 
				{
					GSMWriteCh(tcpWriteBuffer[counterLen]);
					counterLen++;
				}		
				
				// and write --EOF--Pattern-- (without \r)
				GSMWrite("--EOF--Pattern--");
			}	
	
		case 4:
			// Get reply (\r\nOK\r\n)
			vTaskDelay(20);
			// Get OK
			sprintf(msg2send, "OK");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		default:
			break;
	
	}
	
	smInternal = 0;
	// Cmd = 0 only if the last command successfully executed
	mainOpStatus.ExecStat = OP_SUCCESS;
	mainOpStatus.Function = 0;
	mainOpStatus.ErrorCode = 0;
	mainGSMStateMachine = SM_GSM_IDLE;
	return -1;
}
/// @cond debug
//****************************************************************************
//	Only internal use:
//	cTCPRead callback function
//****************************************************************************
int cTCPRead()
{
	char cmdReply[200];
	char msg2send[200];
	int resCheck = 0;
	DWORD tick;
	int countData;
	int chars2read;
	
	switch(smInternal)
	{
		case 0:
			// Check if Buffer is free
			if(GSMBufferSize() > 0)
			{
				// Parse Unsol Message
				mainGSMStateMachine = SM_GSM_CMD_PENDING;
				return -1;
			}
			else
				smInternal++;
			
		case 1:	
			// Send first AT command
			// ----------	TCP Status Update ----------
			sprintf(msg2send, "AT+KTCPSTAT=%d\r",xSocket->number);
			
			GSMWrite(msg2send);
			// Start timeout count
			tick = TickGetDiv64K(); // 1 tick every seconds
			maxtimeout = 60;
			smInternal++;
			
		case 2:
			vTaskDelay(20);
			// Check ECHO 
			countData = 0;
			
			resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);
						
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				#if defined (STACK_USE_UART)
				char debugStr[100];
				sprintf(debugStr, "error on function %d, smInternal %d\r\n", mainOpStatus.Function, smInternal);
				gsmDebugPrint( debugStr);
				vTaskDelay(20);
				#endif
				return mainOpStatus.ErrorCode;
			}
			
		case 3:
			// Get reply "\r\n+KTCPSTAT: <status>,<tcp_notif>,<rem_data>,<rcv_data>\r\n"
			vTaskDelay(20);
			sprintf(msg2send, "+KTCPSTAT");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>+KTCPSTAT: <status>,<tcp_notif>,<rem_data>,<rcv_data><CR><LF>
			
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			else
			{
				// Get status
				char temp[25];
				int res = getfield(':', ',', 5, 1, cmdReply, temp, 500);
				if(res != 1)
				{
					// Execute Error Handler
					gsmDebugPrint( "Error in getfield for +KTCPSTAT socket\r\n");
					break;
				}
				else
				{
					xSocket->status = atoi(temp);
				}
				
				// Get tcp_notif
				res = getfield(',', ',', 5, 1, cmdReply, temp, 500);
				if(res != 1)
				{
					// Execute Error Handler
					gsmDebugPrint( "Error in getfield for +KTCPSTAT socket\r\n");
					break;
				}
				else
				{
					xSocket->notif = atoi(temp);
				}
				
				// Get rcv_data
				res = getfield(',', '\r', 6, 3, cmdReply, temp, 500);
				if(res != 1)
				{
					// Execute Error Handler
					gsmDebugPrint( "Error in getfield for +KTCPSTAT socket\r\n");
					break;
				}
				else
				{
					xSocket->rxLen = atoi(temp);
				}
			}	
			
		case 4:
			// Get reply (\r\nOK\r\n)
			vTaskDelay(1);
			// Get OK
			sprintf(msg2send, "OK");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		case 5:
			if(xSocket->rxLen == 0)
			{
				// Break operation
				break;
			}
			// Send first AT command
			// ----------	TCP Read Command ----------
			if(tcpReadBufferCount > xSocket->rxLen)
				tcpReadBufferCount = xSocket->rxLen;				
			
			if(tcpReadBufferCount > GSM_BUFFER_SIZE)
					tcpReadBufferCount = GSM_BUFFER_SIZE;
			
			sprintf(msg2send, "AT+KTCPRCV=%d,%d\r",xSocket->number, tcpReadBufferCount);
			
			GSMWrite(msg2send);
			// Start timeout count
			tick = TickGetDiv64K(); // 1 tick every seconds
			maxtimeout = 60;
			smInternal++;
			
		case 6:
			vTaskDelay(1);
			// Check ECHO 
			countData = 0;
			
			resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);
						
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		case 7:
			// Get reply "\r\nCONNECT\r\n"
			vTaskDelay(1);
			sprintf(msg2send, "CONNECT");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>CONNECT<CR><LF>
			
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			else
			{
				// Read data from TCP Socket
				int rxCount = 0;
				int retCount = 0;			
				while(rxCount < tcpReadBufferCount)
				{
					char tmp[1];
					retCount = GSMRead(tmp, 1);
					*(tcpReadBuffer+rxCount) = tmp[0];
					rxCount += retCount;
					if(retCount == 0)
						vTaskDelay(1);
				}
				
				// Set tcpReadBufferCount as the effective number of BYTEs read
				tcpReadBufferCount = rxCount;
			}
		
		case 8:
			// Get reply (--EOF--Pattern--\r\nOK\r\n)
			vTaskDelay(1);
			// Get OK
			sprintf(msg2send, "--EOF--Pattern--\r\nOK");
			chars2read = 2;
			countData = 0; // GSM buffer should be: --EOF--Pattern--<CR><LF>OK<CR><LF>
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		default:
			break;
	}
	
	smInternal = 0;
	// Cmd = 0 only if the last command successfully executed
	mainOpStatus.ExecStat = OP_SUCCESS;
	mainOpStatus.Function = 0;
	mainOpStatus.ErrorCode = 0;
	mainGSMStateMachine = SM_GSM_IDLE;
	return -1;
}
/// @cond debug
//****************************************************************************
//	Only internal use:
//	cTCPClientClose callback function
//****************************************************************************
int cTCPClientClose()
{
	char cmdReply[200];
	char msg2send[200];
	int resCheck = 0;
	DWORD tick;
	int countData;
	int chars2read;
	
	switch(smInternal)
	{
		case 0:
			// Check if Buffer is free
			if(GSMBufferSize() > 0)
			{
				// Parse Unsol Message
				mainGSMStateMachine = SM_GSM_CMD_PENDING;
				return -1;
			}
			else
				smInternal++;
		case 1:	
			// Send first AT command
			// ----------	TCP Connection Close	----------
			sprintf(msg2send, "AT+KTCPCLOSE=%d,1\r",xSocket->number);
			
			GSMWrite(msg2send);
			// Start timeout count
			tick = TickGetDiv64K(); // 1 tick every seconds
			maxtimeout = 60;
			smInternal++;
			
		case 2:
			vTaskDelay(20);
			// Check ECHO 
			countData = 0;
			
			resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);
						
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		case 3:
			// Get reply (\r\nOK\r\n)
			vTaskDelay(1);
			// Get OK
			sprintf(msg2send, "OK");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		case 4:	
			// Send AT command
			// ----------	Delete TCP Socket ----------
			sprintf(msg2send, "AT+KTCPDEL=%d\r",xSocket->number);
			
			GSMWrite(msg2send);
			// Start timeout count
			tick = TickGetDiv64K(); // 1 tick every seconds
			maxtimeout = 2;
			smInternal++;
			
		case 5:
			vTaskDelay(20);
			// Check ECHO 
			countData = 0;
			
			resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);
						
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		case 6:
			// Get reply (\r\nOK\r\n)
			vTaskDelay(1);
			// Get OK
			sprintf(msg2send, "OK");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			else
			{
				xSocket->number = INVALID_SOCKET;
			}
				
		default:
			break;
	
	}
	
	smInternal = 0;
	// Cmd = 0 only if the last command successfully executed
	mainOpStatus.ExecStat = OP_SUCCESS;
	mainOpStatus.Function = 0;
	mainOpStatus.ErrorCode = 0;
	mainGSMStateMachine = SM_GSM_IDLE;
	return -1;
}
/// @cond debug
//****************************************************************************
//	Only internal use:
//	cTCPClientOpen callback function
//****************************************************************************
int cTCPClientOpen()
{
	char cmdReply[200];
	char msg2send[200];
	int resCheck = 0;
	DWORD tick;
	int countData;
	int chars2read;
	
	switch(smInternal)
	{
		case 0:
			// Check if Buffer is free
			if(GSMBufferSize() > 0)
			{
				// Parse Unsol Message
				mainGSMStateMachine = SM_GSM_CMD_PENDING;
				return -1;
			}
			else
				smInternal++;
				
		case 1:	
			// Send first AT command
			// ----------	TCP Connection Configuration	----------
			sprintf(msg2send, "AT+KTCPCFG=0,0,\"%s\",%d\r",xIPAddress, xTCPPort);
			
			GSMWrite(msg2send);
			// Start timeout count
			tick = TickGetDiv64K(); // 1 tick every seconds
			maxtimeout = 2;
			smInternal++;
			
		case 2:
			vTaskDelay(1);
			// Check ECHO 
			countData = 0;
			
			resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);
						
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		case 3:
			// Get reply "+KTCPCFG: <socket>"
			vTaskDelay(1);
			sprintf(msg2send, "+KTCPCFG");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>+KTCPCFG: <socket><CR><LF>
			
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			else
			{
				// Get socket number
				char temp[25];
				int res = getfield(':', '\r', 5, 1, cmdReply, temp, 500);
				if(res != 1)
				{
					// Execute Error Handler
					gsmDebugPrint( "Error in getfield\r\n");
					break;
				}
				else
				{
					xSocket->number = atoi(temp);
				}	
			}	
			
		case 4:
			// Get reply (\r\nOK\r\n)
			vTaskDelay(1);
			// Get OK
			sprintf(msg2send, "OK");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		case 5:	
			// ----------	Initiate TCP Connection	----------
			sprintf(msg2send, "AT+KTCPCNX=%d\r",xSocket->number);
			
			GSMWrite(msg2send);
			// Start timeout count
			tick = TickGetDiv64K(); // 1 tick every seconds
			maxtimeout = 180;
			smInternal++;
			
		case 6:
			vTaskDelay(1);
			// Check ECHO 
			countData = 0;
			
			resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);
						
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				xSocket->number = INVALID_SOCKET;
				return mainOpStatus.ErrorCode;
			}
			
		case 7:
			// Get reply (\r\nOK\r\n)
			vTaskDelay(1);
			// Get OK
			sprintf(msg2send, "\r\nOK");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				xSocket->number = INVALID_SOCKET;
				return mainOpStatus.ErrorCode;
			}
			
		default:
			break;
	
	}
	
	smInternal = 0;
	// Cmd = 0 only if the last command successfully executed
	mainOpStatus.ExecStat = OP_SUCCESS;
	mainOpStatus.Function = 0;
	mainOpStatus.ErrorCode = 0;
	mainGSMStateMachine = SM_GSM_IDLE;
	return -1;
}
Example #16
0
/// @cond debug
int  cSMTPParamsClear()
{
    char cmdReply[200];
    char msg2send[200];
    int resCheck = 0;
    DWORD tick;
    int countData;
    int chars2read;

    switch(smInternal)
    {
    case 0:
        // Check if Buffer is free
        if(GSMBufferSize() > 0)
        {
            // Parse Unsol Message
            mainGSMStateMachine = SM_GSM_CMD_PENDING;
            return -1;
        }
        else
            smInternal++;

    case 1:
        // AT+KSMTPSUBJECT
        sprintf(msg2send, "AT+KSMTPCLEAR\r");

        GSMWrite(msg2send);
        // Start timeout count
        tick = TickGetDiv64K(); // 1 tick every seconds
        maxtimeout = 2;
        smInternal++;

    case 2:
        vTaskDelay(1);
        // Check ECHO
        countData = 0;

        resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }

    case 3:
        // Get reply (\r\nOK\r\n)
        vTaskDelay(1);
        // Get OK
        sprintf(msg2send, "OK");
        chars2read = 2;
        countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
        resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

        CheckErr(resCheck, &smInternal, &tick);

        if(resCheck)
        {
            return mainOpStatus.ErrorCode;
        }


    default:
        break;
    }

    smInternal = 0;
    // Cmd = 0 only if the last command successfully executed
    mainOpStatus.ExecStat = OP_SUCCESS;
    mainOpStatus.Function = 0;
    mainOpStatus.ErrorCode = 0;
    mainGSMStateMachine = SM_GSM_IDLE;
    return -1;
}
Example #17
0
/// @cond debug
int cHTTPRequest()
{
	char cmdReply[200];
	char msg2send[200];
	int resCheck = 0;
	DWORD tick;
	int countData;
	int chars2read;
	int msgLength = 0;
        
	switch(smInternal)
    {
        case 0:
            // Check if Buffer is free
            if(GSMBufferSize() > 0)
            {
                // Parse Unsol Message
                mainGSMStateMachine = SM_GSM_CMD_PENDING;
                return -1;
            }
            else
                smInternal++;
        case 1:
            // Send first AT command

            // Calculate tcp write length...
            // Header length:
            if(httpReqType == HTTP_GET)
            {
                msgLength = 131;
            }
            else if(httpReqType == HTTP_POST)
            {
                msgLength = 132;
            }

            msgLength += strlen(httpReqUrl);

            msgLength += strlen(httpWriteBuffer);

            sprintf(msg2send, "%d", strlen(httpWriteBuffer));

            msgLength += strlen(msg2send);

            if(httpParams != HTTP_NO_PARAM)
            {
                msgLength += strlen(httpParams);
            }

            // ----------	TCP Write Command ----------
            sprintf(msg2send, "AT+KTCPSND=%d,%d\r",xSocket->number, msgLength);

            GSMWrite(msg2send);
            // Start timeout count
            tick = TickGetDiv64K(); // 1 tick every seconds
            maxtimeout = 75;// 60;
            smInternal++;

        case 2:
            vTaskDelay(20);
            // Check ECHO
            countData = 0;

            resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }

        case 3:
            // Get reply "\r\nCONNECT\r\n"
            vTaskDelay(20);
            sprintf(msg2send, "\r\nCONNECT");
            chars2read = 2;
            countData = 4; // GSM buffer should be: <CR><LF>CONNECT<CR><LF>

            resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }
            else
            {
                if(httpReqType == HTTP_GET)
                {
                    GSMWrite("GET ");
                }
                else
                {
                    GSMWrite("POST ");
                }

                char* req = strstr(httpReqUrl, "/");
                GSMWrite(req);
                GSMWrite(" HTTP/1.1\r\nHost: ");
                
				int tokenPos;
				for(tokenPos = 0; tokenPos < strlen(httpReqUrl); tokenPos++)
				{
					if(httpReqUrl[tokenPos] == '/')
					{
						break;
					}
					GSMWriteCh(httpReqUrl[tokenPos]);
				}
				
                GSMWrite("\r\nUser-Agent: Flyport-GPRS\r\n");
                if(httpParams != HTTP_NO_PARAM)
                {
                    GSMWrite(httpParams);
                }
                else
                {
                    GSMWrite("Content-Length: ");
                    char contentlength[5];
                    sprintf(contentlength, "%d", strlen(httpWriteBuffer));
                    GSMWrite(contentlength);
                    GSMWrite("\r\nContent-Type: application/x-www-form-urlencoded\r\nAccept: */*");
                }
                GSMWrite("\r\n\r\n");
                GSMWrite(httpWriteBuffer);

                // and write --EOF--Pattern-- (without \r)
                GSMWrite("--EOF--Pattern--");
            }

        case 4:
            // Get reply (\r\nOK\r\n)
            vTaskDelay(20);
            // Get OK
            sprintf(msg2send, "OK\r\n");
            chars2read = 2;
            countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
            resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }

        case 5:
            if(GSMBufferSize() > 0)
            {
                // Parse Unsol Message
                mainGSMStateMachine = SM_GSM_CMD_PENDING;
                return -1;
            }
            // Read 1 char at time on Hilo TCP Buffer to get
            // HTTP Header reply, using GSMpSeek/GSMpRead, etc

            // ----------	TCP Status Update ----------
            sprintf(msg2send, "AT+KTCPSTAT=%d\r",xSocket->number);

            GSMWrite(msg2send);
            // Start timeout count
            tick = TickGetDiv64K(); // 1 tick every seconds
            maxtimeout = 75;// 60;
            smInternal++;

        case 6:
            vTaskDelay(20);
            // Check ECHO
            countData = 0;

            resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }

        case 7:
            // Get reply "\r\n+KTCPSTAT: <status>,<tcp_notif>,<rem_data>,<rcv_data>\r\n"
            vTaskDelay(20);
            sprintf(msg2send, "+KTCPSTAT");
            chars2read = 2;
            countData = 2; // GSM buffer should be: <CR><LF>+KTCPSTAT: <status>,<tcp_notif>,<rem_data>,<rcv_data><CR><LF>

            resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }
            else
            {
                // Get status
                char temp[25];
                int res = getfield(':', ',', 5, 1, cmdReply, temp, 500);
                if(res != 1)
                {
                    // Execute Error Handler
                    gsmDebugPrint( "Error in getfield for +KTCPSTAT socket\r\n");
                    break;
                }
                else
                {
                    xSocket->status = atoi(temp);
                }

                // Get tcp_notif
                res = getfield(',', ',', 5, 1, cmdReply, temp, 500);
                if(res != 1)
                {
                    // Execute Error Handler
                    gsmDebugPrint( "Error in getfield for +KTCPSTAT socket\r\n");
                    break;
                }
                else
                {
                    xSocket->notif = atoi(temp);
                }

                // Get rcv_data
                res = getfield(',', '\r', 6, 3, cmdReply, temp, 500);
                if(res != 1)
                {
                    // Execute Error Handler
                    gsmDebugPrint( "Error in getfield for +KTCPSTAT socket\r\n");
                    break;
                }
                else
                {
                    xSocket->rxLen = atoi(temp);
                }
            }

        case 8:
            // Get reply (\r\nOK\r\n)
            vTaskDelay(1);
            // Get OK
            sprintf(msg2send, "OK\r\n");
            chars2read = 2;
            countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
            resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }
            smInternal++; // exit from the switch!
            break;
        /*
        case 9:
            // check if there are enough BYTEs on TCP Buffer for HTTP Response parsing
            if(xSocket->rxLen < 12)
            {
                // Break operation
                smInternal = 5;
                maxHTTPattempt--;
                break;
            }
            maxHTTPattempt = 10;
            // Send first AT command
            // ----------	TCP Read Command ----------
            httpReadBufferCount = 12;

            sprintf(msg2send, "AT+KTCPRCV=%d,%d\r",xSocket->number, httpReadBufferCount);

            GSMWrite(msg2send);
            // Start timeout count
            tick = TickGetDiv64K(); // 1 tick every seconds
            maxtimeout = 60;
            smInternal++;

        case 10:
            vTaskDelay(20);
            // Check ECHO
            countData = 0;

            resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }

        case 11:
            // Get reply "\r\nCONNECT\r\n"
            vTaskDelay(2);
            sprintf(msg2send, "CONNECT");
            chars2read = 2;
            countData = 2; // GSM buffer should be: <CR><LF>CONNECT<CR><LF>

            resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }

        case 12:
            // Get "HTTP/1.1 "reply:
            // Read data from TCP Socket
            httpReadBufferCount = GSMRead(tmp, 12);
            tmp[12] = '\0';
            // Decrease xSocket->rxLen:
            xSocket->rxLen -= httpReadBufferCount;

            char* httpReplyVal = strstr(tmp, "HTTP/1.1 ");
            if(httpReplyVal != NULL)
            {
                httpCount = atoi(&httpReplyVal[9]);
            }
            xHTTPCode = httpCount;
            httpCount = 0;
            smInternal++;

        case 13:
            // Now flush all the TCP Data until the first \r\n\r\n

            // ----------	TCP Status Update ----------
            sprintf(msg2send, "AT+KTCPSTAT=%d\r",xSocket->number);

            GSMWrite(msg2send);
            // Start timeout count
            tick = TickGetDiv64K(); // 1 tick every seconds
            maxtimeout = 60;
            smInternal++;

        case 14:
            vTaskDelay(2);
            // Check ECHO
            countData = 0;

            resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }

        case 15:
            // Get reply "\r\n+KTCPSTAT: <status>,<tcp_notif>,<rem_data>,<rcv_data>\r\n"
            vTaskDelay(2);
            sprintf(msg2send, "+KTCPSTAT");
            chars2read = 2;
            countData = 2; // GSM buffer should be: <CR><LF>+KTCPSTAT: <status>,<tcp_notif>,<rem_data>,<rcv_data><CR><LF>

            resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }
            else
            {
                // Get status
                char temp[25];
                int res = getfield(':', ',', 5, 1, cmdReply, temp, 500);
                if(res != 1)
                {
                    // Execute Error Handler
                    gsmDebugPrint( "Error in getfield for +KTCPSTAT socket\r\n");
                    break;
                }
                else
                {
                    xSocket->status = atoi(temp);
                }

                // Get tcp_notif
                res = getfield(',', ',', 5, 1, cmdReply, temp, 500);
                if(res != 1)
                {
                    // Execute Error Handler
                    gsmDebugPrint("Error in getfield for +KTCPSTAT socket\r\n");
                    break;
                }
                else
                {
                    xSocket->notif = atoi(temp);
                }

                // Get rcv_data
                res = getfield(',', '\r', 6, 3, cmdReply, temp, 500);
                if(res != 1)
                {
                    // Execute Error Handler
                    gsmDebugPrint("Error in getfield for +KTCPSTAT socket\r\n");
                    break;
                }
                else
                {
                    xSocket->rxLen = atoi(temp);
                }
            }

        case 16:
            // Get reply (\r\nOK\r\n)
            //vTaskDelay(1);
            // Get OK
            sprintf(msg2send, "OK");
            chars2read = 2;
            countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
            resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }

        case 17:
            if(xSocket->rxLen == 0)
            {
                smInternal = 13;
                maxHTTPattempt--;
                if(maxHTTPattempt > 0)
                    vTaskDelay(20);
                else
                    // Break operation
                    break;
            }
            else
            {
                // ----------	TCP Read Command ----------
                sprintf(msg2send, "AT+KTCPRCV=%d,1\r",xSocket->number);

                GSMWrite(msg2send);
                // Start timeout count
                tick = TickGetDiv64K(); // 1 tick every seconds
                maxtimeout = 60;
                smInternal++;
            }

        case 18:
            //vTaskDelay(2);
            // Check ECHO
            countData = 0;

            resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }

        case 19:
            // Get reply "\r\nCONNECT\r\n"
            //vTaskDelay(2);
            sprintf(msg2send, "CONNECT");
            chars2read = 2;
            countData = 2; // GSM buffer should be: <CR><LF>CONNECT<CR><LF>

            resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }
            else
            {
                GSMRead(tmp, 1+22); //our char + "--EOF--Pattern--\r\nOK"
                //UARTWriteCh(1, tmp[0]);
                xSocket->rxLen--;
                if(tmp[0] == termString[httpCount])
                {
                    httpCount++;
                }
                if(httpCount > 4)
                {
                    maxHTTPattempt = -2; // we found the termString as desired
                    break;
                }
                else
                {
                    smInternal = 13;
                }
            }
         * */
            /*
        case 20:
            // Get reply (\r\n--EOF--Pattern--\r\nOK\r\n)
            vTaskDelay(1);
            // Get OK
            sprintf(msg2send, "--EOF--Pattern--\r\nOK");
            chars2read = 2;
            countData = 2; // GSM buffer should be: <CR><LF>--EOF--Pattern--<CR><LF>OK<CR><LF>
            resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);

            CheckErr(resCheck, &smInternal, &tick);

            if(resCheck)
            {
                return mainOpStatus.ErrorCode;
            }
            */

        default:
            // Check if Buffer is free
            if(GSMBufferSize() > 0)
            {
                // Parse Unsol Message
                mainGSMStateMachine = SM_GSM_CMD_PENDING;
                return -1;
            }
            else
                smInternal++;
            break;

    }// switch(smInternal)
    
	smInternal = 0;
	// Cmd = 0 only if the last command successfully executed
	mainOpStatus.ExecStat = OP_SUCCESS;
	mainOpStatus.Function = 0;
	mainOpStatus.ErrorCode = 0;
	mainGSMStateMachine = SM_GSM_IDLE;
	return -1;
}	
Example #18
0
/*********************************************************************
  Function:
  	BOOL SNMPGetVar(SNMP_ID var, SNMP_INDEX index,BYTE* ref, SNMP_VAL* val)
                                   
  Summary:
  	Used to Get/collect OID variable information.

  Description:
 	This is a callback function called by SNMP module. SNMP user must 
 	implement this function in user application and provide appropriate
 	data when called.
   	
  PreCondition:
  	None
 
  parameters:
  	var		-	Variable id whose value is to be returned
    index   -	Index of variable that should be transferred
    ref     -   Variable reference used to transfer
              	multi-byte data
                It is always SNMP_START_OF_VAR when very
                first byte is requested.
                Otherwise, use this as a reference to
                keep track of multi-byte transfers.
    val     -	Pointer to up to 4 byte buffer.
                If var data type is BYTE, transfer data
                  in val->byte
                If var data type is WORD, transfer data in
                  val->word
                If var data type is DWORD, transfer data in
                  val->dword
                If var data type is IP_ADDRESS, transfer data
                  in val->v[] or val->dword
                If var data type is COUNTER32, TIME_TICKS or
                  GAUGE32, transfer data in val->dword
                If var data type is ASCII_STRING or OCTET_STRING
                  transfer data in val->byte using multi-byte
                  transfer mechanism.
 
  Return Values:
  	TRUE	-	If a value exists for given variable at given index.
    FALSE 	-	Otherwise.
 
  Remarks:
 	None.
 ********************************************************************/
BOOL SNMPGetVar(SNMP_ID var, SNMP_INDEX index, BYTE* ref, SNMP_VAL* val)
{
    BYTE myRef;
 	DWORD_VAL dwvHigh, dwvLow;
    DWORD dw;
    DWORD dw10msTicks;

    myRef = *ref;

    switch(var)
    {
    case SYS_UP_TIME:
    {
	 
	    
	    // Get all 48 bits of the internal Tick timer
	    do
	   	{
		   	dwvHigh.Val = TickGetDiv64K();
		   	dwvLow.Val = TickGet();
		} while(dwvHigh.w[0] != dwvLow.w[1]);
	    dwvHigh.Val = dwvHigh.w[1];
	    
		// Find total contribution from lower DWORD
	    dw = dwvLow.Val/(DWORD)TICK_SECOND;
	    dw10msTicks = dw*100ul;
	    dw = (dwvLow.Val - dw*(DWORD)TICK_SECOND)*100ul;		// Find fractional seconds and convert to 10ms ticks
	    dw10msTicks += (dw+((DWORD)TICK_SECOND/2ul))/(DWORD)TICK_SECOND;

		// Itteratively add in the contribution from upper WORD
		while(dwvHigh.Val >= 0x1000ul)
		{
			dw10msTicks += (0x100000000000ull*100ull+(TICK_SECOND/2ull))/TICK_SECOND;
			dwvHigh.Val -= 0x1000;
		}	
		while(dwvHigh.Val >= 0x100ul)
		{
			dw10msTicks += (0x010000000000ull*100ull+(TICK_SECOND/2ull))/TICK_SECOND;
			dwvHigh.Val -= 0x100;
		}	
		while(dwvHigh.Val >= 0x10ul)
		{
			dw10msTicks += (0x001000000000ull*100ull+(TICK_SECOND/2ull))/TICK_SECOND;
			dwvHigh.Val -= 0x10;
		}	
		while(dwvHigh.Val)
		{
			dw10msTicks += (0x000100000000ull*100ull+(TICK_SECOND/2ull))/TICK_SECOND;
			dwvHigh.Val--;
		}
	    
        val->dword = dw10msTicks;
        return TRUE;
    }    

    case LED_D5:
        val->byte = LED2_IO;
        return TRUE;

    case LED_D6:
        val->byte = LED1_IO;
        return TRUE;

    case PUSH_BUTTON:
        // There is only one button - meaning only index of 0 is allowed.
        val->byte = BUTTON0_IO;
        return TRUE;

    case ANALOG_POT0:
        val->word = atoi((char*)AN0String);
        return TRUE;

    case TRAP_RECEIVER_ID:
        if ( index < trapInfo.Size )
        {
            val->byte = index;
            return TRUE;
        }
        break;

    case TRAP_RECEIVER_ENABLED:
        if ( index < trapInfo.Size )
        {
            val->byte = trapInfo.table[index].Flags.bEnabled;
            return TRUE;
        }
        break;

    case TRAP_RECEIVER_IP:
        if ( index < trapInfo.Size )
        {
            val->dword = trapInfo.table[index].IPAddress.Val;
            return TRUE;
        }
        break;

    case TRAP_COMMUNITY:
        if ( index < trapInfo.Size )
        {
            if ( trapInfo.table[index].communityLen == 0u )
                *ref = SNMP_END_OF_VAR;
            else
            {
                val->byte = trapInfo.table[index].community[myRef];

                myRef++;

                if ( myRef == trapInfo.table[index].communityLen )
                    *ref = SNMP_END_OF_VAR;
                else
                    *ref = myRef;
            }
            return TRUE;
        }
        break;

#if defined(USE_LCD)
    case LCD_DISPLAY:
        if ( LCDText[0] == 0u )
            myRef = SNMP_END_OF_VAR;
        else
        {
            val->byte = LCDText[myRef++];
            if ( LCDText[myRef] == 0u )
                myRef = SNMP_END_OF_VAR;
        }

        *ref = myRef;
        return TRUE;
#endif
    }

    return FALSE;
}
Example #19
0
/*****************************************************************************
  Function:
	void SNTPClient(void)

  Summary:
	Periodically checks the current time from a pool of servers.

  Description:
	This function periodically checks a pool of time servers to obtain the
	current date/time.

  Precondition:
	UDP is initialized.

  Parameters:
	None

  Returns:
  	None
  	
  Remarks:
	This function requires once available UDP socket while processing, but
	frees that socket when the SNTP module is idle.
  ***************************************************************************/
void SNTPClient(void)
{
	NTP_PACKET			pkt;
	WORD		 		w;
//	static NODE_INFO	Server;
	static DWORD		dwTimer;
	static UDP_SOCKET	MySocket = INVALID_UDP_SOCKET;
	static enum
	{
		SM_HOME = 0,
		SM_UDP_IS_OPENED,
		//SM_NAME_RESOLVE,
		//SM_ARP_START_RESOLVE,
		//SM_ARP_RESOLVE,
		//SM_ARP_START_RESOLVE2,
		//SM_ARP_RESOLVE2,
		//SM_ARP_START_RESOLVE3,
		//SM_ARP_RESOLVE3,
		//SM_ARP_RESOLVE_FAIL,
		SM_UDP_SEND,
		SM_UDP_RECV,
		SM_SHORT_WAIT,
		SM_WAIT
	} SNTPState = SM_HOME;


	switch(SNTPState)
	{
		case SM_HOME:
			if(MySocket == INVALID_UDP_SOCKET)
				MySocket = UDPOpenEx((DWORD)(PTR_BASE)NTP_SERVER,UDP_OPEN_ROM_HOST,0,NTP_SERVER_PORT);
			
			SNTPState++;
			break;
			
		case SM_UDP_IS_OPENED:
			if(UDPIsOpened(MySocket) == TRUE)
			{
				SNTPState = SM_UDP_SEND;
			}
		/*	else
			{
				UDPClose(MySocket);
				SNTPState = SM_HOME;
				MySocket = INVALID_UDP_SOCKET;
			}
		*/		
			break;

#if 0			
			// Obtain ownership of the DNS resolution module
			if(!DNSBeginUsage())
				break;

			// Obtain the IP address associated with the server name
			DNSResolveROM((ROM BYTE*)NTP_SERVER, DNS_TYPE_A);
			dwTimer = TickGet();
			SNTPState = SM_NAME_RESOLVE;
			break;

		case SM_NAME_RESOLVE:
			// Wait for DNS resolution to complete
			if(!DNSIsResolved(&Server.IPAddr)) 
			{
				if((TickGet() - dwTimer) > (5 * TICK_SECOND)) 
				{
					DNSEndUsage();
					dwTimer = TickGetDiv64K();
					SNTPState = SM_SHORT_WAIT;
				}
				break;
			}
			
			// Obtain DNS resolution result
			if(!DNSEndUsage())
			{
				// No valid IP address was returned from the DNS 
				// server.  Quit and fail for a while if host is not valid.
				dwTimer = TickGetDiv64K();
				SNTPState = SM_SHORT_WAIT;
				break;
			}
			SNTPState = SM_ARP_START_RESOLVE;
			// No need to break

		case SM_ARP_START_RESOLVE:
		case SM_ARP_START_RESOLVE2:
		case SM_ARP_START_RESOLVE3:
			// Obtain the MAC address associated with the server's IP address 
			ARPResolve(&Server.IPAddr);
			dwTimer = TickGet();
			SNTPState++;
			break;

		case SM_ARP_RESOLVE:
		case SM_ARP_RESOLVE2:
		case SM_ARP_RESOLVE3:
			// Wait for the MAC address to finish being obtained
			if(!ARPIsResolved(&Server.IPAddr, &Server.MACAddr))
			{
				// Time out if too much time is spent in this state
				if(TickGet() - dwTimer > 1*TICK_SECOND)
				{
					// Retransmit ARP request by going to next SM_ARP_START_RESOLVE state or fail by going to SM_ARP_RESOLVE_FAIL state.
					SNTPState++;
				}
				break;
			}
			SNTPState = SM_UDP_SEND;
			break;

		case SM_ARP_RESOLVE_FAIL:
			// ARP failed after 3 tries, abort and wait for next time query
			dwTimer = TickGetDiv64K();
			SNTPState = SM_SHORT_WAIT;
			break;
#endif
// case SM_UDP_IS_OPENED:
		case SM_UDP_SEND:
			// Open up the sending UDP socket
			//MySocket = UDPOpen(0, &Server, NTP_SERVER_PORT);
#if 0

			MySocket = UDPOpenEx(NTP_SERVER,UDP_OPEN_ROM_HOST,0,NTP_SERVER_PORT);
			if(MySocket == INVALID_UDP_SOCKET)
				break;
#endif			

			// Make certain the socket can be written to
			if(!UDPIsPutReady(MySocket))
			{
				UDPClose(MySocket);
				SNTPState = SM_HOME;
				MySocket = INVALID_UDP_SOCKET;
				break;
			}

			// Transmit a time request packet
			memset(&pkt, 0, sizeof(pkt));
			pkt.flags.versionNumber = 3;	// NTP Version 3
			pkt.flags.mode = 3;				// NTP Client
			pkt.orig_ts_secs = swapl(NTP_EPOCH);
			UDPPutArray((BYTE*) &pkt, sizeof(pkt));	
			UDPFlush();	
			
			dwTimer = TickGet();
			SNTPState = SM_UDP_RECV;		
			break;

		case SM_UDP_RECV:
			// Look for a response time packet
			if(!UDPIsGetReady(MySocket)) 
			{
				if((TickGet()) - dwTimer > NTP_REPLY_TIMEOUT)
				{
					// Abort the request and wait until the next timeout period
					UDPClose(MySocket);
					//dwTimer = TickGetDiv64K();
					//SNTPState = SM_SHORT_WAIT;
					SNTPState = SM_HOME;
					MySocket = INVALID_UDP_SOCKET;
					break;
				}
				break;
			}
			
			// Get the response time packet
			w = UDPGetArray((BYTE*) &pkt, sizeof(pkt));
			UDPClose(MySocket);
			dwTimer = TickGetDiv64K();
			SNTPState = SM_WAIT;
			MySocket = INVALID_UDP_SOCKET;
			
			// Validate packet size
			if(w != sizeof(pkt)) 
			{
				break;	
			}
			
			// Set out local time to match the returned time
			dwLastUpdateTick = TickGet();
			dwSNTPSeconds = swapl(pkt.tx_ts_secs) - NTP_EPOCH;
			// Do rounding.  If the partial seconds is > 0.5 then add 1 to the seconds count.
			if(((BYTE*)&pkt.tx_ts_fraq)[0] & 0x80)
				dwSNTPSeconds++;

			#ifdef WIFI_NET_TEST
				wifi_net_test_print("SNTP: current time", dwSNTPSeconds);
			#endif
			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(TickGetDiv64K() - dwTimer > (NTP_FAST_QUERY_INTERVAL/65536ull))
			{
				SNTPState = SM_HOME;
				MySocket = INVALID_UDP_SOCKET;
			}
			break;

		case SM_WAIT:
			// Requery the NTP server after a specified NTP_QUERY_INTERVAL time (ex: 10 minutes) has elapsed.
			if(TickGetDiv64K() - dwTimer > (NTP_QUERY_INTERVAL/65536ull))
			{
				SNTPState = SM_HOME;
				MySocket = INVALID_UDP_SOCKET;
			}

			break;
	}
}
Example #20
0
/// @cond debug
int cCALLVoiceStart()
{
	char cmdReply[200];
	char msg2send[200];
	int resCheck = 0;
	DWORD tick;
	int countData;
	int chars2read;
	
	switch (smInternal)
	{
		case 0:
			// Check if Buffer is free
			if(GSMBufferSize() > 0)
			{
				// Parse Unsol Message
				mainGSMStateMachine = SM_GSM_CMD_PENDING;
				return -1;
			}
			else
				smInternal++;
		
		case 1:	
			// Send first AT command
			sprintf(msg2send, "ATD=\"%s\";\r", mainCall.CallerID);
			GSMWrite(msg2send);
			
			// Start timeout count
			tick = TickGetDiv64K(); // 1 tick every seconds
			maxtimeout = 60;
			smInternal++;
		
		case 2:
			// Check ECHO 
			countData = 0;
			resCheck = CheckEcho(countData, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		case 3:
			// Get reply (OK, BUSY, ERROR, etc...)
			vTaskDelay(1);
			// Get OK
			sprintf(msg2send, "OK");
			chars2read = 2;
			countData = 2; // GSM buffer should be: <CR><LF>OK<CR><LF>
			resCheck = CheckCmd(countData, chars2read, tick, cmdReply, msg2send, maxtimeout);
			
			CheckErr(resCheck, &smInternal, &tick);
			
			if(resCheck)
			{
				return mainOpStatus.ErrorCode;
			}
			
		default:
			break;		
	}
	mainCall.Status = CALL_IN_PROG;
	
	smInternal = 0;
	// Cmd = 0 only if the last command successfully executed
	mainOpStatus.ExecStat = OP_SUCCESS;
	mainOpStatus.Function = 0;
	mainOpStatus.ErrorCode = 0;
	mainGSMStateMachine = SM_GSM_IDLE;
	return -1;
}