minutesfixes
authorstephen
Fri, 18 Jun 2010 14:17:01 +0000
changeset 24 86613545ad8c
parent 23 56d1680cbb1e
child 25 36f250b990fc
minutesfixes
Makefile
pbmd
pbmd.c
stateManager.c
stateManager.h
--- a/Makefile	Fri Jun 04 17:21:55 2010 +0100
+++ b/Makefile	Fri Jun 18 14:17:01 2010 +0000
@@ -2,6 +2,7 @@
 CFLAGS=-g -O0 -Wall -I../
 LIBS= -lphidget21 -lpthread -ldl
 
+all: pbmd
 
 stateManager.o : handlers.h
 pbmd.o : stateManager.h
@@ -12,4 +13,4 @@
 	$(CC)  -o $@ $^ $(CFLAGS) $(LIBS)
 
 clean:
-	-rm *.o
+	-rm -f *.o pbmd
Binary file pbmd has changed
--- a/pbmd.c	Fri Jun 04 17:21:55 2010 +0100
+++ b/pbmd.c	Fri Jun 18 14:17:01 2010 +0000
@@ -28,115 +28,123 @@
 int setBootflag(char *bootFileName, char *bootflag);
 
 int main(int argc, char* argv[])
-{           
-    char *progName = getProgName(argv[0]);
-    FILE *logFile;
-    char *snapFileName;
-    char *bootFileName;
-    int sleepTime; 
-    int sleepHourStart;
-    int sleepHourEnd;   
-    int ret;
-       
-    char *bootflag = (char*) malloc( 2 );
-    time_t boottime;
-    
-    time ( &boottime );                 // log time we booted
+{		   
+	char *progName = getProgName(argv[0]);
+	FILE *logFile;
+	char *snapFileName;
+	char *bootFileName;
+	int sleepTime; 
+	int sleepHourStart;
+	int sleepMinStart;   
+	int sleepHourEnd;
+	int sleepMinEnd;   
+	int ret;
+	   
+	char *bootflag = (char*) malloc( 2 );
+	time_t boottime;
+	
+	time ( &boottime );				 // log time we booted
 
-    redirectOutput();
-    
-    openlog( progName, LOG_CONS, LOG_USER );
-    
-    validateArgs( argc, argv );       
-    syslog ( LOG_NOTICE, "Power States: AMBER=%d GREEN=%d", AMBER, GREEN );
-    
-    // extract args    
-    logFile = fopen( argv[1], "a" );    // Open log file
-    snapFileName = argv[2];             // Arg 2 is snapshot file
-    bootFileName = argv[3];             // Arg 3 is boot flag file
-    sleepTime = atoi( argv[4] );        // Arg 4 is sleep interval
-    sleepHourStart = atoi( argv[5] );   // Arg 5 is sleep hour start
-    sleepHourEnd = atoi( argv[6] );     // Arg 6 is sleep hour end
-                                  
-    if (logFile == 0) 
-        syslog ( LOG_ERR, "Could not open log file: %s Continuing without logging", argv[1] );       
-    
-    clearShapFile(snapFileName); 
-    
-    getBootflag ( bootFileName, bootflag );   
-    setBootflag ( bootFileName, BOOTFLAG_MAN_RESTART );
+	redirectOutput();
+	
+	openlog( progName, LOG_CONS, LOG_USER );
+	
+	validateArgs( argc, argv );	   
+	syslog ( LOG_NOTICE, "Power States: AMBER=%d GREEN=%d", AMBER, GREEN );
+	
+	// extract args	
+	logFile = fopen( argv[1], "a" );	// Open log file
+	snapFileName = argv[2];			 // Arg 2 is snapshot file
+	bootFileName = argv[3];			 // Arg 3 is boot flag file
+	sleepTime = atoi( argv[4] );		// Arg 4 is sleep interval
+	if (argc==7) {
+		sleepHourStart = atoi( argv[5] );   // Arg 5 is sleep hour start
+		sleepMinStart = 0;
+		sleepHourEnd = atoi( argv[6] );	 // Arg 6 is sleep hour end
+		sleepMinEnd = 0;
+	} else {
+		sleepHourStart = atoi( argv[5] );   // Arg 5 is sleep hour start
+		sleepMinStart = atoi( argv[6] );
+		sleepHourEnd = atoi( argv[7] );	 // Arg 6 is sleep hour end
+		sleepMinEnd = atoi (argv [8]);
+	}
+								  
+	if (logFile == 0) 
+		syslog ( LOG_ERR, "Could not open log file: %s Continuing without logging", argv[1] );	   
+	
+	clearShapFile(snapFileName); 
+	
+	getBootflag ( bootFileName, bootflag );   
+	setBootflag ( bootFileName, BOOTFLAG_MAN_RESTART );
 
-    fputs("\nYYYY-M-MDD,HH:MM:SS,mVolts,mAmps,State,Spike\n", logFile);
+	fputs("\nYYYY-M-MDD,HH:MM:SS,mVolts,mAmps,State,Spike\n",logFile);
 
-    ret = test_interfacekit(progName, logFile, snapFileName, bootflag, boottime, sleepTime, sleepHourStart, sleepHourEnd);// and off we go
-        
-    fclose ( logFile );
-    ret == 0 ? syslog (LOG_NOTICE, "Program closing" ) : syslog (LOG_ERR, "Program closing with error code: %d", ret );
-    closelog ();
-    free ( bootflag );
-    return ret;
+	ret = test_interfacekit(progName,
+		logFile,
+		snapFileName,
+		bootflag,
+		boottime,
+		sleepTime,
+		sleepHourStart,
+		sleepMinStart,
+		sleepHourEnd,
+		sleepMinEnd);// and off we go
+		
+	fclose ( logFile );
+	ret == 0 ? syslog (LOG_NOTICE, "Program closing" ) : syslog (LOG_ERR, "Program closing with error code: %d", ret );
+	closelog ();
+	free ( bootflag );
+	return ret;
 }
 
 // extract program name from file path
 char* getProgName(char* path)
 {
-    char* ret = strrchr( path, '/' );       //returns null if '/' not found
-    
-    if( ret == NULL )
-        return path;
-    else
-        return ret + 1;
+	char* ret = strrchr( path, '/' );	   //returns null if '/' not found
+	
+	if( ret == NULL )
+		return path;
+	else
+		return ret + 1;
 }
 
 // Close out stdout and point to a file cos if we are running as a demon we need to log this somewhere.
 void redirectOutput()
-{    
-    fclose(stdout);
-    fclose(stderr);
+{	
+	fclose(stdout);
+	fclose(stderr);
 
-    stdout = fopen(LOG_PATH, "a");
-    stderr = fopen(ERR_PATH, "a");
+	stdout = fopen(LOG_PATH, "a");
+	stderr = fopen(ERR_PATH, "a");
 
-    return;
+	return;
 }
 
 int validateArgs(int argc, char* argv[])
 {
-    int i;
-    
-    if ( argc != 7 )        // 5 args inc program name
-    {                                    
-        syslog (LOG_ERR, "Error: Program started with incorrect args. Usage: %s logfile snapshotfile bootflagfile sleeptime sleephourstart sleephourend", argv[0]);
-        exit(1);
-    }
+	if ( argc != 7 && argc != 9 ) {									
+		syslog (LOG_ERR, "Error: Program started with incorrect args. Usage: %s logfile snapshotfile bootflagfile polltime sleephourstart [sleepminstart] sleephourend [sleepminend]", argv[0]);
+		exit(1);
+	}
 
-    for(i=0; i<argc; i++)   // ensure args are not null
-    {
-        if(argv[i] == NULL)
-        {                                       
-            syslog (LOG_ERR, "Error: Program started with incorrect arg %d. Usage: %s logfile snapshotfile bootflagfile sleeptime sleephourstart sleephourend", i, argv[0]);         
-            exit(1);
-        }
-    }
-    
-    syslog (LOG_NOTICE, "Program started correctly with args: logfile=%s, snapshotfile=%s, bootflagfile=%s, sleeptime=%s  sleephourstart=%s sleephourend=%s", 
-        argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]);
-        
-    return 0;
+	syslog (LOG_NOTICE, "Program started correctly with args: logfile=%s, snapshotfile=%s, bootflagfile=%s, sleeptime=%s  sleephourstart=%s sleephourend=%s", 
+		argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]);
+		
+	return 0;
 }
 
 int clearShapFile(char *snapFileName)
 {
-    FILE *filesnap = fopen( snapFileName, "w" );   
-     
-    if (filesnap == 0) 
-    {
-        syslog ( LOG_ERR, "Could not open snapshot file: %s", snapFileName );
-        return -1;
-    }   
-    
-    fclose( filesnap ); // we need to overwrite it every time we write to it    
-    return 0;
+	FILE *filesnap = fopen( snapFileName, "w" );   
+	 
+	if (filesnap == 0) 
+	{
+		syslog ( LOG_ERR, "Could not open snapshot file: %s", snapFileName );
+		return -1;
+	}   
+	
+	fclose( filesnap ); // we need to overwrite it every time we write to it	
+	return 0;
 }
 
 // The system reboots after a sleep period to ensure everyting is restarted properly
