Non-blocking example of the LWIPInterface

Dependencies:   LWIPInterface NetworkSocketAPI mbed-rtos mbed

Non-blocking example for the NetworkSocketAPI. Attempts to get the device's public facing IP address from ifcfg.me using the Happy Eyeballs algorithm to fetch an IPv4 or IPv6 address.

Revision:
66:6a20c7e57306
Parent:
65:826ec2bbec51
--- a/main.cpp	Wed Apr 20 05:20:12 2016 -0500
+++ b/main.cpp	Wed Apr 20 05:42:12 2016 -0500
@@ -15,15 +15,25 @@
  */
 
 #include "mbed.h"
+#include "rtos.h"
 #include "LWIPInterface.h"
 #include "TCPSocket.h"
 
 LWIPInterface eth;
+Semaphore network_sem(1);
 
-DigitalOut led(LED_GREEN);
+DigitalOut blink_led(LED_GREEN);
+DigitalOut network_led(LED_BLUE);
+
 void blink()
 {
-    led = !led;
+    blink_led = !blink_led;
+}
+
+void network_callback()
+{
+    network_led = !network_led;
+    network_sem.release();
 }
 
 int main()
@@ -42,14 +52,34 @@
     SocketAddress addr(&eth, "mbed.org");
     printf("mbed.org resolved to: %s\r\n", addr.get_ip_address());
 
-    TCPSocket socket(&eth);
-    socket.connect("4.ifcfg.me", 23);
+    TCPSocket ipv4socket(&eth);
+    ipv4socket.connect("4.ifcfg.me", 23);
+    ipv4socket.set_blocking(false);
+    ipv4socket.attach(network_callback);
+
+    TCPSocket ipv6socket(&eth);
+    ipv6socket.connect("6.ifcfg.me", 23);
+    ipv6socket.set_blocking(false);
+    ipv6socket.attach(network_callback);
 
-    char buffer[64];
-    int count = socket.recv(buffer, sizeof buffer);
-    printf("public IP address is: %.15s\r\n", &buffer[15]);
+    // Tries to get both an IPv4 and IPv6 address
+    while (network_sem.wait(2500) > 0) {
+        int count;
+        char buffer[64];
+
+        count = ipv4socket.recv(buffer, sizeof buffer);
+        if (count >= 0) {
+            printf("public IPv4 address is: %.15s\r\n", &buffer[15]);
+        }
+
+        count = ipv6socket.recv(buffer, sizeof buffer);
+        if (count >= 0) {
+            printf("public IPv6 address is: %.39s\r\n", &buffer[15]);
+        }
+    }
     
-    socket.close();
+    ipv4socket.close();
+    ipv6socket.close();
     eth.disconnect();
 
     printf("Done\r\n");