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));
46 * Sets the sensor to the desired control mode. No checks are
47 * done to see if setting to the desired mode will conflict with
48 * the current mode - the caller must guarantee this itself.
49 * @param s The sensor whose mode is to be changed
50 * @param mode The mode to be changed to
51 * @param arg An argument specific to the mode to be set.
52 * e.g for CONTROL_START it represents the experiment name.
54 void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg)
61 char filename[BUFSIZ];
62 const char *experiment_name = (const char*) arg;
64 if (snprintf(filename, BUFSIZ, "%s_s%d", experiment_name, s->id) >= BUFSIZ)
66 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
69 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
71 Data_Open(&(s->data_file), filename);
73 case CONTROL_RESUME: //Case fallthrough, no break before
76 s->activated = 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);
85 Log(LOGDEBUG, "Resuming sensor %d", s->id);
89 case CONTROL_EMERGENCY:
92 pthread_join(s->thread, NULL);
93 Log(LOGDEBUG, "Paused sensor %d", s->id);
97 if (s->activated) //May have been paused before
100 pthread_join(s->thread, NULL);
103 Data_Close(&(s->data_file)); // Close DataFile
104 s->newest_data.time_stamp = 0;
105 s->newest_data.value = 0;
106 Log(LOGDEBUG, "Stopped sensor %d", s->id);
109 Fatal("Unknown control mode: %d", mode);
114 * Sets all sensors to the desired mode.
115 * @see Sensor_SetMode for more information.
116 * @param mode The mode to be changed to
117 * @param arg An argument specific to the mode to be set.
119 void Sensor_SetModeAll(ControlModes mode, void * arg)
121 for (int i = 0; i < NUMSENSORS; i++)
122 Sensor_SetMode(&g_sensors[i], mode, arg);
127 * Checks the sensor data for unsafe or unexpected results
128 * @param sensor_id - The ID of the sensor
129 * @param value - The value from the sensor to test
131 void Sensor_CheckData(SensorId id, double value)
133 if( value > thresholds[id].max_error || value < thresholds[id].min_error)
135 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);
136 //new function that stops actuators?
137 //Control_SetMode(CONTROL_EMERGENCY, NULL)
139 else if( value > thresholds[id].max_warn || value < thresholds[id].min_warn)
141 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);
147 * Read a DataPoint from a Sensor; block until value is read
148 * @param id - The ID of the sensor
149 * @param d - DataPoint to set
150 * @returns True if the DataPoint was different from the most recently recorded.
152 bool Sensor_Read(Sensor * s, DataPoint * d)
157 gettimeofday(&t, NULL);
158 d->time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());
160 // Read value based on Sensor Id
164 d->value = (double)(rand() % 100) / 100;
168 static int count = 0;
174 d->value = (double)(rand() % 6) * -( rand() % 2) / ( rand() % 100 + 1);
175 //Gives a value between -5 and 5
178 d->value = t.tv_sec % 2;
181 d->value = (t.tv_sec+1)%2;
184 if( rand() % 100 > 98)
186 d->value = rand() % 2;
187 //Gives 0 or 1 or a 2 every 1/100 times
190 Fatal("Unknown sensor id: %d", s->id);
193 usleep(100000); // simulate delay in sensor polling
195 // Perform sanity check based on Sensor's ID and the DataPoint
196 Sensor_CheckData(s->id, d->value);
198 // Update latest DataPoint if necessary
199 bool result = (d->value != s->newest_data.value);
202 s->newest_data.time_stamp = d->time_stamp;
203 s->newest_data.value = d->value;
209 * Record data from a single Sensor; to be run in a seperate thread
210 * @param arg - Cast to Sensor* - Sensor that the thread will handle
211 * @returns NULL (void* required to use the function with pthreads)
213 void * Sensor_Loop(void * arg)
215 Sensor * s = (Sensor*)(arg);
216 Log(LOGDEBUG, "Sensor %d starts", s->id);
218 // Until the sensor is stopped, record data points
222 //Log(LOGDEBUG, "Sensor %d reads data [%f,%f]", s->id, d.time_stamp, d.value);
223 if (Sensor_Read(s, &d)) // If new DataPoint is read:
225 //Log(LOGDEBUG, "Sensor %d saves data [%f,%f]", s->id, d.time_stamp, d.value);
226 Data_Save(&(s->data_file), &d, 1); // Record it
230 // Needed to keep pthreads happy
232 Log(LOGDEBUG, "Sensor %d finished", s->id);
237 * Get a Sensor given an ID string
238 * @param id_str ID string
239 * @returns Sensor* identified by the string; NULL on error
241 Sensor * Sensor_Identify(const char * id_str)
244 // Parse string as integer
245 int id = strtol(id_str, &end, 10);
251 if (id < 0 || id >= NUMSENSORS)
255 Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
260 * Helper: Begin sensor response in a given format
261 * @param context - the FCGIContext
262 * @param id - ID of sensor
263 * @param format - Format
265 void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
271 FCGI_BeginJSON(context, STATUS_OK);
272 FCGI_JSONLong("id", id);
275 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
281 * Helper: End sensor response in a given format
282 * @param context - the FCGIContext
283 * @param id - ID of the sensor
284 * @param format - Format
286 void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format)
300 * Handle a request to the sensor module
301 * @param context - The context to work in
302 * @param params - Parameters passed
304 void Sensor_Handler(FCGIContext *context, char * params)
307 gettimeofday(&now, NULL);
308 double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
311 double start_time = 0;
312 double end_time = current_time;
313 const char * fmt_str;
316 FCGIValue values[] = {
317 {"id", &id, FCGI_REQUIRED(FCGI_INT_T)},
318 {"format", &fmt_str, FCGI_STRING_T},
319 {"start_time", &start_time, FCGI_DOUBLE_T},
320 {"end_time", &end_time, FCGI_DOUBLE_T},
323 // enum to avoid the use of magic numbers
331 // Fill values appropriately
332 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
334 // Error occured; FCGI_RejectJSON already called
338 // Error checking on sensor id
339 if (id < 0 || id >= NUMSENSORS)
341 FCGI_RejectJSON(context, "Invalid sensor id");
344 Sensor * s = g_sensors+id;
346 DataFormat format = Data_GetFormat(&(values[FORMAT]));
349 Sensor_BeginResponse(context, id, format);
352 Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
355 Sensor_EndResponse(context, id, format);