Merge branch 'master' of github:szmoore/MCTX3420
authorSam Moore <[email protected]>
Fri, 13 Sep 2013 13:47:02 +0000 (21:47 +0800)
committerSam Moore <[email protected]>
Fri, 13 Sep 2013 13:47:02 +0000 (21:47 +0800)
Conflicts:
server/data.c
server/sensor.c

It's pretty scary how much got automatically merged.
Almost as if git is sentient.

1  2 
server/data.c
server/data.h
server/fastcgi.c
server/sensor.c

diff --combined server/data.c
@@@ -14,9 -14,7 +14,8 @@@ void Data_Init(DataFile * df
  {
        // Everything is NULL
        df->filename = NULL;
-       df->read_file = NULL;
-       df->write_file = NULL;
 +      pthread_mutex_init(&(df->mutex), NULL);
+       df->file = NULL;
  }
  
  /**
@@@ -35,26 -33,12 +34,12 @@@ void Data_Open(DataFile * df, const cha
        // Set number of DataPoints
        df->num_points = 0; 
  
-       // Set write FILE*
-       df->write_file = fopen(filename, "wb+");
-       if (df->write_file == NULL)
+       // Set file pointer
+       df->file = fopen(filename, "wb+");
+       if (df->file == NULL)
        {
                Fatal("Error opening DataFile %s - %s", filename, strerror(errno));
        }
-       
-       // Set read FILE*
-       df->read_file = df->write_file;
-       //NOTE: Opening the same file in read mode gives funny results; fread generally reads less than expected
-       // The strerror is: "Transport endpoint is not connected"
-       /*
-       df->read_file = fopen(filename, "rb");
-       if (df->read_file == NULL)
-       {
-               Fatal("Error opening DataFile %s - %s", filename, strerror(errno));
-       }
-       */
  }
  
  /**
@@@ -67,11 -51,10 +52,10 @@@ void Data_Close(DataFile * df
  
        //TODO: Write data to TSV?
  
-       // Clear the FILE*s
-       df->read_file = NULL;
-       df->write_file = NULL;
+       fclose(df->file);
  
-       fclose(df->write_file);
+       // Clear the FILE*s
+       df->file = NULL;
  
        // Clear the filename
        free(df->filename);
   */
  void Data_Save(DataFile * df, DataPoint * buffer, int amount)
  {
-       pthread_mutex_unlock(&(df->mutex));
+       pthread_mutex_lock(&(df->mutex));
        assert(df != NULL);
        assert(buffer != NULL);
        assert(amount >= 0);
  
        // Go to the end of the file
-       if (fseek(df->write_file, 0, SEEK_END) < 0)
+       if (fseek(df->file, 0, SEEK_END) < 0)
        {
                Fatal("Error seeking to end of DataFile %s - %s", df->filename, strerror(errno));
        }
  
        // Attempt to write the DataPoints
-       int amount_written = fwrite(buffer, sizeof(DataPoint), amount, df->write_file);
+       int amount_written = fwrite(buffer, sizeof(DataPoint), amount, df->file);
        
        // Check if the correct number of points were written
        if (amount_written != amount)
        df->num_points += amount_written;
  
        pthread_mutex_unlock(&(df->mutex));
-       
  }
  
  /**
@@@ -132,21 -114,21 +115,21 @@@ int Data_Read(DataFile * df, DataPoint 
        
        // If we would read past the end of the file, reduce the amount of points to read
        
-               if (index + amount > df->num_points)
-               {
-                       Log(LOGDEBUG, "Requested %d points but will only read %d to get to EOF (%d)", amount, df->num_points - index, df->num_points);
-                       amount = df->num_points - index;
-               }
+       if (index + amount > df->num_points)
+       {
+               Log(LOGDEBUG, "Requested %d points but will only read %d to get to EOF (%d)", amount, df->num_points - index, df->num_points);
+               amount = df->num_points - index;
+       }
        
  
        // Go to position in file
-       if (fseek(df->read_file, index*sizeof(DataPoint), SEEK_SET))
+       if (fseek(df->file, index*sizeof(DataPoint), SEEK_SET))
        {
                Fatal("Error seeking to position %d in DataFile %s - %s", index, df->filename, strerror(errno));
        }
  
        // Attempt to read the DataPoints
-       int amount_read = fread(buffer, sizeof(DataPoint), amount, df->read_file);
+       int amount_read = fread(buffer, sizeof(DataPoint), amount, df->file);
  
        // Check if correct number of points were read
        if (amount_read != amount)
   * Print data points between two indexes using a given format
   * @param df - DataFile to print
   * @param start_index - Index to start at (inclusive)
-  * @param end_index - Index to end at (inclusive)
+  * @param end_index - Index to end at (exclusive)
   * @param format - The format to use
   */
  void Data_PrintByIndexes(DataFile * df, int start_index, int end_index, DataFormat format)
        assert(df != NULL);
        assert(start_index >= 0);
        assert(end_index >= 0);