@@ -147,49 +155,49 @@
 // override.
 int getBootflag(char *bootFileName, char *bootflag)
 {
-    FILE *fileboot = fopen(bootFileName, "r");
-    
-    if ( (fileboot == 0) ) 
-    {
-        syslog ( LOG_INFO, "Could not open bootflag file: %s - assuming manual override \"%s\"", bootFileName, BOOTFLAG_MAN_OVERRIDE );       
-        sprintf(bootflag, BOOTFLAG_MAN_OVERRIDE);
-        return -1;
-    }    
-    else // read from boot state file
-    {    
-        fgets(bootflag, 2, fileboot);    // bootflag should be 'S'    
-        syslog ( LOG_INFO, "Opened bootflag file, boot flag is: %s", bootflag); 
-           
-        if ( strncmp (bootflag, BOOTFLAG_NORMAL, 1) == 0 )    
-            syslog ( LOG_INFO, "Bootflag is normal \"%s\"", BOOTFLAG_NORMAL ); 
-        else
-        {
-            syslog ( LOG_INFO, "Bootflag not normal, assuming manual restart \"%s\"", BOOTFLAG_MAN_RESTART ); 
-            sprintf(bootflag, BOOTFLAG_MAN_RESTART);       
-        }
-        
-        fclose( fileboot );
-        return 0;
-    }   
+	FILE *fileboot = fopen(bootFileName, "r");
+	
+	if ( (fileboot == 0) ) 
+	{
+		syslog ( LOG_INFO, "Could not open bootflag file: %s - assuming manual override \"%s\"", bootFileName, BOOTFLAG_MAN_OVERRIDE );	   
+		sprintf(bootflag, BOOTFLAG_MAN_OVERRIDE);
+		return -1;
+	}	
+	else // read from boot state file
+	{	
+		fgets(bootflag, 2, fileboot);	// bootflag should be 'S'	
+		syslog ( LOG_INFO, "Opened bootflag file, boot flag is: %s", bootflag); 
+		   
+		if ( strncmp (bootflag, BOOTFLAG_NORMAL, 1) == 0 )	
+			syslog ( LOG_INFO, "Bootflag is normal \"%s\"", BOOTFLAG_NORMAL ); 
+		else
+		{
+			syslog ( LOG_INFO, "Bootflag not normal, assuming manual restart \"%s\"", BOOTFLAG_MAN_RESTART ); 
+			sprintf(bootflag, BOOTFLAG_MAN_RESTART);	   
+		}
+		
+		fclose( fileboot );
+		return 0;
+	}   
 }   
 
 // clear bootflag file - an S in this file means we are controlling the reboot (eg the user
 // did not manually turn off and on the box
 int setBootflag(char *bootFileName, char *bootflag)
 {
-    FILE *fileboot = fopen(bootFileName, "w");
+	FILE *fileboot = fopen(bootFileName, "w");
 
-    if ( (fileboot == 0) ) 
-    { 
-        syslog ( LOG_ERR, "Could not open bootflag file: %s", bootFileName );
-        return -1;
-    }
-    else    
-    {  
-        syslog ( LOG_INFO, "Writing bootflag \"%s\" to file: %s", bootflag, bootFileName );
-        fputs(bootflag, fileboot);
-        fclose( fileboot );
-        return 0;
-    }   
+	if ( (fileboot == 0) ) 
+	{ 
+		syslog ( LOG_ERR, "Could not open bootflag file: %s", bootFileName );
+		return -1;
+	}
+	else	
+	{  
+		syslog ( LOG_INFO, "Writing bootflag \"%s\" to file: %s", bootflag, bootFileName );
+		fputs(bootflag, fileboot);
+		fclose( fileboot );
+		return 0;
+	}   
 }
 
--- a/stateManager.c	Fri Jun 04 17:21:55 2010 +0100
+++ b/stateManager.c	Fri Jun 18 14:17:01 2010 +0000
@@ -1,172 +1,176 @@
 #include "stateManager.h"
 
