// - SBC Logging To USB -
// This simple demonstration shows how to log data to a USB drive.
// While the SBC does allow connection over a network, this example can be
// useful when you're using an unreliable network, or need more space than
// the SBC has (820MB less the firmware and your files).
//
// Copyright 2014 Phidgets Inc.  All rights reserved.
// This work is licensed under the Creative Commons Attribution 2.5 Canada License.
// view a copy of this license, visit http://creativecommons.org/licenses/by/2.5/ca/

#include <stdio.h>
#include <phidget21.h>
#include <unistd.h>
#include <time.h>
#include <string.h>

//RUN_ALWAYS sets wether you want this program to run in a loop and hold
//the SBC (1) or to run once (0) so you'd have to schedule it yourself
#define RUN_ALWAYS 0
#define SAMPLE_FREQUENCY 60000000 // one minute, for RUN_ALWAYS

#define TEMPERATURE_SENSOR 0
#define FILE_NAME "cdata.log" // will be automatically stored on first usb drive found

int interfacekit_simple()
{
	int result, sensorValue;
    char fileLocation[50];
    char buffer[4][15];
    char checkReadWrite[200];
	const char *err;
    FILE * bashStream;
    FILE * logFile;
    time_t rawtime;
    struct tm * currentTime;
    double temperature;
    
    //Before anything, check that the usb key is attached
    system("mount | grep /dev/sd > /usr/userapps/ctemplog/checkusb.txt");
    bashStream = fopen("/usr/userapps/ctemplog/checkusb.txt", "r");
    strcpy (fileLocation, "/usr/userapps/ctemplog/"); //initalize to a default
    
    if ( bashStream == NULL )
    {
        fprintf(stderr, "Error opening file to check mount point\n");
        return 1;
    }
    
    while(!feof(bashStream))
    {
        if ( fscanf(bashStream, "%s%s%s%s%s%s", buffer[0], buffer[1],
                             fileLocation, buffer[2], buffer[3], checkReadWrite) == 6
            && strstr(checkReadWrite, "rw") != NULL ) //the USB drive is read-write
        {
            strcat(fileLocation, "/");
            strcat(fileLocation, FILE_NAME);
            break;
        }
    }
    
    fclose(bashStream);
    
    //Exit if no USB was found. This condition can be removed
    //if writing to the SBC is okay (i.e. for short logs), not recommended.
    if ( strcmp(fileLocation, "/usr/userapps/ctemplog/") == 0 )
    {
        fprintf(stderr, "Problem finding writable USB drive\n");
        return 0;
    }
    
	//Declare an InterfaceKit handle
	CPhidgetInterfaceKitHandle ifKit = 0;
    
	//Create the InterfaceKit object
	CPhidgetInterfaceKit_create(&ifKit);
    
	//Open the InterfaceKit for device connections
	CPhidget_open((CPhidgetHandle)ifKit, -1);
    
	//Get the program to wait for an interface kit device to be attached
	printf("Waiting for InterfaceKit to be attached...\n");
	if((result = CPhidget_waitForAttachment((CPhidgetHandle)ifKit, 10000)))
	{
		CPhidget_getErrorDescription(result, &err);
		fprintf(stderr, "Problem waiting for attachment: %s\n", err);
		return 0;
	}
    
    //Trigger ratiometric state on
	CPhidgetInterfaceKit_setRatiometric(ifKit, PTRUE);
    
    while (RUN_ALWAYS) //Read temperature forever
    {
        logFile = fopen (fileLocation, "a"); // open the file for appending
        
        if (logFile == NULL)
        {
            fprintf (stderr, "Error opening file: %s\n", fileLocation);
        }
        else
        {
            //get the temperature
            CPhidgetInterfaceKit_getSensorValue(ifKit, TEMPERATURE_SENSOR,
                                                &sensorValue);
            temperature = (sensorValue * 0.22222) - 61.11;
            
            //get the current time
            time (&rawtime);
            currentTime = localtime (&rawtime);
            
            //write to file and close the file for now
            fprintf (logFile, "%s\t%f\n", asctime(currentTime), temperature);
            fclose (logFile);
        }
        
        usleep(SAMPLE_FREQUENCY);
    }
    
    //RUN_ALWAYS is false
    logFile = fopen (fileLocation, "a"); // open the file for appending
    
    if (logFile == NULL)
    {
        fprintf (stderr, "Error opening file: %s\n", fileLocation);
    }
    else
    {
        // CHANGE THIS FOR YOUR SPECIFIC INPUTS
        //get the temperature
        CPhidgetInterfaceKit_getSensorValue(ifKit, TEMPERATURE_SENSOR,
                                            &sensorValue);
        temperature = (sensorValue * 0.22222) - 61.11;
        
        //get the current time
        time (&rawtime);
        currentTime = localtime (&rawtime);
        
        //write to file and close the file for now
        fprintf (logFile, "%s\t%f\n", asctime(currentTime), temperature);
        fclose (logFile);
    }
    
	//Close the phidget and delete the object we created
	CPhidget_close((CPhidgetHandle)ifKit);
	CPhidget_delete((CPhidgetHandle)ifKit);
    
	//Exit
	return 0;
}

int main(int argc, char* argv[])
{
	interfacekit_simple();
	return 0;
}

