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 * Sets the sensor to the desired control mode. No checks are
48 * done to see if setting to the desired mode will conflict with
49 * the current mode - the caller must guarantee this itself.
50 * @param s The sensor whose mode is to be changed
51 * @param mode The mode to be changed to
52 * @param arg An argument specific to the mode to be set.
53 * e.g for CONTROL_START it represents the experiment name.
55 void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg)
62 char filename[BUFSIZ];
63 const char *experiment_name = (const char*) arg;
66 if (snprintf(filename, BUFSIZ, "%s_s%d", experiment_name, s->id) >= BUFSIZ)
68 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
71 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
73 Data_Open(&(s->data_file), filename);
76 s->record_data = true; // Don't forget this!
79 ret = pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
82 Fatal("Failed to create Sensor_Loop for Sensor %d", s->id);
86 case CONTROL_EMERGENCY:
88 s->record_data = false;
91 s->record_data = true;
95 s->record_data = false;
96 pthread_join(s->thread, NULL);
98 Data_Close(&(s->data_file)); // Close DataFile
99 s->newest_data.time_stamp = 0;
100 s->newest_data.value = 0;
103 Fatal("Unknown control mode: %d", mode);
108 * Sets all sensors to the desired mode.
109 * @see Sensor_SetMode for more information.
110 * @param mode The mode to be changed to
111 * @param arg An argument specific to the mode to be set.
113 void Sensor_SetModeAll(ControlModes mode, void * arg)
115 for (int i = 0; i < NUMSENSORS; i++)
116 Sensor_SetMode(&g_sensors[i], mode, arg);
121 * Checks the sensor data for unsafe or unexpected results
122 * @param sensor_id - The ID of the sensor
123 * @param value - The value from the sensor to test
125 void Sensor_CheckData(SensorId id, double value)
127 if( value > thresholds[id].max_error || value < thresholds[id].min_error)
129 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);
130 //new function that stops actuators?
132 else if( value > thresholds[id].max_warn || value < thresholds[id].min_warn)
134 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);
140 * Read a DataPoint from a Sensor; block until value is read
141 * @param id - The ID of the sensor
142 * @param d - DataPoint to set
143 * @returns True if the DataPoint was different from the most recently recorded.
145 bool Sensor_Read(Sensor * s, DataPoint * d)
150 gettimeofday(&t, NULL);
151 d->time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());
153 // Read value based on Sensor Id
157 d->value = (double)(rand() % 100) / 100;
161 static int count = 0;
167 d->value = (double)(rand() % 6) * -( rand() % 2) / ( rand() % 100 + 1);
168 //Gives a value between -5 and 5
171 d->value = t.tv_sec % 2;
174 d->value = (t.tv_sec+1)%2;
177 if( rand() % 100 > 98)
179 d->value = rand() % 2;
180 //Gives 0 or 1 or a 2 every 1/100 times
183 Fatal("Unknown sensor id: %d", s->id);
186 usleep(100000); // simulate delay in sensor polling
188 // Perform sanity check based on Sensor's ID and the DataPoint
189 Sensor_CheckData(s->id, d->value);
191 // Update latest DataPoint if necessary
192 bool result = (d->value != s->newest_data.value);
195 s->newest_data.time_stamp = d->time_stamp;
196 s->newest_data.value = d->value;
202 * Record data from a single Sensor; to be run in a seperate thread
203 * @param arg - Cast to Sensor* - Sensor that the thread will handle
204 * @returns NULL (void* required to use the function with pthreads)
206 void * Sensor_Loop(void * arg)
208 Sensor * s = (Sensor*)(arg);
209 Log(LOGDEBUG, "Sensor %d starts", s->id);
211 // Until the sensor is stopped, record data points
217 //Log(LOGDEBUG, "Sensor %d reads data [%f,%f]", s->id, d.time_stamp, d.value);
218 if (Sensor_Read(s, &d)) // If new DataPoint is read:
220 //Log(LOGDEBUG, "Sensor %d saves data [%f,%f]", s->id, d.time_stamp, d.value);
221 Data_Save(&(s->data_file), &d, 1); // Record it
226 //Do something? wait?
231 // Needed to keep pthreads happy
233 Log(LOGDEBUG, "Sensor %d finished", s->id);
238 * Get a Sensor given an ID string
239 * @param id_str ID string
240 * @returns Sensor* identified by the string; NULL on error
242 Sensor * Sensor_Identify(const char * id_str)
245 // Parse string as integer
246 int id = strtol(id_str, &end, 10);
252 if (id < 0 || id >= NUMSENSORS)
256 Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
261 * Helper: Begin sensor response in a given format
262 * @param context - the FCGIContext
263 * @param id - ID of sensor
264 * @param format - Format
266 void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
272 FCGI_BeginJSON(context, STATUS_OK);
273 FCGI_JSONLong("id", id);
276 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
282 * Helper: End sensor response in a given format
283 * @param context - the FCGIContext
284 * @param id - ID of the sensor
285 * @param format - Format
287 void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format)
301 * Handle a request to the sensor module
302 * @param context - The context to work in
303 * @param params - Parameters passed
305 void Sensor_Handler(FCGIContext *context, char * params)
308 gettimeofday(&now, NULL);
309 double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
312 double start_time = 0;
313 double end_time = current_time;
314 const char * fmt_str;
317 FCGIValue values[] = {
318 {"id", &id, FCGI_REQUIRED(FCGI_INT_T)},
319 {"format", &fmt_str, FCGI_STRING_T},
320 {"start_time", &start_time, FCGI_DOUBLE_T},
321 {"end_time", &end_time, FCGI_DOUBLE_T},
324 // enum to avoid the use of magic numbers
332 // Fill values appropriately
333 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
335 // Error occured; FCGI_RejectJSON already called
339 // Error checking on sensor id
340 if (id < 0 || id >= NUMSENSORS)
342 FCGI_RejectJSON(context, "Invalid sensor id");
345 Sensor * s = g_sensors+id;
347 DataFormat format = Data_GetFormat(&(values[FORMAT]));
350 Sensor_BeginResponse(context, id, format);
353 Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
356 Sensor_EndResponse(context, id, format);