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

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