-       assert(end_index <= df->num_points-1 || df->num_points == 0);
+       assert(end_index <= df->num_points || df->num_points == 0);
  
        const char * fmt_string; // Format for each data point
-       char seperator; // Character used to seperate successive data points
+       char separator; // Character used to seperate successive data points
        
-       // Determine what format string and seperator character to use
+       // Determine what format string and separator character to use
        switch (format)
        {
                case JSON:
                        fmt_string = "[%f,%f]";
-                       seperator = ',';
+                       separator = ',';
                        // For JSON we need an opening bracket
                        FCGI_PrintRaw("["); 
                        break;
                case TSV:
                        fmt_string = "%f\t%f";
-                       seperator = '\n';
+                       separator = '\n';
                        break;
        }
  
-       DataPoint buffer[DATA_BUFSIZ]; // Buffer
-       // initialise buffer to stop stuff complaining
-       memset(buffer, 0, sizeof(DataPoint)*DATA_BUFSIZ);
-       
-       if (start_index < end_index)
+       DataPoint buffer[DATA_BUFSIZ] = {{0}}; // Buffer
+       int index = start_index;
+       // Repeat until all DataPoints are printed
+       while (index < end_index)
        {
+               // Fill the buffer from the DataFile
+               int amount_read = Data_Read(df, buffer, index, DATA_BUFSIZ);
  
-               int index = start_index;
-               // Repeat until all DataPoints are printed
-               while (index <= end_index)
+               // Print all points in the buffer
+               for (int i = 0; i < amount_read && index < end_index; ++i)
                {
-                       // Fill the buffer from the DataFile
-                       int amount_read = Data_Read(df, buffer, index, DATA_BUFSIZ);
-       
-                       // Print all points in the buffer
-                       for (int i = 0; i < amount_read && index <= end_index; ++i)
-                       {
-                               // Print individual DataPoint
-                               FCGI_PrintRaw(fmt_string, buffer[i].time_stamp, buffer[i].value);
-                               
-                               // Last seperator is not required
-                               if (index+1 <= end_index)
-                                       FCGI_PrintRaw("%c", seperator);
-       
-                               // Advance the position in the DataFile
-                               ++index;
-                       }
+                       // Print individual DataPoint
+                       FCGI_PrintRaw(fmt_string, buffer[i].time_stamp, buffer[i].value);
+                       
+                       // Last separator is not required
+                       if (index+1 < end_index)
+                               FCGI_PrintRaw("%c", separator);
+                       // Advance the position in the DataFile
+                       ++index;
                }
        }
        
   * Prints nothing if the time stamp
   * @param df - DataFile to print
   * @param start_time - Time to start from (inclusive)
