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

Dependencies:   WiConnect mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 
00002 #include "Wiconnect.h"
00003 #include "target_config.h"
00004 
00005 #define NETWORK_SSID "<YOUR NETWORK SSID HERE>"
00006 #define NETWORK_PASSWORD "<YOUR NETWORK PASSWORD HERE>"
00007 
00008 #define ECHO_SERVER_ADDRESS  "<YOUR LOCAL IP ADDRESS HERE>"
00009 #define ECHO_SERVER_PORT 7
00010 
00011 
00012 static Serial consoleSerial(STDIO_UART_TX, STDIO_UART_RX);
00013 static char buf[256];
00014 
00015 
00016 int main()
00017 {
00018     WiconnectResult result;
00019     SerialConfig serialConfig(WICONNECT_RX_PIN, WICONNECT_TX_PIN, 256);
00020     Wiconnect wiconnect(serialConfig, 256, NULL, WICONNECT_RESET_PIN);
00021 
00022     consoleSerial.baud(115200);
00023     printf("Initializing WiConnect...\r\n");
00024 
00025     if(WICONNECT_FAILED(result, wiconnect.init(true)))
00026     {
00027         printf("Failed to initialize Wiconnect: %s\r\n", Wiconnect::getWiconnectResultStr(result));
00028         if(result == WICONNECT_FIRMWARE_OUTDATED)
00029         {
00030             printf("** The WiFi firmware is not supported. Run the ota example to update the firmware:\r\n");
00031             printf("https://developer.mbed.org/teams/ACKme/code/wiconnect-ota_example\r\n");
00032         }
00033         for(;;);
00034     }
00035     
00036     printf("Joining network: %s\r\n", NETWORK_SSID);
00037     if(WICONNECT_FAILED(result, wiconnect.join(NETWORK_SSID, NETWORK_PASSWORD)))
00038     {
00039         printf("Failed to join network: %s\r\n", Wiconnect::getWiconnectResultStr(result));
00040         for(;;);
00041     }
00042 
00043     printf("IP Address is %s\n", wiconnect.getIpAddress());
00044 
00045     printf("Connecting to server...\r\n");
00046     TCPSocketConnection socket;
00047     while (socket.connect(ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT) < 0)
00048     {
00049         printf("Unable to connect to (%s) on port (%d)\r\n", ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT);
00050         wait(1);
00051     }
00052 
00053     printf("Sending message...\r\n");
00054     char hello[] = "Hello World\n";
00055     if(socket.send_all(hello, sizeof(hello) - 1) == -1)
00056     {
00057         printf("Failed to send data\r\n");
00058         for(;;);
00059     }
00060 
00061     printf("Receiving response...\r\n");
00062     int n = socket.receive(buf, 256);
00063     if(n == -1)
00064     {
00065         printf("Failed to receive data\r\n");
00066         for(;;);
00067     }
00068     buf[n] = '\0';
00069     printf("%s", buf);
00070 
00071     socket.close();
00072     wiconnect.deinit();
00073 
00074     printf("Finished!");
00075     while(true) {}
00076 }