/*
 * Copyright (c) 2015-2016, Sumio Morioka
 * All rights reserved.
 *
 * This source code was originally written by Dr.Sumio Morioka for use in the 2015-2016 issues of 
 * "the Interface magazine", published by CQ publishing Co.Ltd in Japan (http://www.cqpub.co.jp).
 * The author has no responsibility on any results caused by using this code.
 *
 * - Author: Dr.Sumio Morioka (http://www002.upp.so-net.ne.jp/morioka, FB:Sumio Morioka)
 *
 *
 * IMPORTANT NOTICE:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the copyright holder nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <libwebsockets.h>
#include <linux/i2c-dev.h>
#include <math.h>
#include <memory.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <sysexits.h>
#include <syslog.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>

#define	TIMEOUT_VAL			30000	// unit: ms

struct timespec		tspec;
long				t0_in, t1_in, t0_out, t1_out;


int		socket_fd;				// global

static char		node_hostname[256];
static int		node_port;

void dispip(FILE *fp, char *ipaddr)
{
	char disp_ipaddr[4];
	bcopy(ipaddr,disp_ipaddr,4);
	fprintf(fp, "%u.%u.%u.%u",
				(u_char)disp_ipaddr[0],
				(u_char)disp_ipaddr[1],
				(u_char)disp_ipaddr[2],
				(u_char)disp_ipaddr[3]
			);
}


int init_node_socket(char *hostname, int port)
{
	u_short				sock;
	struct sockaddr_in	addr;
	struct hostent		*node_host;

	// socket
	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
//		fprintf(stderr, "NODE: failed socket()\n");
		return -1;
	}

	// get IP addr of server
	if ((node_host = gethostbyname(hostname)) == NULL) {
//		fprintf(stderr, "NODE: failed gethostbyname(%s)\n", hostname);
		return -1;
	}

	// connect
	bzero((char *)(&addr), sizeof (addr));	// init structure
	addr.sin_family	= AF_INET;
	addr.sin_port	= htons(port);
//	inet_aton(ip_addr, &addr.sin_addr);
	bcopy(node_host->h_addr, (char *)(&addr.sin_addr), node_host->h_length);

	if (connect(sock, (const struct sockaddr *)(&addr), sizeof (addr)) == -1) {
//		fprintf(stderr, "NODE: failed connect()\n");
		return -1;
	}

//	// set to NON-BLOCKING mode
//	u_long	tmp	= 1;
//	ioctl(sock, FIONBIO, &tmp);

//	fprintf(stderr, "NODE: socket initialized [");
//	dispip(stderr, node_host->h_addr);
//	fprintf(stderr, ":%d]\n", port);

	return (int)sock;
}


int main(int argc, const char **argv)
{
	if (argc < 3) {
		fprintf(stderr, "usage: command_name server_hostname server_port\n");
		exit(1);
	}

	strcpy(node_hostname, argv[1]);
	node_port	= atoi(argv[2]);
	socket_fd	= -1;

	int	num	= 0;

	while (1) {
		ssize_t	rlen;
		char	rbuf;

		if (socket_fd >= 0) {
//			rlen	= recv(socket_fd, &rbuf, 1, MSG_DONTWAIT);	// NOTE: non-blocking
			rlen	= read(socket_fd, &rbuf, 1);	// NOTE: blocking
		}

		clock_gettime(CLOCK_MONOTONIC_RAW, &tspec);
		t1_out	= (tspec.tv_nsec / 1000000) + (tspec.tv_sec * 1000);

		if (socket_fd >= 0 && t1_out - t0_out > (long)TIMEOUT_VAL) {
			fprintf(stderr, "%d: time out caused by no request from host. Retry.\n", t1_out);
			close(socket_fd);
			socket_fd	= -1;
		}

		if (socket_fd < 0) {
			socket_fd	= init_node_socket(node_hostname, node_port);
			if (socket_fd >= 0) {
				clock_gettime(CLOCK_MONOTONIC_RAW, &tspec);
				t0_out	= (tspec.tv_nsec / 1000000) + (tspec.tv_sec * 1000);

				fprintf(stderr, "%d: connected to server (%d)\n", t0_out, socket_fd);
			}
			else {
				fprintf(stderr, "cannot connect to server\n");
				exit(1);
			}

			rlen	= 0;
		}

		if (socket_fd >= 0 && rlen >= 1) {	// if there is a request from HUB
			fprintf(stderr, "%c", rbuf);

			// write to socket
			char	buf;
			buf	= (num % 10) + '0';
			num++;

//			send(socket_fd, &buf, 1, MSG_DONTWAIT);		// NOTE: non-blocking
			write(socket_fd, &buf, 1);		// NOTE: blocking

			sleep(1);

			t0_out	= t1_out;
		}
		usleep(10000);		// 10ms
	}

	return 0;
}

// end of file
