view sr-data-logger.c @ 241:65ab87e5a8d6

Add ZMQ library
author Daniele Nicolodi <daniele.nicolodi@obspm.fr>
date Thu, 12 Feb 2015 22:43:46 +0100
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;
}