void UDPSOCKET_BIND_ADDRESS_PORT()
{
#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLE
    int count = fetch_stats();
    for (int j = 0; j < count; j++) {
        TEST_ASSERT_EQUAL(SOCK_CLOSED,  udp_stats[j].state);
    }
#endif

    UDPSocket *sock = new UDPSocket;
    if (!sock) {
        TEST_FAIL();
    }
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(get_interface()));
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->bind(get_interface()->get_ip_address(), 80));

    delete sock;

#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLE
    count = fetch_stats();
    for (int j = 0; j < count; j++) {
        TEST_ASSERT_EQUAL(SOCK_CLOSED, udp_stats[j].state);
    }
#endif
}
Example #2
0
/**
 * Use a connection, checking that it is good
 * Checks via doing an NTP transaction
 */
static void use_connection(OnboardCellularInterface *driver)
{
    const char *ip_address = driver->get_ip_address();
    const char *net_mask = driver->get_netmask();
    const char *gateway = driver->get_gateway();

    TEST_ASSERT(driver->is_connected());

    TEST_ASSERT(ip_address != NULL);
    tr_debug("IP address %s.", ip_address);
    TEST_ASSERT(net_mask != NULL);
    tr_debug("Net mask %s.", net_mask);
    TEST_ASSERT(gateway != NULL);
    tr_debug("Gateway %s.", gateway);

    UDPSocket sock;
    SocketAddress host_address;

    TEST_ASSERT(driver->gethostbyname(MBED_CONF_APP_ECHO_SERVER, &host_address) == 0);
    host_address.set_port(MBED_CONF_APP_ECHO_UDP_PORT);

    tr_debug("UDP: Server %s address: %s on port %d.",
             MBED_CONF_APP_ECHO_SERVER, host_address.get_ip_address(),
             host_address.get_port());

    TEST_ASSERT(sock.open(driver) == 0)

    sock.set_timeout(10000);
    do_udp_echo(&sock, &host_address, 1);

    sock.close();
}
Example #3
0
void UDPSOCKET_BIND_ADDRESS()
{
#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLE
    int count = fetch_stats();
    for (int j = 0; j < count; j++) {
        TEST_ASSERT_EQUAL(SOCK_CLOSED,  udp_stats[j].state);
    }
#endif

    UDPSocket *sock = new UDPSocket;
    if (!sock) {
        TEST_FAIL();
    }
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(NetworkInterface::get_default_instance()));
    SocketAddress sockAddr = SocketAddress(NetworkInterface::get_default_instance()->get_ip_address(), 80);
    nsapi_error_t bind_result = sock->bind(sockAddr);
    if (bind_result == NSAPI_ERROR_UNSUPPORTED) {
        TEST_IGNORE_MESSAGE("bind() not supported");
    } else {
        TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, bind_result);
    }

    delete sock;

#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLE
    count = fetch_stats();
    for (int j = 0; j < count; j++) {
        TEST_ASSERT_EQUAL(SOCK_CLOSED, udp_stats[j].state);
    }