-  * @param end_time - Time to end at (inclusive)
+  * @param end_time - Time to end at (exclusive)
   * @param format - The format to use
   */
  void Data_PrintByTimes(DataFile * df, double start_time, double end_time, DataFormat format)
  {
        assert(df != NULL);
-       assert(start_time >= 0);
-       assert(end_time >= 0);
-       assert(end_time >= start_time);
-       
-       DataPoint closest;
-       // Get starting index
-       int start_index = Data_FindByTime(df, start_time, &closest);
-       // Start time is greater than most recent time stamp
-       if (start_index >= df->num_points-1)
+       //Clamp boundaries
+       if (start_time < 0)
+               start_time = 0;
+       if (end_time < 0)
+               end_time = 0;
+       int start_index = 0, end_index = 0;
+       if (start_time < end_time)
        {
-               if (start_index == 0 || closest.time_stamp < start_time)
-               {
-                       Data_PrintByIndexes(df, 0, 0, format); // Will print "empty" dataset
-                       return;
-               }
+               start_index = Data_FindByTime(df, start_time, NULL);
+               end_index = Data_FindByTime(df, end_time, NULL);
        }
  
-       // Get finishing index
-       int end_index = Data_FindByTime(df, end_time, &closest);
-       // Print data between the indexes
        Data_PrintByIndexes(df, start_index, end_index, format);
  }
  
