3 * @brief Implementation of sensor thread
4 * TODO: Finalise implementation
13 /** Array of sensors, initialised by Sensor_Init **/
14 static Sensor g_sensors[SENSORS_MAX];
15 /** The number of sensors **/
16 int g_num_sensors = 0;
21 * Add and initialise a Sensor
22 * @param name - Human readable name of the sensor
23 * @param read - Function to call whenever the sensor should be read
24 * @param init - Function to call to initialise the sensor (may be NULL)
25 * @param max_error - Maximum error threshold; program will exit if this is exceeded for the sensor reading
26 * @param min_error - Minimum error threshold; program will exit if the sensor reading falls below this value
27 * @param max_warn - Maximum warning threshold; program will log warnings if the value exceeds this threshold
28 * @param min_warn - Minimum warning threshold; program will log warnings if the value falls below this threshold
29 * @returns Number of the sensor added
31 int Sensor_Add(const char * name, int user_id, ReadFn read, InitFn init, CleanFn cleanup, double max_error, double min_error, double max_warn, double min_warn)
33 if (++g_num_sensors > SENSORS_MAX)
35 Fatal("Too many sensors; Increase SENSORS_MAX from %d in sensor.h and recompile", SENSORS_MAX);
36 // We could design the program to use realloc(3)
37 // But since someone who adds a new sensor has to recompile the program anyway...
39 Sensor * s = &(g_sensors[g_num_sensors-1]);
41 s->id = g_num_sensors-1;
43 Data_Init(&(s->data_file));
45 s->read = read; // Set read function
46 s->init = init; // Set init function
48 init(name, user_id); // Call it
50 // Set warning/error thresholds
51 s->thresholds.max_error = max_error;
52 s->thresholds.min_error = min_error;
53 s->thresholds.max_warn = max_warn;
54 s->thresholds.min_warn = min_warn;
60 * Initialise all sensors used by the program
61 * TODO: Edit this to add any extra sensors you need
62 * TODO: Edit the includes as well
64 #include "sensors/resource.h"
65 #include "sensors/strain.h"
66 #include "sensors/piped.h"
69 Sensor_Add("cpu_stime", RESOURCE_CPU_SYS, Resource_Read, NULL, NULL, 1e50,-1e50,1e50,-1e50);
70 Sensor_Add("cpu_utime", RESOURCE_CPU_USER, Resource_Read, NULL, NULL, 1e50,-1e50,1e50,-1e50);
71 //Sensor_Add("../testing/count.py", 0, Piped_Read, Piped_Init, Piped_Cleanup, 1e50,-1e50,1e50,-1e50);
72 //Sensor_Add("strain0", STRAIN0, Strain_Read, Strain_Init, 5000,0,5000,0);
73 //Sensor_Add("strain1", STRAIN1, Strain_Read, Strain_Init, 5000,0,5000,0);
74 //Sensor_Add("strain2", STRAIN2, Strain_Read, Strain_Init, 5000,0,5000,0);
75 //Sensor_Add("strain3", STRAIN3, Strain_Read, Strain_Init, 5000,0,5000,0);
76 //Sensor_Add("pressure0", PRESSURE0, Pressure_Read, Pressure_Init, 5000,0,5000,0);
77 //Sensor_Add("pressure1", PRESSURE1, Pressure_Read, Pressure_Init, 5000,0,5000,0);
78 //Sensor_Add("pressure_feedback", PRESSURE_FEEDBACK, Pressure_Read, Pressure_Init, 5000,0,5000,0);
79 //Sensor_Add("enclosure", ENCLOSURE, Enclosure_Read, Enclosure_Init, 1,1,1,1);
80 //Sensor_Add("dilatometer", DILATOMETER, Dilatometer_Read, Dilatometer_Init, -1,-1,-1,-1);
88 for (int i = 0; i < g_num_sensors; ++i)
90 Sensor * s = g_sensors+i;
91 if (s->cleanup != NULL)
92 s->cleanup(s->user_id);
97 * Sets the sensor to the desired control mode. No checks are
98 * done to see if setting to the desired mode will conflict with
99 * the current mode - the caller must guarantee this itself.
100 * @param s The sensor whose mode is to be changed
101 * @param mode The mode to be changed to
102 * @param arg An argument specific to the mode to be set.
103 * e.g for CONTROL_START it represents the experiment name.
105 void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg)
112 char filename[BUFSIZ];
113 const char *experiment_name = (const char*) arg;
115 if (snprintf(filename, BUFSIZ, "%s_%d", experiment_name, s->id) >= BUFSIZ)
117 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
120 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
122 Data_Open(&(s->data_file), filename);
124 case CONTROL_RESUME: //Case fallthrough, no break before
127 s->activated = true; // Don't forget this!
130 ret = pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
133 Fatal("Failed to create Sensor_Loop for Sensor %d", s->id);
136 Log(LOGDEBUG, "Resuming sensor %d", s->id);
140 case CONTROL_EMERGENCY:
142 s->activated = false;
143 pthread_join(s->thread, NULL);
144 Log(LOGDEBUG, "Paused sensor %d", s->id);
148 if (s->activated) //May have been paused before
150 s->activated = false;
151 pthread_join(s->thread, NULL);
154 Data_Close(&(s->data_file)); // Close DataFile
155 Log(LOGDEBUG, "Stopped sensor %d", s->id);
158 Fatal("Unknown control mode: %d", mode);
163 * Sets all sensors to the desired mode.
164 * @see Sensor_SetMode for more information.
165 * @param mode The mode to be changed to
166 * @param arg An argument specific to the mode to be set.
168 void Sensor_SetModeAll(ControlModes mode, void * arg)
170 for (int i = 0; i < g_num_sensors; i++)
171 Sensor_SetMode(&g_sensors[i], mode, arg);
176 * Checks the sensor data for unsafe or unexpected results
177 * @param sensor_id - The ID of the sensor
178 * @param value - The value from the sensor to test
180 void Sensor_CheckData(Sensor * s, double value)
182 if( value > s->thresholds.max_error || value < s->thresholds.min_error)
184 Log(LOGERR, "Sensor %s at %f is above or below its safety value of %f or %f\n",s->name,value, s->thresholds.max_error, s->thresholds.min_error);
185 //new function that stops actuators?
186 //Control_SetMode(CONTROL_EMERGENCY, NULL)
188 else if( value > s->thresholds.max_warn || value < s->thresholds.min_warn)
190 Log(LOGWARN, "Sensor %s at %f is above or below its warning value of %f or %f\n", s->name,value,s->thresholds.max_warn, s->thresholds.min_warn);
196 * Record data from a single Sensor; to be run in a seperate thread
197 * @param arg - Cast to Sensor* - Sensor that the thread will handle
198 * @returns NULL (void* required to use the function with pthreads)
200 void * Sensor_Loop(void * arg)
202 Sensor * s = (Sensor*)(arg);
203 Log(LOGDEBUG, "Sensor %d starts", s->id);
205 // Until the sensor is stopped, record data points
210 bool success = s->read(s->user_id, &(d.value));
213 gettimeofday(&t, NULL);
214 d.time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());
220 Sensor_CheckData(s, d.value);
221 Data_Save(&(s->data_file), &d, 1); // Record it
224 Log(LOGWARN, "Failed to read sensor %s (%d,%d)", s->name, s->id,s->user_id);
226 usleep(1e5); //TODO: Adjust appropriately
229 // Needed to keep pthreads happy
230 Log(LOGDEBUG, "Sensor %s (%d,%d) finished", s->name,s->id,s->user_id);
235 * Get a Sensor given its name
236 * @returns Sensor with the given name, NULL if there isn't one
238 Sensor * Sensor_Identify(const char * name)
240 for (int i = 0; i < g_num_sensors; ++i)
242 if (strcmp(g_sensors[i].name, name) == 0)
243 return &(g_sensors[i]);
249 * Helper: Begin sensor response in a given format
250 * @param context - the FCGIContext
251 * @param id - ID of sensor
252 * @param format - Format
254 void Sensor_BeginResponse(FCGIContext * context, Sensor * s, DataFormat format)
260 FCGI_BeginJSON(context, STATUS_OK);
261 FCGI_JSONLong("id", s->id);
262 FCGI_JSONLong("user_id", s->user_id); //NOTE: Might not want to expose this?
263 FCGI_JSONPair("name", s->name);
266 FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
272 * Helper: End sensor response in a given format
273 * @param context - the FCGIContext
274 * @param id - ID of the sensor
275 * @param format - Format
277 void Sensor_EndResponse(FCGIContext * context, Sensor * s, DataFormat format)
291 * Handle a request to the sensor module
292 * @param context - The context to work in
293 * @param params - Parameters passed
295 void Sensor_Handler(FCGIContext *context, char * params)
298 gettimeofday(&now, NULL);
299 double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
302 const char * name = "";
303 double start_time = 0;
304 double end_time = current_time;
305 const char * fmt_str;
308 FCGIValue values[] = {
309 {"id", &id, FCGI_INT_T},
310 {"name", &name, FCGI_STRING_T},
311 {"format", &fmt_str, FCGI_STRING_T},
312 {"start_time", &start_time, FCGI_DOUBLE_T},
313 {"end_time", &end_time, FCGI_DOUBLE_T},
316 // enum to avoid the use of magic numbers
325 // Fill values appropriately
326 if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
328 // Error occured; FCGI_RejectJSON already called
332 Sensor * s = &(g_sensors[id]); // If id was not supplied, this defaults to &(g_sensors[0])
333 if (FCGI_RECEIVED(values[NAME].flags))
335 if (FCGI_RECEIVED(values[ID].flags))
337 FCGI_RejectJSON(context, "Can't supply both sensor id and name");
340 s = Sensor_Identify(name);
343 FCGI_RejectJSON(context, "Unknown sensor name");
347 else if (!FCGI_RECEIVED(values[ID].flags))
349 FCGI_RejectJSON(context, "No sensor id or name supplied");
353 DataFormat format = Data_GetFormat(&(values[FORMAT]));
356 Sensor_BeginResponse(context, s, format);
359 Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
362 Sensor_EndResponse(context, s, format);
366 * Get the Name of a Sensor
367 * @param id - ID number
369 const char * Sensor_GetName(int id)
371 return g_sensors[id].name;