#endif
}
Example #4
0
File: main.cpp Project: dinau/mbed
int main() {
    GREENTEA_SETUP(60, "default_auto");

    bool result = false;
    const time_t TIME1970 = 2208988800L;
    int ntp_send_values[12] = {0};
    int ntp_recv_values[12] = {0};

    EthernetInterface eth;
    eth.connect();
    printf("UDP client IP Address is %s\n", eth.get_ip_address());

    UDPSocket sock;
    sock.open(&eth);
    sock.set_timeout(15000);

    SocketAddress nist(&eth, HTTP_SERVER_NAME, HTTP_SERVER_PORT);

    printf("UDP: NIST server %s address: %s on port %d\r\n", HTTP_SERVER_NAME, nist.get_ip_address(), nist.get_port());

    memset(ntp_send_values, 0x00, sizeof(ntp_send_values));
    ntp_send_values[0] = '\x1b';

    while(1) {
        memset(ntp_recv_values, 0x00, sizeof(ntp_recv_values));

        int ret_send = sock.sendto(nist, (void*)ntp_send_values, sizeof(ntp_send_values));
        printf("UDP: Sent %d Bytes to NTP server \n", ret_send);

        SocketAddress source;
        const int n = sock.recvfrom(&source, (void*)ntp_recv_values, sizeof(ntp_recv_values));

        printf("UDP: Recved from NTP server %d Bytes \n", n);

        if (n > 0 && strcmp(source.get_ip_address(), nist.get_ip_address()) == 0) {
            result = true;

            printf("UDP: Values returned by NTP server: \n");
            for (size_t i=0; i < sizeof(ntp_recv_values) / sizeof(ntp_recv_values[0]); ++i) {
                printf("\t[%02d] 0x%X", i, ntohl(ntp_recv_values[i]));

                if (i == 10) {
                    time_t timestamp = ntohl(ntp_recv_values[i]) - TIME1970;
                    printf("\tNTP timestamp is %s", ctime(&timestamp));
                } else {
                    printf("\n");
                }
            }

            break;
        }

        printf("Failed to receive data, retrying in 5 seconds...\n");
        wait(5);
    }

    sock.close();
    eth.disconnect();
    GREENTEA_TESTSUITE_RESULT(result);
}
void UDPSOCKET_SENDTO_TIMEOUT()
{
    char tx_buffer[100];
    fill_tx_buffer_ascii(tx_buffer, sizeof(tx_buffer));

    UDPSocket sock;
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(get_interface()));

    SocketAddress udp_addr;
    get_interface()->gethostbyname(MBED_CONF_APP_ECHO_SERVER_ADDR, &udp_addr);
    udp_addr.set_port(9);

    Timer timer;
    timer.start();
    int sent = sock.sendto(udp_addr, tx_buffer, sizeof(tx_buffer));
    timer.stop();
    TEST_ASSERT_EQUAL(sizeof(tx_buffer), sent);
    TEST_ASSERT(timer.read_ms() <= 100);

    timer.reset();
    timer.start();
    sent = sock.sendto(udp_addr, tx_buffer, sizeof(tx_buffer));
    timer.stop();
    TEST_ASSERT_EQUAL(sizeof(tx_buffer), sent);
    TEST_ASSERT(timer.read_ms() <= 100);
    printf("MBED: Time taken: %fs\n", timer.read());

    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close());
}
Example #6
0
void test_bring_up_down() {
    NetworkInterface* net = MBED_CONF_APP_OBJECT_CONSTRUCTION;

    for (int i = 0; i < COUNT; i++) {
        int err = MBED_CONF_APP_CONNECT_STATEMENT;
        TEST_ASSERT_EQUAL(0, err);

        printf("MBED: IP Address %s\r\n", net->get_ip_address());
        TEST_ASSERT(net->get_ip_address());

        UDPSocket udp;
        err = udp.open(net);
        TEST_ASSERT_EQUAL(0, err);
        err = udp.close();
        TEST_ASSERT_EQUAL(0, err);

        TCPSocket tcp;
        err = tcp.open(net);
        TEST_ASSERT_EQUAL(0, err);
        err = tcp.close();
        TEST_ASSERT_EQUAL(0, err);

        err = net->disconnect();
        TEST_ASSERT_EQUAL(0, err);
    }
}
Example #7
0
int main() {
    GREENTEA_SETUP(20, "udp_echo");

    EthernetInterface eth;
    eth.connect();
    printf("UDP client IP Address is %s\n", eth.get_ip_address());

    greentea_send_kv("target_ip", eth.get_ip_address());

    char recv_key[] = "host_port";
    char ipbuf[60] = {0};
    char portbuf[16] = {0};
    unsigned int port = 0;

    UDPSocket sock;
    sock.open(&eth);
    sock.set_timeout(MBED_CFG_UDP_CLIENT_ECHO_TIMEOUT);

    greentea_send_kv("host_ip", " ");
    greentea_parse_kv(recv_key, ipbuf, sizeof(recv_key), sizeof(ipbuf));

    greentea_send_kv("host_port", " ");
    greentea_parse_kv(recv_key, portbuf, sizeof(recv_key), sizeof(ipbuf));
    sscanf(portbuf, "%u", &port);

    printf("MBED: UDP Server IP address received: %s:%d \n", ipbuf, port);
    SocketAddress udp_addr(ipbuf, port);

    int success = 0;

    for (int i=0; i < ECHO_LOOPS; ++i) {
        prep_buffer(tx_buffer, sizeof(tx_buffer));
        const int ret = sock.sendto(udp_addr, tx_buffer, sizeof(tx_buffer));
        printf("[%02d] sent...%d Bytes \n", i, ret);

        SocketAddress temp_addr;
        const int n = sock.recvfrom(&temp_addr, rx_buffer, sizeof(rx_buffer));
        printf("[%02d] recv...%d Bytes \n", i, n);

        if ((temp_addr == udp_addr &&
             n == sizeof(tx_buffer) &&
             memcmp(rx_buffer, tx_buffer, sizeof(rx_buffer)) == 0)) {
            success += 1;
        }
    }

    bool result = (success > 3*ECHO_LOOPS/4);

    sock.close();
    eth.disconnect();
    GREENTEA_TESTSUITE_RESULT(result);
}
void UDPSOCKET_OPEN_CLOSE_REPEAT()
{
    UDPSocket *sock = new UDPSocket;
    if (!sock) {
        TEST_FAIL();
    }

    for (int i = 0; i < 2; i++) {
        TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(get_interface()));
        TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->close());
    }
    delete sock;
}
Example #9
0
void UDPSOCKET_SENDTO_INVALID()
{
    UDPSocket sock;
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(get_interface()));

    TEST_ASSERT(sock.sendto(NULL, 9, NULL, 0) < 0);
    TEST_ASSERT(sock.sendto("", 9, NULL, 0) < 0);
    TEST_ASSERT(sock.sendto("", 0, NULL, 0) < 0);
    TEST_ASSERT_EQUAL(5, sock.sendto(MBED_CONF_APP_ECHO_SERVER_ADDR, 0, "hello", 5));
    TEST_ASSERT_EQUAL(0, sock.sendto(MBED_CONF_APP_ECHO_SERVER_ADDR, 9, NULL, 0));
    TEST_ASSERT_EQUAL(5, sock.sendto(MBED_CONF_APP_ECHO_SERVER_ADDR, 9, "hello", 5));

    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close());
}
Example #10
0
int main() {
    GREENTEA_SETUP(20, "udp_echo_client");

    EthernetInterface eth;
    eth.connect();
    printf("UDP client IP Address is %s\n", eth.get_ip_address());

    greentea_send_kv("target_ip", eth.get_ip_address());

    bool result = true;

    char recv_key[] = "host_port";
    char ipbuf[60] = {0};
    char portbuf[16] = {0};
    unsigned int port = 0;

    UDPSocket sock;
    sock.open(&eth);

    greentea_send_kv("host_ip", " ");
    greentea_parse_kv(recv_key, ipbuf, sizeof(recv_key), sizeof(ipbuf));

    greentea_send_kv("host_port", " ");
    greentea_parse_kv(recv_key, portbuf, sizeof(recv_key), sizeof(ipbuf));
    sscanf(portbuf, "%u", &port);

    printf("MBED: UDP Server IP address received: %s:%d \n", ipbuf, port);

    SocketAddress addr(ipbuf, port);

    for (int i=0; i < ECHO_LOOPS; ++i) {
        prep_buffer(tx_buffer, sizeof(tx_buffer));
        const int ret = sock.sendto(addr, tx_buffer, sizeof(tx_buffer));
        printf("[%02d] sent...%d Bytes \n", i, ret);

        const int n = sock.recvfrom(&addr, rx_buffer, sizeof(rx_buffer));
        printf("[%02d] recv...%d Bytes \n", i, n);

        if (memcmp(rx_buffer, tx_buffer, sizeof(rx_buffer))) {
            result = false;
            break;
        }
    }

    sock.close();
    eth.disconnect();
    GREENTEA_TESTSUITE_RESULT(result);
}
void UDPSOCKET_BIND_ADDRESS_NULL()
{
    UDPSocket *sock = new UDPSocket;
    if (!sock) {
        TEST_FAIL();
    }
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(NetworkInterface::get_default_instance()));
    nsapi_error_t bind_result = sock->bind(NULL, 1024);
    if (bind_result == NSAPI_ERROR_UNSUPPORTED) {
        TEST_IGNORE_MESSAGE("bind() not supported");
    } else {
        TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, bind_result);
    }

    delete sock;
}
Example #12
0
void UDPSOCKET_SENDTO_INVALID()
{
    UDPSocket sock;
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(NetworkInterface::get_default_instance()));

    TEST_ASSERT(sock.sendto(NULL, 9, NULL, 0) < 0);
    TEST_ASSERT(sock.sendto("", 9, NULL, 0) < 0);
    TEST_ASSERT(sock.sendto("", 0, NULL, 0) < 0);

    nsapi_error_t result = sock.sendto(MBED_CONF_APP_ECHO_SERVER_ADDR, 9, NULL, 0);
    if (result != NSAPI_ERROR_UNSUPPORTED) {
        TEST_ASSERT_EQUAL(0, result);
    }

    TEST_ASSERT_EQUAL(5, sock.sendto(MBED_CONF_APP_ECHO_SERVER_ADDR, 9, "hello", 5));

    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close());
}
Example #13
0
void UDPSOCKET_RECV_TIMEOUT()
{
    SocketAddress udp_addr;
    NetworkInterface::get_default_instance()->gethostbyname(MBED_CONF_APP_ECHO_SERVER_ADDR, &udp_addr);
    udp_addr.set_port(MBED_CONF_APP_ECHO_SERVER_PORT);

    static const int DATA_LEN = 100;
    char buff[DATA_LEN] = {0};

    UDPSocket sock;
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(NetworkInterface::get_default_instance()));
    sock.set_timeout(100);
    sock.sigio(callback(_sigio_handler, ThisThread::get_id()));

    int recvd;
    Timer timer;
    SocketAddress temp_addr;
    int pkt_success = 0;
    for (int i = 0; i < PKT_NUM; i++) {
        TEST_ASSERT_EQUAL(DATA_LEN, sock.sendto(udp_addr, buff, DATA_LEN));
        timer.reset();
        timer.start();
        recvd = sock.recvfrom(&temp_addr, buff, sizeof(buff));
        timer.stop();

        if (recvd == NSAPI_ERROR_WOULD_BLOCK) {
            osSignalWait(SIGNAL_SIGIO, SIGIO_TIMEOUT);
            printf("MBED: recvfrom() took: %dms\n", timer.read_ms());
            TEST_ASSERT_INT_WITHIN(51, 150, timer.read_ms());
            continue;
        } else if (recvd < 0) {
            printf("[bt#%02d] network error %d\n", i, recvd);
            continue;
        } else if (temp_addr != udp_addr) {
            printf("[bt#%02d] packet from wrong address\n", i);
            continue;
        }
        TEST_ASSERT_EQUAL(DATA_LEN, recvd);
        pkt_success++;
    }

    printf("MBED: %d out of %d packets were received.\n", pkt_success, PKT_NUM);
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close());
}
Example #14
0
int main() {
	//create tcp socket and establish a connection
    TCPServerSocket tcpServerSocket;

    int ret = tcpServerSocket.initialize();
    ASSERT(ret == 0);
    
    int serverUdpPort = tcpServerSocket.negotiate();
    ASSERT(serverUdpPort > 1024);

    tcpServerSocket.close();

    //open a udp socket and listen for str
    UDPSocket udpSocket;
    ret = udpSocket.open(serverUdpPort);
    ASSERT(ret == 0);
    LOG("Server opened UDP Port %i\n", serverUdpPort);

    char buf[1024];
    unsigned long remoteIp;
    int remotePort;
    
    //read, reverse string and send it back to client
	int readBytes = udpSocket.read(buf, 1024, remoteIp, remotePort);
	buf[readBytes] = '\0';
    ASSERT(readBytes > 0);
    LOG("Server Received: %s\n", buf);

    //Reverse the string and write to the buffer again
    str_reverse(buf);

    int writeBytes = udpSocket.write(remoteIp, remotePort, (const char *) buf, readBytes);
    ASSERT(writeBytes > 0);
    LOG("Server sent: %s\n", buf);

    udpSocket.close();

    return 0;
}
Example #15
0
/**
 * Test UDP data exchange
 */
