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

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