Esempio n. 1
0
void timeSync(void)
{
	BYTE i;
	signed char j;	
	static TICK			Timer;
	static TICK perodicTick = 0;
	static TICK t = 0;
	static TCP_SOCKET	MySocket = INVALID_SOCKET;
	static NODE_INFO	Server;
	static int arp_tries = 0;
	static int tcp_tries = 0;

	BYTE rcnt=0;
	BYTE ncnt=0;
	char foundData=0;

	if ((tickGet()-t) >= TICK_1S )
    {
		t = tickGet();
		timeNow++;
	}

	switch(smTS)
	{
		case SM_START:
			#if defined(TIMESYNC_DEBUG)
			putrsUART("Start!\r\n");
			#endif
			// Set IP adress to connect to.
			Server.IPAddr.v[0]=193;
			Server.IPAddr.v[1]=11;
			Server.IPAddr.v[2]=249;
			Server.IPAddr.v[3]=54;

			arp_tries = 0;
			tcp_tries = 0;

			smTS = SM_ARP_RESOLVE;
		break;
		
		case SM_ARP_RESOLVE:
			#if defined(TIMESYNC_DEBUG)
			putrsUART("Resolve..\r\n");
			#endif
			// If ARP is redy..
			if (ARPIsTxReady())
			{
				// Resolve the IP adress..
				ARPResolve(&Server.IPAddr);
				arp_tries++;
				Timer = tickGet();
				smTS = SM_ARP_RESOLVED;
			}
		break;

		case SM_ARP_RESOLVED:
			#if defined(TIMESYNC_DEBUG)
			putrsUART("Resolved..\r\n");
			#endif
			// If IP adress is resolved, go to next state
			if (ARPIsResolved(&Server.IPAddr, &Server.MACAddr))
			{
				smTS = SM_CONNECT;
			}
			// If not resolved and spent long time here,
			// Go back to previous state and re-resolve.
			else if (tickGet()-Timer > 1*TICK_1S)
			{
				smTS = SM_ARP_RESOLVE;
			}
			else if (arp_tries>=MAX_ARP_TRIES)
			{
				//Abort
				smTS = SM_ABORT;
			}

		break;

		case SM_CONNECT:
			#if defined(TIMESYNC_DEBUG)
			putrsUART("Connect..\r\n");
			#endif
			// We have an sucessfull ARP, connect..
			MySocket = TCPConnect(&Server, ServerPort);
			tcp_tries++;	

			if(MySocket == INVALID_SOCKET)
			{
				// Do something.
			}
		
			Timer = tickGet();
			smTS = SM_CONNECT_WAIT;

		break;

		case SM_CONNECT_WAIT:
			#if defined(TIMESYNC_DEBUG)
			putrsUART("Connect wait..\r\n");
			#endif
			// Wait for connection..

			if (TCPIsConnected(MySocket))
			{
				smTS = SM_CONNECTED;
			}
			// If not connected and spent long time here,
			// Go back to previous state and re-connect.
			else if (tickGet()-Timer > 5*TICK_1S)
			{
				TCPDisconnect(MySocket);
				MySocket = INVALID_SOCKET;
				smTS = SM_CONNECT;
			}
			else if (tcp_tries>=MAX_TCP_TRIES)
			{
				//Abort
				TCPDisconnect(MySocket);
				MySocket = INVALID_SOCKET;
				smTS = SM_ABORT;
			}


		break;

		case SM_CONNECTED:
			#if defined(TIMESYNC_DEBUG)
			putrsUART("Connected..\r\n");
			#endif
			// Send data.
			Timer = tickGet();

			if(TCPIsPutReady(MySocket))
			{

				TCPPut(MySocket, 'G');
				TCPPut(MySocket, 'E');
				TCPPut(MySocket, 'T');
				TCPPut(MySocket, ' ');
				TCPPut(MySocket, '/');
				TCPPut(MySocket, 't');
				TCPPut(MySocket, 'i');
				TCPPut(MySocket, 'm');
				TCPPut(MySocket, 'e');
				TCPPut(MySocket, '.');
				TCPPut(MySocket, 'p');
				TCPPut(MySocket, 'h');
				TCPPut(MySocket, 'p');
				TCPPut(MySocket, ' ');
				TCPPut(MySocket, 'H');
				TCPPut(MySocket, 'T');
				TCPPut(MySocket, 'T');
				TCPPut(MySocket, 'P');
				TCPPut(MySocket, '/');
				TCPPut(MySocket, '1');
				TCPPut(MySocket, '.');
				TCPPut(MySocket, '0');
				TCPPut(MySocket, '\r');
				TCPPut(MySocket, '\n');
				TCPPut(MySocket, '\r');
				TCPPut(MySocket, '\n');

				// Send the packet
				TCPFlush(MySocket);
				
				smTS = SM_RECEIVE;
			}

		break;

		case SM_RECEIVE:
			#if defined(TIMESYNC_DEBUG)
			putrsUART("Receive..\r\n");
			#endif
			// Client disconnected.
			if(!TCPIsConnected(MySocket))
			{
				smTS = SM_ABORT;
				break;
			}				

			if(TCPIsGetReady(MySocket))
			{
				while(TCPGet(MySocket, &i))
				{
					if (i==CR) rcnt++;
					else if(i==LF) ncnt++;
					else
					{ 
						rcnt=0; 
						ncnt=0; 
					}

					if (foundData==1)
					{
						if (j>=0)
						{	
							timeNow=timeNow+(((DWORD)i)<<(8*j--));
							#if defined(TIMESYNC_DEBUG)
							while(BusyUART()); WriteUART(i);
							#endif
						}
					}

					if(rcnt>1 && ncnt>1) {j=3; timeNow=0; foundData=1;}

					
				}
				smTS = SM_DISCONNECT;	
			}

		break;

		case SM_DISCONNECT:
			#if defined(TIMESYNC_DEBUG)
			putrsUART("\r\nDisconnect\r\n");
			#endif
			foundData=0;
			t = tickGet();
			lastSync = timeNow;
			perodicTick=tickGet();
			TCPDisconnect(MySocket);
			MySocket = INVALID_SOCKET;
			smTS = SM_DONE;
		break;

		case SM_ABORT:
			#if defined(TIMESYNC_DEBUG)
			putrsUART("Abort...\r\n");
			#endif
			smTS = SM_START;
		break;

		case SM_DONE:
			if (tickGet()-perodicTick > SYNC_INTERVAL*TICK_1S)
			{
				#if defined(TIMESYNC_DEBUG)
				putrsUART("GO!\r\n");
				#endif
				smTS = SM_START;
			}
		break;

		default: smTS = SM_START; break;

	}


}
Esempio n. 2
0
/*
 * Main entry point.
 */
