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

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