#include "net\stacktsk.h" #include "net\tick.h" #include "net\helpers.h" #include "net\udp.h" #include "net\arp.h" #include "net\arptsk.h" //Create a UDP socket for receiving and sending data static UDP_SOCKET udpSocketUser; //UDP State machine #define SM_UDP_SEND_ARP 0 #define SM_UDP_WAIT_RESOLVE 1 #define SM_UDP_RESOLVED 2 static BYTE smUdp = SM_UDP_SEND_ARP; //Timers TICK16 tsecMsgSent = 0; //Time last message was sent TICK8 tsecWait = 0; //General purpose wait timer void udpExample(void) { BYTE c; NODE_INFO udpServerNode; //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] = 10; udpServerNode.IPAddr.v[1] = 1; udpServerNode.IPAddr.v[2] = 0; udpServerNode.IPAddr.v[3] = 101; udpSocketUser = UDPOpen(54123, &udpServerNode, 54124); //An error occurred during the UDPOpen() function if (udpSocketUser == INVALID_UDP_SOCKET) { //Add user code here to take action if required! } //Infinite loop. Check if anything is received on UDP port while(1) { switch (smUdp) { case SM_UDP_SEND_ARP: if (ARPIsTxReady()) { //Remember when we sent last request tsecWait = TickGet8bitSec(); //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 ( !PORTB_RB0) { //Send a message every second for as long as PIC port pin B0 is = 0 if (TickGetSecDiff(tsecMsgSent) >= (TICK16)1) { //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(1); //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(); } }