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

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