+#ifndef PATH_MAX
+#define PATH_MAX 1024
+#endif
+
 void display_generic_properties(CPhidgetHandle phid)
 {
-    int sernum, version;
-    const char *deviceptr;
-    
-    CPhidget_getDeviceType(phid, &deviceptr);
-    CPhidget_getSerialNumber(phid, &sernum);
-    CPhidget_getDeviceVersion(phid, &version);
+	int sernum, version;
+	const char *deviceptr;
+	
+	CPhidget_getDeviceType(phid, &deviceptr);
+	CPhidget_getSerialNumber(phid, &sernum);
+	CPhidget_getDeviceVersion(phid, &version);
 
-    printf("%s\n", deviceptr);
-    printf("Version: %8d \nSerialNumber: %10d\n", version, sernum);
-    
-    return;
+	printf("%s\n", deviceptr);
+	printf("Version: %8d \nSerialNumber: %10d\n", version, sernum);
+	
+	return;
 }
 
 void display_IFK_properties(CPhidgetInterfaceKitHandle phid)
 {
-    int numInputs, numOutputs, numSensors;    
-    
-    CPhidgetInterfaceKit_getOutputCount( phid, &numOutputs);
-    CPhidgetInterfaceKit_getInputCount ( phid, &numInputs);
-    CPhidgetInterfaceKit_getSensorCount( phid, &numSensors);    
-    CPhidgetInterfaceKit_setOutputState( phid, 0, 1);
-    
-    display_generic_properties((CPhidgetHandle)phid);
-    
-    printf("Sensors:%d Inputs:%d Outputs:%d\n", numSensors, numInputs, numOutputs);
-    
-    return;
+	int numInputs, numOutputs, numSensors;	
+	
+	CPhidgetInterfaceKit_getOutputCount( phid, &numOutputs);
+	CPhidgetInterfaceKit_getInputCount ( phid, &numInputs);
+	CPhidgetInterfaceKit_getSensorCount( phid, &numSensors);	
+	CPhidgetInterfaceKit_setOutputState( phid, 0, 1);
+	
+	display_generic_properties((CPhidgetHandle)phid);
+	
+	printf("Sensors:%d Inputs:%d Outputs:%d\n", numSensors, numInputs, numOutputs);
+	
+	return;
 }
 
 void display_LCD_properties(CPhidgetTextLCDHandle phid)
 {
-    int numRows, numColumns, backlight, cursor, contrast, cursor_blink;
+	int numRows, numColumns, backlight, cursor, contrast, cursor_blink;
 
-    CPhidgetTextLCD_getRowCount (phid, &numRows);
-    CPhidgetTextLCD_getColumnCount (phid, &numColumns);
-    CPhidgetTextLCD_getBacklight (phid, &backlight);
-    CPhidgetTextLCD_getContrast (phid, &contrast);
-    CPhidgetTextLCD_getCursorOn (phid, &cursor);
-    CPhidgetTextLCD_getCursorBlink (phid, &cursor_blink);
+	CPhidgetTextLCD_getRowCount (phid, &numRows);
+	CPhidgetTextLCD_getColumnCount (phid, &numColumns);
+	CPhidgetTextLCD_getBacklight (phid, &backlight);
+	CPhidgetTextLCD_getContrast (phid, &contrast);
+	CPhidgetTextLCD_getCursorOn (phid, &cursor);
+	CPhidgetTextLCD_getCursorBlink (phid, &cursor_blink);
 
-    display_generic_properties((CPhidgetHandle) phid);
-    
-    printf("# Rows: %d\n# Columns: %d\n", numRows, numColumns);
-    printf("Current Contrast Level: %d\nBacklight Status: %d\n", contrast, backlight);
-    printf("Cursor Status: %d\nCursor Blink Status: %d\n", cursor, cursor_blink);
-    
-    return;
+	display_generic_properties((CPhidgetHandle) phid);
+	
+	printf("# Rows: %d\n# Columns: %d\n", numRows, numColumns);
+	printf("Current Contrast Level: %d\nBacklight Status: %d\n", contrast, backlight);
+	printf("Cursor Status: %d\nCursor Blink Status: %d\n", cursor, cursor_blink);
+	
+	return;
 }
 
 int getVoltage(CPhidgetInterfaceKitHandle IFK)
 {
-    float fValue = 0, avgValue = 0;
-    int Value = 0, i = 0;
+	float fValue = 0, avgValue = 0;
+	int Value = 0, i = 0;
 
-    CPhidgetInterfaceKit_setRatiometric(IFK, PFALSE);                // set to non-ratio
-    sleep(2);                                                        // wait at least 800ms to settle
-    CPhidgetInterfaceKit_getSensorRawValue(IFK, VOLTINDEX, &Value);  // Voltmeter
+	CPhidgetInterfaceKit_setRatiometric(IFK, PFALSE);				// set to non-ratio
+	sleep(2);														// wait at least 800ms to settle
+	CPhidgetInterfaceKit_getSensorRawValue(IFK, VOLTINDEX, &Value);  // Voltmeter
 
-    // Calibration
-    // when the phidget is not connected to anything it returns a voltage of -5V. 
-    // this must be adjusted to zero by adding 5V
-    Value += 5;
+	// Calibration
+	// when the phidget is not connected to anything it returns a voltage of -5V. 
+	// this must be adjusted to zero by adding 5V
+	Value += 5;
 
-    // get an average over 5 readings to allow for sensor noise. 1 per second for 5 seconds
-    for (i = 0; i < 5 ; i++)
-    { 
-        // http://www.phidgets.com/documentation/Phidgets/1123.pdf
-        // If you want maximum accuracy, you can use the RawSensorValue property from the PhidgetInterfaceKit. 
-        // To adjust a formula, substitute (SensorValue) with (RawSensorValue / 4.095)
-        //
-        // The Formula to translate SensorValue into Voltage is:
-        // Voltage (in volts) = (SensorValue x 0.06) - 30        
-        fValue = Value;
-        fValue = (((fValue/4.095)*0.06)-30)*100;    // multiply raw value and up by 100 to keep
-        avgValue += fValue;
-        sleep (1);
-    }
-            
-    return avgValue / 5;
+	// get an average over 5 readings to allow for sensor noise. 1 per second for 5 seconds
+	for (i = 0; i < 5 ; i++)
+	{ 
+		// http://www.phidgets.com/documentation/Phidgets/1123.pdf
+		// If you want maximum accuracy, you can use the RawSensorValue property from the PhidgetInterfaceKit. 
+		// To adjust a formula, substitute (SensorValue) with (RawSensorValue / 4.095)
+		//
+		// The Formula to translate SensorValue into Voltage is:
+		// Voltage (in volts) = (SensorValue x 0.06) - 30		
+		fValue = Value;
+		fValue = (((fValue/4.095)*0.06)-30)*100;	// multiply raw value and up by 100 to keep
+		avgValue += fValue;
+		sleep (1);
+	}
+			
+	return avgValue / 5;
 }
 
 int getAmps(CPhidgetInterfaceKitHandle IFK)
 {
-    float fValue;
-    int Value;
+	float fValue;
+	int Value;
 
-    CPhidgetInterfaceKit_setRatiometric (IFK, PTRUE);                // set to ratiometric
-    sleep(2);                                                        // wait at least 800ms
-    CPhidgetInterfaceKit_getSensorRawValue(IFK, AMPINDEX, &Value);   // Ampmeter
+	CPhidgetInterfaceKit_setRatiometric (IFK, PTRUE);				// set to ratiometric
+	sleep(2);														// wait at least 800ms
+	CPhidgetInterfaceKit_getSensorRawValue(IFK, AMPINDEX, &Value);   // Ampmeter
 
-    // Calibration
-    // when the phidget is not connected to anything it returns a voltage of -2mA. 
-    // this must be adjusted to zero by adding 2mA
-    Value += 2;
+	// Calibration
+	// when the phidget is not connected to anything it returns a voltage of -2mA. 
+	// this must be adjusted to zero by adding 2mA
+	Value += 2;
 
 
-    // http://www.phidgets.com/documentation/Phidgets/1122.pdf
-    // If you want maximum accuracy, you can use the RawSensorValue property from the PhidgetInterfaceKit. 
-    // To adjust a formula, substitute (SensorValue) with (RawSensorValue / 4.095)
-    //
-    // The formula to translate SensorValue into Current is:
-    // DC Amps = (SensorValue / 13.2) - 37.8787    
-    fValue = Value;
-    fValue = (((fValue/4.095)/13.2)-37.8787)*1000;  // multiply raw value to get amps
-    return fValue * -1;                             // invert so + is charging and - is amp draw
+	// http://www.phidgets.com/documentation/Phidgets/1122.pdf
+	// If you want maximum accuracy, you can use the RawSensorValue property from the PhidgetInterfaceKit. 
+	// To adjust a formula, substitute (SensorValue) with (RawSensorValue / 4.095)
+	//
+	// The formula to translate SensorValue into Current is:
+	// DC Amps = (SensorValue / 13.2) - 37.8787	
+	fValue = Value;
+	fValue = (((fValue/4.095)/13.2)-37.8787)*1000;  // multiply raw value to get amps
+	return fValue * -1;							 // invert so + is charging and - is amp draw
 }
 
 int updateSnapshotfile(const char *snapFileName, int Voltage, int Amps,  int state, int spiking)
 {
-    // Snapshot file is a single line file, overwritten each time with the current and latest values
-    time_t rawtime;
-    struct tm * timeinfo;
-    char timeStr [80];
-    char snapEntry [200];
-    char * spikingStr = spiking ? " SPIKE" : "";
-        
-    time ( &rawtime );
-    timeinfo = localtime ( &rawtime );
+	// Snapshot file is a single line file, overwritten each time with the current and latest values
+	time_t rawtime;
+	struct tm * timeinfo;
+	char timeStr [80];
+	char snapEntry [200];
+	char * spikingStr = spiking ? " SPIKE" : "";
+		
+	time ( &rawtime );
+	timeinfo = localtime ( &rawtime );
 
-    strftime (timeStr, 80, "%Y-%m-%d,%H:%M:%S", timeinfo);
+	strftime (timeStr, 80, "%Y-%m-%d,%H:%M:%S", timeinfo);
 
-    FILE *snapfile = fopen( snapFileName, "w" );            // Open file (delete previous)
+	FILE *snapfile = fopen( snapFileName, "w" );			// Open file (delete previous)
 
-    if (snapfile == 0)        
-    {
-        syslog ( LOG_ERR, "Could not open snapshot file: %s", snapFileName );
-        return -1;      
-    }
-    else 
-    {
-        snprintf( snapEntry, 200, "%s %dV%s %dmA %s\n", timeStr, Voltage, spikingStr, Amps, getStateDesc(state) );                                                           
-        fputs( snapEntry, snapfile );
-        fflush( snapfile );
-        fclose( snapfile );
-        return 0;
-    }        
+	if (snapfile == 0)		
+	{
+		syslog ( LOG_ERR, "Could not open snapshot file: %s", snapFileName );
+		return -1;	  
+	}
+	else 
+	{
+		snprintf( snapEntry, 200, "%s %dV%s %dmA %s\n", timeStr, Voltage, spikingStr, Amps, getStateDesc(state) );														   
+		fputs( snapEntry, snapfile );
+		fflush( snapfile );
+		fclose( snapfile );
+		return 0;
+	}		
 }
 
 int updateLogfile(FILE *logfile, int Voltage, int Amps, int state, int spiking, const char *progName)
 {   
-    time_t rawTime;
-    struct tm * timeInfo;
-    char timeStr [80];
-    char hostName [80];    
-    char logEntry [200];
-    char * spikingStr = spiking ? " SPIKE" : "";
-    
-    time ( &rawTime );
-    timeInfo = localtime ( &rawTime );
+	time_t rawTime;
+	struct tm * timeInfo;
+	char timeStr [80];
+	char hostName [80];	
+	char logEntry [200];
+	char * spikingStr = spiking ? " SPIKE" : "";
+	
+	time ( &rawTime );
+	timeInfo = localtime ( &rawTime );
 
-    strftime (timeStr, 80, "%Y-%m-%d,%H:%M:%S", timeInfo);
-    gethostname(hostName, 80);
-    
-    if (logfile == 0)
-    {
-        syslog ( LOG_ERR, "Error: log file not open" );
-        return -1;
-    }
-    else
-    {
-        snprintf( logEntry, 200, "%s %s %s %d %d %s %s\n", timeStr, hostName, progName, Voltage, Amps, getStateDesc(state), spikingStr );
-        fputs( logEntry, logfile );
-        fflush( logfile );
-        return 0;
-    }
+	strftime (timeStr, 80, "%Y-%m-%d,%H:%M:%S", timeInfo);
+	gethostname(hostName, 80);
+	
+	if (logfile == 0)
+	{
+		syslog ( LOG_ERR, "Error: log file not open" );
+		return -1;
+	}
+	else
+	{
+		snprintf( logEntry, 200, "%s %s %s %d %d %s %s\n", timeStr, hostName, progName, Voltage, Amps, getStateDesc(state), spikingStr );
+		fputs( logEntry, logfile );
+		fflush( logfile );
+		return 0;
+	}
 }
 
 // getTimeString returns the time in a string in the form "HH:MM". It takes the current
