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 /** Array of sensor threshold structures defining the safety values of each sensor**/
16 const SensorThreshold thresholds[NUMSENSORS]= {
17 //Max Safety, Min safety, Max warning, Min warning
18 {1,-1,1,-1}, // ANALOG_TEST0
19 {500,0,499,0}, // ANALOG_TEST1
20 {5,-5,4,-4}, // ANALOG_FAIL0
21 {1,0,1,0}, // DIGITAL_TEST0
22 {1,0,1,0}, // DIGITAL_TEST1
23 {1,0,1,0} // DIGITAL_FAIL0
26 /** Human readable names for the sensors **/
27 const char * g_sensor_names[NUMSENSORS] = {
28 "analog_test0", "analog_test1",
29 "analog_fail0", "digital_test0",
30 "digital_test1", "digital_fail0"
34 * One off initialisation of *all* sensors
38 for (int i = 0; i < NUMSENSORS; ++i)
41 Data_Init(&(g_sensors[i].data_file));
42 g_sensors[i].record_data = false;
47 * Start a Sensor recording DataPoints
48 * @param s - The Sensor to start
49 * @param experiment_name - Prepended to DataFile filename
51 void Sensor_Start(Sensor * s, const char * experiment_name)
54 char filename[BUFSIZ];
55 if (sprintf(filename, "%s_s%d", experiment_name, s->id) >= BUFSIZ)
57 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
60 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
62 Data_Open(&(s->data_file), filename);
64 s->record_data = true; // Don't forget this!
67 pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
71 * Stop a Sensor from recording DataPoints. Blocks until it has stopped.
72 * @param s - The Sensor to stop
74 void Sensor_Stop(Sensor * s)
79 s->record_data = false;
80 pthread_join(s->thread, NULL); // Wait for thread to exit
81 Data_Close(&(s->data_file)); // Close DataFile
82 s->newest_data.time_stamp = 0;
83 s->newest_data.value = 0;
92 for (int i = 0; i < NUMSENSORS; ++i)
93 Sensor_Stop(g_sensors+i);
99 void Sensor_StartAll(const char * experiment_name)
101 for (int i = 0; i < NUMSENSORS; ++i)
102 Sensor_Start(g_sensors+i, experiment_name);
107 * Checks the sensor data for unsafe or unexpected results
108 * @param sensor_id - The ID of the sensor
109 * @param value - The value from the sensor to test
111 void Sensor_CheckData(SensorId id, double value)
113 if( value > thresholds[id].max_error || value < thresholds[id].min_error)
115 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);
116 //new function that stops actuators?
118 else if( value > thresholds[id].max_warn || value < thresholds[id].min_warn)
120 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);
126 * Read a DataPoint from a Sensor; block until value is read
127 * @param id - The ID of the sensor
128 * @param d - DataPoint to set
129 * @returns True if the DataPoint was different from the most recently recorded.
131 bool Sensor_Read(Sensor * s, DataPoint * d)
136 gettimeofday(&t, NULL);
137 d->time_stamp = TIMEVAL_DIFF(t, g_options.start_time);
139 // Read value based on Sensor Id
143 d->value = (double)(rand() % 100) / 100;
147 static int count = 0;
153 d->value = (double)(rand() % 6) * -( rand() % 2) / ( rand() % 100 + 1);
154 //Gives a value between -5 and 5
157 d->value = t.tv_sec % 2;
160 d->value = (t.tv_sec+1)%2;
163 if( rand() % 100 > 98)
165 d->value = rand() % 2;
166 //Gives 0 or 1 or a 2 every 1/100 times
169 Fatal("Unknown sensor id: %d", s->id);
172 usleep(100000); // simulate delay in sensor polling
174 // Perform sanity check based on Sensor's ID and the DataPoint
175 Sensor_CheckData(s->id, d->value);
177 // Update latest DataPoint if necessary
178 bool result = (d->value != s->newest_data.value);
181 s->newest_data.time_stamp = d->time_stamp;
182 s->newest_data.value = d->value;
188 * Record data from a single Sensor; to be run in a seperate thread
189 * @param arg - Cast to Sensor* - Sensor that the thread will handle
190 * @returns NULL (void* required to use the function with pthreads)
192 void * Sensor_Loop(void * arg)
194 Sensor * s = (Sensor*)(arg);
195 Log(LOGDEBUG, "Sensor %d starts", s->id);
197 // Until the sensor is stopped, record data points
198 while (s->record_data)
201 //Log(LOGDEBUG, "Sensor %d reads data [%f,%f]", s->id, d.time_stamp, d.value);
202 if (Sensor_Read(s, &d)) // If new DataPoint is read:
204 //Log(LOGDEBUG, "Sensor %d saves data [%f,%f]", s->id, d.time_stamp, d.value);
205 Data_Save(&(s->data_file), &d, 1); // Record it
209 // Needed to keep pthreads happy
211 Log(LOGDEBUG, "Sensor %d finished", s->id);
216 * Get a Sensor given an ID string
217 * @param id_str ID string
218 * @returns Sensor* identified by the string; NULL on error
220 Sensor * Sensor_Identify(const char * id_str)
223 // Parse string as integer
224 int id = strtol(id_str, &end, 10);
230 if (id < 0 || id >= NUMSENSORS)
234 Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
239 * Helper: Begin sensor response in a given format
240 * @param context - the FCGIContext
241 * @param id - ID of sensor
242 * @param format - Format
244 void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
250 FCGI_BeginJSON(context, STATUS_OK);
251 FCGI_JSONLong("id", id);
254 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
260 * Helper: End sensor response in a given format
261 * @param context - the FCGIContext
262 * @param id - ID of the sensor
263 * @param format - Format
265 void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format)
279 * Handle a request to the sensor module
280 * @param context - The context to work in
281 * @param params - Parameters passed
283 void Sensor_Handler(FCGIContext *context, char * params)
286 gettimeofday(&now, NULL);
287 double current_time = TIMEVAL_DIFF(now, g_options.start_time);
290 double start_time = 0;
291 double end_time = current_time;
292 const char * fmt_str;
295 FCGIValue values[] = {
296 {"id", &id, FCGI_REQUIRED(FCGI_INT_T)},
297 {"format", &fmt_str, FCGI_STRING_T},
298 {"start_time", &start_time, FCGI_DOUBLE_T},
299 {"end_time", &end_time, FCGI_DOUBLE_T},
302 // enum to avoid the use of magic numbers
310 // Fill values appropriately
311 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
313 // Error occured; FCGI_RejectJSON already called
317 // Error checking on sensor id
318 if (id < 0 || id >= NUMSENSORS)
320 FCGI_RejectJSON(context, "Invalid sensor id");
323 Sensor * s = g_sensors+id;
325 DataFormat format = Data_GetFormat(&(values[FORMAT]));
328 Sensor_BeginResponse(context, id, format);
331 Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
334 Sensor_EndResponse(context, id, format);