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)
41 char filename[BUFSIZ];
42 if (sprintf(filename, "%s_%d", experiment_name, s->id) >= BUFSIZ)
44 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
46 Data_Open(&(s->data_file), filename);
48 pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
52 * Stop a Sensor from recording DataPoints. Blocks until it has stopped.
53 * @param s - The Sensor to stop
55 void Sensor_Stop(Sensor * s)
59 s->record_data = false;
60 pthread_join(s->thread, NULL);
61 Data_Close(&(s->data_file));
70 for (int i = 0; i < NUMSENSORS; ++i)
71 Sensor_Stop(g_sensors+i);
77 void Sensor_StartAll(const char * experiment_name)
79 for (int i = 0; i < NUMSENSORS; ++i)
80 Sensor_Start(g_sensors+i, experiment_name);
84 * Read a DataPoint from a Sensor; block until value is read
85 * @param id - The ID of the sensor
86 * @param d - DataPoint to set
87 * @returns True if the DataPoint was different from the most recently recorded.
89 bool Sensor_Read(Sensor * s, DataPoint * d)
94 gettimeofday(&t, NULL);
95 d->time_stamp = TIMEVAL_DIFF(t, g_options.start_time);
97 // Read value based on Sensor Id
101 d->value = (double)(rand() % 100) / 100;
106 static int count = 0;
111 d->value = t.tv_sec % 2;
114 d->value = (t.tv_sec+1)%2;
117 Fatal("Unknown sensor id: %d", s->id);
120 usleep(100000); // simulate delay in sensor polling
122 // Perform sanity check based on Sensor's ID and the DataPoint
123 Sensor_CheckData(s->id, d);
125 // Update latest DataPoint if necessary
126 bool result = (d->value != s->newest_data.value);
129 s->newest_data.time_stamp = d->time_stamp;
135 * Checks the sensor data for unsafe or unexpected results
136 * @param sensor_id - The ID of the sensor
137 * @param d - DataPoint to check
139 void Sensor_CheckData(SensorId id, DataPoint * d)
147 if( *sensor value* > ANALOG_TEST0_SAFETY)
149 LogEx(LOGERR, GetData, Sensor analog_test0 is above the safe value);
150 //new log function that stops actuators?
152 //Also include a warning level?
153 else if( *sensor value* > ANALOG_TEST0_WARN)
155 LogEx(LOGWARN, GetData, Sensor analog_test0);
164 * Record data from a single Sensor; to be run in a seperate thread
165 * @param arg - Cast to Sensor* - Sensor that the thread will handle
166 * @returns NULL (void* required to use the function with pthreads)
168 void * Sensor_Loop(void * arg)
170 Sensor * s = (Sensor*)(arg);
172 // Until the sensor is stopped, record data points
173 while (s->record_data)
176 if (Sensor_Read(s, &d)) // If new DataPoint is read:
178 Data_Save(&(s->data_file), &d, 1); // Record it
182 // Needed to keep pthreads happy
187 * Get a Sensor given an ID string
188 * @param id_str ID string
189 * @returns Sensor* identified by the string; NULL on error
191 Sensor * Sensor_Identify(const char * id_str)
194 // Parse string as integer
195 int id = strtol(id_str, &end, 10);
201 if (id < 0 || id >= NUMSENSORS)
205 Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
210 * Helper: Begin sensor response in a given format
211 * @param context - the FCGIContext
212 * @param format - Format
213 * @param id - ID of sensor
215 void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
221 FCGI_BeginJSON(context, STATUS_OK);
222 FCGI_JSONLong("id", id);
223 FCGI_JSONKey("data");
226 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
232 * Helper: End sensor response in a given format
233 * @param context - the FCGIContext
234 * @param id - ID of the sensor
235 * @param format - Format
237 void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format)
251 * Handle a request to the sensor module
252 * @param context - The context to work in
253 * @param params - Parameters passed
255 void Sensor_Handler(FCGIContext *context, char * params)
258 gettimeofday(&now, NULL);
259 double current_time = TIMEVAL_DIFF(now, g_options.start_time);
262 double start_time = 0;
263 double end_time = current_time;
267 FCGIValue values[] = {
268 {"id", &id, FCGI_REQUIRED(FCGI_LONG_T)},
269 {"format", &fmt_str, FCGI_STRING_T},
270 {"start_time", &start_time, FCGI_DOUBLE_T},
271 {"end_time", &end_time, FCGI_DOUBLE_T},
274 // enum to avoid the use of magic numbers
282 // Fill values appropriately
283 if (!FCGI_ParseRequest(context, params, values, sizeof(values)))
285 // Error occured; FCGI_RejectJSON already called
289 // Error checking on sensor id
290 if (id < 0 || id >= NUMSENSORS)
292 Log(LOGERR, "Invalid id %d", id);
293 FCGI_RejectJSON(context, "Invalid id"); // Whoops, I do still need this!
296 DataFormat format = JSON;
298 // Check if format type was specified
299 if (FCGI_RECEIVED(values[FORMAT].flags))
301 if (strcmp(fmt_str, "json") == 0)
303 else if (strcmp(fmt_str, "tsv") == 0)
306 Log(LOGERR, "Unknown format type \"%s\"", fmt_str);
310 Sensor * s = g_sensors+id;
313 Sensor_BeginResponse(context, id, format);
315 // If a time was specified
316 if (FCGI_RECEIVED(values[START_TIME].flags) || FCGI_RECEIVED(values[END_TIME].flags))
318 // Wrap times relative to the current time
320 start_time += current_time;
322 end_time += current_time;
324 // Print points by time range
325 Data_PrintByTimes(&(s->data_file), start_time, end_time, format);
328 else // No time was specified; just return a recent set of points
330 pthread_mutex_lock(&(s->data_file.mutex));
331 int start_index = s->data_file.num_points-DATA_BUFSIZ;
332 int end_index = s->data_file.num_points-1;
333 pthread_mutex_unlock(&(s->data_file.mutex));
335 // Print points by indexes
336 Data_PrintByIndexes(&(s->data_file), start_index, end_index, format);
340 Sensor_EndResponse(context, id, format);