
#include "udp_send.h" 
#include "main.h"
#include <string.h>
#include <stdio.h>
#include "stm32f2xx.h"
#include "lwip/opt.h"
#include "lwip/tcp.h"
#include "lwip/sys.h"
#include "lwip/memp.h"
#include "lwip/api.h"

#include "lwip/sockets.h"

volatile int8_t sockfd=-1;
#define UDP_LOCAL_PORT 12345
#define UDP_REMOTE_PORT 54321
#define SERCER_IP_ADDRESS "192.168.2.211"       //接收服务器ip
struct sockaddr_in remote_addr;

int udp_log_start()
{
	int ret;
	struct sockaddr_in local_addr;
	// 创建UDP套接字
  sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sockfd < -1) {
    perror("Error creating socket");
		goto exit;
  }
	local_addr.sin_family=AF_INET;
	local_addr.sin_port=htons(UDP_LOCAL_PORT);
	local_addr.sin_addr.s_addr=INADDR_ANY;
	ret = bind(sockfd, (struct sockaddr *)&local_addr, sizeof(local_addr));
  if(ret < 0)
	{ 
    lwip_close(sockfd);
    sockfd = -1;
    goto exit;
  }
	//设置远程服务器地址 TODO：服务器地址配置后自动获取
	remote_addr.sin_family=AF_INET;
	remote_addr.sin_port=htons(UDP_REMOTE_PORT);
	inet_aton(SERCER_IP_ADDRESS,&(remote_addr.sin_addr));
	return 1;
	
exit:
			return -1;
}

void udp_log_close()
{
	lwip_close(sockfd);
	sockfd=-1;
}

int fputc(int ch, FILE *f)
{
	if(sockfd>=0)
	{
		sendto(sockfd, &ch, 1, 0, (struct sockaddr *)&remote_addr,sizeof(remote_addr));
    return ch;
	}
	return 1;
}

int udp_send_printf(char *p)
{
	if(sockfd>=0)
	{
		 sendto(sockfd, p, strlen(p), 0, (struct sockaddr *)&remote_addr,sizeof(remote_addr));
	}
	return 1;
}