@@ -174,315 +178,364 @@
 // wakeTime is 0.
 void getTimeString (int wakeTimeSec, char *wakeTimeStr)
 {
-    time_t rawtime;
-    struct tm * timeinfo;
+	time_t rawtime;
+	struct tm * timeinfo;
 
-    time ( &rawtime );
-    rawtime = rawtime + wakeTimeSec;
-    timeinfo = localtime ( &rawtime );
+	time ( &rawtime );
+	rawtime = rawtime + wakeTimeSec;
+	timeinfo = localtime ( &rawtime );
 
-    strftime (wakeTimeStr, 20, "%H:%M", timeinfo);
-    return;
+	strftime (wakeTimeStr, 20, "%H:%M", timeinfo);
+	return;
 }
 
-void getnewState(int Voltage, const char *bootflag, int *newState, int sleepHourStart, int sleepHourEnd)
+void getnewState(int Voltage,
+	const char *bootflag,
+	int *newState,
+	int sleepHourStart,
+	int sleepMinStart,
+	int sleepHourEnd,
+	int sleepMinEnd)
 {
-    int localState = 0;
-    
-    time_t rawtime;
-    struct tm * timeinfo;    
-    
-    time ( &rawtime );
-    timeinfo = localtime ( &rawtime );       
-    mktime ( timeinfo );
+	int localState = 0;
+	
+	time_t rawtime;
+	struct tm * timeinfo;	
+	
+	time ( &rawtime );
+	timeinfo = localtime ( &rawtime );	   
+	mktime ( timeinfo );
 
-    if ( strncmp(bootflag, BOOTFLAG_NORMAL, 1) != 0 )   // Anything except an S will mean manual start
-        localState = OVERRIDE;
-        
-    else if (timeinfo->tm_hour < sleepHourEnd || timeinfo->tm_hour >= sleepHourStart )
-        localState = SLEEP;
-    
-    else if ( Voltage >= GREEN) 
-        localState = UP;
-    
-    else if ( AMBER <= Voltage && Voltage < GREEN ) 
-        localState = STBYSHORT;
+	// are we now in a time when we're due to sleep?
+	// let's assume not
+	int sleepytime=0;
+	// does sleep period span midnight?
+	int spanmidnight=0;
+	if (sleepHourEnd<sleepHourStart) {
+		spanmidnight=1;
+	} else if (sleepHourEnd==sleepHourStart &&
+		sleepMinStart>sleepMinEnd) {
+		spanmidnight=1;
+	}	
+	if (spanmidnight==0) { // sleep if start<=now<end
+		if 	(	
+		(timeinfo->tm_hour>=sleepHourStart && timeinfo->tm_min>=sleepMinStart)
+		&&
+		(timeinfo->tm_hour<sleepHourEnd && timeinfo->tm_min<sleepMinEnd)
+		) 
+			sleepytime=1;
+	} else { // sleep if start<=now || now<end
+		if 	(	
+		(timeinfo->tm_hour>=sleepHourStart && timeinfo->tm_min>=sleepMinStart)
+		||
+		(timeinfo->tm_hour<sleepHourEnd && timeinfo->tm_min<sleepMinEnd)
+		) 
+			sleepytime=1;
+	}
+	
+	// Anything except an S will mean manual start
+	if ( strncmp(bootflag, BOOTFLAG_NORMAL, 1) != 0 ) 
+		localState = OVERRIDE;
+	else if (sleepytime) 
+		localState = SLEEP;
+	else if ( Voltage >= GREEN) 
+		localState = UP;
+	else if ( AMBER <= Voltage && Voltage < GREEN ) 
+		localState = STBYSHORT;
+	else //Voltage < AMBER
+		localState = STBYLONG;
+		
+	if ( *newState != localState )
+		syslog ( LOG_INFO, "Moving from state %s to state %s, bootflag=%s, voltage=%dV", 
+			getStateDesc(*newState), getStateDesc(localState), bootflag, Voltage );
+	else
+		syslog ( LOG_DEBUG, "Remaining in same state %s, bootflag=%s, voltage=%dV", 
+			getStateDesc(localState), bootflag, Voltage );
 
-    else //Voltage < AMBER
-        localState = STBYLONG;
-          
-        
-    if ( *newState != localState )
-        syslog ( LOG_INFO, "Moving from state %s to state %s, bootflag=%s, voltage=%dV", 
-                getStateDesc(*newState), getStateDesc(localState), bootflag, Voltage );
-    else
-        syslog ( LOG_DEBUG, "Remaining in same state %s, bootflag=%s, voltage=%dV", 
-                getStateDesc(localState), bootflag, Voltage );
-
-    *newState = localState; 
-    return;               
+	*newState = localState; 
+	return;			   
 }
 
 void closeCPhidget(CPhidgetHandle handle)
 {
-    CPhidget_close(handle);
-    CPhidget_delete(handle);
-    return;
-}         
+	CPhidget_close(handle);
+	CPhidget_delete(handle);
+	return;
+}		 
 
 //if the rate of change in voltage is greater than the max allowable, a spike has occured
 //if spike:  set voltage & voltageTime to prev value and return 1
 //otherwise: update prevVoltage to voltage and return 0
 int testVoltageSpike(int *prevVoltage, time_t *prevVoltageTime, int *Voltage, time_t *VoltageTime)
 {
-    const float maxRateOfChange = 1;
-    
-    float deltaSeconds = (*VoltageTime) - (*prevVoltageTime);    
-    float deltaVoltage = (*Voltage) - (*prevVoltage); 
-    deltaVoltage = deltaVoltage < 0 ? -1 * deltaVoltage : deltaVoltage;     //use abs value
-        
-    // eg. if the voltage changes by more than 1 volt over 100 sec a spike has occured
-    if( deltaVoltage / deltaSeconds > maxRateOfChange )
-    {
-        syslog ( LOG_ERR, "Voltage spike from: %dV to: %dV in %d seconds. Using prevVoltage: %dV", *prevVoltage, *Voltage, (int)deltaSeconds, *prevVoltage ); 
-	    *Voltage=*prevVoltage;
-	    *VoltageTime=*prevVoltageTime; 
-	    return 1;           
-    }  
-    else 
-    {
-	    *prevVoltage = *Voltage;
-	    *prevVoltageTime = *VoltageTime;            
-	    return 0;
-    }
+	const float maxRateOfChange = 1;
+	
+	float deltaSeconds = (*VoltageTime) - (*prevVoltageTime);	
+	float deltaVoltage = (*Voltage) - (*prevVoltage); 
+	deltaVoltage = deltaVoltage < 0 ? -1 * deltaVoltage : deltaVoltage;	 //use abs value
+		
+	// eg. if the voltage changes by more than 1 volt over 100 sec a spike has occured
+	if( deltaVoltage / deltaSeconds > maxRateOfChange )
+	{
+		syslog ( LOG_ERR, "Voltage spike from: %dV to: %dV in %d seconds. Using prevVoltage: %dV", *prevVoltage, *Voltage, (int)deltaSeconds, *prevVoltage ); 
+		*Voltage=*prevVoltage;
+		*VoltageTime=*prevVoltageTime; 
+		return 1;		   
+	}  
+	else 
+	{
+		*prevVoltage = *Voltage;
+		*prevVoltageTime = *VoltageTime;			
+		return 0;
+	}
 }
