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 "analog_fail0", "digital_test0",
19 "digital_test1", "digital_fail0"
23 * One off initialisation of *all* sensors
27 for (int i = 0; i < NUMSENSORS; ++i)
30 Data_Init(&(g_sensors[i].data_file));
31 g_sensors[i].record_data = false;
36 * Start a Sensor recording DataPoints
37 * @param s - The Sensor to start
38 * @param experiment_name - Prepended to DataFile filename
40 void Sensor_Start(Sensor * s, const char * experiment_name)
43 char filename[BUFSIZ];
44 if (sprintf(filename, "%s_%d", experiment_name, s->id) >= BUFSIZ)
46 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
49 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
51 Data_Open(&(s->data_file), filename);
53 s->record_data = true; // Don't forget this!
56 pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
60 * Stop a Sensor from recording DataPoints. Blocks until it has stopped.
61 * @param s - The Sensor to stop
63 void Sensor_Stop(Sensor * s)
68 s->record_data = false;
69 pthread_join(s->thread, NULL); // Wait for thread to exit
70 Data_Close(&(s->data_file)); // Close DataFile
71 s->newest_data.time_stamp = 0;
72 s->newest_data.value = 0;
81 for (int i = 0; i < NUMSENSORS; ++i)
82 Sensor_Stop(g_sensors+i);
88 void Sensor_StartAll(const char * experiment_name)
90 for (int i = 0; i < NUMSENSORS; ++i)
91 Sensor_Start(g_sensors+i, experiment_name);
96 * Checks the sensor data for unsafe or unexpected results
97 * @param sensor_id - The ID of the sensor
98 * @param value - The value from the sensor to test
100 void Sensor_CheckData(SensorId id, double value)
106 if( value > ANALOG_FAIL0_SAFETY || value < ANALOG_FAIL0_MIN_SAFETY)
108 Log(LOGERR, "Sensor analog_fail0 is above or below its safety value of %d or %d\n", ANALOG_FAIL0_SAFETY, ANALOG_FAIL0_MIN_SAFETY);
109 //new function that stops actuators?
111 else if( value > ANALOG_FAIL0_WARN || value < ANALOG_FAIL0_MIN_WARN)
113 Log(LOGWARN, "Sensor analog_test0 is above or below its warning value of %d or %d\n", ANALOG_FAIL0_WARN, ANALOG_FAIL0_MIN_WARN);
119 if( value != 0 && value != 1)
121 Log(LOGERR, "Sensor digital_fail0 is not 0 or 1\n");
127 //So it doesn't complain about the missing cases - in practice we will need all sensors to be checked as above, no need to include a default as we should only pass valid sensor_id's; unless for some reason we have a sensor we don't need to check (but then why would you pass to this function in the first place :P)
134 * Read a DataPoint from a Sensor; block until value is read
135 * @param id - The ID of the sensor
136 * @param d - DataPoint to set
137 * @returns True if the DataPoint was different from the most recently recorded.
139 bool Sensor_Read(Sensor * s, DataPoint * d)
144 gettimeofday(&t, NULL);
145 d->time_stamp = TIMEVAL_DIFF(t, g_options.start_time);
147 // Read value based on Sensor Id
151 d->value = (double)(rand() % 100) / 100;
156 static int count = 0;
161 d->value = (double)(rand() % 6) * -( rand() % 2) / ( rand() % 100 + 1);
162 //Gives a value between -5 and 5
163 CheckSensor(sensor_id, d->value);
166 d->value = t.tv_sec % 2;
169 d->value = (t.tv_sec+1)%2;
172 if( rand() % 100 > 98)
174 d->value = rand() % 2;
175 //Gives 0 or 1 or a 2 every 1/100 times
176 CheckSensor(sensor_id, d->value);
179 Fatal("Unknown sensor id: %d", s->id);
182 usleep(100000); // simulate delay in sensor polling
184 // Perform sanity check based on Sensor's ID and the DataPoint
185 Sensor_CheckData(s->id, d);
187 // Update latest DataPoint if necessary
188 bool result = (d->value != s->newest_data.value);
191 s->newest_data.time_stamp = d->time_stamp;
192 s->newest_data.value = d->value;
198 * Record data from a single Sensor; to be run in a seperate thread
199 * @param arg - Cast to Sensor* - Sensor that the thread will handle
200 * @returns NULL (void* required to use the function with pthreads)
202 void * Sensor_Loop(void * arg)
204 Sensor * s = (Sensor*)(arg);
205 Log(LOGDEBUG, "Sensor %d starts", s->id);
207 // Until the sensor is stopped, record data points
208 while (s->record_data)
211 //Log(LOGDEBUG, "Sensor %d reads data [%f,%f]", s->id, d.time_stamp, d.value);
212 if (Sensor_Read(s, &d)) // If new DataPoint is read:
214 //Log(LOGDEBUG, "Sensor %d saves data [%f,%f]", s->id, d.time_stamp, d.value);
215 Data_Save(&(s->data_file), &d, 1); // Record it
219 // Needed to keep pthreads happy
221 Log(LOGDEBUG, "Sensor %d finished", s->id);
226 * Get a Sensor given an ID string
227 * @param id_str ID string
228 * @returns Sensor* identified by the string; NULL on error
230 Sensor * Sensor_Identify(const char * id_str)
233 // Parse string as integer
234 int id = strtol(id_str, &end, 10);
240 if (id < 0 || id >= NUMSENSORS)
244 Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
249 * Helper: Begin sensor response in a given format
250 * @param context - the FCGIContext
251 * @param format - Format
252 * @param id - ID of sensor
254 void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
260 FCGI_BeginJSON(context, STATUS_OK);
261 FCGI_JSONLong("id", id);
262 FCGI_JSONKey("data");
265 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
271 * Helper: End sensor response in a given format
272 * @param context - the FCGIContext
273 * @param id - ID of the sensor
274 * @param format - Format
276 void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format)
290 * Handle a request to the sensor module
291 * @param context - The context to work in
292 * @param params - Parameters passed
294 void Sensor_Handler(FCGIContext *context, char * params)
297 gettimeofday(&now, NULL);
298 double current_time = TIMEVAL_DIFF(now, g_options.start_time);
301 double start_time = 0;
302 double end_time = current_time;
306 FCGIValue values[] = {
307 {"id", &id, FCGI_REQUIRED(FCGI_LONG_T)},
308 {"format", &fmt_str, FCGI_STRING_T},
309 {"start_time", &start_time, FCGI_DOUBLE_T},
310 {"end_time", &end_time, FCGI_DOUBLE_T},
313 // enum to avoid the use of magic numbers
321 // Fill values appropriately
322 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
324 // Error occured; FCGI_RejectJSON already called
331 // Error checking on sensor id
332 if (id < 0 || id >= NUMSENSORS)
334 Log(LOGERR, "Invalid id %d", id);
341 DataFormat format = JSON;
343 // Check if format type was specified
344 if (FCGI_RECEIVED(values[FORMAT].flags))
346 if (strcmp(fmt_str, "json") == 0)
348 else if (strcmp(fmt_str, "tsv") == 0)
351 Log(LOGERR, "Unknown format type \"%s\"", fmt_str);
357 Sensor_BeginResponse(context, id, format);
359 // If a time was specified
360 if ((s != NULL) && (FCGI_RECEIVED(values[START_TIME].flags) || FCGI_RECEIVED(values[END_TIME].flags)))
362 // Wrap times relative to the current time
364 start_time += current_time;
366 end_time += current_time;
368 // Print points by time range
369 Data_PrintByTimes(&(s->data_file), start_time, end_time, format);
372 else if (s != NULL) // No time was specified; just return a recent set of points
374 pthread_mutex_lock(&(s->data_file.mutex));
375 int start_index = s->data_file.num_points-DATA_BUFSIZ;
376 int end_index = s->data_file.num_points-1;
377 pthread_mutex_unlock(&(s->data_file.mutex));
385 // Print points by indexes
386 Log(LOGDEBUG, "Sensor %d file \"%s\" indexes %d->%d", s->id, s->data_file.filename, start_index, end_index);
387 Data_PrintByIndexes(&(s->data_file), start_index, end_index, format);
391 Sensor_EndResponse(context, id, format);