// tcpclient.cpp
//

#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_STREAM, 0);

	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 a connection attempt will be made.  Modify these
		// values accordingly to match you device configuration.
		char * AddressToConnectTo = "192.168.3.227";		// Change this to be the IP address for your device
		unsigned short PortToConnectTo = 9101;			// Default base port #
		
		printf("Connecting to %s:%u\n", AddressToConnectTo, PortToConnectTo);
		if (MySocketConnect(MySocket, AddressToConnectTo, PortToConnectTo) == 0)
		{
			printf("Connection succeeded\n");

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

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

			unsigned char RecvData[256] = {0};
			int BytesReceived = MySocketRecv(MySocket, RecvData, sizeof(RecvData));

			if (BytesReceived > 0)
			{
				printf("Received:\n");
				HexDumpData(RecvData, BytesReceived);
			}

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

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

	return 0;
}