-        
+		
 char* getStateDesc(int state)
 {
-    if ( state == INIT )
-        return "Initialise";
-    else if ( state == STBYLONG )
-        return "STBYLONG";
-    else if ( state == STBYSHORT )
-        return "STBYSHORT";
-    else if ( state == OVERRIDE )
-        return "OVERRIDE"; 
-    else if ( state == SLEEP )
-        return "SLEEP";
-    else if ( state == UP )
-        return "UP";     
-    else    
-        return "INVALID STATE";            
-}         
-        
-int test_interfacekit(const char *progName, FILE *logfile, const char *snapFileName, char * bootflag, time_t boottime, int sleepTime, int sleepHourStart, int sleepHourEnd)
+	if ( state == INIT )
+		return "Initialise";
+	else if ( state == STBYLONG )
+		return "STBYLONG";
+	else if ( state == STBYSHORT )
+		return "STBYSHORT";
+	else if ( state == OVERRIDE )
+		return "OVERRIDE"; 
+	else if ( state == SLEEP )
+		return "SLEEP";
+	else if ( state == UP )
+		return "UP";	 
+	else	
+		return "INVALID STATE";			
+}		 
+		
+int test_interfacekit(const char *progName,
+	FILE *logfile,
+	const char *snapFileName,
+	char * bootflag,
+	time_t boottime,
+	int sleepTime,
+	int sleepHourStart,
+	int sleepMinStart,
+	int sleepHourEnd,
+	int sleepMinEnd)
 {
-    syslog ( LOG_DEBUG, 
-            "test_interfacekit called with args: progName=%s, logfile=..., snapFileName=%s, bootflag=%s, boottime=..., sleepTime=%d",
-            progName, snapFileName, bootflag, sleepTime);
-    
-    int err;
-    int lightTrigger;
-    int prevVoltage = 0, Voltage = 0, Amps = 0;
-    int tts;
-    int newState = 0;
-    int ret;
-    int spiking;
-    int spikecount;
-    
-    time_t timenow, prevVoltageTime, VoltageTime;
-    
-    const int bufferSize = 21;//there is only space for 20 char on each line of the LCD
-    char buffer0 [bufferSize];
-    char buffer1 [bufferSize];
-    char *wakeTimeStr = malloc(20);
+	syslog ( LOG_DEBUG, 
+			"test_interfacekit called with args: progName=%s, logfile=..., snapFileName=%s, bootflag=%s, boottime=..., sleepTime=%d",
+			progName, snapFileName, bootflag, sleepTime);
+	
+	int err;
+	int lightTrigger;
+	int prevVoltage = 0, Voltage = 0, Amps = 0;
+	int tts;
+	int newState = 0;
+	int ret;
+	int spiking;
+	int spikecount;
+	
+	time_t timenow, prevVoltageTime, VoltageTime;
+	
+	const int bufferSize = 21;//there is only space for 20 char on each line of the LCD
+	char buffer0 [bufferSize];
+	char buffer1 [bufferSize];
+	char *wakeTimeStr = malloc(20);
 
-    CPhidgetInterfaceKitHandle IFK = 0;
-    CPhidgetInterfaceKit_create(&IFK);
+	CPhidgetInterfaceKitHandle IFK = 0;
+	CPhidgetInterfaceKit_create(&IFK);
+
+	CPhidgetTextLCDHandle LCD = 0;
+	CPhidgetTextLCD_create (&LCD);
+	
+	/******************************************************************************************/
+	
+	//CPhidget_enableLogging(PHIDGET_LOG_VERBOSE, NULL);
+	
+	setHandlers(IFK, LCD);	// Set up handlers for the Interface Kit & TextLCD
 
-    CPhidgetTextLCDHandle LCD = 0;
-    CPhidgetTextLCD_create (&LCD);
-    
-    /******************************************************************************************/
-    
-    //CPhidget_enableLogging(PHIDGET_LOG_VERBOSE, NULL);
-    
-    setHandlers(IFK, LCD);    // Set up handlers for the Interface Kit & TextLCD
+	CPhidget_open((CPhidgetHandle)IFK, -1);
+	CPhidget_open((CPhidgetHandle)LCD, -1);
 
-    CPhidget_open((CPhidgetHandle)IFK, -1);
-    CPhidget_open((CPhidgetHandle)LCD, -1);
+	//get the program to wait 10 seconds for an TextLCD device to be attached
+	syslog ( LOG_DEBUG, "Waiting %d seconds for LCD to be attached...", LCD_WAIT_TIME/1000 );	
+	if( (err = CPhidget_waitForAttachment((CPhidgetHandle)LCD, LCD_WAIT_TIME)) != EPHIDGET_OK )
+	{
+		const char *errStr;
+		CPhidget_getErrorDescription(err, &errStr);
+		syslog ( LOG_ERR, "Error waiting for LCD attachment: %d %s", err, errStr ); 
+		
+		closeCPhidget((CPhidgetHandle)IFK);
+		closeCPhidget((CPhidgetHandle)LCD);
+		return -1;
+	}
+	//display_LCD_properties(LCD);	//Display the properties of the attached Text LCD device
+	
+	//Set the LCD startup screen   
+	snprintf (buffer0, bufferSize, "Welcome to N4C");
+	snprintf (buffer1, bufferSize, "Loading...");
+
+	CPhidgetTextLCD_setDisplayString (LCD, 0, buffer0); 
+	CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);		
+	
+	//wait 5 seconds for attachment of the Interface Kit
+	syslog ( LOG_DEBUG, "Waiting %d seconds for IFK to be attached...", IFK_WAIT_TIME/1000 );
+	if( (err = CPhidget_waitForAttachment((CPhidgetHandle)IFK, IFK_WAIT_TIME)) != EPHIDGET_OK )
+	{
+		const char *errStr;
+		CPhidget_getErrorDescription( err, &errStr );
+		syslog ( LOG_ERR, "Error waiting for IFK attachment: %d %s", err, errStr );		   
 
-    //get the program to wait 10 seconds for an TextLCD device to be attached
-    syslog ( LOG_DEBUG, "Waiting %d seconds for LCD to be attached...", LCD_WAIT_TIME/1000 );    
-    if( (err = CPhidget_waitForAttachment((CPhidgetHandle)LCD, LCD_WAIT_TIME)) != EPHIDGET_OK )
-    {
-        const char *errStr;
-        CPhidget_getErrorDescription(err, &errStr);
-        syslog ( LOG_ERR, "Error waiting for LCD attachment: %d %s", err, errStr ); 
-        
-        closeCPhidget((CPhidgetHandle)IFK);
-        closeCPhidget((CPhidgetHandle)LCD);
-        return -1;
-    }
-    //display_LCD_properties(LCD);    //Display the properties of the attached Text LCD device
-    
-    //Set the LCD startup screen   
-    snprintf (buffer0, bufferSize, "Welcome to N4C");
-    snprintf (buffer1, bufferSize, "Loading...");
-
-    CPhidgetTextLCD_setDisplayString (LCD, 0, buffer0); 
-    CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);        
-    
-    //wait 5 seconds for attachment of the Interface Kit
-    syslog ( LOG_DEBUG, "Waiting %d seconds for IFK to be attached...", IFK_WAIT_TIME/1000 );
-    if( (err = CPhidget_waitForAttachment((CPhidgetHandle)IFK, IFK_WAIT_TIME)) != EPHIDGET_OK )
-    {
-        const char *errStr;
-        CPhidget_getErrorDescription( err, &errStr );
-        syslog ( LOG_ERR, "Error waiting for IFK attachment: %d %s", err, errStr );           
+		closeCPhidget((CPhidgetHandle)IFK);
+		closeCPhidget((CPhidgetHandle)LCD);
+		return -1;
+	}
+	//display_IFK_properties(IFK);	//Display the properties of the attached Interface Kit device
+	
+	CPhidgetInterfaceKit_getSensorChangeTrigger (IFK, 0, &lightTrigger);
+	
+	/******************************************************************************************/
+	
+	time (&prevVoltageTime);			//initialise previous voltage time 
+	prevVoltage = getVoltage(IFK);	  //ininitalise voltage		
+		
+	spiking = 1;
+	spikecount = 0;
+	while ( spiking ) 
+	{
+		sleep(10);
+		time (&VoltageTime);
+		Voltage = getVoltage(IFK); 
+		spiking = testVoltageSpike(&prevVoltage, &prevVoltageTime, &Voltage, &VoltageTime);   
+		
+		if ( spiking ) 
+			syslog ( LOG_ERR, "Initial voltage spike occured - acquiring new voltage to retest" );	
+			
+		if ( spikecount++ > SPIKELIMIT ) 
+		{
+			syslog ( LOG_ERR, "Error initial voltage spike continuing after %d tests, closing program", spikecount );
+						   
+			snprintf (buffer0, bufferSize, "Voltage Spike");
+			snprintf (buffer1, bufferSize, "Power App Restart");
 
-        closeCPhidget((CPhidgetHandle)IFK);
-        closeCPhidget((CPhidgetHandle)LCD);
-        return -1;
-    }
-    //display_IFK_properties(IFK);    //Display the properties of the attached Interface Kit device
-    
-    CPhidgetInterfaceKit_getSensorChangeTrigger (IFK, 0, &lightTrigger);
-    
-    /******************************************************************************************/
-    
-    time (&prevVoltageTime);            //initialise previous voltage time 
-    prevVoltage = getVoltage(IFK);      //ininitalise voltage        
-        
-    spiking = 1;
-    spikecount = 0;
-    while ( spiking ) 
-    {
-        sleep(10);
-        time (&VoltageTime);
-        Voltage = getVoltage(IFK); 
-	    spiking = testVoltageSpike(&prevVoltage, &prevVoltageTime, &Voltage, &VoltageTime);   
-	    
-	    if ( spiking ) 
-    	    syslog ( LOG_ERR, "Initial voltage spike occured - acquiring new voltage to retest" );    
-            
-        if ( spikecount++ > SPIKELIMIT ) 
-        {
-            syslog ( LOG_ERR, "Error initial voltage spike continuing after %d tests, closing program", spikecount );
-                           
-            snprintf (buffer0, bufferSize, "Voltage Spike");
-            snprintf (buffer1, bufferSize, "Power App Restart");
+			CPhidgetTextLCD_setDisplayString (LCD, 0, buffer0); 
+			CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);  
+			
+			closeCPhidget((CPhidgetHandle)IFK);
+			closeCPhidget((CPhidgetHandle)LCD); 
+			return 1;
+		}		 
+	}
+	
+	while(1)
+	{		  
+		time (&VoltageTime);
+		Voltage = getVoltage(IFK);			 
+		spiking = testVoltageSpike(&prevVoltage, &prevVoltageTime, &Voltage, &VoltageTime);
+		
+		Amps = getAmps(IFK);
 
-            CPhidgetTextLCD_setDisplayString (LCD, 0, buffer0); 
-            CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);  
-            
-            closeCPhidget((CPhidgetHandle)IFK);
-            closeCPhidget((CPhidgetHandle)LCD); 
-            return 1;
-        }         
-    }
-    
-    while(1)
-    {          
-        time (&VoltageTime);
-        Voltage = getVoltage(IFK);             
-        spiking = testVoltageSpike(&prevVoltage, &prevVoltageTime, &Voltage, &VoltageTime);
-        
-        Amps = getAmps(IFK);
+		getnewState (Voltage,
+			bootflag,
+			&newState,
+			sleepHourStart,
+			sleepMinStart,
+			sleepHourEnd,
+			sleepMinEnd);
 
-        getnewState (Voltage, bootflag, &newState, sleepHourStart, sleepHourEnd);
-
-        updateLogfile (logfile, Voltage, Amps, newState, spiking, progName);
-        updateSnapshotfile (snapFileName, Voltage, Amps, newState, spiking);
+		updateLogfile (logfile, Voltage, Amps, newState, spiking, progName);
+		updateSnapshotfile (snapFileName, Voltage, Amps, newState, spiking);
 
-        // Now Update the LCD
-        getTimeString (0, wakeTimeStr);
-        snprintf (buffer0, bufferSize, "V:%4d A:%-5d %s", Voltage, Amps,wakeTimeStr);
-        snprintf (buffer1, bufferSize, "%-s", getStateDesc(newState));
+		// Now Update the LCD
+		getTimeString (0, wakeTimeStr);
+		snprintf (buffer0, bufferSize, "V:%4d A:%-5d %s", Voltage, Amps,wakeTimeStr);
+		snprintf (buffer1, bufferSize, "%-s", getStateDesc(newState));
 
-        CPhidgetTextLCD_setDisplayString (LCD, 0, buffer0);
-        CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);
-    
-        // Do what the state demands        
-        syslog ( LOG_DEBUG, "Begin main while loop: State is %s", getStateDesc(newState) ); 
-        
-        if(newState == STBYLONG)
-        {
-            // sleep for 3 hours, then wake, reboot
-            getTimeString (STBYLONG_TIME, wakeTimeStr);
-            snprintf (buffer1, bufferSize, "%-s Wake@%-s", getStateDesc(newState), wakeTimeStr);
-            
-            CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);
-        
-            syslog ( LOG_NOTICE, "Going to STBYLONG, back at: %s", wakeTimeStr);
-            
-            if ( (ret = system ("/etc/stbylong.sh")) != 0 );
-                syslog ( LOG_ERR, "STBYLONG failed to run. Error: %d", ret);    
-                
-            closeCPhidget((CPhidgetHandle)IFK);
-            closeCPhidget((CPhidgetHandle)LCD);    
-            return 0;       
-        }
-        else if(newState == STBYSHORT)
-        {
-            // sleep for 30 mins, then wake, reboot
-            getTimeString (STBYSHORT_TIME, wakeTimeStr);
-            snprintf (buffer1, bufferSize, "%-s Wake@%-s", getStateDesc(newState), wakeTimeStr);
+		CPhidgetTextLCD_setDisplayString (LCD, 0, buffer0);
+		CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);
+	
+		// Do what the state demands		
+		syslog ( LOG_DEBUG, "Begin main while loop: State is %s", getStateDesc(newState) ); 
+		
+		if(newState == STBYLONG)
+		{
+			// sleep for 3 hours, then wake, reboot
+			getTimeString (STBYLONG_TIME, wakeTimeStr);
+			snprintf (buffer1, bufferSize, "%-s Wake@%-s", getStateDesc(newState), wakeTimeStr);
+			
+			CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);
+		
+			syslog ( LOG_NOTICE, "Going to STBYLONG, back at: %s", wakeTimeStr);
+			
+			if ( (ret = system ("/etc/stbylong.sh")) != 0 );
+				syslog ( LOG_ERR, "STBYLONG failed to run. Error: %d", ret);	
+				
+			closeCPhidget((CPhidgetHandle)IFK);
+			closeCPhidget((CPhidgetHandle)LCD);	
+			return 0;	   
+		}
+		else if(newState == STBYSHORT)
+		{
+			// sleep for 30 mins, then wake, reboot
+			getTimeString (STBYSHORT_TIME, wakeTimeStr);
+			snprintf (buffer1, bufferSize, "%-s Wake@%-s", getStateDesc(newState), wakeTimeStr);
 
-            CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);
-        
-            syslog ( LOG_NOTICE, "Going to STBYSHORT, back at: %s", wakeTimeStr);
-            
-            if ( (ret = system ("/etc/stbyshort.sh")) != 0) 
-                syslog ( LOG_ERR, "STBYSHORT failed to run. Error: %d", ret);      
+			CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);
+		
+			syslog ( LOG_NOTICE, "Going to STBYSHORT, back at: %s", wakeTimeStr);
+			
+			if ( (ret = system ("/etc/stbyshort.sh")) != 0) 
+				syslog ( LOG_ERR, "STBYSHORT failed to run. Error: %d", ret);	  
 
