TCP echo client using the WiConnect library and mbed TCP Socket API.

Dependencies:   WiConnect mbed

main.cpp

Committer:
dan_ackme
Date:
2014-11-27
Revision:
7:f70f91038918
Parent:
6:b425959b75f0

File content as of revision 7:f70f91038918:


#include "Wiconnect.h"
#include "target_config.h"

#define NETWORK_SSID "<YOUR NETWORK SSID HERE>"
#define NETWORK_PASSWORD "<YOUR NETWORK PASSWORD HERE>"

#define ECHO_SERVER_ADDRESS  "<YOUR LOCAL IP ADDRESS HERE>"
#define ECHO_SERVER_PORT 7


static Serial consoleSerial(STDIO_UART_TX, STDIO_UART_RX);
static char buf[256];


int main()
{
    WiconnectResult result;
    SerialConfig serialConfig(WICONNECT_RX_PIN, WICONNECT_TX_PIN, 256);
    Wiconnect wiconnect(serialConfig, 256, NULL, WICONNECT_RESET_PIN);

    consoleSerial.baud(115200);
    printf("Initializing WiConnect...\r\n");

    if(WICONNECT_FAILED(result, wiconnect.init(true)))
    {
        printf("Failed to initialize Wiconnect: %s\r\n", Wiconnect::getWiconnectResultStr(result));
        if(result == WICONNECT_FIRMWARE_OUTDATED)
        {
            printf("** The WiFi firmware is not supported. Run the ota example to update the firmware:\r\n");
            printf("https://developer.mbed.org/teams/ACKme/code/wiconnect-ota_example\r\n");
        }
        for(;;);
    }
    
    printf("Joining network: %s\r\n", NETWORK_SSID);
    if(WICONNECT_FAILED(result, wiconnect.join(NETWORK_SSID, NETWORK_PASSWORD)))
    {
        printf("Failed to join network: %s\r\n", Wiconnect::getWiconnectResultStr(result));
        for(;;);
    }

    printf("IP Address is %s\n", wiconnect.getIpAddress());

    printf("Connecting to server...\r\n");
    TCPSocketConnection socket;
    while (socket.connect(ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT) < 0)
    {
        printf("Unable to connect to (%s) on port (%d)\r\n", ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT);
        wait(1);
    }

    printf("Sending message...\r\n");
    char hello[] = "Hello World\n";
    if(socket.send_all(hello, sizeof(hello) - 1) == -1)
    {
        printf("Failed to send data\r\n");
        for(;;);
    }

    printf("Receiving response...\r\n");
    int n = socket.receive(buf, 256);
    if(n == -1)
    {
        printf("Failed to receive data\r\n");
        for(;;);
    }
    buf[n] = '\0';
    printf("%s", buf);

    socket.close();
    wiconnect.deinit();

    printf("Finished!");
    while(true) {}
}