Zoltan Hudak
/
TcpClient_ENC28J60
Simple TCP/IP Client using the UIPEthernet library for ENC28J60 Ethernet boards.
main.cpp
- Committer:
- hudakz
- Date:
- 2019-09-07
- Revision:
- 5:873c7a86fad2
- Parent:
- 4:9f42e50733be
File content as of revision 5:873c7a86fad2:
/* * TcpClient example using the UIPEthernet library for ENC28J60 Ethernet boards. * */ #include "mbed.h" #include "UipEthernet.h" #include "TcpClient.h" #define IP "192.168.1.35" #define GATEWAY "192.168.1.1" #define NETMASK "255.255.255.0" const uint8_t MAC[6] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; UipEthernet net(MAC, D11, D12, D13, D10); // mac, mosi, miso, sck, cs /** * @brief * @note * @param * @retval */ int main() { const time_t TIMEOUT = 5; // Connection timeout time time_t timeOut; char data[] = "GET / HTTP/1.1\r\nHost: ifconfig.io\r\nConnection: close\r\n\r\n"; char* remaining; uint8_t* recvBuf; int result; printf("Starting ...\r\n"); //net.set_network(IP, NETMASK, GATEWAY); // include this to use static IP address net.connect(); // Show the network address const char* ip = net.get_ip_address(); const char* netmask = net.get_netmask(); const char* gateway = net.get_gateway(); printf("IP address: %s\n", ip ? ip : "None"); printf("Netmask: %s\n", netmask ? netmask : "None"); printf("Gateway: %s\n", gateway ? gateway : "None"); // Open a socket on the network interface, and create a TCP connection to ifconfig.io TcpClient socket; result = socket.open(&net); if (result != 0) { printf("Error! socket.open() returned: %d\n", result); } timeOut = time(NULL) + TIMEOUT; printf("Connecting to the 'ifconfig.io' server ...\r\n"); result = socket.connect("ifconfig.io", 80); if (result != 0) { printf("Error! socket.connect() returned: %d\n", result); goto DISCONNECT; } printf("Server connected.\r\n"); printf("Sending data to server:\r\n"); remaining = data; result = strlen(remaining); while (result) { result = socket.send((uint8_t*)remaining, strlen(remaining)); if (result < 0) { printf("Error! socket.send() returned: %d\n", result); goto DISCONNECT; } printf("%.*s", result, remaining); remaining += result; } printf("Waiting for data from server:\r\n"); while (socket.available() == 0) { if (time(NULL) > timeOut) { printf("Connection time out.\r\n"); goto DISCONNECT; } } printf("Data received:\r\n"); while ((result = socket.available()) > 0) { recvBuf = (uint8_t*)malloc(result); result = socket.recv(recvBuf, result); if (result < 0) { printf("Error! socket.recv() returned: %d\n", result); goto DISCONNECT; } printf("%.*s\r\n", result, recvBuf); free(recvBuf); } printf("\r\n"); DISCONNECT: // Close the socket to return its memory and bring down the network interface socket.close(); // Bring down the ethernet interface net.disconnect(); printf("Done\n"); }