// UDPSerial.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "hexdumpdata.h"
#include "mysocket.h"

int main(int argc, char* argv[])
{
	printf("Start\n");

	printf("Creating socket ...\n");
	int MySocket = MySocketOpen(SOCK_DGRAM, 9000);

	if (MySocket != -1)
	{
		struct sockaddr_in SockAddr = {0};
		size_t SockAddrLength = sizeof(SockAddr);

		getsockname(MySocket, (struct sockaddr *)&SockAddr, &SockAddrLength);
		printf("Socket created on %s:%u\n", inet_ntoa(SockAddr.sin_addr), SockAddr.sin_port);

		// IMPORTANT!
		//
		// This is the IP Address and port number of the device to
		// which data will be sent.  Modify these values accordingly
		// to match you device configuration.
		char * AddressToSendTo = "192.168.3.227";		// Change this to be the IP address for your device
		unsigned short PortToSendTo = 9000;			// Default base port # for serial port 1

		unsigned char SendData[] =
		{
			0x1b, '$',
			'H', 'e', 'l', 'l', 'o', ' ',
			'W', 'o', 'r', 'l', 'd',
		};

		printf("Sending:\n");
		HexDumpData(SendData, sizeof(SendData));

		MySocketSendTo(MySocket, SendData, sizeof(SendData), AddressToSendTo, PortToSendTo);

		unsigned char RecvData[256] = {0};
		int BytesReceived = 0;

		char AddressReceivedFrom[32];
		size_t AddressReceivedFromLength = sizeof(AddressReceivedFrom);

		if ((BytesReceived = MySocketRecvFrom(MySocket, RecvData, sizeof(RecvData), AddressReceivedFrom, &AddressReceivedFromLength)) > 0)
		{
			printf("Received data from %s\n", AddressReceivedFrom);
			HexDumpData(RecvData, BytesReceived);
		}

		printf("Closing socket\n");
		MySocketClose(MySocket);

		printf("Finish\n");
	}
	else
	{
		printf("Socket creation failed\n");
	}

	return 0;
}

