+/**
+ * Helper: End sensor response in a given format
+ * @param context - the FCGIContext
+ * @param id - ID of the sensor
+ * @param format - Format
+ */
+void Sensor_EndResponse(FCGIContext * context, Sensor * s, DataFormat format)
+{
+ // End response
+ switch (format)
+ {
+ case JSON:
+ FCGI_EndJSON();
+ break;
+ default:
+ break;
+ }
+}
+
+/**
+ * Handle a request to the sensor module
+ * @param context - The context to work in
+ * @param params - Parameters passed
+ */
+void Sensor_Handler(FCGIContext *context, char * params)
+{
+ struct timeval now;
+ gettimeofday(&now, NULL);
+ double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
+
+ int id = 0;
+ const char * name = "";
+ double start_time = 0;
+ double end_time = current_time;
+ const char * fmt_str;
+ double sample_s = 0;
+
+ // key/value pairs
+ FCGIValue values[] = {
+ {"id", &id, FCGI_INT_T},
+ {"name", &name, FCGI_STRING_T},
+ {"format", &fmt_str, FCGI_STRING_T},
+ {"start_time", &start_time, FCGI_DOUBLE_T},
+ {"end_time", &end_time, FCGI_DOUBLE_T},
+ {"sample_s", &sample_s, FCGI_DOUBLE_T}
+ };
+
+ // enum to avoid the use of magic numbers
+ typedef enum {
+ ID,
+ NAME,
+ FORMAT,
+ START_TIME,
+ END_TIME,
+ SAMPLE_S
+ } SensorParams;
+
+ // Fill values appropriately
+ if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
+ {
+ // Error occured; FCGI_RejectJSON already called
+ return;
+ }
+
+ Sensor * s = NULL;
+ if (FCGI_RECEIVED(values[NAME].flags))
+ {
+ if (FCGI_RECEIVED(values[ID].flags))
+ {
+ FCGI_RejectJSON(context, "Can't supply both sensor id and name");
+ return;
+ }
+ s = Sensor_Identify(name);
+ if (s == NULL)
+ {
+ FCGI_RejectJSON(context, "Unknown sensor name");
+ return;
+ }
+ }
+ else if (!FCGI_RECEIVED(values[ID].flags))
+ {
+ FCGI_RejectJSON(context, "No sensor id or name supplied");
+ return;
+ }
+ else if (id < 0 || id >= g_num_sensors)
+ {
+ FCGI_RejectJSON(context, "Invalid sensor id");
+ return;
+ }
+ else
+ {
+ s = &(g_sensors[id]);
+ }
+
+ // Adjust sample rate if necessary
+ if (FCGI_RECEIVED(values[SAMPLE_S].flags))
+ {
+ if (sample_s < 0)
+ {
+ FCGI_RejectJSON(context, "Negative sampling speed!");
+ return;
+ }
+ s->sample_us = 1e6*sample_s;
+ }
+
+
+ DataFormat format = Data_GetFormat(&(values[FORMAT]));
+
+ // Begin response
+ Sensor_BeginResponse(context, s, format);
+
+ // Print Data
+ Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
+
+ // Finish response
+ Sensor_EndResponse(context, s, format);
+
+}
+
+/**
+ * Get the Name of a Sensor
+ * @param id - ID number
+ */
+const char * Sensor_GetName(int id)
+{
+ return g_sensors[id].name;
+}
+
+