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

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