void test_udp_echo()
{
    UDPSocket sock;
    SocketAddress host_address;
    int x;
    int size;

    driver.disconnect();
    TEST_ASSERT(do_connect(&driver) == 0);

    TEST_ASSERT(driver.gethostbyname(MBED_CONF_APP_ECHO_SERVER, &host_address) == 0);
    host_address.set_port(MBED_CONF_APP_ECHO_UDP_PORT);

    tr_debug("UDP: Server %s address: %s on port %d.",
             MBED_CONF_APP_ECHO_SERVER, host_address.get_ip_address(),
             host_address.get_port());

    TEST_ASSERT(sock.open(&driver) == 0)

    sock.set_timeout(10000);

    // Test min, max, and some random sizes in-between
    do_udp_echo(&sock, &host_address, 1);
    do_udp_echo(&sock, &host_address, MBED_CONF_APP_UDP_MAX_PACKET_SIZE);
    for (x = 0; x < 10; x++) {
        size = (rand() % MBED_CONF_APP_UDP_MAX_PACKET_SIZE) + 1;
        size = fix(size, MBED_CONF_APP_UDP_MAX_PACKET_SIZE + 1);
        do_udp_echo(&sock, &host_address, size);
    }

    sock.close();

    drop_connection(&driver);

    tr_debug("%d UDP packets of size up to %d byte(s) echoed successfully.", x,
             MBED_CONF_APP_UDP_MAX_PACKET_SIZE);
}
Example #16
0
    void echo() {
        int success = 0;

        int err = sock.open(net);
        TEST_ASSERT_EQUAL(0, err);

        sock.set_timeout(MBED_CFG_UDP_CLIENT_ECHO_TIMEOUT);

        for (int i = 0; success < ECHO_LOOPS; i++) {
            prep_buffer(id, uuid, tx_buffer, sizeof(tx_buffer));
            const int ret = sock.sendto(udp_addr, tx_buffer, sizeof(tx_buffer));
            if (ret >= 0) {
                iomutex.lock();
                printf("[ID:%01d][%02d] sent %d bytes - %.*s  \n", id, i, ret, ret, tx_buffer);
                iomutex.unlock();
            } else {
                iomutex.lock();
                printf("[ID:%01d][%02d] Network error %d\n", id, i, ret);
                iomutex.unlock();
                continue;
            }

            SocketAddress temp_addr;
            const int n = sock.recvfrom(&temp_addr, rx_buffer, sizeof(rx_buffer));
            if (n >= 0) {
                iomutex.lock();
                printf("[ID:%01d][%02d] recv %d bytes - %.*s  \n", id, i, n, n, tx_buffer);
                iomutex.unlock();
            } else {
                iomutex.lock();
                printf("[ID:%01d][%02d] Network error %d\n", id, i, n);
                iomutex.unlock();
                continue;
            }

            if ((temp_addr == udp_addr &&
                 n == sizeof(tx_buffer) &&
                 memcmp(rx_buffer, tx_buffer, sizeof(rx_buffer)) == 0)) {
                success += 1;
                iomutex.lock();
                printf("[ID:%01d][%02d] success #%d\n", id, i, success);
                iomutex.unlock();
                continue;
            }

            // failed, clean out any remaining bad packets
            sock.set_timeout(0);
            while (true) {
                err = sock.recvfrom(NULL, NULL, 0);
                if (err == NSAPI_ERROR_WOULD_BLOCK) {
                    break;
                }
            }
            sock.set_timeout(MBED_CFG_UDP_CLIENT_ECHO_TIMEOUT);
        }

        result = success == ECHO_LOOPS;

        err = sock.close();
        TEST_ASSERT_EQUAL(0, err);
        if (err) {
            result = false;
        }
    }
