3 * @brief Implementation of sensor thread
4 * TODO: Finalise implementation
12 /** Array of sensors, initialised by Sensor_Init **/
13 static Sensor g_sensors[NUMSENSORS]; //global to this file
15 /** Human readable names for the sensors **/
16 const char * g_sensor_names[NUMSENSORS] = {
17 "analog_test0", "analog_test1",
18 "digital_test0", "digital_test1"
22 * One off initialisation of *all* sensors
26 for (int i = 0; i < NUMSENSORS; ++i)
29 Data_Init(&(g_sensors[i].data_file));
30 g_sensors[i].record_data = false;
35 * Start a Sensor recording DataPoints
36 * @param s - The Sensor to start
37 * @param experiment_name - Prepended to DataFile filename
39 void Sensor_Start(Sensor * s, const char * experiment_name)
42 char filename[BUFSIZ];
43 if (sprintf(filename, "%s_%d", experiment_name, s->id) >= BUFSIZ)
45 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
48 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
50 Data_Open(&(s->data_file), filename);
52 s->record_data = true; // Don't forget this!
55 pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
59 * Stop a Sensor from recording DataPoints. Blocks until it has stopped.
60 * @param s - The Sensor to stop
62 void Sensor_Stop(Sensor * s)
67 s->record_data = false;
68 pthread_join(s->thread, NULL); // Wait for thread to exit
69 Data_Close(&(s->data_file)); // Close DataFile
70 s->newest_data.time_stamp = 0;
71 s->newest_data.value = 0;
80 for (int i = 0; i < NUMSENSORS; ++i)
81 Sensor_Stop(g_sensors+i);
87 void Sensor_StartAll(const char * experiment_name)
89 for (int i = 0; i < NUMSENSORS; ++i)
90 Sensor_Start(g_sensors+i, experiment_name);
94 * Read a DataPoint from a Sensor; block until value is read
95 * @param id - The ID of the sensor
96 * @param d - DataPoint to set
97 * @returns True if the DataPoint was different from the most recently recorded.
99 bool Sensor_Read(Sensor * s, DataPoint * d)
104 gettimeofday(&t, NULL);
105 d->time_stamp = TIMEVAL_DIFF(t, g_options.start_time);
107 // Read value based on Sensor Id
111 d->value = (double)(rand() % 100) / 100;
116 static int count = 0;
121 d->value = t.tv_sec % 2;
124 d->value = (t.tv_sec+1)%2;
127 Fatal("Unknown sensor id: %d", s->id);
130 usleep(100000); // simulate delay in sensor polling
132 // Perform sanity check based on Sensor's ID and the DataPoint
133 Sensor_CheckData(s->id, d);
135 // Update latest DataPoint if necessary
136 bool result = (d->value != s->newest_data.value);
139 s->newest_data.time_stamp = d->time_stamp;
140 s->newest_data.value = d->value;
146 * Checks the sensor data for unsafe or unexpected results
147 * @param sensor_id - The ID of the sensor
148 * @param d - DataPoint to check
150 void Sensor_CheckData(SensorId id, DataPoint * d)
158 if( *sensor value* > ANALOG_TEST0_SAFETY)
160 LogEx(LOGERR, GetData, Sensor analog_test0 is above the safe value);
161 //new log function that stops actuators?
163 //Also include a warning level?
164 else if( *sensor value* > ANALOG_TEST0_WARN)
166 LogEx(LOGWARN, GetData, Sensor analog_test0);
175 * Record data from a single Sensor; to be run in a seperate thread
176 * @param arg - Cast to Sensor* - Sensor that the thread will handle
177 * @returns NULL (void* required to use the function with pthreads)
179 void * Sensor_Loop(void * arg)
181 Sensor * s = (Sensor*)(arg);
182 Log(LOGDEBUG, "Sensor %d starts", s->id);
184 // Until the sensor is stopped, record data points
185 while (s->record_data)
188 //Log(LOGDEBUG, "Sensor %d reads data [%f,%f]", s->id, d.time_stamp, d.value);
189 if (Sensor_Read(s, &d)) // If new DataPoint is read:
191 //Log(LOGDEBUG, "Sensor %d saves data [%f,%f]", s->id, d.time_stamp, d.value);
192 Data_Save(&(s->data_file), &d, 1); // Record it
196 // Needed to keep pthreads happy
198 Log(LOGDEBUG, "Sensor %d finished", s->id);
203 * Get a Sensor given an ID string
204 * @param id_str ID string
205 * @returns Sensor* identified by the string; NULL on error
207 Sensor * Sensor_Identify(const char * id_str)
210 // Parse string as integer
211 int id = strtol(id_str, &end, 10);
217 if (id < 0 || id >= NUMSENSORS)
221 Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
226 * Helper: Begin sensor response in a given format
227 * @param context - the FCGIContext
228 * @param format - Format
229 * @param id - ID of sensor
231 void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
237 FCGI_BeginJSON(context, STATUS_OK);
238 FCGI_JSONLong("id", id);
239 FCGI_JSONKey("data");
242 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
248 * Helper: End sensor response in a given format
249 * @param context - the FCGIContext
250 * @param id - ID of the sensor
251 * @param format - Format
253 void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format)
267 * Handle a request to the sensor module
268 * @param context - The context to work in
269 * @param params - Parameters passed
271 void Sensor_Handler(FCGIContext *context, char * params)
274 gettimeofday(&now, NULL);
275 double current_time = TIMEVAL_DIFF(now, g_options.start_time);
278 double start_time = 0;
279 double end_time = current_time;
283 FCGIValue values[] = {
284 {"id", &id, FCGI_REQUIRED(FCGI_LONG_T)},
285 {"format", &fmt_str, FCGI_STRING_T},
286 {"start_time", &start_time, FCGI_DOUBLE_T},
287 {"end_time", &end_time, FCGI_DOUBLE_T},
290 // enum to avoid the use of magic numbers
298 // Fill values appropriately
299 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
301 // Error occured; FCGI_RejectJSON already called
308 // Error checking on sensor id
309 if (id < 0 || id >= NUMSENSORS)
311 Log(LOGERR, "Invalid id %d", id);
318 DataFormat format = JSON;
320 // Check if format type was specified
321 if (FCGI_RECEIVED(values[FORMAT].flags))
323 if (strcmp(fmt_str, "json") == 0)
325 else if (strcmp(fmt_str, "tsv") == 0)
328 Log(LOGERR, "Unknown format type \"%s\"", fmt_str);
334 Sensor_BeginResponse(context, id, format);
336 // If a time was specified
337 if ((s != NULL) && (FCGI_RECEIVED(values[START_TIME].flags) || FCGI_RECEIVED(values[END_TIME].flags)))
339 // Wrap times relative to the current time
341 start_time += current_time;
343 end_time += current_time;
345 // Print points by time range
346 Data_PrintByTimes(&(s->data_file), start_time, end_time, format);
349 else if (s != NULL) // No time was specified; just return a recent set of points
351 pthread_mutex_lock(&(s->data_file.mutex));
352 int start_index = s->data_file.num_points-DATA_BUFSIZ;
353 int end_index = s->data_file.num_points-1;
354 pthread_mutex_unlock(&(s->data_file.mutex));
362 // Print points by indexes
363 Log(LOGDEBUG, "Sensor %d file \"%s\" indexes %d->%d", s->id, s->data_file.filename, start_index, end_index);
364 Data_PrintByIndexes(&(s->data_file), start_index, end_index, format);
368 Sensor_EndResponse(context, id, format);