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

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