Merge branch 'master' of https://github.com/firefields/MCTX3420
[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         {1,-1,1,-1},            // ANALOG_TEST0
20         {500,0,499,0},          // ANALOG_TEST1
21         {5000,0,5000,0},                // ANALOG_REALTEST
22         {5,-5,4,-4},            // ANALOG_FAIL0
23         {1,0,1,0},                      // DIGITAL_TEST0
24         {1,0,1,0},                      // DIGITAL_TEST1
25         {1,0,1,0},                      // DIGITAL_REALTEST
26         {1,0,1,0}                       // DIGITAL_FAIL0
27 };
28
29 /** Human readable names for the sensors **/
30 const char * g_sensor_names[NUMSENSORS] = {     
31         "analog_test0", "analog_test1", 
32         "analog_realtest", "analog_fail0",
33         "digital_test0", "digital_test1", 
34         "digital_realtest", "digital_fail0"
35 };
36
37 /**
38  * One off initialisation of *all* sensors
39  */
40 void Sensor_Init()
41 {
42         for (int i = 0; i < NUMSENSORS; ++i)
43         {
44                 g_sensors[i].id = i;
45                 Data_Init(&(g_sensors[i].data_file));
46         }
47
48         // Get the required ADCs
49         ADC_Export(0);
50
51         // GPIO1_28 used as a pulse for sampling
52         //GPIO_Export(GPIO1_28);
53         // GPIO0_30 toggled during sampling
54         //GPIO_Export(GPIO0_30);
55 }
56
57 /**
58  * Sets the sensor to the desired control mode. No checks are
59  * done to see if setting to the desired mode will conflict with
60  * the current mode - the caller must guarantee this itself.
61  * @param s The sensor whose mode is to be changed
62  * @param mode The mode to be changed to
63  * @param arg An argument specific to the mode to be set. 
64  *            e.g for CONTROL_START it represents the experiment name.
65  */
66 void Sensor_SetMode(Sensor * s, ControlModes mode, void * arg)
67 {
68         switch(mode)
69         {
70                 case CONTROL_START:
71                         {
72                                 // Set filename
73                                 char filename[BUFSIZ];
74                                 const char *experiment_name = (const char*) arg;
75
76                                 if (snprintf(filename, BUFSIZ, "%s_s%d", experiment_name, s->id) >= BUFSIZ)
77                                 {
78                                         Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
79                                 }
80
81                                 Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
82                                 // Open DataFile
83                                 Data_Open(&(s->data_file), filename);
84                         }
85                 case CONTROL_RESUME: //Case fallthrough, no break before
86                         {
87                                 int ret;
88                                 s->activated = true; // Don't forget this!
89
90                                 // Create the thread
91                                 ret = pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
92                                 if (ret != 0)
93                                 {
94                                         Fatal("Failed to create Sensor_Loop for Sensor %d", s->id);
95                                 }
96
97                                 Log(LOGDEBUG, "Resuming sensor %d", s->id);
98                         }
99                 break;
100
101                 case CONTROL_EMERGENCY:
102                 case CONTROL_PAUSE:
103                         s->activated = false;
104                         pthread_join(s->thread, NULL);
105                         Log(LOGDEBUG, "Paused sensor %d", s->id);
106                 break;
107                 
108                 case CONTROL_STOP:
109                         if (s->activated) //May have been paused before
110                         {
111                                 s->activated = false;
112                                 pthread_join(s->thread, NULL);
113                         }
114
115                         Data_Close(&(s->data_file)); // Close DataFile
116                         s->newest_data.time_stamp = 0;
117                         s->newest_data.value = 0;
118                         Log(LOGDEBUG, "Stopped sensor %d", s->id);
119                 break;
120                 default:
121                         Fatal("Unknown control mode: %d", mode);
122         }
123 }
124
125 /**
126  * Sets all sensors to the desired mode. 
127  * @see Sensor_SetMode for more information.
128  * @param mode The mode to be changed to
129  * @param arg An argument specific to the mode to be set.
130  */
131 void Sensor_SetModeAll(ControlModes mode, void * arg)
132 {
133         for (int i = 0; i < NUMSENSORS; i++)
134                 Sensor_SetMode(&g_sensors[i], mode, arg);
135 }
136
137
138 /**
139  * Checks the sensor data for unsafe or unexpected results 
140  * @param sensor_id - The ID of the sensor
141  * @param value - The value from the sensor to test
142  */
143 void Sensor_CheckData(SensorId id, double value)
144 {
145         if( value > thresholds[id].max_error || value < thresholds[id].min_error)
146         {
147                 Log(LOGERR, "Sensor %s at %f is above or below its safety value of %f or %f\n", value, g_sensor_names[id],thresholds[id].max_error, thresholds[id].min_error);
148                 //new function that stops actuators?
149                 //Control_SetMode(CONTROL_EMERGENCY, NULL)
150         }
151         else if( value > thresholds[id].max_warn || value < thresholds[id].min_warn)
152         {
153                 Log(LOGWARN, "Sensor %s at %f is above or below its warning value of %f or %f\n", value, g_sensor_names[id],thresholds[id].max_warn, thresholds[id].min_warn);  
154         }
155 }
156
157
158 /**
159  * Read a DataPoint from a Sensor; block until value is read
160  * @param id - The ID of the sensor
161  * @param d - DataPoint to set
162  * @returns True if the DataPoint was different from the most recently recorded.
163  */
164 bool Sensor_Read(Sensor * s, DataPoint * d)
165 {
166         
167         // Set time stamp
168         struct timeval t;
169         gettimeofday(&t, NULL);
170         d->time_stamp = TIMEVAL_DIFF(t, *Control_GetStartTime());
171
172         static bool result = true;
173         
174         
175         // Read value based on Sensor Id
176         switch (s->id)
177         {
178                 case 2:
179                 {
180                         static bool set = false;
181                         int raw_adc = 0;
182                         //GPIO_Set(GPIO0_30, true);
183                         ADC_Read(ADC0, &raw_adc);
184                         d->value = (double)raw_adc;     //ADC #0 on the Beaglebone
185                         //Log(LOGDEBUG, "Got value %f from ADC0", d->value);
186                         //GPIO_Set(GPIO0_30, false);
187                         set = !set;
188                         //GPIO_Set(GPIO1_28, set);
189
190                         usleep(100000);
191                         
192                         break;
193                 }
194                 
195                 default:
196                         d->value = rand() % 2;
197                         usleep(1000000);
198                         break;
199                 
200
201                 case ANALOG_TEST0:
202                 {
203                         d->value = (double)(rand() % 100) / 100;
204                         break;
205                 }
206                 case ANALOG_TEST1:
207                 {
208                         static int count = 0;
209                         count %= 500;
210                         d->value = count++;
211                         break;
212                 }
213
214                 case ANALOG_FAIL0:
215                         d->value = 0;
216                         //d->value = (double)(rand() % 6) * -( rand() % 2) / ( rand() % 100 + 1);
217                         //Gives a value between -5 and 5
218                         break;
219                 case DIGITAL_TEST0:
220                         d->value = t.tv_sec % 2;
221
222                         break;
223                 case DIGITAL_TEST1:
224                         d->value = (t.tv_sec+1)%2;
225                         break;
226                 case DIGITAL_REALTEST:
227                 {
228                         d->value = 0; //d->value must be something... valgrind...
229                 // Can pass pin as argument, just using 20 as an example here
230                 // Although since pins will be fixed, can just define it here if we need to
231                         //d->value = pinRead(20);       //Pin 20 on the Beaglebone
232                         break;
233                 }
234                 case DIGITAL_FAIL0:
235                         if( rand() % 100 > 98)
236                                 d->value = 2;
237                         d->value = rand() % 2; 
238                         //Gives 0 or 1 or a 2 every 1/100 times
239                         break;
240                 //default:
241                 //      Fatal("Unknown sensor id: %d", s->id);
242                 //      break;
243         }       
244         
245
246         // Perform sanity check based on Sensor's ID and the DataPoint
247         Sensor_CheckData(s->id, d->value);
248
249         // Update latest DataPoint if necessary
250         
251         if (result)
252         {
253                 s->newest_data.time_stamp = d->time_stamp;
254                 s->newest_data.value = d->value;
255         }
256
257 #ifdef _BBB
258         //Not all cases have usleep, easiest here.
259         usleep(1000000);
260 #endif
261         return result;
262 }
263
264 /**
265  * Record data from a single Sensor; to be run in a seperate thread
266  * @param arg - Cast to Sensor* - Sensor that the thread will handle
267  * @returns NULL (void* required to use the function with pthreads)
268  */
269 void * Sensor_Loop(void * arg)
270 {
271         Sensor * s = (Sensor*)(arg);
272         Log(LOGDEBUG, "Sensor %d starts", s->id);
273
274         // Until the sensor is stopped, record data points
275         while (s->activated)
276         {
277                 DataPoint d;
278                 //Log(LOGDEBUG, "Sensor %d reads data [%f,%f]", s->id, d.time_stamp, d.value);
279                 if (Sensor_Read(s, &d)) // If new DataPoint is read:
280                 {
281                         //Log(LOGDEBUG, "Sensor %d saves data [%f,%f]", s->id, d.time_stamp, d.value);
282                         Data_Save(&(s->data_file), &d, 1); // Record it
283                 }
284         }
285         
286         // Needed to keep pthreads happy
287
288         Log(LOGDEBUG, "Sensor %d finished", s->id);
289         return NULL;
290 }
291
292 /**
293  * Get a Sensor given an ID string
294  * @param id_str ID string
295  * @returns Sensor* identified by the string; NULL on error
296  */
297 Sensor * Sensor_Identify(const char * id_str)
298 {
299         char * end;
300         // Parse string as integer
301         int id = strtol(id_str, &end, 10);
302         if (*end != '\0')
303         {
304                 return NULL;
305         }
306         // Bounds check
307         if (id < 0 || id >= NUMSENSORS)
308                 return NULL;
309
310
311         Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
312         return g_sensors+id;
313 }
314
315 /**
316  * Helper: Begin sensor response in a given format
317  * @param context - the FCGIContext
318  * @param id - ID of sensor
319  * @param format - Format
320  */
321 void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
322 {
323         // Begin response
324         switch (format)
325         {
326                 case JSON:
327                         FCGI_BeginJSON(context, STATUS_OK);
328                         FCGI_JSONLong("id", id);
329                         FCGI_JSONPair("name", g_sensor_names[id]);
330                         break;
331                 default:
332                         FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
333                         break;
334         }
335 }
336
337 /**
338  * Helper: End sensor response in a given format
339  * @param context - the FCGIContext
340  * @param id - ID of the sensor
341  * @param format - Format
342  */
343 void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format)
344 {
345         // End response
346         switch (format)
347         {
348                 case JSON:
349                         FCGI_EndJSON();
350                         break;
351                 default:
352                         break;
353         }
354 }
355
356 /**
357  * Handle a request to the sensor module
358  * @param context - The context to work in
359  * @param params - Parameters passed
360  */
361 void Sensor_Handler(FCGIContext *context, char * params)
362 {
363         struct timeval now;
364         gettimeofday(&now, NULL);
365         double current_time = TIMEVAL_DIFF(now, *Control_GetStartTime());
366
367         int id = 0;
368         double start_time = 0;
369         double end_time = current_time;
370         const char * fmt_str;
371
372         // key/value pairs
373         FCGIValue values[] = {
374                 {"id", &id, FCGI_REQUIRED(FCGI_INT_T)}, 
375                 {"format", &fmt_str, FCGI_STRING_T}, 
376                 {"start_time", &start_time, FCGI_DOUBLE_T}, 
377                 {"end_time", &end_time, FCGI_DOUBLE_T},
378         };
379
380         // enum to avoid the use of magic numbers
381         typedef enum {
382                 ID,
383                 FORMAT,
384                 START_TIME,
385                 END_TIME,
386         } SensorParams;
387         
388         // Fill values appropriately
389         if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
390         {
391                 // Error occured; FCGI_RejectJSON already called
392                 return;
393         }
394
395         // Error checking on sensor id
396         if (id < 0 || id >= NUMSENSORS)
397         {
398                 FCGI_RejectJSON(context, "Invalid sensor id");
399                 return;
400         }
401         Sensor * s = g_sensors+id;
402
403         DataFormat format = Data_GetFormat(&(values[FORMAT]));
404
405         // Begin response
406         Sensor_BeginResponse(context, id, format);
407
408         // Print Data
409         Data_Handler(&(s->data_file), &(values[START_TIME]), &(values[END_TIME]), format, current_time);
410         
411         // Finish response
412         Sensor_EndResponse(context, id, format);
413 }
414
415
416

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