#include "stdout.h"
#include "user_interface.h"
#include "osapi.h"
#include "espconn.h"
#include "mem.h"


static struct espconn* pUdpDbgServer;

#define PORT 20202

void ICACHE_FLASH_ATTR dbg_udp(char *msg)
{
        if (pUdpDbgServer) {
                espconn_sent(pUdpDbgServer, (unsigned char *)msg, strlen(msg)+1 );
        }
}

static void ICACHE_FLASH_ATTR network_sent(void *arg)
{
}

static void ICACHE_FLASH_ATTR network_received(void *arg, char *data, unsigned short len)
{
}


void ICACHE_FLASH_ATTR dbg_udp_start(unsigned long ip)
{

    if (ip == 0x00)
	ip = 0xffffffff;

    if (!pUdpDbgServer) {
            pUdpDbgServer = (struct espconn *)os_zalloc(sizeof(struct espconn));
    } else {
        espconn_disconnect(pUdpDbgServer);
    }
    pUdpDbgServer->type=ESPCONN_UDP;
    pUdpDbgServer->state=ESPCONN_NONE;
    pUdpDbgServer->proto.udp= (esp_udp *)os_zalloc(sizeof(esp_udp));
    pUdpDbgServer->proto.udp->local_port =  espconn_port(); 
    pUdpDbgServer->proto.udp->remote_port = PORT;

    os_memcpy(pUdpDbgServer->proto.udp->remote_ip, &ip, 4);
    ip = 0;
    os_memcpy(pUdpDbgServer->proto.udp->local_ip, &ip, 4);

    if(espconn_create(pUdpDbgServer) == 0)
    {
        espconn_connect(pUdpDbgServer);
        espconn_regist_recvcb(pUdpDbgServer, network_received);
        espconn_regist_sentcb(pUdpDbgServer, network_sent);
        os_printf("UDBG RDY\n");
    }
}