-            closeCPhidget((CPhidgetHandle)IFK);
-            closeCPhidget((CPhidgetHandle)LCD);                
-            return 0;                                 
-        }
-        else if(newState == OVERRIDE)                
-        {
-            // stay up for OVERRIDE_TIME, then sleep, wake, reboot
-            time (&timenow);
-            tts = OVERRIDE_TIME - (timenow - boottime);
-            syslog ( LOG_DEBUG, "In OVERRIDE %d sec to sleep", tts ); 
-            
-            snprintf (buffer1, bufferSize, "%-s Time:%dmin", getStateDesc(newState), (tts/60)+1);
-            CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);
-    
-            if (timenow > boottime + OVERRIDE_TIME) 
-            {
-                syslog ( LOG_INFO, "OVERRIDE %d mins expired, switching to normal mode", OVERRIDE_TIME/60 );                 
-                snprintf(bootflag, 2, BOOTFLAG_NORMAL);
-            }      
-        }
-        else if(newState == SLEEP)
-        {
-            // We're running during night time - go to sleep
-            snprintf (buffer1, bufferSize, "%-s Wake@%2d:00", getStateDesc(newState), sleepHourEnd);
+			closeCPhidget((CPhidgetHandle)IFK);
+			closeCPhidget((CPhidgetHandle)LCD);				
+			return 0;								 
+		}
+		else if(newState == OVERRIDE)				
+		{
+			// stay up for OVERRIDE_TIME, then sleep, wake, reboot
+			time (&timenow);
+			tts = OVERRIDE_TIME - (timenow - boottime);
+			syslog ( LOG_DEBUG, "In OVERRIDE %d sec to sleep", tts ); 
+			
+			snprintf (buffer1, bufferSize, "%-s Time:%dmin", getStateDesc(newState), (tts/60)+1);
+			CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);
+	
+			if (timenow > boottime + OVERRIDE_TIME) 
+			{
+				syslog ( LOG_INFO, "OVERRIDE %d mins expired, switching to normal mode", OVERRIDE_TIME/60 );				 
+				snprintf(bootflag, 2, BOOTFLAG_NORMAL);
+			}	  
+		}
+		else if(newState == SLEEP)
+		{
+			// We're running during night time - go to sleep
+			snprintf (buffer1, bufferSize, "%-s Wake@%2d:%02d", 
+				getStateDesc(newState), sleepHourEnd,sleepMinEnd);
 
-            CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);
-        
-            syslog ( LOG_NOTICE, "Going to SLEEPRTC, back at: %s", wakeTimeStr);  
-            
-            if ( (ret = system ("/etc/sleeprtc.sh")) != 0 ) 
-                syslog ( LOG_ERR, "SLEEPRTC failed to run. Error: %d", ret);  
-                
-            closeCPhidget((CPhidgetHandle)IFK);
-            closeCPhidget((CPhidgetHandle)LCD);
-            return 0;
-        }
-        else if(newState == UP)
-        {
-            // normal running here
-            syslog ( LOG_DEBUG, "In UP state" ); 
-        }
-        else
-            syslog ( LOG_ERR, "Error invalid state: %d", newState);
+			CPhidgetTextLCD_setDisplayString (LCD, 1, buffer1);
+		
+			char rtccmd[PATH_MAX];
+			snprintf(rtccmd,PATH_MAX,"/etc/sleeprtc.sh %02d:%02d",
+					sleepHourEnd,sleepMinEnd);
+			syslog ( LOG_NOTICE, "Going to SLEEPRTC, back at: %s, cmd: %s", 
+				wakeTimeStr,rtccmd);  
+	  
+			if ( (ret = system (rtccmd)) != 0 ) 
+				syslog ( LOG_ERR, "SLEEPRTC failed to run. Error: %d", ret);  
+				
+			closeCPhidget((CPhidgetHandle)IFK);
+			closeCPhidget((CPhidgetHandle)LCD);
+			return 0;
+		}
+		else if(newState == UP)
+		{
+			// normal running here
+			syslog ( LOG_DEBUG, "In UP state" ); 
+		}
+		else
+			syslog ( LOG_ERR, "Error invalid state: %d", newState);
 
