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

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