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

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