@@@ -279,7 -245,7 +246,7 @@@ int Data_FindByTime(DataFile * df, doub
  {
        assert(df != NULL);
        assert(time_stamp >= 0);
-       assert(closest != NULL);
+       //assert(closest != NULL);
  
        DataPoint tmp; // Current DataPoint in binary search
  
        return index;
        
  }
 +
 +/**
 + * Helper; handle FCGI response that requires data
 + * Should be called first.
 + * @param df - DataFile to access
 + * @param start - Info about start_time param 
 + * @param end - Info about end_time param
 + * @param fmt - Info about format param
 + * @param current_time - Current time
 + */
 +void Data_Handler(DataFile * df, FCGIValue * start, FCGIValue * end, DataFormat format, double current_time)
 +{
 +      double start_time = *(double*)(start->value);
 +      double end_time = *(double*)(end->value);
 +
 +      if (format == JSON)
 +      {
 +              FCGI_JSONKey("data");
 +      }
 +
 +      // If a time was specified
 +      if (FCGI_RECEIVED(start->flags) || FCGI_RECEIVED(end->flags))
 +      {
 +              // Wrap times relative to the current time
 +              if (start_time < 0)
 +                      start_time += current_time;
 +              if (end_time < 0)
 +                      end_time += current_time;
 +
 +              // Print points by time range
 +              Data_PrintByTimes(df, start_time, end_time, format);
 +
 +      }
 +      else // No time was specified; just return a recent set of points
 +      {
 +              pthread_mutex_lock(&(df->mutex));
 +                      int start_index = df->num_points-DATA_BUFSIZ;
 +                      int end_index = df->num_points-1;
 +              pthread_mutex_unlock(&(df->mutex));
 +
 +              // Bounds check
 +              if (start_index < 0)
 +                      start_index = 0;
 +              if (end_index < 0)
 +                      end_index = 0;
 +
 +              // Print points by indexes
 +              Data_PrintByIndexes(df, start_index, end_index, format);
 +      }
 +
 +}
 +
 +/**
 + * Helper - Convert human readable format string to DataFormat
 + * @param fmt - FCGIValue to use
 + */
 +DataFormat Data_GetFormat(FCGIValue * fmt)
 +{
 +      char * fmt_str = *(char**)(fmt->value);
 +      // Check if format type was specified
 +      if (FCGI_RECEIVED(fmt->flags))
 +      {
 +              if (strcmp(fmt_str, "json") == 0)
 +                      return JSON;
 +              else if (strcmp(fmt_str, "tsv") == 0)
 +                      return TSV;
 +              else
 +                      Log(LOGERR, "Unknown format type \"%s\"", fmt_str);
 +      }
 +      return JSON;
 +}
diff --combined server/data.h
@@@ -34,8 -34,7 +34,7 @@@ typedef enu
   */
  typedef struct
  {
-       FILE * read_file; // used for reading
-       FILE * write_file; // used for writing
+       FILE * file; // file pointer
        int num_points; // Number of DataPoints in the file
        char * filename; // Name of the file
        pthread_mutex_t mutex; // Mutex around num_points
@@@ -51,7 -50,4 +50,7 @@@ extern void Data_PrintByIndexes(DataFil
  extern void Data_PrintByTimes(DataFile * df, double start_time, double end_time, DataFormat format); // Print data between time values
  extern int Data_FindByTime(DataFile * df, double time_stamp, DataPoint * closest); // Find index of DataPoint with the closest timestamp to that given
  
 +extern void Data_Handler(DataFile * df, FCGIValue * start, FCGIValue * end, DataFormat format, double current_time); // Helper; given FCGI params print data
 +extern DataFormat Data_GetFormat(FCGIValue * fmt); // Helper; convert human readable format string to DataFormat
 +
  #endif //_DATAPOINT_H
diff --combined server/fastcgi.c
@@@ -12,7 -12,6 +12,7 @@@
  
  #include "common.h"
  #include "sensor.h"
 +#include "actuator.h"
  #include "control.h"
  #include "options.h"
  
@@@ -238,14 -237,19 +238,19 @@@ bool FCGI_ParseRequest(FCGIContext *con
                                        case FCGI_BOOL_T:
                                                *((bool*) val->value) = true;
                                                break;
-                                       case FCGI_LONG_T:
-                                               *((long*) val->value) = strtol(value, &ptr, 10);
+                                       case FCGI_INT_T: case FCGI_LONG_T: {
+                                               long parsed = strtol(value, &ptr, 10);
                                                if (!*value || *ptr) {
                                                        snprintf(buf, BUFSIZ, "Expected int for '%s' but got '%s'", key, value);
                                                        FCGI_RejectJSON(context, FCGI_EscapeJSON(buf));
                                                        return false;
                                                }
-                                               break;
+                                               if (FCGI_TYPE(val->flags) == FCGI_INT_T)
+                                                       *((int*) val->value) = parsed;
+                                               else
+                                                       *((long*) val->value) = parsed;
+                                       }       break;
                                        case FCGI_DOUBLE_T:
                                                *((double*) val->value) = strtod(value, &ptr);
                                                if (!*value || *ptr) {
@@@ -440,8 -444,6 +445,6 @@@ void * FCGI_RequestLoop (void *data
        
        Log(LOGDEBUG, "First request...");
        while (FCGI_Accept() >= 0) {
-               
                Log(LOGDEBUG, "Got request #%d", context.response_number);
                ModuleHandler module_handler = NULL;
                char module[BUFSIZ], params[BUFSIZ];
                        module_handler = Control_Handler;
                } else if (!strcmp("sensors", module)) {
                        module_handler = Sensor_Handler;
 +              } else if (!strcmp("actuators", module)) {
 +                      module_handler = Actuator_Handler;
                }
  
                context.current_module = module;
diff --combined server/sensor.c
  /** Array of sensors, initialised by Sensor_Init **/
  static Sensor g_sensors[NUMSENSORS]; //global to this file
  
+ /** Array of sensor threshold structures defining the safety values of each sensor**/
+ const SensorThreshold thresholds[NUMSENSORS]= {
+       //Max Safety, Min safety, Max warning, Min warning
+       {1,-1,1,-1},            // ANALOG_TEST0
+       {500,0,499,0},          // ANALOG_TEST1
+       {5,-5,4,-4},            // ANALOG_FAIL0
+       {1,0,1,0},              // DIGITAL_TEST0
+       {1,0,1,0},              // DIGITAL_TEST1
+       {1,0,1,0}               // DIGITAL_FAIL0
+ };
  /** Human readable names for the sensors **/
  const char * g_sensor_names[NUMSENSORS] = {   
        "analog_test0", "analog_test1", 
-       "digital_test0", "digital_test1"
+       "analog_fail0", "digital_test0", 
+       "digital_test1", "digital_fail0"
  };
  
  /**
@@@ -27,7 -39,7 +39,7 @@@ void Sensor_Init(
        {
                g_sensors[i].id = i;
                Data_Init(&(g_sensors[i].data_file));
-               g_sensors[i].record_data = false;
+               g_sensors[i].record_data = false;       
        }
  }
  
@@@ -40,7 -52,7 +52,7 @@@ void Sensor_Start(Sensor * s, const cha
  {
        // Set filename
        char filename[BUFSIZ];
 -      if (sprintf(filename, "%s_%d", experiment_name, s->id) >= BUFSIZ)
 +      if (sprintf(filename, "%s_s%d", experiment_name, s->id) >= BUFSIZ)
        {
                Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
        }
@@@ -90,6 -102,26 +102,26 @@@ void Sensor_StartAll(const char * exper
                Sensor_Start(g_sensors+i, experiment_name);
  }
  
+ /**
+  * Checks the sensor data for unsafe or unexpected results 
+  * @param sensor_id - The ID of the sensor
+  * @param value - The value from the sensor to test
+  */
+ void Sensor_CheckData(SensorId id, double value)
+ {
+       if( value > thresholds[id].max_error || value < thresholds[id].min_error)
+       {
+               Log(LOGERR, "Sensor %s is above or below its safety value of %f or %f\n", g_sensor_names[id],thresholds[id].max_error, thresholds[id].min_error);
+               //new function that stops actuators?
+       }
+       else if( value > thresholds[id].max_warn || value < thresholds[id].min_warn)
+       {
+               Log(LOGWARN, "Sensor %s is above or below its warning value of %f or %f\n", g_sensor_names[id],thresholds[id].max_warn, thresholds[id].min_warn);       
+       }
+ }
  /**
   * Read a DataPoint from a Sensor; block until value is read
   * @param id - The ID of the sensor
@@@ -110,19 -142,29 +142,29 @@@ bool Sensor_Read(Sensor * s, DataPoint 
                case ANALOG_TEST0:
                        d->value = (double)(rand() % 100) / 100;
                        break;
                case ANALOG_TEST1:
                {
                        static int count = 0;
+                       count %= 500;
                        d->value = count++;
                        break;
                }
+               case ANALOG_FAIL0:
+                       d->value = (double)(rand() % 6) * -( rand() % 2) / ( rand() % 100 + 1);
+                       //Gives a value between -5 and 5
+                       break;
                case DIGITAL_TEST0:
                        d->value = t.tv_sec % 2;
                        break;
                case DIGITAL_TEST1:
                        d->value = (t.tv_sec+1)%2;
                        break;
+               case DIGITAL_FAIL0:
+                       if( rand() % 100 > 98)
+                               d->value = 2;
+                       d->value = rand() % 2; 
+                       //Gives 0 or 1 or a 2 every 1/100 times
+                       break;
                default:
                        Fatal("Unknown sensor id: %d", s->id);
                        break;
        usleep(100000); // simulate delay in sensor polling
  
        // Perform sanity check based on Sensor's ID and the DataPoint
-       Sensor_CheckData(s->id, d);
+       Sensor_CheckData(s->id, d->value);
  
        // Update latest DataPoint if necessary
        bool result = (d->value != s->newest_data.value);
        return result;
  }
  
- /**
-  * Checks the sensor data for unsafe or unexpected results 
-  * @param sensor_id - The ID of the sensor
-  * @param d - DataPoint to check
-  */
- void Sensor_CheckData(SensorId id, DataPoint * d)
- {
-       //TODO: Implement
-       /*
-       switch (sensor_id)
-       {
-               case ANALOG_TEST0:
-               {
-                       if( *sensor value* > ANALOG_TEST0_SAFETY)
-                       {
-                               LogEx(LOGERR, GetData, Sensor analog_test0 is above the safe value);
-                       //new log function that stops actuators?
-                       }
-                       //Also include a warning level?
-                       else if( *sensor value* > ANALOG_TEST0_WARN)
-                       {
-                               LogEx(LOGWARN, GetData, Sensor analog_test0);   
-                       }
-               }
-       }
-       */
- }
-               
  /**
   * Record data from a single Sensor; to be run in a seperate thread
   * @param arg - Cast to Sensor* - Sensor that the thread will handle
@@@ -225,8 -238,8 +238,8 @@@ Sensor * Sensor_Identify(const char * i
  /**
   * Helper: Begin sensor response in a given format
   * @param context - the FCGIContext
-  * @param format - Format
   * @param id - ID of sensor
+  * @param format - Format
   */
  void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
  {
                case JSON:
                        FCGI_BeginJSON(context, STATUS_OK);
                        FCGI_JSONLong("id", id);
 -                      FCGI_JSONKey("data");
                        break;
                default:
                        FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
@@@ -276,11 -290,11 +289,11 @@@ void Sensor_Handler(FCGIContext *contex
        int id = 0;
        double start_time = 0;
        double end_time = current_time;
-       char * fmt_str;
+       const char * fmt_str;
  
        // key/value pairs
        FCGIValue values[] = {
-               {"id", &id, FCGI_REQUIRED(FCGI_LONG_T)}, 
+               {"id", &id, FCGI_REQUIRED(FCGI_INT_T)}, 
                {"format", &fmt_str, FCGI_STRING_T}, 
                {"start_time", &start_time, FCGI_DOUBLE_T}, 
                {"end_time", &end_time, FCGI_DOUBLE_T},
                // Error occured; FCGI_RejectJSON already called
                return;
        }
 -      else if (id < 0 || id >= NUMSENSORS)
 +
 +      // Error checking on sensor id
 +      if (id < 0 || id >= NUMSENSORS)
        {
 -              FCGI_RejectJSON(context, "Invalid sensor id specified");
 +              FCGI_RejectJSON(context, "Invalid sensor id");
                return;
        }
 -
 -      // Get Sensor and format
        Sensor * s = g_sensors+id;
 -      DataFormat format = JSON;
 -
 -      // Check if format type was specified
 -      if (FCGI_RECEIVED(values[FORMAT].flags))
 -      {
 -              if (strcmp(fmt_str, "json") == 0)
 -                      format = JSON;
 -              else if (strcmp(fmt_str, "tsv") == 0)
 -                      format = TSV;
 -              else 
 -              {
 -                      FCGI_RejectJSON(context, "Unknown format type specified.");
 -                      return;
 -              }
 -      }
 +      
 +      DataFormat format = Data_GetFormat(&(values[FORMAT]));
  
        // Begin response
        Sensor_BeginResponse(context, id, format);
 -      
 -      // If a time was specified
 -      if (FCGI_RECEIVED(values[START_TIME].flags) || FCGI_RECEIVED(values[END_TIME].flags))
 -      {
 -              // Wrap times relative to the current time
 -              if (start_time < 0)
 -                      start_time += current_time;
 -              if (end_time < 0)
 -                      end_time += current_time;
 -
 -              // Print points by time range
 -              Data_PrintByTimes(&(s->data_file), start_time, end_time, format);
 -      }
 -      else // No time was specified; just return a recent set of points
 -      {
 -              pthread_mutex_lock(&(s->data_file.mutex));
 -                      int start_index = s->data_file.num_points-DATA_BUFSIZ;
 -                      int end_index = s->data_file.num_points;
 -              pthread_mutex_unlock(&(s->data_file.mutex));
 -
 -              // Bounds check
 -              if (start_index < 0)
 -                      start_index = 0;
 -              if (end_index < 0)
 -                      end_index = 0;
 -
 -              // Print points by indexes
 -              Log(LOGDEBUG, "Sensor %d file \"%s\" indexes %d->%d", s->id, s->data_file.filename, start_index, end_index);
 -              Data_PrintByIndexes(&(s->data_file), start_index, end_index, format);
 -      }
 +
 +      // Print Data
 +      Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
        
        // Finish response
        Sensor_EndResponse(context, id, format);
  }
  
  

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