-        fflush (stdout);
-        sleep (sleepTime);
+		fflush (stdout);
+		sleep (sleepTime);
 
-    }//end while    
+	}//end while	
 }
 
--- a/stateManager.h	Fri Jun 04 17:21:55 2010 +0100
+++ b/stateManager.h	Fri Jun 18 14:17:01 2010 +0000
@@ -50,17 +50,45 @@
 int getVoltage(CPhidgetInterfaceKitHandle IFK);
 int getAmps(CPhidgetInterfaceKitHandle IFK);
 
-int updateSnapshotfile(const char *snapFileName, int Voltage, int Amps, int state, int spiking);
-int updateLogfile(FILE *logfile, int Voltage, int Amps, int state, int spiking, const char *progName);
+int updateSnapshotfile(const char *snapFileName,
+	int Voltage,
+	int Amps,
+	int state,
+	int spiking);
+int updateLogfile(FILE *logfile,
+	int Voltage,
+	int Amps,
+	int state,
+	int spiking,
+	const char *progName);
 
-void getTimeString (int wakeTime, char *wakeTimeStr);
-void getnewState(int Voltage, const char *bootflag, int *newState, int sleepHourStart, int sleepHourEnd);
+void getTimeString (int wakeTime,
+	char *wakeTimeStr);
+void getnewState(int Voltage,
+	const char *bootflag,
+	int *newState,
+	int sleepHourStart,
+	int sleepMinStart,
+	int sleepHourEnd,
+	int sleepMinEnd);
 void closeCPhidget(CPhidgetHandle handle);
-int testVoltageSpike(int *prevVoltage, time_t *prevVoltageTime, int *Voltage, time_t *VoltageTime);
+int testVoltageSpike(int *prevVoltage,
+	time_t *prevVoltageTime,
+	int *Voltage,
+	time_t *VoltageTime);
 
 char* getStateDesc(int state);
 
-int test_interfacekit(const char *progName, FILE *logfile, const char *snapFileName, char * bootflag, time_t boottime, int sleepTime, int sleepHourStart, int sleepHourEnd);
+int test_interfacekit(const char *progName,
+	FILE *logfile,
+	const char *snapFileName,
+	char * bootflag,
+	time_t boottime,
+	int sleepTime,
+	int sleepHourStart,
+	int sleepMinStart,
+	int sleepHourEnd,
+	int sleepMinEnd);
 
 #endif