Merge pull request #34 from Callum-/master
[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 <math.h>
11
12 /** Array of sensors, initialised by Sensor_Init **/
13 static Sensor g_sensors[NUMSENSORS]; //global to this file
14
15 /** Array of sensor threshold structures defining the safety values of each sensor**/
16 const SensorThreshold thresholds[NUMSENSORS]= {
17         //Max Safety, Min safety, Max warning, Min warning
18         {1,-1,1,-1},            // ANALOG_TEST0
19         {500,0,499,0},          // ANALOG_TEST1
20         {5,-5,4,-4},            // ANALOG_FAIL0
21         {1,0,1,0},              // DIGITAL_TEST0
22         {1,0,1,0},              // DIGITAL_TEST1
23         {1,0,1,0}               // DIGITAL_FAIL0
24 };
25
26 /** Human readable names for the sensors **/
27 const char * g_sensor_names[NUMSENSORS] = {     
28         "analog_test0", "analog_test1", 
29         "analog_fail0", "digital_test0", 
30         "digital_test1", "digital_fail0"
31 };
32
33 /**
34  * One off initialisation of *all* sensors
35  */
36 void Sensor_Init()
37 {
38         for (int i = 0; i < NUMSENSORS; ++i)
39         {
40                 g_sensors[i].id = i;
41                 Data_Init(&(g_sensors[i].data_file));
42                 g_sensors[i].record_data = false;       
43         }
44 }
45
46 /**
47  * Start a Sensor recording DataPoints
48  * @param s - The Sensor to start
49  * @param experiment_name - Prepended to DataFile filename
50  */
51 void Sensor_Start(Sensor * s, const char * experiment_name)
52 {
53         // Set filename
54         char filename[BUFSIZ];
55         if (sprintf(filename, "%s_%d", experiment_name, s->id) >= BUFSIZ)
56         {
57                 Fatal("Experiment name \"%s\" too long (>%d)", experiment_name, BUFSIZ);
58         }
59
60         Log(LOGDEBUG, "Sensor %d with DataFile \"%s\"", s->id, filename);
61         // Open DataFile
62         Data_Open(&(s->data_file), filename);
63
64         s->record_data = true; // Don't forget this!
65
66         // Create the thread
67         pthread_create(&(s->thread), NULL, Sensor_Loop, (void*)(s));
68 }
69
70 /**
71  * Stop a Sensor from recording DataPoints. Blocks until it has stopped.
72  * @param s - The Sensor to stop
73  */
74 void Sensor_Stop(Sensor * s)
75 {
76         // Stop
77         if (s->record_data)
78         {
79                 s->record_data = false;
80                 pthread_join(s->thread, NULL); // Wait for thread to exit
81                 Data_Close(&(s->data_file)); // Close DataFile
82                 s->newest_data.time_stamp = 0;
83                 s->newest_data.value = 0;
84         }
85 }
86
87 /**
88  * Stop all Sensors
89  */
90 void Sensor_StopAll()
91 {
92         for (int i = 0; i < NUMSENSORS; ++i)
93                 Sensor_Stop(g_sensors+i);
94 }
95
96 /**
97  * Start all Sensors
98  */
99 void Sensor_StartAll(const char * experiment_name)
100 {
101         for (int i = 0; i < NUMSENSORS; ++i)
102                 Sensor_Start(g_sensors+i, experiment_name);
103 }
104
105
106 /**
107  * Checks the sensor data for unsafe or unexpected results 
108  * @param sensor_id - The ID of the sensor
109  * @param value - The value from the sensor to test
110  */
111 void Sensor_CheckData(SensorId id, double value)
112 {
113         if( value > thresholds[id].max_error || value < thresholds[id].min_error)
114         {
115                 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);
116                 //new function that stops actuators?
117         }
118         else if( value > thresholds[id].max_warn || value < thresholds[id].min_warn)
119         {
120                 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);       
121         }
122 }
123
124
125 /**
126  * Read a DataPoint from a Sensor; block until value is read
127  * @param id - The ID of the sensor
128  * @param d - DataPoint to set
129  * @returns True if the DataPoint was different from the most recently recorded.
130  */
131 bool Sensor_Read(Sensor * s, DataPoint * d)
132 {
133         
134         // Set time stamp
135         struct timeval t;
136         gettimeofday(&t, NULL);
137         d->time_stamp = TIMEVAL_DIFF(t, g_options.start_time);
138
139         // Read value based on Sensor Id
140         switch (s->id)
141         {
142                 case ANALOG_TEST0:
143                         d->value = (double)(rand() % 100) / 100;
144                         break;
145                 case ANALOG_TEST1:
146                 {
147                         static int count = 0;
148                         count %= 500;
149                         d->value = count++;
150                         break;
151                 }
152                 case ANALOG_FAIL0:
153                         d->value = (double)(rand() % 6) * -( rand() % 2) / ( rand() % 100 + 1);
154                         //Gives a value between -5 and 5
155                         break;
156                 case DIGITAL_TEST0:
157                         d->value = t.tv_sec % 2;
158                         break;
159                 case DIGITAL_TEST1:
160                         d->value = (t.tv_sec+1)%2;
161                         break;
162                 case DIGITAL_FAIL0:
163                         if( rand() % 100 > 98)
164                                 d->value = 2;
165                         d->value = rand() % 2; 
166                         //Gives 0 or 1 or a 2 every 1/100 times
167                         break;
168                 default:
169                         Fatal("Unknown sensor id: %d", s->id);
170                         break;
171         }       
172         usleep(100000); // simulate delay in sensor polling
173
174         // Perform sanity check based on Sensor's ID and the DataPoint
175         Sensor_CheckData(s->id, d->value);
176
177         // Update latest DataPoint if necessary
178         bool result = (d->value != s->newest_data.value);
179         if (result)
180         {
181                 s->newest_data.time_stamp = d->time_stamp;
182                 s->newest_data.value = d->value;
183         }
184         return result;
185 }
186
187 /**
188  * Record data from a single Sensor; to be run in a seperate thread
189  * @param arg - Cast to Sensor* - Sensor that the thread will handle
190  * @returns NULL (void* required to use the function with pthreads)
191  */
192 void * Sensor_Loop(void * arg)
193 {
194         Sensor * s = (Sensor*)(arg);
195         Log(LOGDEBUG, "Sensor %d starts", s->id);
196
197         // Until the sensor is stopped, record data points
198         while (s->record_data)
199         {
200                 DataPoint d;
201                 //Log(LOGDEBUG, "Sensor %d reads data [%f,%f]", s->id, d.time_stamp, d.value);
202                 if (Sensor_Read(s, &d)) // If new DataPoint is read:
203                 {
204                         //Log(LOGDEBUG, "Sensor %d saves data [%f,%f]", s->id, d.time_stamp, d.value);
205                         Data_Save(&(s->data_file), &d, 1); // Record it
206                 }
207         }
208         
209         // Needed to keep pthreads happy
210
211         Log(LOGDEBUG, "Sensor %d finished", s->id);
212         return NULL;
213 }
214
215 /**
216  * Get a Sensor given an ID string
217  * @param id_str ID string
218  * @returns Sensor* identified by the string; NULL on error
219  */
220 Sensor * Sensor_Identify(const char * id_str)
221 {
222         char * end;
223         // Parse string as integer
224         int id = strtol(id_str, &end, 10);
225         if (*end != '\0')
226         {
227                 return NULL;
228         }
229         // Bounds check
230         if (id < 0 || id >= NUMSENSORS)
231                 return NULL;
232
233
234         Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
235         return g_sensors+id;
236 }
237
238 /**
239  * Helper: Begin sensor response in a given format
240  * @param context - the FCGIContext
241  * @param id - ID of sensor
242  * @param format - Format
243  */
244 void Sensor_BeginResponse(FCGIContext * context, SensorId id, DataFormat format)
245 {
246         // Begin response
247         switch (format)
248         {
249                 case JSON:
250                         FCGI_BeginJSON(context, STATUS_OK);
251                         FCGI_JSONLong("id", id);
252                         FCGI_JSONKey("data");
253                         break;
254                 default:
255                         FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
256                         break;
257         }
258 }
259
260 /**
261  * Helper: End sensor response in a given format
262  * @param context - the FCGIContext
263  * @param id - ID of the sensor
264  * @param format - Format
265  */
266 void Sensor_EndResponse(FCGIContext * context, SensorId id, DataFormat format)
267 {
268         // End response
269         switch (format)
270         {
271                 case JSON:
272                         FCGI_EndJSON();
273                         break;
274                 default:
275                         break;
276         }
277 }
278
279 /**
280  * Handle a request to the sensor module
281  * @param context - The context to work in
282  * @param params - Parameters passed
283  */
284 void Sensor_Handler(FCGIContext *context, char * params)
285 {
286         struct timeval now;
287         gettimeofday(&now, NULL);
288         double current_time = TIMEVAL_DIFF(now, g_options.start_time);
289
290         int id = 0;
291         double start_time = 0;
292         double end_time = current_time;
293         const char * fmt_str;
294
295         // key/value pairs
296         FCGIValue values[] = {
297                 {"id", &id, FCGI_REQUIRED(FCGI_INT_T)}, 
298                 {"format", &fmt_str, FCGI_STRING_T}, 
299                 {"start_time", &start_time, FCGI_DOUBLE_T}, 
300                 {"end_time", &end_time, FCGI_DOUBLE_T},
301         };
302
303         // enum to avoid the use of magic numbers
304         typedef enum {
305                 ID,
306                 FORMAT,
307                 START_TIME,
308                 END_TIME,
309         } SensorParams;
310         
311         // Fill values appropriately
312         if (!FCGI_ParseRequest(context, params, values, sizeof(values)/sizeof(FCGIValue)))
313         {
314                 // Error occured; FCGI_RejectJSON already called
315                 return;
316         }
317         else if (id < 0 || id >= NUMSENSORS)
318         {
319                 FCGI_RejectJSON(context, "Invalid sensor id specified");
320                 return;
321         }
322
323         // Get Sensor and format
324         Sensor * s = g_sensors+id;
325         DataFormat format = JSON;
326
327         // Check if format type was specified
328         if (FCGI_RECEIVED(values[FORMAT].flags))
329         {
330                 if (strcmp(fmt_str, "json") == 0)
331                         format = JSON;
332                 else if (strcmp(fmt_str, "tsv") == 0)
333                         format = TSV;
334                 else 
335                 {
336                         FCGI_RejectJSON(context, "Unknown format type specified.");
337                         return;
338                 }
339         }
340
341         // Begin response
342         Sensor_BeginResponse(context, id, format);
343         
344         // If a time was specified
345         if (FCGI_RECEIVED(values[START_TIME].flags) || FCGI_RECEIVED(values[END_TIME].flags))
346         {
347                 // Wrap times relative to the current time
348                 if (start_time < 0)
349                         start_time += current_time;
350                 if (end_time < 0)
351                         end_time += current_time;
352
353                 // Print points by time range
354                 Data_PrintByTimes(&(s->data_file), start_time, end_time, format);
355         }
356         else // No time was specified; just return a recent set of points
357         {
358                 pthread_mutex_lock(&(s->data_file.mutex));
359                         int start_index = s->data_file.num_points-DATA_BUFSIZ;
360                         int end_index = s->data_file.num_points;
361                 pthread_mutex_unlock(&(s->data_file.mutex));
362
363                 // Bounds check
364                 if (start_index < 0)
365                         start_index = 0;
366                 if (end_index < 0)
367                         end_index = 0;
368
369                 // Print points by indexes
370                 Log(LOGDEBUG, "Sensor %d file \"%s\" indexes %d->%d", s->id, s->data_file.filename, start_index, end_index);
371                 Data_PrintByIndexes(&(s->data_file), start_index, end_index, format);
372         }
373         
374         // Finish response
375         Sensor_EndResponse(context, id, format);
376         
377 }
378
379
380

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