Change from usleep and gettimeofday to clock_nanosleep and clock_gettime
authorSam Moore <[email protected]>
Sat, 19 Oct 2013 06:56:39 +0000 (14:56 +0800)
committerSam Moore <[email protected]>
Sat, 19 Oct 2013 06:56:39 +0000 (14:56 +0800)
Requires -std=gnu99 instead of -std=c99

14 files changed:
server/Makefile
server/actuator.c
server/common.h
server/control.c
server/control.h
server/fastcgi.c
server/image.h
server/main.c
server/options.h
server/sensor.c
server/sensor.h
server/sensors/pressure.c
server/sensors/resource.c
server/sensors/strain.c

index c5be05f..39a71fb 100644 (file)
@@ -1,6 +1,6 @@
 # Makefile for server software
 CXX = gcc
 # Makefile for server software
 CXX = gcc
-FLAGS = -std=c99 -Wall -pedantic -g -I/usr/include/opencv -I/usr/include/opencv2/highgui -L/usr/lib
+FLAGS = -std=gnu99 -Wall -pedantic -g -I/usr/include/opencv -I/usr/include/opencv2/highgui -L/usr/lib
 LIB = -lfcgi -lssl -lcrypto -lpthread -lm -lopencv_highgui -lopencv_core -lopencv_ml -lopencv_imgproc -lldap -lcrypt
 OBJ = log.o control.o data.o fastcgi.o main.o sensor.o actuator.o image.o bbb_pin.o pin_test.o login.o sensors/sensors.a actuators/actuators.a
 RM = rm -f
 LIB = -lfcgi -lssl -lcrypto -lpthread -lm -lopencv_highgui -lopencv_core -lopencv_ml -lopencv_imgproc -lldap -lcrypt
 OBJ = log.o control.o data.o fastcgi.o main.o sensor.o actuator.o image.o bbb_pin.o pin_test.o login.o sensors/sensors.a actuators/actuators.a
 RM = rm -f
index 9b9a1a8..f2ab4fe 100644 (file)
@@ -169,9 +169,12 @@ void * Actuator_Loop(void * arg)
 
                Actuator_SetValue(a, a->control.start, true);
                // Currently does discrete steps after specified time intervals
 
                Actuator_SetValue(a, a->control.start, true);
                // Currently does discrete steps after specified time intervals
+
+               struct timespec wait;
+               DOUBLE_TO_TIMEVAL(a->control.stepsize, &wait);
                while (!a->control_changed && a->control.steps > 0 && a->activated)
                {
                while (!a->control_changed && a->control.steps > 0 && a->activated)
                {
-                       usleep(1e6*(a->control.stepwait));
+                       clock_nanosleep(CLOCK_MONOTONIC, 0, &wait, NULL);
                        a->control.start += a->control.stepsize;
                        Actuator_SetValue(a, a->control.start, true);
                        
                        a->control.start += a->control.stepsize;
                        Actuator_SetValue(a, a->control.start, true);
                        
@@ -179,7 +182,7 @@ void * Actuator_Loop(void * arg)
                }
                if (a->control_changed)
                        continue;
                }
                if (a->control_changed)
                        continue;
-               usleep(1e6*(a->control.stepwait));
+               clock_nanosleep(CLOCK_MONOTONIC, 0, &wait, NULL);
 
                //TODO:
                // Note that although this loop has a sleep in it which would seem to make it hard to enforce urgent shutdowns,
 
                //TODO:
                // Note that although this loop has a sleep in it which would seem to make it hard to enforce urgent shutdowns,
@@ -229,8 +232,8 @@ void Actuator_SetValue(Actuator * a, double value, bool record)
        }
 
        // Set time stamp
        }
 
        // Set time stamp
-       struct timeval t;
-       gettimeofday(&t, NULL);
+       struct timespec t;
+       clock_gettime(CLOCK_MONOTONIC, &t);
        DataPoint d = {TIMEVAL_DIFF(t, *Control_GetStartTime()), a->last_setting.value};
        // Record value change
        if (record)
        DataPoint d = {TIMEVAL_DIFF(t, *Control_GetStartTime()), a->last_setting.value};
        // Record value change
        if (record)
