Merge remote-tracking branch 'upstream/master'
[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 user_id - User identifier
24  * @param read - Function to call whenever the sensor should be read
25  * @param init - Function to call to initialise the sensor (may be NULL)
26  * @param max_error - Maximum error threshold; program will exit if this is exceeded for the sensor reading
27  * @param min_error - Minimum error threshold; program will exit if the sensor reading falls below this value
28  * @param max_warn - Maximum warning threshold; program will log warnings if the value exceeds this threshold
29  * @param min_warn - Minimum warning threshold; program will log warnings if the value falls below this threshold
30  * @returns Number of actuators added so far
31  */
32 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 {
34         if (++g_num_sensors > SENSORS_MAX)
35         {
36                 Fatal("Too many sensors; Increase SENSORS_MAX from %d in sensor.h and recompile", SENSORS_MAX);
37                 // We could design the program to use realloc(3)
38                 // But since someone who adds a new sensor has to recompile the program anyway...
39         }
40         Sensor * s = &(g_sensors[g_num_sensors-1]);
41
42         s->id = g_num_sensors-1;
43         s->user_id = user_id;
44         Data_Init(&(s->data_file));
45         s->name = name;
46         s->read = read; // Set read function
47         s->init = init; // Set init function
48         if (init != NULL)
49                 init(name, user_id); // Call it
50
51         // Start by averaging values taken over a second
52         s->sample_us = 1e6;
53         s->averages = 1;
54
55         // Set warning/error thresholds
56         s->thresholds.max_error = max_error;
57         s->thresholds.min_error = min_error;
58         s->thresholds.max_warn = max_warn;
59         s->thresholds.min_warn = min_warn;
60
61         return g_num_sensors;
62 }
63
64 /**
65  * Initialise all sensors used by the program
66  * TODO: Edit this to add any extra sensors you need
67  * TODO: Edit the includes as well
68  */
69 #include "sensors/resource.h"
70 #include "sensors/strain.h"
71 #include "sensors/piped.h"
72 void Sensor_Init()
73 {
74         Sensor_Add("cpu_stime", RESOURCE_CPU_SYS, Resource_Read, NULL, NULL, 1e50,-1e50,1e50,-1e50);    
75         Sensor_Add("cpu_utime", RESOURCE_CPU_USER, Resource_Read, NULL, NULL, 1e50,-1e50,1e50,-1e50);   
76         //Sensor_Add("../testing/count.py", 0, Piped_Read, Piped_Init, Piped_Cleanup, 1e50,-1e50,1e50,-1e50);
77         //Sensor_Add("strain0", STRAIN0, Strain_Read, Strain_Init, 5000,0,5000,0);
78         //Sensor_Add("strain1", STRAIN1, Strain_Read, Strain_Init, 5000,0,5000,0);
79         //Sensor_Add("strain2", STRAIN2, Strain_Read, Strain_Init, 5000,0,5000,0);
80         //Sensor_Add("strain3", STRAIN3, Strain_Read, Strain_Init, 5000,0,5000,0);
81         //Sensor_Add("pressure0", PRESSURE0, Pressure_Read, Pressure_Init, 5000,0,5000,0);
82         //Sensor_Add("pressure1", PRESSURE1, Pressure_Read, Pressure_Init, 5000,0,5000,0);
83         //Sensor_Add("pressure_feedback", PRESSURE_FEEDBACK, Pressure_Read, Pressure_Init, 5000,0,5000,0);
84         //Sensor_Add("enclosure", ENCLOSURE, Enclosure_Read, Enclosure_Init, 1,1,1,1);
85         //Sensor_Add("dilatometer", DILATOMETER, Dilatometer_Read, Dilatometer_Init, -1,-1,-1,-1);
86 }
87
88 /**
89  * Cleanup all sensors
90  */
91 void Sensor_Cleanup()
92 {
93         for (int i = 0; i < g_num_sensors; ++i)
94         {
95                 Sensor * s = g_sensors+i;
96                 if (s->cleanup != NULL)
97                         s->cleanup(s->user_id);
98         }
99 }
100
101 /**
102  * Sets the sensor to the desired control mode. No checks are
103  * done to see if setting to the desired mode will conflict with
104  * the current mode - the caller must guarantee this itself.
105  * @param s The sensor whose mode is to be changed
106  * @param mode The mode to be changed to
107  * @param arg An argument specific to the mode to be set. 
108  *            e.g for CONTROL_START it represents the experiment name.
109  */
110 void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg)
111 {
112         switch(mode)
113         {
114                 case CONTROL_START:
115                         {
116                                 // Set filename
117                                 char filename[BUFSIZ];
118                                 const char *experiment_name = (const char*) arg;
119
120                                 if (snprintf(filename, BUFSIZ, "%s_%d", experiment_name, s->id) >= BUFSIZ)
121                                 {
122                                         Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
123                                 }
124
125                                 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
126                                 // Open DataFile
127                                 Data_Open(&(s->data_file), filename);
128                         }
129                 case CONTROL_RESUME: //Case fallthrough, no break before
130                         {
131                                 int ret;
132                                 s->activated = true; // Don't forget this!
133
134                                 // Create the thread
135                                 ret = pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
136                                 if (ret != 0)
137                                 {
138                                         Fatal("Failed to create Sensor_Loop for Sensor %d", s->id);
139                                 }
140
141                                 Log(LOGDEBUG, "Resuming sensor %d", s->id);
142                         }
143                 break;
144
145                 case CONTROL_EMERGENCY:
146                 case CONTROL_PAUSE:
147                         s->activated = false;
148                         pthread_join(s->thread, NULL);
149                         Log(LOGDEBUG, "Paused sensor %d", s->id);
150                 break;
151                 
152                 case CONTROL_STOP:
153                         if (s->activated) //May have been paused before
154                         {
155                                 s->activated = false;
156                                 pthread_join(s->thread, NULL);
157                         }
158
159                         Data_Close(&(s->data_file)); // Close DataFile
160                         Log(LOGDEBUG, "Stopped sensor %d", s->id);
161                 break;
162                 default:
163                         Fatal("Unknown control mode: %d", mode);
164         }
165 }
166
167 /**
168  * Sets all sensors to the desired mode. 
169  * @see Sensor_SetMode for more information.
170  * @param mode The mode to be changed to
171  * @param arg An argument specific to the mode to be set.
172  */
173 void Sensor_SetModeAll(ControlModes mode, void * arg)
174 {
175         for (int i = 0; i < g_num_sensors; i++)
176                 Sensor_SetMode(&g_sensors[i], mode, arg);
177 }
178
179
180 /**
181  * Checks the sensor data for unsafe or unexpected results 
182  * @param sensor_id - The ID of the sensor
183  * @param value - The value from the sensor to test
184  */
185 void Sensor_CheckData(Sensor * s, double value)
186 {
187         if( value > s->thresholds.max_error || value < s->thresholds.min_error)
188         {
189                 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);
190                 //new function that stops actuators?
191                 //Control_SetMode(CONTROL_EMERGENCY, NULL)
192         }
193         else if( value > s->thresholds.max_warn || value < s->thresholds.min_warn)
194         {
195                 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         }
197 }
198
199
200 /**
201  * Record data from a single Sensor; to be run in a seperate thread
202  * @param arg - Cast to Sensor* - Sensor that the thread will handle
203  * @returns NULL (void* required to use the function with pthreads)
204  */
205 void * Sensor_Loop(void * arg)
206 {
207         Sensor * s = (Sensor*)(arg);
208         Log(LOGDEBUG, "Sensor %d starts", s->id);
209
210         // Until the sensor is stopped, record data points
211         while (s->activated)
212         {
213                 DataPoint d;
214                 d.value = 0;
215                 bool success = s->read(s->user_id, &(d.value));
216
217                 struct timeval t;
218                 gettimeofday(&t, NULL);
219                 d.time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());        
220                 
221                 if (success)
222                 {
223
224
225                         Sensor_CheckData(s, d.value);
226                         Data_Save(&(s->data_file), &d, 1); // Record it
227                 }
228                 else
229                         Log(LOGWARN, "Failed to read sensor %s (%d,%d)", s->name, s->id,s->user_id);
230
231                 usleep(s->sample_us);
232         }
233         
234         // Needed to keep pthreads happy
235         Log(LOGDEBUG, "Sensor %s (%d,%d) finished", s->name,s->id,s->user_id);
236         return NULL;
237 }
238
239 /**
240  * Get a Sensor given its name
241  * @returns Sensor with the given name, NULL if there isn't one
242  */
243 Sensor * Sensor_Identify(const char * name)
244 {       
245         for (int i = 0; i < g_num_sensors; ++i)
246         {
247                 if (strcmp(g_sensors[i].name, name) == 0)
248                         return &(g_sensors[i]);
249         }
250         return NULL;
251 }
252
253 /**
254  * Helper: Begin sensor response in a given format
255  * @param context - the FCGIContext
256  * @param id - ID of sensor
257  * @param format - Format
258  */
259 void Sensor_BeginResponse(FCGIContext * context, Sensor * s, DataFormat format)
260 {
261         // Begin response
262         switch (format)
263         {
264                 case JSON:
265                         FCGI_BeginJSON(context, STATUS_OK);
266                         FCGI_JSONLong("id", s->id);
267                         FCGI_JSONLong("user_id", s->user_id); //NOTE: Might not want to expose this?
268                         FCGI_JSONPair("name", s->name);
269                         break;
270                 default:
271                         FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
272                         break;
273         }
274 }
275
276 /**
277  * Helper: End sensor response in a given format
278  * @param context - the FCGIContext
279  * @param id - ID of the sensor
280  * @param format - Format
281  */
282 void Sensor_EndResponse(FCGIContext * context, Sensor * s, DataFormat format)
283 {
284         // End response
285         switch (format)
286         {
287                 case JSON:
288                         FCGI_EndJSON();
289                         break;
290                 default:
291                         break;
292         }
293 }
294
295 /**
296  * Handle a request to the sensor module
297  * @param context - The context to work in
298  * @param params - Parameters passed
299  */
300 void Sensor_Handler(FCGIContext *context, char * params)
301 {
302         struct timeval now;
303         gettimeofday(&now, NULL);
304         double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
305
306         int id = 0;
307         const char * name = "";
308         double start_time = 0;
309         double end_time = current_time;
310         const char * fmt_str;
311         double sample_s = 0;
312
313         // key/value pairs
314         FCGIValue values[] = {
315                 {"id", &id, FCGI_INT_T}, 
316                 {"name", &name, FCGI_STRING_T},
317                 {"format", &fmt_str, FCGI_STRING_T}, 
318                 {"start_time", &start_time, FCGI_DOUBLE_T}, 
319                 {"end_time", &end_time, FCGI_DOUBLE_T},
320                 {"sample_s", &sample_s, FCGI_DOUBLE_T}
321         };
322
323         // enum to avoid the use of magic numbers
324         typedef enum {
325                 ID,
326                 NAME,
327                 FORMAT,
328                 START_TIME,
329                 END_TIME,
330                 SAMPLE_S
331         } SensorParams;
332         
333         // Fill values appropriately
334         if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
335         {
336                 // Error occured; FCGI_RejectJSON already called
337                 return;
338         }
339
340         Sensor * s = NULL;
341         if (FCGI_RECEIVED(values[NAME].flags))
342         {
343                 if (FCGI_RECEIVED(values[ID].flags))
344                 {
345                         FCGI_RejectJSON(context, "Can't supply both sensor id and name");
346                         return;
347                 }
348                 s = Sensor_Identify(name);
349                 if (s == NULL)
350                 {
351                         FCGI_RejectJSON(context, "Unknown sensor name");
352                         return;
353                 }
354         }
355         else if (!FCGI_RECEIVED(values[ID].flags))
356         {
357                 FCGI_RejectJSON(context, "No sensor id or name supplied");
358                 return;
359         }
360         else if (id < 0 || id >= g_num_sensors)
361         {
362                 FCGI_RejectJSON(context, "Invalid sensor id");
363                 return;
364         }
365         else
366         {
367                 s = &(g_sensors[id]);
368         }
369
370         // Adjust sample rate if necessary
371         if (FCGI_RECEIVED(values[SAMPLE_S].flags))
372         {
373                 if (sample_s < 0)
374                 {
375                         FCGI_RejectJSON(context, "Negative sampling speed!");
376                         return;
377                 }               
378                 s->sample_us = 1e6*sample_s;
379         }
380         
381         
382         DataFormat format = Data_GetFormat(&(values[FORMAT]));
383
384         // Begin response
385         Sensor_BeginResponse(context, s, format);
386
387         // Print Data
388         Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
389         
390         // Finish response
391         Sensor_EndResponse(context, s, format);
392
393 }
394
395 /**
396  * Get the Name of a Sensor
397  * @param id - ID number
398  */
399 const char * Sensor_GetName(int id)
400 {
401         return g_sensors[id].name;
402 }
403
404
405

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