#include <stdio.h>
#include <unistd.h>
#include <string>

#include "../hubolib.h"

using namespace HuboLib;
using namespace std;

/*
Compile and link: 
	g++ AnalogDump.cpp -L../ -lhubo -lpthread -lrt -o AnalogDump
Run:
	sudo ./AnalogDump
Purpose:
	Dump all analog channels into a file.
*/

string GetDateTime(char seperator, char timeSeperator);
bool AppendFile(string sFile, string sText);

int main(int argc, char* argv[])
{
	if (argc != 3)
	{
		printf ("Usage: \n  Analogdump <sample rate [ms]> <filename>\n  example: Analogdump 1000 test.csv\n");
		return 0;
	}

	long logSpeed = 1000;
	if (sscanf (argv[1], "%ld", &logSpeed) != 1)
	{
		printf ("Logspeed could not be determined!\n");
		return 0;
	}
	
	char buffer [128];
	if (sscanf (argv[2], "%s", buffer) != 1)
	{
		printf ("File name could not be determined!\n");
		return 0;
	}
	string sFile = buffer;
	
	// Initialize the library once in your program.
	if (!Initialize())
	{
		printf ("Error: Initialize\n");
		return 1;
	}
	
	// Define all channels to be read (set to 1) from the ADC.
	unsigned short overSampling[MAX_MCP3x08_CHANNELS] = { 1, 1, 1, 1, 1, 1, 1, 1 };
	Set_MCP3x08_Oversampling (overSampling);
	
	// Wait as long until we have valid values in the buffer.
	Wait_For_MCP3x08_Buffered_Values();
	
	int 			channel = 0;
	unsigned long 	adcCount; 
	double	 		volt;
	string sLine = "";
	
	while (1)
	{
		sLine = GetDateTime(' ', ':');
		sLine += " ";
		
		for (int channel=0; channel<MAX_MCP3x08_CHANNELS; channel++)
		{
			// Read channel and output its value.
			if (Get_AI_Channel (channel, adcCount, volt))
			{
				sprintf (buffer, "%04ld ", adcCount);
			}
			else 
			{
				sprintf (buffer, "    ");
			}
			sLine += buffer;
		}
		sLine +="\n";
		printf ("%s", sLine.c_str());
		AppendFile(sFile, sLine);
		
		usleep(1000L * logSpeed);
	}
	
	// Free library resources.
	Uninitialize();
	
	return 0;
}

string GetDateTime(char seperator, char timeSeperator)
{
	time_t t = time(0);   // get time now
    struct tm *pNow = localtime (&t);
	char buffer[128];
	sprintf (buffer, "%02d.%02d.%d%c%02d%c%02d%c%02d", pNow->tm_mday, (pNow->tm_mon + 1), (pNow->tm_year + 1900), seperator, pNow->tm_hour, timeSeperator, pNow->tm_min, timeSeperator, pNow->tm_sec);
	// printf ("Time = %s\n", buffer);
	return string(buffer);
}

bool AppendFile(string sFile, string sText)
{
	FILE* pFile = fopen (sFile.c_str(), "a+");
	if (!pFile)
		return false;
	bool bResult = fputs (sText.c_str(), pFile) > 0;
	fflush (pFile);
	fclose(pFile);
	return bResult;
}

