Multi-Hackers / SocketModem

Dependents:   M2X_dev axeda_wrapper_dev MTS_M2x_Example1 MTS_Cellular_Connect_Example ... more

tests/test_TCP_Socket_Echo.h

Committer:
sgodinez
Date:
2013-12-19
Revision:
44:86fa8f50a1df
Parent:
41:81d035fb0b6a
Child:
53:27c9622de0f9

File content as of revision 44:86fa8f50a1df:

#ifndef _TEST_TCP_SOCKET_ECHO_H_
#define _TEST_TCP_SOCKET_ECHO_H_


//Setup a netcat server with command: ncat -l 5798 -k -c 'xargs -n1 --null echo'

void testTcpSocketEcho() {
    using namespace mts;
    
    Cellular::Code code;
    const int TEST_PORT = 5798;
    const std::string TEST_SERVER("204.26.122.96");
    const char buffer[] = "*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890*";
    const int size = sizeof(buffer); 
    char echoData[size];
    
    printf("TCP SOCKET TESTING\r\n");
    printf("Setting APN\r\n");
    code = Cellular::getInstance()->setApn("b2b.tmobile.com");
    if(code == Cellular::CELL_OK) {
        printf("Success!\r\n");
    } else {
        printf("Error during APN setup [%d]\r\n", (int)code);
    }
    
    printf("Setting Socket Closeable\r\n");
    code = Cellular::getInstance()->setSocketCloseable();
    if(code == Cellular::CELL_OK) {
        printf("Success!\r\n");
    } else {
        printf("Error setting socket closeable [%d]\r\n", (int)code);
    }
    
    printf("Establishing PPP Connection\r\n");
    if(Cellular::getInstance()->connect()) {
        printf("Success!\r\n");
    } else {
        printf("Error during PPP connection\r\n");
    }
       
    printf("Opening a TCP Socket\r\n");
    if(Cellular::getInstance()->open(TEST_SERVER, TEST_PORT, IPStack::TCP)) {
        printf("Success!\r\n");   
    } else {
        printf("Error during TCP socket open [%s:%d]\r\n", TEST_SERVER.c_str(), TEST_PORT);
    }
    
    printf("Sending buffer\r\n");
    int bytesWritten = Cellular::getInstance()->write(buffer, size, 10000);
    if(bytesWritten == size) {
        printf("Successfully sent buffer\r\n");
    } else {
        printf("Failed to send buffer\r\n");   
    }
    
    printf("Receiving echo (timeout = 15 seconds)\r\n");
    Timer tmr;
    int bytesRead = 0;
    tmr.start();
    do {
        bytesRead += Cellular::getInstance()->read(&echoData[bytesRead], size - bytesRead, 1000);
        printf("Total bytes read %d\r\n", bytesRead);
    } while (tmr.read_ms() <= 15000 && bytesRead < size);

    //Safely Cap at Max Size
    echoData[size - 1] = '\0';
    printf("Comparing Buffers\r\n");
    printf("SENT: [%s]\r\n", buffer);
    printf("RECV: [%s]\r\n", echoData);
    
    for(int i = 0; i < size - 1; i++) {
        if(buffer[i] != echoData[i]) {
            printf("Buffers do not match at index %d\r\n", i);
            break;   
        }   
    }
    
    printf("Closing socket\r\n");
    Cellular::getInstance()->close();
    
    
    printf("Disconnecting\r\n");
    Cellular::getInstance()->disconnect();   
}

#endif