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

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