view sr-data-logger.c @ 261:a03df7dc98f8

Add xsocket wrappers
author Daniele Nicolodi <daniele.nicolodi@obspm.fr>
date Tue, 16 Jun 2015 15:09:23 +0200
parents 97112b45b838
children
line wrap: on
line source

#include <ansi_c.h>
#include <utility.h>
#include <inifile.h>
#include <tcpsupp.h>

#include "config.h"
#include "logging.h"
#include "sr-data-logger.h"


#define CONF_SECTION_NAME "Sr data logger"


int sr_datalogger_init(struct datalogger *dl)
{
	int rv;
	char path[MAX_PATHNAME_LEN];
	
	/* load configuration file */
	GetIniFilePath(path);
	IniText c = Ini_New(TRUE);
	Ini_ReadFromFile(c, path);

	/* read configuration */
	rv = Ini_GetStringCopy(c, CONF_SECTION_NAME, "id", &(dl->id));
	if (rv <= 0)
		return -1;
	rv = Ini_GetStringCopy(c, CONF_SECTION_NAME, "host", &(dl->host));
	if (rv <= 0)
		return -1;
	rv = Ini_GetInt(c, CONF_SECTION_NAME, "port", &(dl->port));
	if (rv <= 0)
		return -1;
	
	/* dispose configuration */
	Ini_Dispose(c);
	
	return 0;
}


void sr_datalogger_dispose(struct datalogger *dl)
{
	DisconnectFromTCPServer(dl->sock);
	free(dl->host);
	free(dl->id);
}


static int sr_datalogger_connect(struct datalogger *dl)
{
	return ConnectToTCPServer(&(dl->sock), dl->port, dl->host, NULL, NULL, 1);
}	


/* MJD functiom used by the Sr programs */
static inline double utc2mjd(double utc)
{
	return 15020.0 + utc / 86400.0;
}


int __sr_datalogger_send(struct datalogger *dl, double utc, double data)
{
	int rv;
	char buffer[1024];

	/* connect */
	if (! dl->sock) {
		rv = sr_datalogger_connect(dl);
		if (rv < 0)
			return rv;
		logmessage(INFO, "connected to Sr data logger %s:%d", dl->host, dl->port);
	}

	snprintf(buffer, sizeof(buffer), "%s %.7f %.8f", dl->id, utc2mjd(utc), data);
	rv = ClientTCPWrite(dl->sock, buffer, strlen(buffer) + 1, 0);
	if (rv < 0) {
		/* reconnect and resend */
		dl->sock = 0;
		__sr_datalogger_send(dl, utc, data);
	}
	
	return 0;
}