Example #17
0
void UDPSOCKET_OPEN_LIMIT()
{
    int open_sockets[2] = {0};

    for (int i = 0; i < 2; i++) {
        UDPSocketItem *socket_list_head = NULL;
        UDPSocketItem *it;

        UDPSocket *sock;
        int ret;
        while (true) {
            sock = new UDPSocket;
            if (!sock) {
                break;
            }
            ret = sock->open(NetworkInterface::get_default_instance());
            if (ret == NSAPI_ERROR_NO_MEMORY || ret == NSAPI_ERROR_NO_SOCKET) {
                printf("[round#%02d] unable to open new socket, error: %d\n", i, ret);
                delete sock;
                break;
            }

            // Hopefully this doesn't interfere when trying to allocate more sockets
            it = new UDPSocketItem;
            if (!it) {
                delete sock;
                break;
            }

            it->sock = sock;
            // Order of items in the list doesn't matter
            it->next = socket_list_head;
            socket_list_head = it;
        }

        if (!socket_list_head) {
            break;
        }
#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLE
        int count = fetch_stats();
        int open_count = 0;
        for (int j = 0; j < count; j++) {
            if ((udp_stats[j].state == SOCK_OPEN) && (udp_stats[j].proto == NSAPI_UDP)) {
                open_count++;
            }
        }
        TEST_ASSERT(open_count >= 3);
#endif
        UDPSocketItem *tmp;
        for (UDPSocketItem *it = socket_list_head; it;) {
            ++open_sockets[i];
            tmp = it;
            it = it->next;
            socket_list_head = it;
            delete tmp->sock;
            delete tmp;
        }
        printf("[round#%02d] %d sockets opened\n", i, open_sockets[i]);
    }
    TEST_ASSERT_EQUAL(open_sockets[0], open_sockets[1]);
    // In case of lwIP one is taken by DHCP -> reduction by one to three
    TEST_ASSERT(open_sockets[0] >= 3);
}
Example #18
0
void test_udp_dtls_handshake() {
    EthernetInterface eth;
    int err = eth.connect();
    TEST_ASSERT_EQUAL(0, err);

    printf("MBED: UDPClient IP address is '%s'\n", eth.get_ip_address());
    printf("MBED: UDPClient waiting for server IP and port...\n");

    greentea_send_kv("target_ip", eth.get_ip_address());

    bool result = false;

    char recv_key[] = "host_port";
    char ipbuf[60] = {0};
    char portbuf[16] = {0};
    unsigned int port = 0;

    greentea_send_kv("host_ip", " ");
    greentea_parse_kv(recv_key, ipbuf, sizeof(recv_key), sizeof(ipbuf));

    greentea_send_kv("host_port", " ");
    greentea_parse_kv(recv_key, portbuf, sizeof(recv_key), sizeof(ipbuf));
    sscanf(portbuf, "%u", &port);

    printf("MBED: UDP Server IP address received: %s:%d \n", ipbuf, port);

    // align each size to 4-bits
    for (int i = 0; i < udp_dtls_handshake_count; i++) {
        udp_dtls_handshake_pattern[i] = (~0xf & udp_dtls_handshake_pattern[i]) + 0x10;
    }

    printf("MBED: DTLS pattern [");
    for (int i = 0; i < udp_dtls_handshake_count; i++) {
        printf("%d", udp_dtls_handshake_pattern[i]);
        if (i != udp_dtls_handshake_count-1) {
            printf(", ");
        }
    }
    printf("]\r\n");

    UDPSocket sock;
    SocketAddress udp_addr(ipbuf, port);
    sock.set_timeout(MBED_CFG_UDP_DTLS_HANDSHAKE_TIMEOUT);

    for (int attempt = 0; attempt < MBED_CFG_UDP_DTLS_HANDSHAKE_RETRIES; attempt++) {
        err = sock.open(&eth);
        TEST_ASSERT_EQUAL(0, err);

        for (int i = 0; i < udp_dtls_handshake_count; i++) {
            buffer[i] = udp_dtls_handshake_pattern[i] >> 4;
        }

        err = sock.sendto(udp_addr, buffer, udp_dtls_handshake_count);
        printf("UDP: tx -> %d\r\n", err);
        TEST_ASSERT_EQUAL(udp_dtls_handshake_count, err);

        int step = 0;
        while (step < udp_dtls_handshake_count) {
            err = sock.recvfrom(NULL, buffer, sizeof(buffer));
            printf("UDP: rx <- %d ", err);

            // check length
            if (err != udp_dtls_handshake_pattern[step]) {
                printf("x (expected %d)\r\n", udp_dtls_handshake_pattern[step]);
                break;
            }

            // check quick xor of packet
            uint8_t check = 0;
            for (int j = 0; j < udp_dtls_handshake_pattern[step]; j++) {
                check ^= buffer[j];
            }

            if (check != 0) {
                printf("x (checksum 0x%02x)\r\n", check);
                break;
            }

            // successfully got a packet
            printf("\r\n");
            step += 1;
        }

        err = sock.close();
        TEST_ASSERT_EQUAL(0, err);

        // got through all steps, test passed
        if (step == udp_dtls_handshake_count) {
            result = true;
            break;
        }
    }

    eth.disconnect();
    TEST_ASSERT(result);
}
int main(int argc, char* argv[]) {

    //parse args
    if (argc != 5) {
        std::cout << "This program requires 4 arguments in the following format!" << std::endl;
        std::cout << "sender <host address of emulator> <udp port number of emulator in FWD direction>" << "\n"
                  << "<udp port number of sender to receive acks> <fileName>" << std::endl;
        std::cout << "Example: sender 192.168.89.78 49998 11234 test.txt" << std::endl;
        return 1;
    }


    const char* ipAddr = argv[1];
    if (0 == strcmp(ipAddr, "localhost")) {
        ipAddr = "127.0.0.1";
    }

    unsigned long remoteIp = inet_addr(ipAddr);
    int remotePort = atoi(argv[2]);
    int senderPort = atoi(argv[3]);
    const char* fileName = argv[4];

    int totalPackets = 0;
    int totalBytes = 0;

    int sentPackets = 0;
    int sentBytes = 0;

    int seqNum = 0;
    signal(SIGALRM, signal_alarm_handler);
    bool timer_on = false;
    list<Packet *> packetsToSend;
    list<Packet *> packetsSent;

    //Open the file and prepare the packets for transmission
    ifstream transferFile(fileName);
    ofstream seqLog(seqFile);
    ofstream ackLog(ackFile);

    if (!(seqLog.is_open() && ackLog.is_open())) {
        return 1;
    }

    if (transferFile.is_open()) {
        char buffer[Packet::MAX_DATA_LENGTH];

        while(false == transferFile.eof()) {
            transferFile.read(buffer, Packet::MAX_DATA_LENGTH);
            Packet* packet = Packet::createPacket(seqNum, transferFile.gcount(), buffer);
            packetsToSend.insert(packetsToSend.end(), packet);

            LOG("Inserted packet %i in the queue\n", totalPackets);

            seqNum++;
            seqNum %= Packet::MAX_SEQ_NUMBER;
            totalPackets++;
            totalBytes += packet->getLength();
        }
    } else {
        LOG("The input file was not found..\n");
        return 1;
    }

    transferFile.close();

    //Add EOT packet
    Packet *eotPacket = Packet::createEOT(seqNum);
    packetsToSend.insert(packetsToSend.end(), eotPacket);
    totalPackets++;

    LOG("Packets ready for transmission: %i\n", totalPackets);
    LOG("Total data to be sent: %i\n", totalBytes);

    //open a udp socket and listen for str
    UDPSocket udpSocket;
    int ret = udpSocket.open(senderPort);
    ASSERT(ret == 0);
    LOG("Sender is transmitting & receiving on UDP Port %i\n", senderPort);

    /**
    * Core Logic
    * The sender can be in three states
    * 1. SEND_DATA : Sends a packet as long as data is available and window size is permitted
    * 2. RECV_ACK : Receives an acknowledgement for a previously sent data
    * 3. RESEND_DATA: If an ACK is not received for a previously sent data within timer, resend the data
    */
    while ((packetsToSend.size() > 0) || (packetsSent.size() > 0)) {
        if (udpSocket.hasData()) {
            g_state = SENDER_RECV_ACK;
        }

        switch(g_state)
        {
        /**
        * Within the WINDOW_SIZE, if data is available, send it.
        * Remove it from packetsToSend, and add it to packetsSent
        * If timer is off, turn it on.
        */
        case SENDER_SEND_DATA: {
            if (packetsSent.size() < WINDOW_SIZE && packetsToSend.size() > 0) {
                list<Packet *>::iterator itr = packetsToSend.begin();
                Packet *packet = (*itr);
                char *packetData = packet->getUDPData();
                udpSocket.write(remoteIp, remotePort, packetData, packet->getUDPSize());
                sentPackets++;
                sentBytes += packet->getLength();

                seqLog << packet->getSeqNum() << endl;
                LOG("Sent packet seqnum %i, packet number %i\n", packet->getSeqNum(), sentPackets);
                LOG("Sent bytes: %i\n", sentBytes);

                if (false == timer_on) {
                    alarm(TIMER_SECS);
                    timer_on = true;
                }

                free(packetData);

                packetsToSend.remove(packet);
                packetsSent.insert(packetsSent.end(), packet);
            }
        }
        break;

        /**
        * 1. RECV Packet.
        * 2. Check if the ack number belongs to any packets in packetsSent.
        * 3. If yes, delete all packets upto and before.
        * 4. If not, discard packet
        * 5. If any packets are sent and not recieved ack, start timer again.
        */
        case SENDER_RECV_ACK: {
            char buffer[Packet::MAX_PACKET_LENGTH];
            unsigned long ip;
            int port;
            int length = Packet::MAX_PACKET_LENGTH;
            udpSocket.read(buffer, length, ip, port);

            Packet *packet = Packet::parseUDPData(buffer);
            int seqNum = packet->getSeqNum();
            ackLog << seqNum << endl;

            //since it is cumulative keep deleting until seq num is found on packetsSent
            list<Packet *>::iterator itr = packetsSent.begin();
            while (itr != packetsSent.end() && comparePacket((*itr)->getSeqNum(), seqNum) <= 0) { //less than or equal
                Packet *sentPacket = (*itr);
                packetsSent.remove(sentPacket);
                itr = packetsSent.begin();

                delete(sentPacket);
            }

            delete(packet);

            if (packetsSent.size() > 0) {
                alarm(TIMER_SECS);
            }

            g_state = SENDER_SEND_DATA;

        }
        break;

        /**
        * 1. Resend data if timeout.
        * 2. Send all packets in packetsToSend
        */
        case SENDER_RESEND_DATA: {
            for (list<Packet *>::iterator itr = packetsSent.begin(); itr != packetsSent.end(); ++itr) {
                Packet *packet = (*itr);
                char *packetData = packet->getUDPData();
                udpSocket.write(remoteIp, remotePort, packetData, packet->getUDPSize());

                seqLog << packet->getSeqNum() << endl;
                LOG("Resent packet seqnum %i\n", packet->getSeqNum());

                if (false == timer_on) {
                    alarm(TIMER_SECS);
                    timer_on = true;
                }

                free(packetData);
            }
        }
        break;

        default: {
            ASSERT(0); //invalid state
        }
        }
    }

    LOG("End of Transmission. Exiting \n");
    udpSocket.close();
    seqLog.close();
    ackLog.close();

    ASSERT(totalBytes == sentBytes);
    ASSERT(totalPackets == sentPackets);

    return 0;
}
Example #20
0
int main(int argc, char *argv[]) {
    
    //parse args
    if (argc != 5) {
        std::cout << "This program requires 4 arguments in the following format!" << std::endl;
        std::cout << "receiver <ipAddress of network emulator> <udp port of emulator to receive ACKs from receiver>" << endl
        << "<udp port number used by receiver to receive data> <fileName>" << std::endl;
        std::cout << "Example: receiver 192.123.45.87 49999 11235 recv_test.txt" << std::endl;
        return 1;
    }


    const char* ipAddr = argv[1];
    if (0 == strcmp(ipAddr, "localhost")) {
    	ipAddr = "127.0.0.1";
    }

    unsigned long remoteIp = inet_addr(ipAddr);
    int remotePort = atoi(argv[2]);
    int receiverPort = atoi(argv[3]);
    const char *recvFile = argv[4];

    list<Packet *> packetsReceived;
    unsigned int totalBytes = 0;
    unsigned int expectingSeqNum = 0;
    bool firstPacketReceived = false;

	//create a udp socket
	UDPSocket udpSocket;
	udpSocket.open(receiverPort);
	LOG("Receiver opened UDP port at %i\n", receiverPort);

	ofstream arrivalLog(arrivalFile);
	if (!arrivalLog.is_open()) {
		LOG("Arrival log file cannot be opened\n");
		return 1;
	}

	/**
	* RECV Packet.
	* If the sequence number is expected, add it to packets list. Send Ack.
	* If not discard and send previous ack.
	*/
	while (true) {
		char buf[Packet::MAX_PACKET_LENGTH];
		unsigned long ip; int port;
		udpSocket.read(buf, Packet::MAX_PACKET_LENGTH, ip, port);
		
		Packet *packet = Packet::parseUDPData(buf);
		arrivalLog << packet->getSeqNum() << endl;
		LOG("Received packet %i, length %i\n", packet->getSeqNum(), packet->getLength());

		if ((unsigned int) packet->getSeqNum() == expectingSeqNum) {
			if (packet->getType() == 1) { //data packet
				sendAckPacket(udpSocket, expectingSeqNum, remoteIp, remotePort);

				totalBytes += packet->getLength();
				LOG("Received %i bytes\n", totalBytes);

				expectingSeqNum++;
				expectingSeqNum %= Packet::MAX_SEQ_NUMBER;

				packetsReceived.insert(packetsReceived.end(), packet);

				LOG("Total packets received %i\n", (unsigned int) packetsReceived.size());

				if (false == firstPacketReceived) {
					firstPacketReceived = true;
				}
			} else if (packet->getType() == 2) { //eot packet
				LOG("EOT Packet received.. \n");
				sendEotPacket(udpSocket, expectingSeqNum, remoteIp, remotePort);
				break;
			}			
		} else {
			if (true == firstPacketReceived) {
				int previousSeqNum = expectingSeqNum - 1;
				previousSeqNum = (previousSeqNum + Packet::MAX_SEQ_NUMBER) % Packet::MAX_SEQ_NUMBER;

				sendAckPacket(udpSocket, previousSeqNum, remoteIp, remotePort);
			}

			delete(packet);
		}
	}

	udpSocket.close();

	LOG("Received %u packets \n", (unsigned int) packetsReceived.size());

	//Write to a file.
	ofstream transferFile(recvFile);
	if (transferFile.is_open()) {
		for (list<Packet *>::iterator itr = packetsReceived.begin(); itr != packetsReceived.end(); ++itr) {
			Packet *packet = (*itr);
			transferFile.write(packet->getData(), packet->getLength());
			delete(packet);
		}
	}
	LOG("Finished writing %u bytes to the file\n", totalBytes);

	transferFile.close();
	arrivalLog.close();

	return 0;
}
Example #21
0
// --------------------------------------------------------------------------
// ARDrone::getConfig()
// Description  : Get current configurations of AR.Drone.
// Return value : SUCCESS: 1  FAILURE: 0
// --------------------------------------------------------------------------
int ARDrone::getConfig(void)
{
    // Open the IP address and port
    TCPSocket sockConfig;
    if (!sockConfig.open(ip, ARDRONE_CONFIG_PORT)) {
        CVDRONE_ERROR("TCPSocket::open(port=%d) failed. (%s, %d)\n", ARDRONE_CONFIG_PORT, __FILE__, __LINE__);
        return 0;
    }

    // Send requests
    UDPSocket tmpCommand;
    tmpCommand.open(ip, ARDRONE_COMMAND_PORT);
    tmpCommand.sendf("AT*CTRL=%d,5,0\r", seq++);
    tmpCommand.sendf("AT*CTRL=%d,4,0\r", seq++);
    msleep(500);
    tmpCommand.close();

    // Receive data
    char buf[4096] = {'\0'};
    int size = sockConfig.receive((void*)&buf, sizeof(buf));

    // Received something
    if (size > 0) {
        // Clear config struct
        memset(&config, 0, sizeof(ARDRONE_CONFIG));

        // Parsing configurations
        char *token = strtok(buf, "\n");
        if (token != NULL) parse(token, &config);
        while (token != NULL) {
            token = strtok(NULL, "\n");
            if (token != NULL) parse(token, &config);
        }
    }

    #if 0
    // For debug
    printf("general.num_version_config = %d\n", config.general.num_version_config);
    printf("general.num_version_mb = %d\n", config.general.num_version_mb);
    printf("general.num_version_soft = %s\n", config.general.num_version_soft);
    printf("general.drone_serial = %s\n", config.general.drone_serial);
    printf("general:soft_build_date = %s\n", config.general.soft_build_date);
    printf("general:motor1_soft = %f\n", config.general.motor1_soft);
    printf("general:motor1_hard = %f\n", config.general.motor1_hard);
    printf("general:motor1_supplier = %f\n", config.general.motor1_supplier);
    printf("general:motor2_soft = %f\n", config.general.motor2_soft);
    printf("general:motor2_hard = %f\n", config.general.motor2_hard);
    printf("general:motor2_supplier = %f\n", config.general.motor2_supplier);
    printf("general:motor3_soft = %f\n", config.general.motor3_soft);
    printf("general:motor3_hard = %f\n", config.general.motor3_hard);
    printf("general:motor3_supplier = %f\n", config.general.motor3_supplier);
    printf("general:motor4_soft = %f\n", config.general.motor4_soft);
    printf("general:motor4_hard = %f\n", config.general.motor4_hard);
    printf("general:motor4_supplier = %f\n", config.general.motor4_supplier);
    printf("general.ardrone_name = %s\n", config.general.ardrone_name);
    printf("general.flying_time = %d\n", config.general.flying_time);
    printf("general.navdata_demo = %s\n", config.general.navdata_demo ? "true" : "false");
    printf("general.com_watchdog = %d\n", config.general.com_watchdog);
    printf("general.video_enable = %s\n", config.general.video_enable ? "true" : "false");
    printf("general.vision_enable = %s\n", config.general.vision_enable ? "true" : "false");
    printf("general.vbat_min = %d\n", config.general.vbat_min);
    printf("general.localtime = %d\n", config.general.localtime);
    printf("general.navdata_options = %d\n", config.general.navdata_options);
    printf("control:accs_offset = {%f, %f, %f}\n", config.control.accs_offset[0], config.control.accs_offset[1], config.control.accs_offset[2]);
    printf("control:accs_gains = { %f %f %f %f %f %f %f %f %f }\n", config.control.accs_gains[0], config.control.accs_gains[1], config.control.accs_gains[2], config.control.accs_gains[3], config.control.accs_gains[4], config.control.accs_gains[5], config.control.accs_gains[6], config.control.accs_gains[7], config.control.accs_gains[8]);
    printf("control:gyros_offset = { %f %f %f }\n", config.control.gyros_offset[0], config.control.gyros_offset[1], config.control.gyros_offset[2]);
    printf("control:gyros_gains = { %f %f %f }\n", config.control.gyros_gains[0], config.control.gyros_gains[1], config.control.gyros_gains[2]);
    printf("control:gyros110_offset = { %f %f }\n", config.control.gyros110_offset[0], config.control.gyros110_offset[1]);
    printf("control:gyros110_gains = { %f %f }\n", config.control.gyros110_gains[0], config.control.gyros110_gains[1]);
    printf("control:magneto_offset = { %f %f %f }\n", config.control.magneto_offset[0], config.control.magneto_offset[1], config.control.magneto_offset[2]);
    printf("control:magneto_radius = %f\n", config.control.magneto_radius);
    printf("control:gyro_offset_thr_x = %f\n", config.control.gyro_offset_thr_x);
    printf("control:gyro_offset_thr_y = %f\n", config.control.gyro_offset_thr_y);
    printf("control:gyro_offset_thr_z = %f\n", config.control.gyro_offset_thr_z);
    printf("control:pwm_ref_gyros = %d\n", config.control.pwm_ref_gyros);
    printf("control:osctun_value = %d\n", config.control.osctun_value);
    printf("control:osctun_test = %s\n", config.control.osctun_test ? "true" : "false");
    printf("control:altitude_max = %d\n", config.control.altitude_max);
    printf("control:altitude_min = %d\n", config.control.altitude_min);
    printf("control:outdoor = %s\n", config.control.outdoor ? "true" : "false");
    printf("control:flight_without_shell = %s\n", config.control.flight_without_shell ? "true" : "false");
    printf("control:autonomous_flight = %s\n", config.control.autonomous_flight ? "true" : "false");
    printf("control:flight_anim = %d,%d\n", config.control.flight_anim[0], config.control.flight_anim[1]);
    printf("control:control_level = %d\n", config.control.control_level);
    printf("control:euler_angle_max = %f\n", config.control.euler_angle_max);
    printf("control:control_iphone_tilt = %f\n", config.control.control_iphone_tilt);
    printf("control:control_vz_max = %f\n", config.control.control_vz_max);
    printf("control:control_yaw = %f\n", config.control.control_yaw);
    printf("control:manual_trim = %s\n", config.control.manual_trim ? "true" : "false");
    printf("control:indoor_euler_angle_max = %f\n", config.control.indoor_euler_angle_max);
    printf("control:indoor_control_vz_max = %f\n", config.control.indoor_control_vz_max);
    printf("control:indoor_control_yaw = %f\n", config.control.indoor_control_yaw);
    printf("control:outdoor_euler_angle_max = %f\n", config.control.outdoor_euler_angle_max);
    printf("control:outdoor_control_vz_max = %f\n", config.control.outdoor_control_vz_max);
    printf("control:outdoor_control_yaw = %f\n", config.control.outdoor_control_yaw);
    printf("control:flying_mode = %d\n", config.control.flying_mode);
    printf("control:hovering_range = %d\n", config.control.hovering_range);
    printf("network:ssid_single_player = %s\n", config.network.ssid_single_player);
    printf("network:ssid_multi_player = %s\n", config.network.ssid_multi_player);
    printf("network:wifi_mode = %d\n", config.network.wifi_mode);
    printf("network:wifi_rate = %d\n", config.network.wifi_rate);
    printf("network:owner_mac = %s\n", config.network.owner_mac);
    printf("pic:ultrasound_freq = %d\n", config.pic.ultrasound_freq);
    printf("pic:ultrasound_watchdog = %d\n", config.pic.ultrasound_watchdog);
    printf("pic:pic_version = %d\n", config.pic.pic_version);
    printf("video:camif_fps = %d\n", config.video.camif_fps);
    printf("video:camif_buffers = %d\n", config.video.camif_buffers);
    printf("video:num_trackers = %d\n", config.video.num_trackers);
    printf("video:video_storage_space = %d\n", config.video.video_storage_space);
    printf("video:video_on_usb = %s\n", config.video.video_on_usb ? "true" : "false");
    printf("video:video_file_index = %d\n", config.video.video_file_index);
    printf("video:bitrate = %d\n", config.video.bitrate);
    printf("video:bitrate_ctrl_mode = %d\n", config.video.bitrate_ctrl_mode);
    printf("video:bitrate_storage = %d\n", config.video.bitrate_storage);
    printf("video:codec_fps = %d\n", config.video.codec_fps);
    printf("video:video_codec = %d\n", config.video.video_codec);
    printf("video:video_slices = %d\n", config.video.video_slices);
    printf("video:video_live_socket = %d\n", config.video.video_live_socket);
    printf("video:max_bitrate = %d\n", config.video.max_bitrate);
    printf("video:video_channel = %d\n", config.video.video_channel);
    printf("leds:leds_anim = %d,%d,%d\n", config.leds.leds_anim[0], config.leds.leds_anim[1], config.leds.leds_anim[2]);
    printf("detect:enemy_colors = %d\n", config.detect.enemy_colors);
    printf("detect:enemy_without_shell = %d\n", config.detect.enemy_without_shell);
    printf("detect:groundstripe_colors = %d\n", config.detect.groundstripe_colors);
    printf("detect:detect_type = %d\n", config.detect.detect_type);
    printf("detect:detections_select_h = %d\n", config.detect.detections_select_h);
    printf("detect:detections_select_v_hsync = %d\n", config.detect.detections_select_v_hsync);
    printf("detect:detections_select_v = %d\n", config.detect.detections_select_v);
    printf("syslog:output = %d\n", config.syslog.output);
    printf("syslog:max_size = %d\n", config.syslog.max_size);
    printf("syslog:nb_files = %d\n", config.syslog.nb_files);
    printf("custom:application_desc = %s\n", config.custom.application_desc);
    printf("custom:profile_desc = %s\n", config.custom.profile_desc);
    printf("custom:session_desc = %s\n", config.custom.session_desc);
    printf("custom:application_id = %s\n", config.custom.application_id);
    printf("custom:profile_id = %s\n", config.custom.profile_id);
    printf("custom:session_id = %s\n", config.custom.session_id);
    printf("userbox:userbox_cmd = %d\n", config.userbox.userbox_cmd);
    printf("gps:latitude = %f\n", config.gps.latitude);
    printf("gps:longitude = %f\n", config.gps.longitude);
    printf("gps:altitude = %f\n", config.gps.altitude);
    #endif

    // Finalize
    sockConfig.close();

    return 1;
}