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

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