]> git.gir.st - tmk_keyboard.git/blob - tmk_core/tool/mbed/mbed-sdk/libraries/tests/net/echo/udp_client/main.cpp
Merge commit '1fe4406f374291ab2e86e95a97341fd9c475fcb8'
[tmk_keyboard.git] / tmk_core / tool / mbed / mbed-sdk / libraries / tests / net / echo / udp_client / main.cpp
1 #include "mbed.h"
2 #include "rtos.h"
3 #include "test_env.h"
4 #include "EthernetInterface.h"
5 #include <algorithm>
6
7 #define CHECK(RC, STEP) if (RC < 0) error(STEP": %d\r\n", RC)
8
9 namespace {
10 const int BUFFER_SIZE = 64;
11 const int MAX_ECHO_LOOPS = 100;
12 const char ASCII_MAX = '~' - ' ';
13
14 struct s_ip_address {
15 int ip_1;
16 int ip_2;
17 int ip_3;
18 int ip_4;
19 };
20 }
21
22 char char_rand() {
23 return (rand() % ASCII_MAX) + ' ';
24 }
25
26 int main() {
27 MBED_HOSTTEST_TIMEOUT(20);
28 MBED_HOSTTEST_SELECT(udpecho_client_auto);
29 MBED_HOSTTEST_DESCRIPTION(UDP echo client);
30 MBED_HOSTTEST_START("NET_6");
31
32 char buffer[BUFFER_SIZE] = {0};
33 char out_buffer[BUFFER_SIZE] = {0};
34 s_ip_address ip_addr = {0, 0, 0, 0};
35 int port = 0;
36 bool result = true;
37
38 printf("MBED: UDPCllient waiting for server IP and port...\r\n");
39 scanf("%d.%d.%d.%d:%d", &ip_addr.ip_1, &ip_addr.ip_2, &ip_addr.ip_3, &ip_addr.ip_4, &port);
40 printf("MBED: Address received: %d.%d.%d.%d:%d\r\n", ip_addr.ip_1, ip_addr.ip_2, ip_addr.ip_3, ip_addr.ip_4, port);
41
42 EthernetInterface eth;
43 int rc = eth.init(); //Use DHCP
44 CHECK(rc, "eth init");
45
46 rc = eth.connect();
47 CHECK(rc, "connect");
48 printf("IP: %s\n", eth.getIPAddress());
49
50 UDPSocket socket;
51 rc = socket.init();
52 CHECK(rc, "socket init");
53
54 printf("MBED: UDPClient IP Address is %s\r\n", eth.getIPAddress());
55 sprintf(buffer, "%d.%d.%d.%d", ip_addr.ip_1, ip_addr.ip_2, ip_addr.ip_3, ip_addr.ip_4);
56
57 Endpoint echo_server;
58 rc = echo_server.set_address(buffer, port);
59 CHECK(rc, "set_address");
60
61 for (int i =0; i < MAX_ECHO_LOOPS; i++) {
62 std::generate(out_buffer, out_buffer + BUFFER_SIZE, char_rand);
63 rc = socket.sendTo(echo_server, out_buffer, sizeof(out_buffer));
64 CHECK(rc, "sendTo");
65
66 const int n = socket.receiveFrom(echo_server, buffer, sizeof(buffer));
67 CHECK(n, "receiveFrom");
68
69 if (memcmp(buffer, out_buffer, BUFFER_SIZE) != 0) {
70 result = false;
71 break;
72 }
73 }
74
75 if (notify_completion_str(result, buffer)) {
76 socket.sendTo(echo_server, buffer, strlen(buffer));
77 }
78
79 socket.close();
80 eth.disconnect();
81 MBED_HOSTTEST_RESULT(result);
82 }
Imprint / Impressum