MAJOR refactoring of Sensors code
[matches/MCTX3420.git] / server / sensor.c
1 /**
2  * @file sensor.c
3  * @brief Implementation of sensor thread
4  * TODO: Finalise implementation
5  */
6
7 #include "common.h"
8 #include "sensor.h"
9 #include "options.h"
10 #include "bbb_pin.h"
11 #include <math.h>
12
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;
17
18
19
20 /** 
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
30  */
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)
32 {
33         if (++g_num_sensors > SENSORS_MAX)
34         {
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...
38         }
39         Sensor * s = &(g_sensors[g_num_sensors-1]);
40
41         s->id = g_num_sensors-1;
42         s->user_id = user_id;
43         Data_Init(&(s->data_file));
44         s->name = name;
45         s->read = read; // Set read function
46         s->init = init; // Set init function
47         if (init != NULL)
48                 init(name, user_id); // Call it
49
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;
55
56         return g_num_sensors;
57 }
58
59 /**
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
63  */
64 #include "sensors/resource.h"
65 #include "sensors/strain.h"
66 #include "sensors/piped.h"
67 void Sensor_Init()
68 {
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);
81 }
82
83 /**
84  * Cleanup all sensors
85  */
86 void Sensor_Cleanup()
87 {
88         for (int i = 0; i < g_num_sensors; ++i)
89         {
90                 Sensor * s = g_sensors+i;
91                 if (s->cleanup != NULL)
92                         s->cleanup(s->user_id);
93         }
94 }
95
96 /**
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.
104  */
105 void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg)
106 {
107         switch(mode)
108         {
109                 case CONTROL_START:
110                         {
111                                 // Set filename
112                                 char filename[BUFSIZ];
113                                 const char *experiment_name = (const char*) arg;
114
115                                 if (snprintf(filename, BUFSIZ, "%s_%d", experiment_name, s->id) >= BUFSIZ)
116                                 {
117                                         Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
118                                 }
119
120                                 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
121                                 // Open DataFile
122                                 Data_Open(&(s->data_file), filename);
123                         }
124                 case CONTROL_RESUME: //Case fallthrough, no break before
125                         {
126                                 int ret;
127                                 s->activated = true; // Don't forget this!
128
129                                 // Create the thread
130                                 ret = pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
131                                 if (ret != 0)
132                                 {
133                                         Fatal("Failed to create Sensor_Loop for Sensor %d", s->id);
134                                 }
135
136                                 Log(LOGDEBUG, "Resuming sensor %d", s->id);
137                         }
138                 break;
139
140                 case CONTROL_EMERGENCY:
141                 case CONTROL_PAUSE:
142                         s->activated = false;
143                         pthread_join(s->thread, NULL);
144                         Log(LOGDEBUG, "Paused sensor %d", s->id);
145                 break;
146                 
147                 case CONTROL_STOP:
148                         if (s->activated) //May have been paused before
149                         {
150                                 s->activated = false;
151                                 pthread_join(s->thread, NULL);
152                         }
153
154                         Data_Close(&(s->data_file)); // Close DataFile
155                         Log(LOGDEBUG, "Stopped sensor %d", s->id);
156                 break;
157                 default:
158                         Fatal("Unknown control mode: %d", mode);
159         }
160 }
161
162 /**
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.
167  */
168 void Sensor_SetModeAll(ControlModes mode, void * arg)
169 {
170         for (int i = 0; i < g_num_sensors; i++)
171                 Sensor_SetMode(&g_sensors[i], mode, arg);
172 }
173
174
175 /**
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
179  */
180 void Sensor_CheckData(Sensor * s, double value)
181 {
182         if( value > s->thresholds.max_error || value < s->thresholds.min_error)
183         {
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)
187         }
188         else if( value > s->thresholds.max_warn || value < s->thresholds.min_warn)
189         {
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);        
191         }
192 }
193
194
195 /**
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)
199  */
200 void * Sensor_Loop(void * arg)
201 {
202         Sensor * s = (Sensor*)(arg);
203         Log(LOGDEBUG, "Sensor %d starts", s->id);
204
205         // Until the sensor is stopped, record data points
206         while (s->activated)
207         {
208                 DataPoint d;
209                 d.value = 0;
210                 bool success = s->read(s->user_id, &(d.value));
211
212                 struct timeval t;
213                 gettimeofday(&t, NULL);
214                 d.time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());        
215                 
216                 if (success)
217                 {
218
219
220                         Sensor_CheckData(s, d.value);
221                         Data_Save(&(s->data_file), &d, 1); // Record it
222                 }
223                 else
224                         Log(LOGWARN, "Failed to read sensor %s (%d,%d)", s->name, s->id,s->user_id);
225
226                 usleep(1e5); //TODO: Adjust appropriately 
227         }
228         
229         // Needed to keep pthreads happy
230         Log(LOGDEBUG, "Sensor %s (%d,%d) finished", s->name,s->id,s->user_id);
231         return NULL;
232 }
233
234 /**
235  * Get a Sensor given its name
236  * @returns Sensor with the given name, NULL if there isn't one
237  */
238 Sensor * Sensor_Identify(const char * name)
239 {       
240         for (int i = 0; i < g_num_sensors; ++i)
241         {
242                 if (strcmp(g_sensors[i].name, name) == 0)
243                         return &(g_sensors[i]);
244         }
245         return NULL;
246 }
247
248 /**
249  * Helper: Begin sensor response in a given format
250  * @param context - the FCGIContext
251  * @param id - ID of sensor
252  * @param format - Format
253  */
254 void Sensor_BeginResponse(FCGIContext * context, Sensor * s, DataFormat format)
255 {
256         // Begin response
257         switch (format)
258         {
259                 case JSON:
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);
264                         break;
265                 default:
266                         FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
267                         break;
268         }
269 }
270
271 /**
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
276  */
277 void Sensor_EndResponse(FCGIContext * context, Sensor * s, DataFormat format)
278 {
279         // End response
280         switch (format)
281         {
282                 case JSON:
283                         FCGI_EndJSON();
284                         break;
285                 default:
286                         break;
287         }
288 }
289
290 /**
291  * Handle a request to the sensor module
292  * @param context - The context to work in
293  * @param params - Parameters passed
294  */
295 void Sensor_Handler(FCGIContext *context, char * params)
296 {
297         struct timeval now;
298         gettimeofday(&now, NULL);
299         double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
300
301         int id = 0;
302         const char * name = "";
303         double start_time = 0;
304         double end_time = current_time;
305         const char * fmt_str;
306
307         // key/value pairs
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},
314         };
315
316         // enum to avoid the use of magic numbers
317         typedef enum {
318                 ID,
319                 NAME,
320                 FORMAT,
321                 START_TIME,
322                 END_TIME,
323         } SensorParams;
324         
325         // Fill values appropriately
326         if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
327         {
328                 // Error occured; FCGI_RejectJSON already called
329                 return;
330         }
331
332         Sensor * s = &(g_sensors[id]); // If id was not supplied, this defaults to &(g_sensors[0])
333         if (FCGI_RECEIVED(values[NAME].flags))
334         {
335                 if (FCGI_RECEIVED(values[ID].flags))
336                 {
337                         FCGI_RejectJSON(context, "Can't supply both sensor id and name");
338                         return;
339                 }
340                 s = Sensor_Identify(name);
341                 if (s == NULL)
342                 {
343                         FCGI_RejectJSON(context, "Unknown sensor name");
344                         return;
345                 }
346         }
347         else if (!FCGI_RECEIVED(values[ID].flags))
348         {
349                 FCGI_RejectJSON(context, "No sensor id or name supplied");
350                 return;
351         }
352
353         DataFormat format = Data_GetFormat(&(values[FORMAT]));
354
355         // Begin response
356         Sensor_BeginResponse(context, s, format);
357
358         // Print Data
359         Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
360         
361         // Finish response
362         Sensor_EndResponse(context, s, format);
363 }
364
365 /**
366  * Get the Name of a Sensor
367  * @param id - ID number
368  */
369 const char * Sensor_GetName(int id)
370 {
371         return g_sensors[id].name;
372 }
373
374
375

UCC git Repository :: git.ucc.asn.au