Udp socket sample program. This program will send back the received packet.

Dependencies:   NyFileSystems libMiMic mbed-rtos mbed

main.cpp

Committer:
nyatla
Date:
2015-09-15
Revision:
30:2be65b31e086
Parent:
29:821fd574d883

File content as of revision 30:2be65b31e086:

/**
 * @file
 * Udpsocket sample.<br/>
 * This program is to test of UDP socket.
 * The program send a echo back packet when receive a packet.
 * 
 */
#include "mbed.h"
#include "rtos.h"
#include "SDFileSystem.h"
#include "mimic.h"
#include "utils/PlatformInfo.h"
#include "fsdata.h"


NetConfig cfg; //create network configulation

DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);


int main()
{
    MiMicNetIf netif;
    Net* net=new Net(netif);//Net constructor must be created after started RTOS

    // manual setting
    cfg.setIpAddr(192,168,128,39);
    cfg.setNetMask(255,255,255,0);
    cfg.setGateway(192,168,128,254);    
    cfg.setSrvUPnP(false);
    cfg.setSrvMdns(false);

    // Create tcp socket with 512 bytes RX buffer.(This size same as maximum size of receiveable UDP packet)
    // Socket must create between "net.start" with "new Net()"
    // If you want to receive data without buffering, please email to MiMic project.
    UdpSocket socket(1234,512);
    
    //Start network
    net->start(cfg);


    led1=1;
    for(;;){
        //wait for packet
        IpAddr peer_host;
        unsigned short port;
        const void* rx;
        //get packet pointer and peer info.
        led2=1;
        int l=socket.precvFrom(rx,&peer_host,&port);
        if(l<0){
            //Error
            led2=0;
            break;
        }
        if(l==0){
            //timeout
            led2=0;
            continue;
        }
        led3=1;
        if(!socket.sendTo(peer_host,port,(const char*)rx,l)){
            //Error
            led2=0;
            led3=0;
            led4=1;
            break;
        }
        Thread::wait(100);//show LED blinking!
        //move to next packet
        socket.precvNext();
        led2=0;
        led3=0;
    }
    led1=0;
    return 0;
}