/*
 * julius.cpp
 *
 */
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "HA_config.h"
#include "HA_log.h"
#include "HA_port.h"
#include "socketutil.h"
#include "header.h"
#include "vsclient.h"

static int connectToVehicleStatusServer(const char * const hostname, const int port)
{
	int fd;

	struct sockaddr_in dstAddr;
	::memset(&dstAddr, 0, sizeof(dstAddr));
	dstAddr.sin_port = htons(port);
	dstAddr.sin_family = AF_INET;
	dstAddr.sin_addr.s_addr = inet_addr(hostname);

	fd = ::socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) {
		LOGE("VehicleStatus socket error");
		return(-1);
	}

	// connect
	if (::connect(fd, (struct sockaddr *) &dstAddr, sizeof(dstAddr)) != 0) {
		close(fd);
		return(-1);
	}

	return(fd);
}

int getSourceTrackerThreshold(const char * const hostname, const int port, float *thresh, int *updated)
{
    float read_thresh = 0.0f;
	const int socket_fd = ::connectToVehicleStatusServer(hostname, port);

	/* サーバに接続できなかったら何もしない */
	if(socket_fd < 0) {
		return -1;
	}

	::writesock(socket_fd, "\n\0", 2, NULL, NULL);
	::readsock(socket_fd, &read_thresh, sizeof(read_thresh), NULL, NULL);
	if((*thresh) != read_thresh){
	    (*updated) = 1;
	    (*thresh) = read_thresh;
	}
	else {
	    (*updated) = 0;
	}

	::close(socket_fd);

	return(0);
}