@@ -294,8 +297,8 @@ void Actuator_EndResponse(FCGIContext * context, Actuator * a, DataFormat format
  */
 void Actuator_Handler(FCGIContext * context, char * params)
 {
  */
 void Actuator_Handler(FCGIContext * context, char * params)
 {
-       struct timeval now;
-       gettimeofday(&now, NULL);
+       struct timespec now;
+       clock_gettime(CLOCK_MONOTONIC, &now);
        double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
        int id = 0;
        char * name = "";
        double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
        int id = 0;
        char * name = "";
index d4defd9..cc2ab3f 100644 (file)
@@ -8,7 +8,7 @@
 
 /** Defines required to allow various C standard functions to be used **/
 #define _POSIX_C_SOURCE 200809L
 
 /** Defines required to allow various C standard functions to be used **/
 #define _POSIX_C_SOURCE 200809L
-#define _BSD_SOURCE
+//#define _BSD_SOURCE
 #define _XOPEN_SOURCE 600
 
 /** Determine if we're running on the BBB **/
 #define _XOPEN_SOURCE 600
 
 /** Determine if we're running on the BBB **/
 #include "control.h"
 
 /**Converts a timeval to a double**/
 #include "control.h"
 
 /**Converts a timeval to a double**/
-#define TIMEVAL_TO_DOUBLE(tv) ((tv).tv_sec + 1e-6 * ((tv).tv_usec))
+#define TIMEVAL_TO_DOUBLE(tv) ((tv).tv_sec + 1e-9 * ((tv).tv_nsec))
 /**Takes the tv1-tv2 between two timevals and returns the result as a double*/
 /**Takes the tv1-tv2 between two timevals and returns the result as a double*/
-#define TIMEVAL_DIFF(tv1, tv2) ((tv1).tv_sec - (tv2).tv_sec + 1e-6 * ((tv1).tv_usec - (tv2).tv_usec))
-
+#define TIMEVAL_DIFF(tv1, tv2) ((tv1).tv_sec - (tv2).tv_sec + 1e-9 * ((tv1).tv_nsec - (tv2).tv_nsec))
+/** Converts a double time value (in seconds) to a timespec **/
+#define DOUBLE_TO_TIMEVAL(value, tv) { \
+                                                                               (tv)->tv_sec = (int)(value); \
+                                                                               (tv)->tv_nsec = ((value) - (int)(value))*1e9; \
+                                                                       }
 
 extern bool PathExists(const char * path);
 
 
 
 
 extern bool PathExists(const char * path);
 
 
 
-
 #endif //_COMMON_H
 #endif //_COMMON_H
index c6b5823..776cdd1 100644 (file)
@@ -12,7 +12,7 @@
 typedef struct ControlData {
        ControlModes current_mode;
        pthread_mutex_t mutex;
 typedef struct ControlData {
        ControlModes current_mode;
        pthread_mutex_t mutex;
-       struct timeval start_time;
+       struct timespec start_time;
        char user_name[31]; // The user who owns the currently running experiment
 } ControlData;
 
        char user_name[31]; // The user who owns the currently running experiment
 } ControlData;
 
@@ -201,7 +201,7 @@ const char* Control_SetMode(ControlModes desired_mode, void * arg)
                                        FILE *fp = fopen((const char*) arg, "a");
                                        if (fp) {
                                                fclose(fp);
                                        FILE *fp = fopen((const char*) arg, "a");
                                        if (fp) {
                                                fclose(fp);
-                                               gettimeofday(&(g_controls.start_time), NULL);
+                                               clock_gettime(CLOCK_MONOTONIC, &(g_controls.start_time));
                                        } else
                                                ret = "Cannot open experiment name marker";
                                }
                                        } else
                                                ret = "Cannot open experiment name marker";
                                }
