UDP echo with thread

main.cpp

Committer:
JohnnyK
Date:
2019-05-05
Revision:
1:9c712ebb90d3
Parent:
0:9f56faada164
Child:
2:01b03970605d

File content as of revision 1:9c712ebb90d3:

#include "mbed.h" //MbedOS 5.12.2
#include "EthernetInterface.h" 

#define ADDRESS "10.0.1.14" //Here place IP of your PC
#define PORT 20

Thread thread;
DigitalOut led1(LED1);
DigitalOut led2(LED2);

void udpEcho(){
    EthernetInterface eth;
    UDPSocket sock; 
    SocketAddress addr(0,PORT);
    eth.connect(); 
    const char *ip = eth.get_ip_address();
    // Check ip
    if(ip){ 
        printf("IP address is: %s\n", ip);
        sock.open(&eth);
        sock.bind(PORT);
        char buffer[] = "Hello World, UDP Echo server"; 
        printf("Sending message '%s' to server (%s)\n",buffer,ip); 
        sock.sendto(ADDRESS, PORT, buffer, sizeof(buffer));
        printf("Waiting for message...\n");
        
        while(1) {
            char in_buffer[80];
            int n = sock.recvfrom(&addr, &in_buffer, sizeof(in_buffer)); 
            in_buffer[n] = '\0'; 
            printf("Recieved: %s\n", in_buffer);
            
            char out_buffer[80];
            n = sprintf(out_buffer,"Echo - %s", in_buffer);
            out_buffer[n] = '\0';
            printf("Send back: %s\n", out_buffer);
            sock.sendto(addr.get_ip_address(),PORT , out_buffer, sizeof(out_buffer));
            led2 =! led2;
        } 
        /*sock.close();
        eth.disconnect(); */
    }else{
        printf("No IP\n");
        //eth.disconnect();
        printf("Thread end\n");
    }
}


int main() { 
    printf("UDP echo starting...\n");
    thread.start(callback(udpEcho));
    wait(1);
    
    while(1) {
        led1 =! led1;
        wait(1);
    } 
}