Skip to content
Snippets Groups Projects
logger.c 2.32 KiB
Newer Older
burneykb's avatar
burneykb committed
/* Author: Kris Burney
 *
 * Logger file for holding functions pertaining to loging to a file.
 */
#include "logger.h"
#include <stdio.h>
#include <err.h>
#include <pthread.h>
burneykb's avatar
burneykb committed

static FILE * quadlog_file = NULL;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
burneykb's avatar
burneykb committed

int createLogFile(int argc, char* argv)
{
	if (quadlog_file != NULL) {
		return -1;
	}

	if (pthread_mutex_lock(&mutex)) {
		err(-2, "pthrtead_mutex_lock (%s:%d):", __FILE__, __LINE__);
	}

	char log_file[300];
	strcpy(log_file, "logs/");
burneykb's avatar
burneykb committed
	if(argc >= 2)
	{
		strncat(log_file, argv, 294);
burneykb's avatar
burneykb committed
		printf("Creating log file '%s'...\n",log_file);
		quadlog_file = fopen(log_file, "a");
	} else {
burneykb's avatar
burneykb committed
		time_t rawtime;
		char timestr [30];
		time(&rawtime);
		sprintf(timestr,"%s",ctime(&rawtime));

		// Lets convert space to _ in
		char *p = timestr;
		size_t i = 0;
burneykb's avatar
burneykb committed
		while(i < strlen(timestr))
		{ 
		    if (*p == ' ')
		          *p = '_';
			i++;
			p++;
		}

		// timestr has a weird char at the end of it.
		// we will not include it in our file name
		strncat(log_file, timestr, strlen(timestr) -1 );
		strcat(log_file, ".txt");
		printf("Creating log file '%s'...\n",log_file);
		quadlog_file = fopen(log_file, "a");
	}
	if (pthread_mutex_unlock(&mutex)) {
		err(-2, "pthrtead_mutex_unlock (%s:%d):", __FILE__, __LINE__);
burneykb's avatar
burneykb committed
	}
burneykb's avatar
burneykb committed
}

int updateLogFile(const struct ucart_vrpn_TrackerData * td)
burneykb's avatar
burneykb committed
{
	int retval;

	if (pthread_mutex_lock(&mutex)) {
		err(-2, "pthrtead_mutex_lock (%s:%d):", __FILE__, __LINE__);
	}
     
	retval = fprintf(quadlog_file, 
			"FPS: %lf Pos (xyz): (%lf %lf %lf) Att (pry): (%lf %lf %lf)\n",
burneykb's avatar
burneykb committed
		td->fps, td->x, td->y, td->z, td->pitch, td->roll, td->yaw);

	if (pthread_mutex_unlock(&mutex)) {
		err(-2, "pthrtead_mutex_unlock (%s:%d):", __FILE__, __LINE__);
	}
	
	return retval;
burneykb's avatar
burneykb committed
}

int writeStringToLog(const char * string)
burneykb's avatar
burneykb committed
{
	int retval;

	if (pthread_mutex_lock(&mutex)) {
		err(-2, "pthrtead_mutex_lock (%s:%d):", __FILE__, __LINE__);
	}

	retval = fprintf(quadlog_file, "%s", string);

	if (pthread_mutex_unlock(&mutex)) {
		err(-2, "pthrtead_mutex_unlock (%s:%d):", __FILE__, __LINE__);
	}

	return retval;
}

void closeLogFile(void)
{
	if (pthread_mutex_lock(&mutex)) {
		err(-2, "pthrtead_mutex_lock (%s:%d):", __FILE__, __LINE__);
	}

	fclose(quadlog_file);

	if (pthread_mutex_unlock(&mutex)) {
		err(-2, "pthrtead_mutex_unlock (%s:%d):", __FILE__, __LINE__);
	}

burneykb's avatar
burneykb committed
}