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

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