#include "lwip/opt.h"
#include "lwip/sys.h"
#include "lwip/api.h"
#include "debug.h"
#include "lwip/tcp.h"
#include "board.h"
#include "udp.h"
#include "dev_flash.h"


typedef struct{
  struct netconn *conn;
  struct netbuf *buf;// 接收的数据
  ip_addr_t dst_ip;
  int dst_port;
}self_def;


void *tappend(void *p,void *del);




static void udp_thread(void *arg)
{
  self_def *s=arg;
  err_t err;
  LWIP_UNUSED_ARG(arg);
  ip_addr_t dst;
  const sys_param_def *par=sys_param();
  IP4_ADDR(&dst,par->host_ip[0],par->host_ip[1],par->host_ip[2],par->host_ip[3]);

  while (1) {

    s->conn = netconn_new(NETCONN_UDP);
    err=netconn_bind(s->conn, IP_ADDR_ANY, 7777);
    if (err == ERR_OK) {
      void *data;
      u16_t len;
      while ((err = netconn_recv(s->conn, &s->buf)) == ERR_OK) {
        do {
             netbuf_data(s->buf, &data, &len);
             s->dst_ip=*netbuf_fromaddr(s->buf);
             s->dst_port=netbuf_fromport(s->buf);
             array_def *arr=arr_creat();
             arr_appends(arr,data,len);
             arr_append(arr,0);
             // 字符数据命令字为0
             emit udp_recv_signal(s,"string",0,arr_temp(arr),"ok");
        } while (netbuf_next(s->buf) >= 0);
        netbuf_delete(s->buf);
      }
    }
    else
    {
      DBG_LOG("udp:err=%d",err);
    }
    netconn_close(s->conn);
    netconn_delete(s->conn);
    sys_msleep(1000);
  }
}



static int myudp_init(void)
{
  self_def *s=calloc(1,sizeof(self_def));
  sys_thread_new("udp_thread", udp_thread, s, 2048, 29);
  app_variable("udp",s,0);
  return 0;
}
app_init_export(myudp_init)



void udp_reply_call(void *obj,uint8_t cmd,array_def *data)
{
  self_def *s=obj;
  err_t err;
  if(s->dst_port!=0){
    struct netbuf *sbuf=netbuf_new();
    netbuf_ref(sbuf,arr_data(data),arr_length(data));
    err=netconn_sendto(s->conn,sbuf,&s->dst_ip,s->dst_port);
    netbuf_delete(sbuf);
  }
}





