]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/tests/net/echo/tcp_client_loop/main.cpp
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / tests / net / echo / tcp_client_loop / main.cpp
1 #include "mbed.h"
2 #include "test_env.h"
3 #include "EthernetInterface.h"
4 #include <algorithm>
5
6 namespace {
7     const int BUFFER_SIZE = 64;
8     const int MAX_ECHO_LOOPS = 1000;
9     const char ASCII_MAX = '~' - ' ';
10
11     struct s_ip_address
12     {
13         int ip_1;
14         int ip_2;
15         int ip_3;
16         int ip_4;
17     };
18 }
19
20 char char_rand() {
21     return (rand() % ASCII_MAX) + ' ';
22 }
23
24 int main() {
25     MBED_HOSTTEST_TIMEOUT(20);
26     MBED_HOSTTEST_SELECT(tcpecho_client_auto);
27     MBED_HOSTTEST_DESCRIPTION(TCP client echo loop);
28     MBED_HOSTTEST_START("NET_13");
29
30     char buffer[BUFFER_SIZE] = {0};
31     char out_buffer[BUFFER_SIZE] = {0};
32     s_ip_address ip_addr = {0, 0, 0, 0};
33     int port = 0;
34
35     printf("MBED: TCPCllient waiting for server IP and port...\r\n");
36     scanf("%d.%d.%d.%d:%d", &ip_addr.ip_1, &ip_addr.ip_2, &ip_addr.ip_3, &ip_addr.ip_4, &port);
37     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);
38
39     EthernetInterface eth;
40     eth.init(); //Use DHCP
41     eth.connect();
42
43     printf("MBED: TCPClient IP Address is %s\r\n", eth.getIPAddress());
44     sprintf(buffer, "%d.%d.%d.%d", ip_addr.ip_1, ip_addr.ip_2, ip_addr.ip_3, ip_addr.ip_4);
45
46     TCPSocketConnection socket;
47     while (socket.connect(buffer, port) < 0) {
48         printf("MBED: TCPCllient unable to connect to %s:%d\r\n", buffer, port);
49         wait(1);
50     }
51
52     // Test loop for multiple client connections
53     bool result = true;
54     int count_error = 0;
55     for (int i = 0; i < MAX_ECHO_LOOPS; i++) {
56         std::generate(out_buffer, out_buffer + BUFFER_SIZE, char_rand);
57         socket.send_all(out_buffer, BUFFER_SIZE);
58
59         int n = socket.receive(buffer, BUFFER_SIZE);
60         if (n > 0)
61         {
62             bool echoed = memcmp(out_buffer, buffer, BUFFER_SIZE) == 0;
63             result = result && echoed;
64             if (echoed == false) {
65                 count_error++;  // Count error messages
66             }
67         }
68     }
69
70     printf("MBED: Loop messages passed: %d / %d\r\n", MAX_ECHO_LOOPS - count_error, MAX_ECHO_LOOPS);
71
72     if (notify_completion_str(result, buffer)) {
73         socket.send_all(buffer, strlen(buffer));
74     }
75     socket.close();
76     eth.disconnect();
77     MBED_HOSTTEST_RESULT(result);
78 }