Example #1
0
/****************************************************************************
  MAIN APPLICATION ENTRY POINT
****************************************************************************/
int main(void)
{
	// Initialize application specific hardware
	HWInit(HWDEFAULT);	

	// Initializing the UART for the debug
	#if defined	(STACK_USE_UART)
	UARTInit(1, UART_DBG_DEF_BAUD);
	UARTOn(1);
	_dbgwrite("Flyport starting...");
	#endif

	//	Queue creation - will be used for communication between the stack and other tasks
	xQueue = xQueueCreate(3, sizeof (int));

	xSemFrontEnd = xSemaphoreCreateMutex();
	
	
	//	RTOS starting
	if (xSemFrontEnd != NULL) 
	{
		// Creates the task to handle all TCPIP functions
		xTaskCreate(TCPIPTask, (signed char*) "TCP", STACK_SIZE_TCPIP,
		NULL, tskIDLE_PRIORITY + 1, &hTCPIPTask);
	
		// Start of the RTOS scheduler, this function should never return
		vTaskStartScheduler();
	}
	
	_dbgwrite("Unexpected end of program...\r\n");

	while(1);
	return -1;
}
Example #2
0
static void printResponse()
{
	_dbgwrite("\n\rResponse Header:\n\r");
	_dbgwrite(respHeader);
	_dbgwrite("\n\rResponse Body:\n\r");
	_dbgwrite(respBody);
	_dbgwrite("\n\r");
}
Example #3
0
// INCOMING CALL
void OnRing(char* phoneNumber)
{
	#if defined(STACK_USE_UART)
	char buf[20];
	_dbgwrite("Event: On Ring\r\nPhone number: ");
	sprintf(buf, "%s", phoneNumber);
	_dbgwrite(buf);
	_dbgwrite("\r\n");
	#endif
}
Example #4
0
void OnSMSSentReport(int msgreference, int msgreport)
{
	#if defined(STACK_USE_UART)
	char buf[30];
	_dbgwrite("Event: On SMS Sent Report\r\n");
	sprintf(buf, "message reference:%d\r\n", msgreference);
	_dbgwrite(buf);
	sprintf(buf, "report value:%d\r\n", msgreport);
	_dbgwrite(buf);
	#endif
}
Example #5
0
void OnError(int error, int errorNumber)
{
	#if defined(STACK_USE_UART)
	char numErr[10];
	_dbgwrite("Event: On Error\r\nerror: ");
	sprintf(numErr, "%d\r\n", error);
	_dbgwrite(numErr);
	_dbgwrite("error number: ");
	sprintf(numErr, "%d\r\n", errorNumber);
	_dbgwrite(numErr);
	#endif
}
void FOTAEraseFlash()
{
    unsigned long int mem_ind;
	_dbgwrite("Erasing flash... ");
	for (mem_ind = FLASH_START_ADD; mem_ind < 0x1FFFFF; mem_ind += PAGE_SIZE)
	{
		vTaskSuspendAll();
		SPIFlashEraseSector(mem_ind);
		xTaskResumeAll();
	}
	_dbgwrite("Done!\r\n");
}
Example #7
0
void OnSMSReceived(BYTE memtype, int index)
{
	#if defined(STACK_USE_UART)
	_dbgwrite("Event: On SMS Received\r\nmemory type: ");
	if(memtype == SM_MEM)
		_dbgwrite("SIM card");
	else
		_dbgwrite("Module Memory");
	_dbgwrite("\r\nmemory index: ");
	char smsRec[7];
	sprintf(smsRec, "%d\r\n", index);
	_dbgwrite(smsRec);
	#endif
}
Example #8
0
void OnRegistration(BYTE Status)
{
	#if defined(STACK_USE_UART)
	_dbgwrite("Event: On Registration\r\n");
	switch(Status)
	{
		case 0:
			_dbgwrite( "Not registered\r\n");
			break;
		case 1:
			_dbgwrite( "Registered on Network\r\n");
			break;
		case 2:
			_dbgwrite("Searching for new operator\r\n");
			break;
		case 3:
			_dbgwrite("Registration denied\r\n");
			break;
		case 4:
			_dbgwrite("Unkown registration status\r\n");
			break;
		case 5:
			_dbgwrite("Roaming\r\n");
			break;
	}		
	#endif
}
long FTPFileSize(TCP_SOCKET cmdSock, char fileName[])
{
	char cmd[strlen(fileName) + 10], len[12];
	int res;
	strcpy(cmd, "SIZE ");
	strcat(cmd, fileName);
	
	FTPRxFlush(cmdSock, 100);
	res = FTPSendCmd(cmdSock, cmd, len, 12);
	if (res < 0)
		return res;
	_dbgwrite("FTPFileSize:");
	_dbgwrite(len);
	if (res == 550)
		return FTP_FILE_NOT_FOUND;
	if (res == 213)
		return atol(len);
	return FTP_ERR_WRONG_ANSWER;
}
Example #10
0
/**
* Internal utils
*/
static void connect()
{
	respHeader[0]='\0';
	respBody[0]='\0';

	socket = TCPClientOpen(EVRYTHNG_API_HOST, EVRYTHNG_API_PORT);	
	while(!TCPisConn(socket))
    {
		vTaskDelay(30);
		_dbgwrite(".");
    }
	_dbgwrite("\r\nTCP connection OK\r\n");
		
	TCPSSLStart(socket);
	char buff[100];
	sprintf(buff, "SSL stat: %d\r\n", TCPSSLStatus(socket));
	_dbgwrite(buff);
	while(TCPSSLStatus(socket) == 1);
	sprintf(buff, "SSL stat: %d\r\n", TCPSSLStatus(socket));		
	_dbgwrite(buff);
	
}
int FTPRxFlush(TCP_SOCKET FTPtoflush, int timeout) 
{	
	int counter = 0, counter2 = 0;
	char res[50];
	int len;
	
	//	Waiting for the first characters
	while (FTPRxLen(FTPtoflush) == 0)
	{
		vTaskDelay(1);
		counter++;
		if (counter == timeout)
			return 1;	//	No chars to flush
	}
	
	counter = 0;

	while (FTPRxLen(FTPtoflush))
	{	
		// 	The size of dummy array res is 50 char, so len is resized, in case there are more chars in buffer
		len = FTPRxLen(FTPtoflush);
		if (len > 49)
			len = 49;
		FTPRead( FTPtoflush, res, len);
		res[len] = 0;
		_dbgwrite(res);
		//	Waiting for new characters on FTP buffer, the timeout is inserted as parameter by the user
		while (FTPRxLen(FTPtoflush) == 0 )
		{
			counter++;
			vTaskDelay(1);
			if (counter == timeout)
			{
				//	Timeout is reached, but a check on the last char is 
				//	performed, since it must be '\r' or '\n'
				if ( (res[len-1]=='\r') || (res[len-1]=='\n') )
					break;
				else
				{
					counter2++;
					if (counter2 == 3)
						break;
					counter = 0;
				}
			}
		}
	}
	return 0;	//	FTP buffer flushed
}
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))
				{
					_dbgwrite("FTPStreamWrite: timeout by server disconnection\r\n");
					errHandling(&dataSocket);
					streamStat = FTP_STREAM_NOT_CONN;
					return len;
				}
				else
				{
					_dbgwrite("FTPStreamWrite: timeout\r\n");
					return len;
				}
			}
		}
		return len;
	}
	else if (!FTPisConn(dataSocket))
		return FTP_DATA_NO_CONNECTED;
	else 
		return FTP_STREAM_INVALID_OP;
}
BYTE MD5IntegrityCheck(BYTE* buffer, BYTE fileCount)
{
    BYTE operationRep = 0;
     
    //	MD5 INTEGRITY CHECK ON MEMORY
    BYTE resmd[16];
    HASH_SUM Hash;
    _dbgline("Calculating md5 from memory...");
    MD5Initialize(&Hash);
    long unsigned int f_ind = 0;
    BYTE b_read[2];
    unsigned long int md5_ind = FLASH_START_ADD;
    md5_ind += FW_SIZE*(unsigned long int)(fileCnt);
	unsigned long int stopSize = FW_SIZE;
	if(fileCount == 8) // Last file...
	{
		stopSize = (unsigned long int)FW_LAST_SIZE;
	}
	for (f_ind = 0; f_ind < stopSize; f_ind++)
	{
		vTaskSuspendAll();
		SPIFlashReadArray(md5_ind+f_ind, b_read, 1);
		xTaskResumeAll();
		HashAddData(&Hash, b_read, 1);
	}
	
    MD5Calculate(&Hash, resmd);
    BYTE i;
    char rr[3];

    _dbgline("MD5:");
    for (i=0; i<16; i++)
    {
        sprintf(rr,"%X ",resmd[i]);
        _dbgwrite(rr);
        if (resmd[i] != (BYTE) buffer[i])
        {
            operationRep = 1;
        }
    }
    return operationRep;
}
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;
	
}
Example #15
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	
	}
}
int FTPStreamOpen(TCP_SOCKET cmdSock, char fileName[], char mode[])
{
	//	Stream opening started only if stream is not connected
	if ( (dataSocket == INVALID_SOCKET) &&	(streamStat == FTP_STREAM_NOT_CONN) )
	{
		char pasvBuff[16 + strlen(fileName)];	
		int cnt = 0, servReply;
		char code[5];
	
		//	Check on command socket connection
		if ( (!FTPisConn(cmdSock))|| (cmdSock == INVALID_SOCKET) )
			return FTP_SOCK_NOT_CONNECTED;
			
		//	Reading file size
		if (strcmp(mode, RETR) == 0)
		{
			_dbgwrite("StreamOpen: RETR\r\n");
			streamLen = FTPFileSize(cmdSock, fileName);
			if (streamLen < 0)
				return streamLen;
		}
		else if(strcmp(mode, STOR) == 0)
		{
			_dbgwrite("StreamOpen: STOR\r\n");
		}
		else if(strcmp(mode, APPE) == 0)
		{
			_dbgwrite("StreamOpen: APPE\r\n");
		}
		//	Connection in passive mode
		dataSocket = FTPClientPasv(cmdSock, pasvBuff); 
		
		//	Waiting for data socket connection
		while (!FTPisConn(dataSocket))
		{
			cnt++;
			vTaskDelay(10);
			if (cnt == 30)
			{
				errHandling(&dataSocket);
				return FTP_DATA_NO_CONNECTED;
			}
		}	
		
		//	Append file command APPE/STOR/RETR...
		FTPMultiWrite(cmdSock, (BYTE*)mode,5);
		FTPMultiWrite(cmdSock, (BYTE*)fileName, strlen(fileName));
		FTPMultiWrite(cmdSock, (BYTE*)"\r\n", 2);
		//	Reading answer from server
		servReply = FTPAnswer(cmdSock, code);
		if (servReply != 0)
		{
			errHandling(&dataSocket);
			return FTP_ERR_SERV_TIMEOUT;
		}	
		
	 	if ( ( strcmp(code,"150") != 0 ) && ( strcmp(code,"125") != 0 ) )
			return atoi(code);
		if ( (strcmp( mode, APPE) == 0) || (strcmp( mode, STOR) == 0) )
			streamStat = FTP_STREAM_WRITING;
		else if(strcmp( mode, RETR) == 0)
		{
			streamRBytes = 0;
			streamStat = FTP_STREAM_READING;
		}
		return FTP_CONNECTED;
	}
	else
		return FTP_STREAM_INVALID_OP;
}
int FTPConnect(TCP_SOCKET *FTPConn, char *ftp_addr, char ftp_port[], char ftp_usr[], char ftp_pwd[])
{
	int err_count = 0;
	int code_rep = 0, flush_rep = 0;
	_dbgwrite("Server IP:");
	_dbgwrite(ftp_addr);
	_dbgwrite("\r\nServer port:");
	_dbgwrite(ftp_port);
	_dbgwrite("\r\n");
	
	//	#1 - SOCKET OPENING: A new FTP socket is open to connect to the remote server
	if (FTPisConn(*FTPConn))
	{
		return FTP_CONNECTED;
	}
	*FTPConn = INVALID_SOCKET;
	*FTPConn = FTPClientOpen(ftp_addr, ftp_port);	
	vTaskDelay(50);
	
	//	Socket creation check: if an internal error occured, 
	//	Flyport retries up to 3 times to create the socket
	while ( (*FTPConn == INVALID_SOCKET) && (err_count < 3) )
	{
		err_count++;
		vTaskDelay(20);
		errHandling(FTPConn);
		vTaskDelay(10);
		*FTPConn = FTPClientOpen(ftp_addr, ftp_port);
		vTaskDelay(20);
	}
	
	// EXCEPTION HANDLING: socket was not created
	if (*FTPConn == INVALID_SOCKET)
		return FTP_ERR_NOT_CREATED;
		
	// Socket is created, now let's check the connection
	// Flyport will wait up to 10 seconds for connection with server
	err_count = 0;
	while ( (!FTPisConn(*FTPConn)) && (err_count < 20) )
	{
		_dbgwrite("Server searching...");
		vTaskDelay(50);
		err_count++;
	}
	_dbgwrite("\r\n");
	
	//	EXCEPTION HANDLING: server not found
	if (!FTPisConn(*FTPConn))
	{
		errHandling(FTPConn);
		return FTP_ERR_SERV_NOT_FOUND;
	}
	_dbgwrite("FTPConnect: SERVER FOUND\r\n");
	
	//	Reading the response code from the server 
	//	(expected response code: 220)
	char code[5];
	code_rep = FTPAnswer(*FTPConn, code);
	
	//	EXCEPTION HANDLING: timeout and bad server answer
	if (code_rep != 0)
	{
		errHandling(FTPConn);
		return FTP_ERR_SERV_TIMEOUT;
	}
	if (strcmp(code, "220") != 0)
	{
		errHandling(FTPConn);
		return atoi(code);
	}
	else 
		_dbgwrite("FTPConnect: SERVER ANSWERED\r\n");

 	flush_rep = FTPRxFlush(*FTPConn, 300);

	vTaskDelay(50);
	
	
 	//	#2 - SENDING USERNAME TO SERVER
 	FTPMultiWrite(*FTPConn, (BYTE*)"USER ", 5);
 	FTPMultiWrite(*FTPConn, (BYTE*)ftp_usr, strlen(ftp_usr));
 	FTPMultiWrite(*FTPConn, (BYTE*)"\r\n", 2);

	code_rep = FTPAnswer(*FTPConn, code);
	//	EXCEPTION HANDLING: server timeout
	if (code_rep != 0)
	{
		if (FTPisConn(*FTPConn))
		{
			errHandling(FTPConn);
			return FTP_ERR_SERV_TIMEOUT;
		}
		else
		{
			errHandling(FTPConn);
			return FTP_ERR_SERV_DISCONNECTED;
		}	
	}
	
	//	EXCEPTION HANDLING: wrong answer from server
 	if ( strcmp(code,"331") != 0 )
	{
		errHandling(FTPConn);
 		return atoi(code);
	}
 	else
 		_dbgwrite("USER OK\r\n");
 	flush_rep = FTPRxFlush(*FTPConn, 100);
 		
 		
 	// #3 - SENDING PASSWORD TO SERVER
  	FTPMultiWrite(*FTPConn, (BYTE*)"PASS ", 5);
	if (ftp_pwd != FTP_NO_PASS)
		FTPMultiWrite(*FTPConn, (BYTE*)ftp_pwd, strlen(ftp_pwd));
 	FTPMultiWrite(*FTPConn, (BYTE*)"\r\n", 2);
	
	code_rep = FTPAnswer(*FTPConn, code);
	//	EXCEPTION HANDLING: server timeout
	if (code_rep != 0)
	{
		if (FTPisConn(*FTPConn))
		{
			errHandling(FTPConn);
			return FTP_ERR_SERV_TIMEOUT;
		}
		else
		{
			errHandling(FTPConn);
			return FTP_ERR_SERV_DISCONNECTED;
		}	
	}
	
	//	EXCEPTION HANDLING: wrong password and unknow answer from server
 	if ( strcmp(code,"230") != 0 )
 	{
	 	if (strcmp(code,"530") == 0 )
		{
			errHandling(FTPConn);
	 		return FTP_ERR_WRONG_LOGIN;
		}	
	 	else
		{
			errHandling(FTPConn);
	 		return atoi(code);	
		}
	 }
  	else
 		_dbgwrite("PASSWORD OK\r\n");
 	flush_rep = FTPRxFlush(*FTPConn, 100);
 	//	Everything went OK, returning connected status 	
	return FTP_CONNECTED;
}
Example #18
0
File: Main.c Project: aiyi/flyport
/*****************************************************************************
 FUNCTION 	GSMTask
			Main function to handle the HiLo stack
 
 RETURNS  	None
 
 PARAMS		None
*****************************************************************************/
void GSMTask()
{
	//	Function pointers for the callback function of the HiLo stack 
	FP_GSM[1] = cSMSSend;
	FP_GSM[2] = cSMSRead;
	FP_GSM[3] = cSMSDelete;

	FP_GSM[5] = cSMTPParamsClear;
	FP_GSM[6] = cSMTPParamsSet;
	FP_GSM[7] = cSMTPEmailTo;
	FP_GSM[8] = cSMTPEmailSend;
	FP_GSM[10] = cCALLHangUp;
	FP_GSM[11] = cCALLVoiceStart;
	FP_GSM[12] = cFTPConfig;
	FP_GSM[13] = cFTPReceive;
	FP_GSM[14] = cFTPSend;
	FP_GSM[15] = cFTPDelete;
	
	FP_GSM[17] = cLLWrite;
	FP_GSM[18] = cLLModeEnable;		// it will be executed only if Standard mode is enabled
	FP_GSM[19] = cSTDModeEnable;	// it will be executed only if LowLevel mode is enabled
	FP_GSM[20] = cTCPClientOpen;
	FP_GSM[21] = cTCPClientClose;
	FP_GSM[22] = cTCPStatus;
	FP_GSM[23] = cTCPWrite;
	FP_GSM[24] = cTCPRead;
	FP_GSM[25] = cTCPRxFlush;
	FP_GSM[26] = cAPNConfig;
	FP_GSM[27] = cHTTPRequest;
	FP_GSM[28] = cGSMHibernate;
	FP_GSM[29] = cGSMOn;
	FP_GSM[30] = cFSWrite;
	FP_GSM[31] = cFSRead;
	FP_GSM[32] = cFSDelete;
	FP_GSM[33] = cFSSize;
	FP_GSM[34] = cFSAppend;
	FP_GSM[35] = cGSMSignal;
	
	// Initialization of tick only at the startup of the device
	if (hFlyTask == NULL)
	{
	    TickInit();
	}  
	
	if (hFlyTask == NULL)
	{
		_dbgwrite("Flyport GPRS/3G starting...\r\n");
		_dbgwrite("setting up HiLo module...\r\n");
				
		// Enter Standard Mode:
		while(HiloStdModeOn(baudComp[7])); // 115200 baud...
	}
	
	if (hFlyTask == NULL)
	{
		//	Creates the task dedicated to user code
		xTaskCreate(FlyportTask,(signed char*) "FLY" , (configMINIMAL_STACK_SIZE *4 ), 
		NULL, tskIDLE_PRIORITY + 1, &hFlyTask);	
	}
//-------------------------------------------------------------------------------------------
//|							--- COOPERATIVE MULTITASKING LOOP ---							|
//-------------------------------------------------------------------------------------------
    while(1)
    {
	    switch(mainGSMStateMachine)
	    {
	    	case SM_GSM_IDLE:
	    		GSMUnsol(NO_ERR);
	    		// Check on the queue to verify if other task have requested some stack function
				xStatus = xQueueReceive(xQueue,&Cmd,0);
				CmdCheck(OP_EXECUTION);
				break;
			
			case SM_GSM_CMD_PENDING:
				GSMUnsol(CMD_UNEXPECTED);
	    		// Check on the queue to verify if other task have requested some stack function
				CmdCheck(OP_EXECUTION);
				break;
			
			case SM_GSM_LL_MODE:
				CmdCheck(OP_LL);
				break;
				
			case SM_GSM_HW_FAULT:
				vTaskSuspend(hFlyTask);
				_dbgwrite("Reset HiLo module...\r\n");
				mainGSM.HWReady = FALSE;
				HiloReset();
				
				// Enter Standard Mode:
				while(HiloStdModeOn(baudComp[7])); // 115200 baud...
				
				mainGSMStateMachine = SM_GSM_IDLE;
				mainOpStatus.Function = 0;
				mainOpStatus.ExecStat = OP_SUCCESS;
				mainOpStatus.ErrorCode = 0;
				mainGSM.HWReady = TRUE;
				vTaskResume(hFlyTask);
				break;
				
			case SM_GSM_HIBERNATE:
				// GSMUnsol(NO_ERR);
				// Accept only function 29 (cGSMOn)
				if(mainOpStatus.Function == 29)
					CmdCheck(OP_EXECUTION);
				else if(mainOpStatus.Function != 0)
				{
					mainOpStatus.ExecStat = OP_HIB_ERR;
					mainOpStatus.Function = 0;
					mainOpStatus.ErrorCode = -1;
				}
				break;
	    }
	}
}