Skip to content
Snippets Groups Projects
cli_monitor.c 1.84 KiB
Newer Older
burneykb's avatar
burneykb committed
#define _GNU_SOURCE

#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#include <time.h>
#include <unistd.h>

#include "cli_monitor.h"

burneykb's avatar
burneykb committed
static void timespec_diff(struct timespec *start,  struct timespec *result);

burneykb's avatar
burneykb committed
int cli_monitor(struct backend_conn * conn,	int argc, char **argv) {
	int c, result;
	int timeFlag = 0;

	static struct timespec startTime;
	static struct timespec elapsedTime;
	static struct timespec lastChecked;
	static int nsecs, rate = 10;

 	while ((c = getopt(argc, argv, "t:r:")) != -1) {
		switch(c) {
			case 't' :
				nsecs = atoi(optarg);
				timeFlag = 1;
				break;
			case 'r' :
				rate = atoi(optarg) + 1;
				break;
			default :
				break;
		}
	}

	if(timeFlag) {
		clock_gettime(CLOCK_REALTIME, &startTime);
		clock_gettime(CLOCK_REALTIME, &lastChecked);
		while((result = monitor(conn)) == 0) {
			timespec_diff(&startTime, &elapsedTime);
			if(elapsedTime.tv_sec > nsecs) {
				break;
			}
			while(1) {
				timespec_diff(&lastChecked, &elapsedTime);
				if(elapsedTime.tv_nsec >= (long) ((SECOND_IN_NANO * 2) / rate)) {
					clock_gettime(CLOCK_REALTIME, &lastChecked);
					break;
				}
			}
		}
	} else {
		return monitor(conn);
	}

	return result;
}

int monitor(struct backend_conn * conn) {
	static char * line = "monitor\n";
	printf("monitoring\n");
	int size;
	if((size = ucart_backendWrite(conn, line)) < 0 ) {
		return 1;
	}

burneykb's avatar
burneykb committed
	//TODO : HANDLE RETURN DATA

burneykb's avatar
burneykb committed
	return 0;
}

burneykb's avatar
burneykb committed
static void timespec_diff(struct timespec *start, struct timespec *result)
burneykb's avatar
burneykb committed
{
	struct timespec stop;
	clock_gettime(CLOCK_REALTIME, &stop);
    if ((stop.tv_nsec - start->tv_nsec) < 0) {
        result->tv_sec = stop.tv_sec - start->tv_sec - 1;
        result->tv_nsec = stop.tv_nsec - start->tv_nsec + 1000000000;
    } else {
        result->tv_sec = stop.tv_sec - start->tv_sec;
        result->tv_nsec = stop.tv_nsec - start->tv_nsec;
    }

    return;
}