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

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