void main(void)
{
    TICK8  tsecWait = 0;           //General purpose wait timer
    TICK16 tsecMsgSent = 0;        //Time last message was sent
    TICK16 tsecBlinker = 0;  
    BYTE main_state;				// what are the inputs
	BYTE main_inputs;				// who has the transmit
    char c;
    NODE_INFO udpServerNode;

    //Initialize AppConfig structure
    appcfgInit();
    
    //Initialize any application specific hardware.
    InitializeBoard();

    //Initialize all stack related components.
    TickInit();

    //Initialize the TCP/IP stack
    StackInit();


    /////////////////////////////////////////////////
    //Initialize UDP socket

    //Initialize remote IP and address with 10.1.0.101. The MAC address is
    //is not intialized yet, but after we receive an ARP responce.
    //Configure for local port 54123 and remote port 54124.
    udpServerNode.IPAddr.v[0] = 255;
    udpServerNode.IPAddr.v[1] = 255;
    udpServerNode.IPAddr.v[2] = 255;
    udpServerNode.IPAddr.v[3] = 255;
    udpSocketUser = UDPOpen(54123, &udpServerNode, 54124);
	//udpSocketUser = UDPOpen(54123, NULL, 54124);
	smUdp = SM_UDP_RESOLVED;
    
    //An error occurred during the UDPOpen() function
    if (udpSocketUser == INVALID_UDP_SOCKET) {
        //Add user code here to take action if required!
    }

    /*
     * Once all items are initialized, go into infinite loop and let stack items execute
     * their tasks. If the application needs to perform its own task, it should be done at
     * the end of while loop. Note that this is a "co-operative mult-tasking" mechanism where
     * every task performs its tasks (whether all in one shot or part of it) and returns so
     * that other tasks can do their job. If a task needs very long time to do its job, it
     * must broken down into smaller pieces so that other tasks can have CPU time.
     */
    while(1)
    {
	    ServiceBoard();
		if (TickGetSecDiff(tsecBlinker) >= (TICK16)1) 
		{
			tsecBlinker = TickGetSec();     //Update with current time
			//Toggle system LED 
#ifdef BLINKTIME
            TRISB_RB6 = 0;
            LATB6 ^= 1;
#endif
		}
        switch (smUdp) {
        case SM_UDP_SEND_ARP:
            if (ARPIsTxReady()) {
                tsecWait = TickGet8bitSec();   //Remember when we sent last request
                
                //Send ARP request for given IP address
                ARPResolve(&udpServerNode.IPAddr);
                
                smUdp = SM_UDP_WAIT_RESOLVE;
            }
            break;
        case SM_UDP_WAIT_RESOLVE:
            //The IP address has been resolved, we now have the MAC address of the
            //node at 10.1.0.101
            if (ARPIsResolved(&udpServerNode.IPAddr, &udpServerNode.MACAddr)) {
                smUdp = SM_UDP_RESOLVED;
            }
            //If not resolved after 2 seconds, send next request
            else {
                if (TickGetDiff8bitSec(tsecWait) >= (TICK8)2) {
                    smUdp = SM_UDP_SEND_ARP;
                }
            }
            break;
        case SM_UDP_RESOLVED:
            if ( 1 || !PORTB_RB0) {
                //Send a message every second for as long as PIC port pin B0 is = 0
                if ((TickGetSecDiff(tsecMsgSent) >= (TICK16)1) ||
					((main_state != old_state) || (main_inputs != old_inputs))) {
                    //Checks if there is a transmit buffer ready for accepting data, and that the given socket
                    //is valid (not equal to INVALID_UDP_SOCKET for example)
                    if (UDPIsPutReady(udpSocketUser)) {
                        tsecMsgSent = TickGetSec();     //Update with current time

                        //Send a UDP Datagram with one byte only indicating the status We are only interrested in the first byte of the message.
                        UDPPut('H');UDPPut('E');UDPPut('L');UDPPut('L');UDPPut('O');
						UDPPut(old_state);
						UDPPut(old_inputs);
						main_state = old_state;
						main_inputs = old_inputs;
                        //Send contents of transmit buffer, and free buffer
                        UDPFlush();
                       	
						//Toggle system LED each time a message is sent
                    	TRISB_RB6 = 0;
                    	LATB6 ^= 1; 
                    }

                    
                }
            }
            break;
        }

        //This task performs normal stack task including checking for incoming packet,
        //type of packet and calling appropriate stack entity to process it.
        StackTask();

        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        // ADD USER CODE HERE
        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    }
}
void lftp_task( void )
{	
	WORD ttt;
	BYTE c;
	BOOL bPreLine;
	BOOL bPostLine;
	
	// Nothing to do if we don't have a link
	if ( !MACIsLinked() ) return;
	
	// check if state machine is stuck somewhere and reset the it after a while if needed :
    if ( ( ftp_state != LFTP_STATE_NONE ) && 
	    	( TickGetDiff( TickGet(), lastActivity) > ( LFTP_TIMEOUT * TICK_SECOND ) ) ) {
		
		// Close ftp client socker if open
		//if ( TCPIsConnected( ftpsocket ) ) {
        	writeRomString2Socket( quit );
        	TCPDisconnect( ftpsocket );
        	ftpsocket = UNKNOWN_SOCKET;
        //}
        
        // Close data socket if open
        TCPDisconnect( datasocket );
        datasocket = UNKNOWN_SOCKET;
		
		// Check if we should try again or if its time
		// to pack it in
        cntBeforeFail++;
        if ( cntBeforeFail > LFTP_MAX_RETRIES ) {
	    	
	    	cntBeforeFail = 0;
	    	ftp_state = LFTP_STATE_NONE;		// Give up...
	    	bftpLoadWork = FALSE;	// Work is done - failed
	    	
	    }
 
        ftp_state = LFTP_STATE_NONE;
    }
		
		
		
	switch( ftp_state ) {
	
		// **
		// Start to work if its time to do so
		
		case LFTP_STATE_NONE:
		
			// Check timer and see if we should fetch
			// data from the server.
			lastActivity = TickGet();
			
			if ( bftpLoadWork ) {
				ftp_state = LFTP_STATE_ARP;	// Must get MAC address for server
				cntBeforeFail = 0;			// Init. failure counter
				DBG_OUT('A');
			}
			break;
			
			
		//**
		// Resolve the MAC address of the ftp server
			
		case LFTP_STATE_ARP:
			
			ftp_nodeinfo.IPAddr.v[ 0 ] = LFTP_SERVER_IP_v0;
			ftp_nodeinfo.IPAddr.v[ 1 ] = LFTP_SERVER_IP_v1;
			ftp_nodeinfo.IPAddr.v[ 2 ] = LFTP_SERVER_IP_v2;
			ftp_nodeinfo.IPAddr.v[ 3 ] = LFTP_SERVER_IP_v3;
			
			if ( ARPIsTxReady() ) {	
				DBG_OUT('B');
				ARPResolve( &ftp_nodeinfo.IPAddr );	// resolve IP adress
				ftp_state = LFTP_STATE_ARP_RESOLVE;
				lastActivity = TickGet();
			}
			break;	
		
			
		// **
		// Check if the ftp MAC address is resolved
			
		case LFTP_STATE_ARP_RESOLVE:	
			if ( ARPIsResolved( &ftp_nodeinfo.IPAddr, &ftp_nodeinfo.MACAddr ) ) {
				DBG_OUT('D');
				ftp_state = LFTP_STATE_CONNECT;
				lastActivity = TickGet();	
			}
			break;			
			
			
			
		// **
		// Connect to ftp server
			
		case LFTP_STATE_CONNECT:				
			
			// Try to connect				
			ftpsocket = TCPConnect( &ftp_nodeinfo, LFTP_PORT );
			if ( INVALID_SOCKET != ftpsocket ) {
				DBG_OUT('E');
				ftp_state = LFTP_STATE_CONNECT_WAIT;
				lastActivity = TickGet();
			}
			break;
		
			
		// **
		// Waiting for ftp connection
		
		case LFTP_STATE_CONNECT_WAIT:
		
			if ( TCPIsConnected( ftpsocket ) ) {
				DBG_OUT('F');
				ftp_state = LFTP_STATE_USER;
				lastActivity = TickGet();	
			}
			break;
				
							
							
		// Here we wait for server connection and send
		// USER command if OK	
		case LFTP_STATE_USER:

			// Fetch data if we are connected
			if ( TCPIsGetReady( ftpsocket ) ) {
					
				// get first digit
				while( TCPGet( ftpsocket, &c ) ) {
					if ( isdigit( c ) ) break;
				}
					
				// If connected with positive response "2xx - xxxxxxxx..."
				// we send username. If not we just timeout
				if ( '2' == c ) {
					DBG_OUT('G');
					writeRomString2Socket( user );
					ftp_state = LFTP_STATE_PASS;
					lastActivity = TickGet();
				}
					
				TCPDiscard( ftpsocket );
				 	
			}
			break;	
			
			
			
			// **
			// Here we wait for response from USER command
			// and send PASS command if OK
			
			case LFTP_STATE_PASS:
				
			// Fetch data if we are connected
			if ( TCPIsGetReady( ftpsocket ) ) {
				
				DBG_OUT('$');
					
				// get first digit
				while( TCPGet( ftpsocket, &c ) ) {
					DBG_OUT(c);
					if ( isdigit( c ) ) break;
				}
					
				// If connected with positive response "3xx - xxxxxxxx..."
				// we send username. If not we just timeout
				if ( ('3' == c ) || ('2' == c ) ) {
					DBG_OUT('H');
					writeRomString2Socket( pass );
					ftp_state = LFTP_STATE_PASV;	
					lastActivity = TickGet();
				}
					
				TCPDiscard( ftpsocket );
						
			}
			break;
			
			
			
			// **
			// Here we wait for response of PASS command
			// and send PASV command if positive and also
			// creates the data socket
			
			case LFTP_STATE_PASV:
		 
			// Fetch data if we are connected
			if ( TCPIsGetReady( ftpsocket ) ) {
				
				DBG_OUT('!');					
				
				// get first digit
				while( TCPGet( ftpsocket, &c ) ) {
					DBG_OUT(c);
					if ( isdigit( c ) ) break;
				}
					
				// If connected with positive response "2xx - xxxxxxxx..."
				// we send username. If not we just timeout
				if ( '2' == c ) {
					DBG_OUT('I');	
						
					writeRomString2Socket( pasv );
					ftp_state = LFTP_STATE_RETR;
					lastActivity = TickGet();
							
				}
					
				TCPDiscard( ftpsocket );	
				 	
			}
			break;
			
			
			// **
			// Here we wait for the result of PASV command
			// and parse its data
			// if OK we send RETR and go on to the next state
			
			case LFTP_STATE_RETR:
	 				
				// Fetch data if we are connected
				if ( TCPIsGetReady( ftpsocket ) ) {
					
					TCPGet( ftpsocket, &c );
					
					if ( '2' == c ) {
						
						DBG_OUT('J');
						
						// Get pasv parameters
						getPasvParams();
						
						// retrive file
						writeRomString2Socket( retr );
						
						ttt = portdata;
						while ( ttt ) {
							DBG_OUT('0' + (ttt % 10) );
							ttt = ttt / 10;
						} 
						
						ftp_state = LFTP_STATE_DATA_CONNECT;		
					}
					
					TCPDiscard( ftpsocket );					
				}
			break;
		
		
			// **
			// Connect to the data socket
		
			case LFTP_STATE_DATA_CONNECT:
			
				// Try to connect				
				datasocket = TCPConnect( &ftp_nodeinfo, portdata );
				if ( INVALID_SOCKET != datasocket ) {
					DBG_OUT('K');
					ftp_state = LFTP_STATE_WAIT_DATA_CONNECT; 
					lastActivity = TickGet();
				}
			break;
			
			
			// **
			// Wait for the data connection to establish
			
			case LFTP_STATE_WAIT_DATA_CONNECT:
			
				if ( TCPIsConnected( datasocket ) ) {
					DBG_OUT('L');
					//writeRomString2Socket( lftpDataSocket, crlf );
					ftp_state = LFTP_STATE_FETCH_DATA;
					lastActivity = TickGet();
				}
				
				// Check for reply on ftp socket FIX!!!!
				if ( TCPIsGetReady( ftpsocket ) ) {	
					DBG_OUT('?');
					while( TCPGet( ftpsocket, &c ) ) {
						DBG_OUT( c );
					}
					TCPDiscard( ftpsocket );
				}
			break;
		
			
			
			// **
			// Fetch the data and send it out on the
			// serial i/f
			
			case LFTP_STATE_FETCH_DATA:
 
				// Fetch data if we are connected
				if ( TCPIsGetReady( datasocket ) ) {	
					DBG_OUT('M');
					
					// Framework start
					serPutByte( 0x00  );
					serPutByte( 0xff  );
					serPutByte( 0xff  );
					serPutByte( 0x01  );
					serPutByte( 0x01  );
					serPutByte( 0x01  );
					
					bPreLine = FALSE;
					bPostLine = FALSE;
					
					// get data
					while( TCPGet( datasocket, &c ) ) {
						
						if ( 0x0d == c ) {
							// We skip CR
						}
						else if ( 0x0a == c ) {
							// Send end line stuff
							serPutByte( 0xff );
							bPreLine = FALSE;
							bPostLine = TRUE;
						}
						else {
							bPostLine = FALSE;	// no end line codes sent
							if ( !bPreLine ) {
								// Send preline stuff
								bPreLine = TRUE;
								serPutByte( 0x01 );
								serPutByte( 0x03 );
								serPutByte( 0xef );
								serPutByte( 0xb0 );
							}
							serPutByte( c );
						}
					}
					
					// If we end with a row without LF we must send
					// Line end stuff
					if ( !bPostLine ) {
						serPutByte( 0xff );
					}
					
					// Framework end
					serPutByte( 0xff  );
					serPutByte( 0x00  );
					
					ftp_state = LFTP_STATE_END;
					TCPDiscard( datasocket );	
				}
				
				
				// Check for data on ftp socket
				if ( TCPIsGetReady( ftpsocket ) ) {	
					
					while( TCPGet( ftpsocket, &c ) ) {
						DBG_OUT( c );
					}
					TCPDiscard( ftpsocket );
				}
				
			break;
				
				
				
			// **
			// We are done for this time
				
			case LFTP_STATE_END:
				DBG_OUT('*');
				TCPDisconnect( ftpsocket );
				TCPDisconnect( datasocket );
				bftpLoadWork = FALSE;	// Work is done
				ftp_state = LFTP_STATE_NONE;
			break;
	}	
}