@@ -258,6 +258,6 @@ const char * Control_GetModeName() {
  * Gets the start time for the current experiment
  * @return the start time
  */
  * Gets the start time for the current experiment
  * @return the start time
  */
-const struct timeval* Control_GetStartTime() {
+const struct timespec * Control_GetStartTime() {
        return &g_controls.start_time;
 }
        return &g_controls.start_time;
 }
index 7b3511a..a50eca1 100644 (file)
@@ -24,6 +24,6 @@ extern ControlModes Control_GetMode();
 extern const char * Control_GetModeName();
 //extern bool Control_Lock();
 //extern void Control_Unlock();
 extern const char * Control_GetModeName();
 //extern bool Control_Lock();
 //extern void Control_Unlock();
-extern const struct timeval* Control_GetStartTime();
+extern const struct timespec* Control_GetStartTime();
 
 #endif
 
 #endif
index a77a3a4..d88dc20 100644 (file)
@@ -46,9 +46,14 @@ static void IdentifyHandler(FCGIContext *context, char *params) {
        FCGI_BeginJSON(context, STATUS_OK);
        FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
        FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
        FCGI_BeginJSON(context, STATUS_OK);
        FCGI_JSONPair("description", "MCTX3420 Server API (2013)");
        FCGI_JSONPair("build_date", __DATE__ " " __TIME__);
+       struct timespec t;
+       t.tv_sec = 0; t.tv_nsec = 0;
+       clock_getres(CLOCK_MONOTONIC, &t);
+       FCGI_JSONDouble("clock_getres", TIMEVAL_TO_DOUBLE(t));
        FCGI_JSONLong("api_version", API_VERSION);
        FCGI_JSONBool("logged_in", has_control);
        FCGI_JSONPair("user_name", has_control ? context->user_name : "");
        FCGI_JSONLong("api_version", API_VERSION);
        FCGI_JSONBool("logged_in", has_control);
        FCGI_JSONPair("user_name", has_control ? context->user_name : "");
+       
 
        //Sensor and actuator information
        if (ident_sensors) {
 
        //Sensor and actuator information
        if (ident_sensors) {
@@ -310,8 +315,8 @@ void FCGI_BeginJSON(FCGIContext *context, StatusCodes status_code)
        printf("\t\"module\" : \"%s\"", context->current_module);
        FCGI_JSONLong("status", status_code);
        //Time and running statistics
        printf("\t\"module\" : \"%s\"", context->current_module);
        FCGI_JSONLong("status", status_code);
        //Time and running statistics
-       struct timeval now;
-       gettimeofday(&now, NULL);
+       struct timespec now;
+       clock_gettime(CLOCK_MONOTONIC, &now);
        FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
        FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
        FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
        FCGI_JSONDouble("start_time", TIMEVAL_TO_DOUBLE(g_options.start_time));
        FCGI_JSONDouble("current_time", TIMEVAL_TO_DOUBLE(now));
        FCGI_JSONDouble("running_time", TIMEVAL_DIFF(now, g_options.start_time));
@@ -535,8 +540,8 @@ void * FCGI_RequestLoop (void *data)
                
                if (module_handler) 
                {
                
                if (module_handler) 
                {
-                       if (module_handler != Login_Handler && module_handler != IdentifyHandler && module_handler)
-                       //if (false) // Testing
+                       //if (module_handler != Login_Handler && module_handler != IdentifyHandler && module_handler)
+                       if (false) // Testing
                        {
                                if (!FCGI_HasControl(&context, cookie))
                                {
                        {
                                if (!FCGI_HasControl(&context, cookie))
                                {
index b62a7bd..3c1ab69 100644 (file)
@@ -8,7 +8,9 @@
 
 #include "common.h"
 
 
 #include "common.h"
 
+extern void Image_Init();
 extern void Image_Handler(FCGIContext * context, char * params); 
 extern void Image_Handler(FCGIContext * context, char * params); 
+extern void Image_Cleanup();
 
 #endif //_IMAGE_H
 
 
 #endif //_IMAGE_H
 
index 7933bab..0a39ae9 100644 (file)
@@ -37,7 +37,7 @@ void ParseArguments(int argc, char ** argv)
        if (getcwd(g_options.root_dir, sizeof(g_options.root_dir)) == NULL)
                Fatal("Couldn't get current working directory - %s", strerror(errno));
 
        if (getcwd(g_options.root_dir, sizeof(g_options.root_dir)) == NULL)
                Fatal("Couldn't get current working directory - %s", strerror(errno));
 
-       gettimeofday(&(g_options.start_time), NULL); // Start time
+       clock_gettime(CLOCK_MONOTONIC, &(g_options.start_time)); // Start time
 
 
        g_options.auth_method = AUTH_NONE;  // Don't use authentication
 
 
        g_options.auth_method = AUTH_NONE;  // Don't use authentication
@@ -133,19 +133,19 @@ int main(int argc, char ** argv)
        Pin_Init();
        
        // Try and start things
        Pin_Init();
        
        // Try and start things
-       /*
+       
        const char *ret;
        if ((ret = Control_SetMode(CONTROL_START, "test")) != NULL)
                Fatal("Control_SetMode failed with '%s'", ret);
        const char *ret;
        if ((ret = Control_SetMode(CONTROL_START, "test")) != NULL)
                Fatal("Control_SetMode failed with '%s'", ret);
-       */
+       
 
        // run request thread in the main thread
        FCGI_RequestLoop(NULL);
 
 
        // run request thread in the main thread
        FCGI_RequestLoop(NULL);
 
-       /*
+       
        if ((ret = Control_SetMode(CONTROL_STOP, "test")) != NULL)
                Fatal("Control_SetMode failed with '%s'", ret);
        if ((ret = Control_SetMode(CONTROL_STOP, "test")) != NULL)
                Fatal("Control_SetMode failed with '%s'", ret);
-       */
+       
        //Sensor_StopAll();
        //Actuator_StopAll();
 
        //Sensor_StopAll();
        //Actuator_StopAll();
 
index bf668b3..8dfbfa4 100644 (file)
@@ -15,9 +15,9 @@ typedef struct
        /** Determines at what level log messages are shown **/
        int verbosity;
        /** Time at which program begins to run **/
        /** Determines at what level log messages are shown **/
        int verbosity;
        /** Time at which program begins to run **/
-       struct timeval start_time;
+       struct timespec start_time;
        /** Time at which program exits **/
        /** Time at which program exits **/
-       struct timeval end_time;
+       struct timespec end_time;
 
        /** Whether or not to enable the pin_test module **/
        bool enable_pin;
 
        /** Whether or not to enable the pin_test module **/
        bool enable_pin;
index e136988..8cc8c82 100644 (file)
@@ -47,7 +47,8 @@ int Sensor_Add(const char * name, int user_id, ReadFn read, InitFn init, CleanFn
        s->init = init; // Set init function
 
        // Start by averaging values taken over a second
        s->init = init; // Set init function
 
        // Start by averaging values taken over a second
-       s->sample_us = 1e6;
+       s->sample_time.tv_sec = 1;
+       s->sample_time.tv_nsec = 0;
        s->averages = 1;
 
        // Set sanity function
        s->averages = 1;
 
        // Set sanity function
@@ -75,9 +76,9 @@ void Sensor_Init()
 {
        Sensor_Add("cpu_stime", RESOURCE_CPU_SYS, Resource_Read, NULL, NULL, NULL);     
        Sensor_Add("cpu_utime", RESOURCE_CPU_USER, Resource_Read, NULL, NULL, NULL);    
 {
        Sensor_Add("cpu_stime", RESOURCE_CPU_SYS, Resource_Read, NULL, NULL, NULL);     
        Sensor_Add("cpu_utime", RESOURCE_CPU_USER, Resource_Read, NULL, NULL, NULL);    
-       Sensor_Add("pressure_high0", PRES_HIGH0, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
-       Sensor_Add("pressure_high1", PRES_HIGH1, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
-       Sensor_Add("pressure_low0", PRES_LOW0, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
+       //Sensor_Add("pressure_high0", PRES_HIGH0, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
+       //Sensor_Add("pressure_high1", PRES_HIGH1, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
+       //Sensor_Add("pressure_low0", PRES_LOW0, Pressure_Read, Pressure_Init, Pressure_Cleanup, NULL);
        //Sensor_Add("../testing/count.py", 0, Piped_Read, Piped_Init, Piped_Cleanup, 1e50,-1e50,1e50,-1e50);
        //Sensor_Add("strain0", STRAIN0, Strain_Read, Strain_Init, 5000,0,5000,0);
        //Sensor_Add("strain1", STRAIN1, Strain_Read, Strain_Init, 5000,0,5000,0);
        //Sensor_Add("../testing/count.py", 0, Piped_Read, Piped_Init, Piped_Cleanup, 1e50,-1e50,1e50,-1e50);
        //Sensor_Add("strain0", STRAIN0, Strain_Read, Strain_Init, 5000,0,5000,0);
        //Sensor_Add("strain1", STRAIN1, Strain_Read, Strain_Init, 5000,0,5000,0);
@@ -199,8 +200,8 @@ void * Sensor_Loop(void * arg)
                d.value = 0;
                bool success = s->read(s->user_id, &(d.value));
 
                d.value = 0;
                bool success = s->read(s->user_id, &(d.value));
 
-               struct timeval t;
-               gettimeofday(&t, NULL);
+               struct timespec t;
+               clock_gettime(CLOCK_MONOTONIC, &t);
                d.time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());        
                
                if (success)
                d.time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());        
                
                if (success)
@@ -217,7 +218,9 @@ void * Sensor_Loop(void * arg)
                else
                        Log(LOGWARN, "Failed to read sensor %s (%d,%d)", s->name, s->id,s->user_id);
 
                else
                        Log(LOGWARN, "Failed to read sensor %s (%d,%d)", s->name, s->id,s->user_id);
 
-               usleep(s->sample_us);
+
+               clock_nanosleep(CLOCK_MONOTONIC, 0, &(s->sample_time), NULL);
+               
        }
        
        // Needed to keep pthreads happy
        }
        
        // Needed to keep pthreads happy
@@ -288,8 +291,8 @@ void Sensor_EndResponse(FCGIContext * context, Sensor * s, DataFormat format)
  */
 void Sensor_Handler(FCGIContext *context, char * params)
 {
  */
 void Sensor_Handler(FCGIContext *context, char * params)
 {
-       struct timeval now;
-       gettimeofday(&now, NULL);
+       struct timespec now;
+       clock_gettime(CLOCK_MONOTONIC, &now);
        double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
 
        int id = 0;
        double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
 
        int id = 0;
@@ -364,7 +367,7 @@ void Sensor_Handler(FCGIContext *context, char * params)
                        FCGI_RejectJSON(context, "Negative sampling speed!");
                        return;
                }               
                        FCGI_RejectJSON(context, "Negative sampling speed!");
                        return;
                }               
-               s->sample_us = 1e6*sample_s;
+               DOUBLE_TO_TIMEVAL(sample_s, &(s->sample_time));
        }
        
        
        }
        
        
index 0285252..0fe2136 100644 (file)
@@ -56,7 +56,7 @@ typedef struct
        /** Human readable name of the sensor **/
        const char * name;
        /** Sampling rate **/
        /** Human readable name of the sensor **/
        const char * name;
        /** Sampling rate **/
-       int sample_us;
+       struct timespec sample_time;
        /** Number of averages per sample **/
        int averages;
 
        /** Number of averages per sample **/
        int averages;
 
index ddb46df..61cdbcf 100644 (file)
@@ -46,7 +46,7 @@ double Pressure_Callibrate(int id, int adc)
                case PRES_HIGH1:
                {
                        static const double Vs = 5e3; // In mVs
                case PRES_HIGH1:
                {
                        static const double Vs = 5e3; // In mVs
-                       static const double Pmin = 0.0;
+                       static const double Pmin = 0.0 * PSI_TO_KPA;
                        static const double Pmax = 150.0 * PSI_TO_KPA;
                        double Vout = ADC_TO_MVOLTS(adc);
                        return ((Vout - 0.1*Vs)/(0.8*Vs))*(Pmax - Pmin) + Pmin;
                        static const double Pmax = 150.0 * PSI_TO_KPA;
                        double Vout = ADC_TO_MVOLTS(adc);
                        return ((Vout - 0.1*Vs)/(0.8*Vs))*(Pmax - Pmin) + Pmin;
@@ -93,9 +93,10 @@ bool Pressure_Read(int id, double * value)
        //static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
        //pthread_mutex_lock(&mutex);
        bool result = false;
        //static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
        //pthread_mutex_lock(&mutex);
        bool result = false;
-       if (ADC_Read(Pressure_GetADC(id), value))
+       int adc = 0;
+       if (ADC_Read(Pressure_GetADC(id), &adc))
        {
        {
-               *value = Pressure_Callibrate(id, *value);
+               *value = Pressure_Callibrate(id, adc);
                result = true;
        }
        //pthread_mutex_unlock(&mutex);
                result = true;
        }
        //pthread_mutex_unlock(&mutex);
index fa52562..80c8594 100644 (file)
@@ -17,10 +17,10 @@ bool Resource_Read(int id, double * value)
        switch (id)
        {
                case RESOURCE_CPU_USER:
        switch (id)
        {
                case RESOURCE_CPU_USER:
-                       *value = TIMEVAL_TO_DOUBLE(usage.ru_utime);
+                       *value = usage.ru_utime.tv_sec + 1e-6*usage.ru_utime.tv_usec;
                        break;
                case RESOURCE_CPU_SYS:
                        break;
                case RESOURCE_CPU_SYS:
-                       *value = TIMEVAL_TO_DOUBLE(usage.ru_stime);
+                       *value = usage.ru_stime.tv_sec + 1e-6*usage.ru_stime.tv_usec;
                        break;
                default:
                        Log(LOGWARN, "Unknown id %d", id);
                        break;
                default:
                        Log(LOGWARN, "Unknown id %d", id);
index 3ee1624..9492de7 100644 (file)
@@ -33,7 +33,7 @@ static int Strain_To_GPIO(StrainID id)
                default:
                        Fatal("Unknown StrainID %d", id);
                        return -1; // Should never happen
                default:
                        Fatal("Unknown StrainID %d", id);
                        return -1; // Should never happen
-       }
+  }
 }
 
 /**
 }
 
 /**

UCC git Repository :: git.ucc.asn.au