DNS, DHCPClient, Http Client, TCP Client, GET

Dependencies:   WIZnetInterface mbed

main.cpp

Committer:
embeddist
Date:
2015-07-06
Revision:
0:7d9fbdfdd41a

File content as of revision 0:7d9fbdfdd41a:

#include "mbed.h"
#include "EthernetInterface.h"

#define ECHO_SERVER_PORT   80 // HTTP defaults to port 80
char serverName[] = "openweathermap.org";    
#define BUFFER_SIZE 2048

DigitalOut myled(LED1);

// Initialize the Ethernet client library
EthernetInterface eth;

int main() {
    char http_cmd[]= "GET / HTTP/1.0\r\n\r\n";    
    char buffer[BUFFER_SIZE];  
  
    // Enter a MAC address for your controller below.
    uint8_t mac_addr[6] = {0x00, 0x08, 0xDC, 0x1D, 0x62, 0x11}; 
    
    // initializing MAC address
    eth.init(mac_addr);

    // Check Ethenret Link
    if(eth.link() == true)
        printf("- Ethernet PHY Link-Done \r\n");
    else
        printf("- Ethernet PHY Link- Fail\r\n");

    // Start Ethernet connecting: Trying to get an IP address using DHCP
    if ( eth.connect() < 0 ){
        printf("Fail - Ethernet Connecing");
    }else{
        // Print your local IP address:
        printf("IP=%s\n\r",eth.getIPAddress());
        printf("MASK=%s\n\r",eth.getNetworkMask());
        printf("GW=%s\n\r",eth.getGateway());
    }
            
    // Initialize the TCPSocketConnection
    // with the IP address and port of the server 
    // that you want to connect to (port 80 is default for HTTP):
    TCPSocketConnection sock;
    if(sock.connect(serverName, ECHO_SERVER_PORT)<0){
       //you didn't get a connection to the server:
        printf("- connection failed\r\n");
    }else{
        printf("- connected\r\n");
        wait(3);
        while( sock.is_connected()==false)
        {
            printf(".");
        }
        // Make & Send a HTTP request:
        sock.send_all(http_cmd, sizeof(http_cmd));        
    }
    
    while(true) {     
       
        int n = sock.receive_all(buffer, BUFFER_SIZE);
        if(n<0) 
        {
            break;
        }
        else
        {
            for(int i=0; i<n; i++)  printf("%c",buffer[i]);
        }        
        
        if(sock.is_connected()==false){
            sock.close();
            while(true)
            {
                //led blinky
                myled = 1;
                wait(0.2);
                myled = 0;
                wait(0.2);            
            }        
        }
    }
    sock.close();
}