Make it actually compile...
[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[NUMSENSORS]; //global to this file
15
16 /** Array of sensor threshold structures defining the safety values of each sensor**/
17 const SensorThreshold thresholds[NUMSENSORS]= {
18         //Max Safety, Min safety, Max warning, Min warning
19         {5000,0,5000,0},
20         {5000,0,5000,0},
21         {5000,0,5000,0},
22         {5000,0,5000,0},
23         {5000,0,5000,0},
24         {5000,0,5000,0},
25         {5000,0,5000,0},
26         {5000,0,5000,0},
27         {1, 1, 1, 1}
28 };
29
30 /** Human readable names for the sensors **/
31 const char * g_sensor_names[NUMSENSORS] = {     
32         "strain0",
33         "strain1",
34         "strain2",
35         "strain3",
36         "pressure0",
37         "pressure1",
38         "pressure_feedback",
39         "microphone",
40         "enclosure"
41 };
42
43 /**
44  * One off initialisation of *all* sensors
45  */
46 void Sensor_Init()
47 {
48         for (int i = 0; i < NUMSENSORS; ++i)
49         {
50                 g_sensors[i].id = i;
51                 Data_Init(&(g_sensors[i].data_file));
52         }
53
54
55
56         // Get the required ADCs
57         ADC_Export(ADC0); // Strain gauges x 4
58         ADC_Export(ADC1); // Pressure sensor 1
59         ADC_Export(ADC2); // Pressure sensor 2
60         // ADC3 still unused (!?)
61         ADC_Export(ADC4); // Pressure regulator feedback(?) signal
62         ADC_Export(ADC5); // Microphone
63
64         // Get GPIO pins //TODO: Confirm pins used with Electronics Team
65         GPIO_Export(GPIO0_30); // Mux A (strain 1)
66         GPIO_Set(GPIO0_30, false);
67         GPIO_Export(GPIO1_28); // Mux B (strain 2)
68         GPIO_Set(GPIO1_28, false);
69         GPIO_Export(GPIO0_31); // Mux C (strain 3)
70         GPIO_Set(GPIO0_31, false);
71         GPIO_Export(GPIO1_16); // Mux D (strain 4)
72         GPIO_Set(GPIO1_16, false);
73
74         GPIO_Export(GPIO0_31); // Enclosure switch
75 }
76
77 /**
78  * Sets the sensor to the desired control mode. No checks are
79  * done to see if setting to the desired mode will conflict with
80  * the current mode - the caller must guarantee this itself.
81  * @param s The sensor whose mode is to be changed
82  * @param mode The mode to be changed to
83  * @param arg An argument specific to the mode to be set. 
84  *            e.g for CONTROL_START it represents the experiment name.
85  */
86 void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg)
87 {
88         switch(mode)
89         {
90                 case CONTROL_START:
91                         {
92                                 // Set filename
93                                 char filename[BUFSIZ];
94                                 const char *experiment_name = (const char*) arg;
95
96                                 if (snprintf(filename, BUFSIZ, "%s_s%d", experiment_name, s->id) >= BUFSIZ)
97                                 {
98                                         Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
99                                 }
100
101                                 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
102                                 // Open DataFile
103                                 Data_Open(&(s->data_file), filename);
104                         }
105                 case CONTROL_RESUME: //Case fallthrough, no break before
106                         {
107                                 int ret;
108                                 s->activated = true; // Don't forget this!
109
110                                 // Create the thread
111                                 ret = pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
112                                 if (ret != 0)
113                                 {
114                                         Fatal("Failed to create Sensor_Loop for Sensor %d", s->id);
115                                 }
116
117                                 Log(LOGDEBUG, "Resuming sensor %d", s->id);
118                         }
119                 break;
120
121                 case CONTROL_EMERGENCY:
122                 case CONTROL_PAUSE:
123                         s->activated = false;
124                         pthread_join(s->thread, NULL);
125                         Log(LOGDEBUG, "Paused sensor %d", s->id);
126                 break;
127                 
128                 case CONTROL_STOP:
129                         if (s->activated) //May have been paused before
130                         {
131                                 s->activated = false;
132                                 pthread_join(s->thread, NULL);
133                         }
134
135                         Data_Close(&(s->data_file)); // Close DataFile
136                         s->newest_data.time_stamp = 0;
137                         s->newest_data.value = 0;
138                         Log(LOGDEBUG, "Stopped sensor %d", s->id);
139                 break;
140                 default:
141                         Fatal("Unknown control mode: %d", mode);
142         }
143 }
144
145 /**
146  * Sets all sensors to the desired mode. 
147  * @see Sensor_SetMode for more information.
148  * @param mode The mode to be changed to
149  * @param arg An argument specific to the mode to be set.
150  */
151 void Sensor_SetModeAll(ControlModes mode, void * arg)
152 {
153         for (int i = 0; i < NUMSENSORS; i++)
154                 Sensor_SetMode(&g_sensors[i], mode, arg);
155 }
156
157
158 /**
159  * Checks the sensor data for unsafe or unexpected results 
160  * @param sensor_id - The ID of the sensor
161  * @param value - The value from the sensor to test
162  */
163 void Sensor_CheckData(SensorId id, double value)
164 {
165         if( value > thresholds[id].max_error || value < thresholds[id].min_error)
166         {
167                 Log(LOGERR, "Sensor %s at %f is above or below its safety value of %f or %f\n", g_sensor_names[id],value, thresholds[id].max_error, thresholds[id].min_error);
168                 //new function that stops actuators?
169                 //Control_SetMode(CONTROL_EMERGENCY, NULL)
170         }
171         else if( value > thresholds[id].max_warn || value < thresholds[id].min_warn)
172         {
173                 Log(LOGWARN, "Sensor %s at %f is above or below its warning value of %f or %f\n", g_sensor_names[id],value,thresholds[id].max_warn, thresholds[id].min_warn);   
174         }
175 }
176
177
178 /**
179  * Read a DataPoint from a Sensor; block until value is read
180  * @param id - The ID of the sensor
181  * @param d - DataPoint to set
182  * @returns True if the DataPoint was different from the most recently recorded.
183  */
184 bool Sensor_Read(Sensor * s, DataPoint * d)
185 {
186         
187
188
189         static bool result = true;
190
191         //TODO: Remove this, code should be refactored to not use so many threads
192         // Although... if it works, it works...
193         static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 
194
195         pthread_mutex_lock(&mutex); //TODO: Reduce the critical section
196
197         usleep(10);
198
199         // Set time stamp
200         struct timeval t;
201         gettimeofday(&t, NULL);
202         d->time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());       
203         
204         // Read value based on Sensor Id
205         int value; bool success = true;
206         //TODO: Can probably do this nicer than a switch (define a function pointer for each sensor)
207         //              Can probably make the whole sensor thing a lot nicer with a linked list of sensors...
208         //              (Then to add more sensors to the software, someone just writes an appropriate read function and calls Sensor_Add(...) at init)
209         //              (I will do this. Don't do it before I get a chance, I don't trust you :P)
210         switch (s->id)
211         {
212                 //TODO: Strain gauges should have their own critical section, rest of sensors probably don't need to be in a critical section
213                 case STRAIN0:
214                         success &= GPIO_Set(GPIO0_30, true);
215                         success &= ADC_Read(ADC0, &value);
216                         success &= GPIO_Set(GPIO0_30, false);
217                         if (!success)
218                                 Fatal("Error reading strain gauge 0");
219                         break;
220                 case STRAIN1:
221                         success &= GPIO_Set(GPIO1_28, true);
222                         success &= ADC_Read(ADC0, &value);
223                         success &= GPIO_Set(GPIO1_28, false);
224                         if (!success)
225                                 Fatal("Error reading strain gauge 1");
226                         break;
227                 case STRAIN2:
228                         success &= GPIO_Set(GPIO0_31, true);
229                         success &= ADC_Read(ADC0, &value);
230                         success &= GPIO_Set(GPIO0_31, false);
231                 case STRAIN3:
232                         success &= GPIO_Set(GPIO1_16, true);
233                         success &= ADC_Read(ADC0, &value);
234                         success &= GPIO_Set(GPIO1_16, false);
235                         if (!success)
236                                 Fatal("Error reading strain gauge 2");  
237                         break;          
238                 case PRESSURE0:
239                         success &= ADC_Read(ADC1, &value);
240                         break;
241                 case PRESSURE1:
242                         success &= ADC_Read(ADC5, &value);
243                         break;
244                 case PRESSURE_FEEDBACK:
245                         success &= ADC_Read(ADC4, &value);
246                         break;
247                 case MICROPHONE:
248                         success &= ADC_Read(ADC2, &value);
249                         break;
250                 case ENCLOSURE:
251                 {
252                         bool why_do_i_need_to_do_this = false;
253                         success &= GPIO_Read(GPIO0_31, &why_do_i_need_to_do_this);
254                         value = (int)why_do_i_need_to_do_this;
255                         break;
256                 }
257                 case DILATOMETER:
258                 {
259                         // Will definitely cause issues included in the same critical section as ADC reads
260                         // (since it will be the longest sensor to sample, everything else will have to keep waiting on it)
261                         value = 0;
262                         break;
263                 }
264                 
265         }       
266
267         d->value = (double)(value); //TODO: Calibration? Or do calibration in GUI
268
269         pthread_mutex_unlock(&mutex); //TODO: Reduce the critical section
270         
271
272         // Perform sanity check based on Sensor's ID and the DataPoint
273         Sensor_CheckData(s->id, d->value);
274
275         // Update latest DataPoint if necessary
276         
277         if (result)
278         {
279                 s->newest_data.time_stamp = d->time_stamp;
280                 s->newest_data.value = d->value;
281         }
282
283 #ifdef _BBB
284         //Not all cases have usleep, easiest here.
285         //TODO: May want to add a control option to adjust the sampling rate for each sensor?
286         //              Also, we can get a more accurate sampling rate if instead of a fixed sleep, we calculate how long to sleep each time.
287         usleep(100000);
288 #endif
289
290         /*
291         if (success)
292                 Log(LOGDEBUG, "Successfully read sensor %d (for once)", s->id);
293         else
294                 Log(LOGDEBUG, "Failed to read sensor %d (again)", s->id);
295         */
296         return result && success;
297 }
298
299 /**
300  * Record data from a single Sensor; to be run in a seperate thread
301  * @param arg - Cast to Sensor* - Sensor that the thread will handle
302  * @returns NULL (void* required to use the function with pthreads)
303  */
304 void * Sensor_Loop(void * arg)
305 {
306         Sensor * s = (Sensor*)(arg);
307         Log(LOGDEBUG, "Sensor %d starts", s->id);
308
309         // Until the sensor is stopped, record data points
310         while (s->activated)
311         {
312                 DataPoint d;
313                 //Log(LOGDEBUG, "Sensor %d reads data [%f,%f]", s->id, d.time_stamp, d.value);
314                 if (Sensor_Read(s, &d)) // If new DataPoint is read:
315                 {
316                         //Log(LOGDEBUG, "Sensor %d saves data [%f,%f]", s->id, d.time_stamp, d.value);
317                         Data_Save(&(s->data_file), &d, 1); // Record it
318                 }
319         }
320         
321         // Needed to keep pthreads happy
322
323         Log(LOGDEBUG, "Sensor %d finished", s->id);
324         return NULL;
325 }
326
327 /**
328  * Get a Sensor given an ID string
329  * @param id_str ID string
330  * @returns Sensor* identified by the string; NULL on error
331  */
332 Sensor * Sensor_Identify(const char * id_str)
333 {
334         char * end;
335         // Parse string as integer
336         int id = strtol(id_str, &end, 10);
337         if (*end != '\0')
338         {
339                 return NULL;
340         }
341         // Bounds check
342         if (id < 0 || id >= NUMSENSORS)
343                 return NULL;
344
345
346         Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
347         return g_sensors+id;
348 }
349
350 /**
351  * Helper: Begin sensor response in a given format
352  * @param context - the FCGIContext
353  * @param id - ID of sensor
354  * @param format - Format
355  */
356 void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
357 {
358         // Begin response
359         switch (format)
360         {
361                 case JSON:
362                         FCGI_BeginJSON(context, STATUS_OK);
363                         FCGI_JSONLong("id", id);
364                         FCGI_JSONPair("name", g_sensor_names[id]);
365                         break;
366                 default:
367                         FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
368                         break;
369         }
370 }
371
372 /**
373  * Helper: End sensor response in a given format
374  * @param context - the FCGIContext
375  * @param id - ID of the sensor
376  * @param format - Format
377  */
378 void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format)
379 {
380         // End response
381         switch (format)
382         {
383                 case JSON:
384                         FCGI_EndJSON();
385                         break;
386                 default:
387                         break;
388         }
389 }
390
391 /**
392  * Handle a request to the sensor module
393  * @param context - The context to work in
394  * @param params - Parameters passed
395  */
396 void Sensor_Handler(FCGIContext *context, char * params)
397 {
398         struct timeval now;
399         gettimeofday(&now, NULL);
400         double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
401
402         int id = 0;
403         double start_time = 0;
404         double end_time = current_time;
405         const char * fmt_str;
406
407         // key/value pairs
408         FCGIValue values[] = {
409                 {"id", &id, FCGI_REQUIRED(FCGI_INT_T)}, 
410                 {"format", &fmt_str, FCGI_STRING_T}, 
411                 {"start_time", &start_time, FCGI_DOUBLE_T}, 
412                 {"end_time", &end_time, FCGI_DOUBLE_T},
413         };
414
415         // enum to avoid the use of magic numbers
416         typedef enum {
417                 ID,
418                 FORMAT,
419                 START_TIME,
420                 END_TIME,
421         } SensorParams;
422         
423         // Fill values appropriately
424         if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
425         {
426                 // Error occured; FCGI_RejectJSON already called
427                 return;
428         }
429
430         // Error checking on sensor id
431         if (id < 0 || id >= NUMSENSORS)
432         {
433                 FCGI_RejectJSON(context, "Invalid sensor id");
434                 return;
435         }
436         Sensor * s = g_sensors+id;
437
438         DataFormat format = Data_GetFormat(&(values[FORMAT]));
439
440         // Begin response
441         Sensor_BeginResponse(context, id, format);
442
443         // Print Data
444         Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
445         
446         // Finish response
447         Sensor_EndResponse(context, id, format);
448 }
449
450
451

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