/*
 *** author: zhouchao
 *** date: 2019-03-28
 *** version: 1.00
 *** e-mail:  zhouchao@storlead.com  1959353124@qq.com
 *** brief: LM73 driver
 ***
*/


#include "udp.h"


int udpserver_init(int argc, char *argv[])
{
	uint8_t serverIP[50] = {0};
	unsigned short serverPort = 0;
	int serverSocket = 0;
	int iret=0;	
	strcpy(serverIP,"192.168.0.15");
	serverPort = atoi("623");
	//create UDP socket
	serverSocket = socket(AF_INET,SOCK_DGRAM,0);
	if(serverSocket == 0)
	{
		printf("create UDP socket error\n");
		return 0;
	}	

	struct sockaddr_in serverAddr;
	int addr_len = sizeof(struct sockaddr_in);
	memset(&serverAddr,0, sizeof(struct sockaddr_in));

	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(serverPort);
	serverAddr.sin_addr.s_addr = inet_addr(serverIP);

	//bind socket
	iret = bind(serverSocket,(struct sockaddr *)&serverAddr,addr_len);
	if(iret < 0)
	{
		printf("bind error\n");
		return 0;
	}
	return serverSocket;
	
}


int udp_receiver(int serverSocket,uint8_t * rec_buf,uint16_t buf_leng,struct sockaddr_in * clientAddr)
{
	int dataLen = 0;
	unsigned short clientport = 0;
	char clientIP[50] = {0};
	struct sockaddr_in  clientAddr_t;
	int addr_len = sizeof(struct sockaddr_in);
	
	memset(rec_buf, 0,buf_leng );
	dataLen = recvfrom(serverSocket,rec_buf, buf_leng,0,
	                    (struct sockaddr *)clientAddr, &addr_len);	
	return dataLen;
}

int udp_send(int serverSocket,uint8_t * send_buf,uint16_t buf_leng,struct sockaddr_in * clientAddr)
{
	int dataLen = 0;
	int addr_len = sizeof(struct sockaddr_in);

	dataLen = sendto(serverSocket,send_buf, buf_leng,0,
	                    (struct sockaddr *)clientAddr, addr_len);	
	return dataLen;
}
