Add relative times, allow "points" param to work with "start_time"
[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 const char * g_sensor_names[NUMSENSORS] = {     
15         "analog_test0", "analog_test1", 
16         "digital_test0", "digital_test1"
17 };
18
19 /**
20  * Read a data value from a sensor; block until value is read
21  * @param sensor_id - The ID of the sensor
22  * @param d - DataPoint to set
23  * @returns NULL for digital sensors when data is unchanged, otherwise d
24  */
25 DataPoint * GetData(SensorId sensor_id, DataPoint * d)
26 {
27         // switch based on the sensor_id at the moment for testing;
28         // might be able to just directly access ADC from sensor_id?
29         //TODO: Implement for real sensors
30
31         
32         //TODO: We should ensure the time is *never* allowed to change on the server if we use gettimeofday
33         //              Another way people might think of getting the time is to count CPU cycles with clock()
34         //              But this will not work because a) CPU clock speed may change on some devices (RPi?) and b) It counts cycles used by all threads
35         
36         struct timeval t;
37         gettimeofday(&t, NULL);
38         d->time_stamp = (t.tv_sec - g_options.start_time.tv_sec) + 1e-6*(t.tv_usec - g_options.start_time.tv_usec);
39
40         // Make time relative
41         //d->time_stamp.tv_sec -= g_options.start_time.tv_sec;
42         //d->time_stamp.tv_usec -= g_options.start_time.tv_usec;
43         
44         switch (sensor_id)
45         {
46                 case ANALOG_TEST0:
47                 {
48                         //CheckSensor( sensor_id, *sensor value*); 
49                 
50                         static int count = 0;
51                         d->value = count++;
52                         break;
53                 }
54                 case ANALOG_TEST1:
55                         d->value = (double)(rand() % 100) / 100;
56                         break;
57         
58                 //TODO: For digital sensors, consider only updating when sensor is actually changed
59                 case DIGITAL_TEST0:
60                         d->value = t.tv_sec % 2;
61                         break;
62                 case DIGITAL_TEST1:
63                         d->value = (t.tv_sec+1)%2;
64                         break;
65                 default:
66                         Fatal("Unknown sensor id: %d", sensor_id);
67                         break;
68         }       
69         usleep(100000); // simulate delay in sensor polling
70
71         return d;
72 }
73
74 /**
75  * Checks the sensor data for unsafe or unexpected results 
76  * @param sensor_id - The ID of the sensor
77  *
78 *
79 void CheckSensor( SensorId sensor_id)
80 {
81         switch (sensor_id)
82         {
83                 case ANALOG_TEST0:
84                 {
85                         if( *sensor value* > ANALOG_TEST0_SAFETY)
86                         {
87                                 LogEx(LOGERR, GetData, Sensor analog_test0 is above the safe value);
88                         //new log function that stops actuators?
89                         }
90                         //Also include a warning level?
91                         else if( *sensor value* > ANALOG_TEST0_WARN)
92                         {
93                                 LogEx(LOGWARN, GetData, Sensor analog_test0);   
94                         }
95                 }
96         }
97                 
98         
99 */      
100
101
102 /**
103  * Destroy a sensor
104  * @param s - Sensor to destroy
105  */
106 void Destroy(Sensor * s)
107 {
108         // Maybe move the binary file into long term file storage?
109         fclose(s->file);
110 }
111
112
113
114 /**
115  * Initialise a sensor
116  * @param s - Sensor to initialise
117  */
118 void Init(Sensor * s, int id)
119 {
120         s->write_index = 0;
121         s->id = id;
122         s->points_written = 0;
123         s->points_read = 0;
124
125         #define FILENAMESIZE 3
126         char filename[FILENAMESIZE];
127         if (s->id >= pow(10, FILENAMESIZE))
128         {
129                 Fatal("Too many sensors! FILENAMESIZE is %d; increase it and recompile.", FILENAMESIZE);
130         }
131
132         pthread_mutex_init(&(s->mutex), NULL);
133                 
134         sprintf(filename, "%d", s->id);
135         unlink(filename); //TODO: Move old files somewhere
136
137         s->file = fopen(filename, "a+b"); // open binary file
138         Log(LOGDEBUG, "Initialised sensor %d; binary file is \"%s\"", id, filename);
139 }
140
141
142 /**
143  * Run the main sensor polling loop
144  * @param arg - Cast to Sensor* - Sensor that the thread will handle
145  * @returns NULL (void* required to use the function with pthreads)
146  */
147 void * Sensor_Main(void * arg)
148 {
149         Sensor * s = (Sensor*)(arg);
150
151         while (Thread_Runstate() == RUNNING) //TODO: Exit condition
152         {
153                 // The sensor will write data to a buffer until it is full
154                 // Then it will open a file and dump the buffer to the end of it.
155                 // Rinse and repeat
156
157                 // The reason I've added the buffer is because locks are expensive
158                 // But maybe it's better to just write data straight to the file
159                 // I'd like to do some tests by changing SENSOR_DATABUFSIZ
160
161                 while (s->write_index < SENSOR_DATABUFSIZ)
162                 {
163                         DataPoint * d = &(s->buffer[s->write_index]);
164                         if (GetData(s->id, d) == NULL)
165                         {
166                                 Fatal("Error collecting data");
167                         }
168                         s->write_index += 1;
169                 }
170
171                 //Log(LOGDEBUG, "Filled buffer");
172
173                 // CRITICAL SECTION (no threads should be able to read/write the file at the same time)
174                 pthread_mutex_lock(&(s->mutex));
175                         //TODO: Valgrind complains about this fseek: "Syscall param write(buf) points to uninitialised byte(s)"
176                         //              Not sure why, but we should find out and fix it.
177                         fseek(s->file, 0, SEEK_END);
178                         int amount_written = fwrite(s->buffer, sizeof(DataPoint), SENSOR_DATABUFSIZ, s->file);
179                         if (amount_written != SENSOR_DATABUFSIZ)
180                         {
181                                 Fatal("Wrote %d data points and expected to write %d to \"%s\" - %s", amount_written, SENSOR_DATABUFSIZ, strerror(errno));
182                         }
183                         s->points_written += amount_written;
184                         //Log(LOGDEBUG, "Wrote %d data points for sensor %d", amount_written, s->id);
185                 pthread_mutex_unlock(&(s->mutex));
186                 // End of critical section
187
188                 s->write_index = 0; // reset position in buffer
189                 
190         }
191         Log(LOGDEBUG, "Thread for sensor %d exits", s->id);
192         return NULL; 
193 }
194
195 /**
196  * Get position in a binary sensor file with a timestamp using a binary search
197  * @param s - Sensor to use
198  * @param time_stamp - Timestamp
199  * @param count - If not NULL, used to provide number of searches required
200  * @param found - If not NULL, set to the closest DataPoint
201  * @returns Integer giving the *closest* index in the file
202  * TODO: Refactor or replace?
203  */
204 int FindTime(Sensor * s, double time_stamp, int * count, DataPoint * found)
205 {
206         DataPoint d;
207
208         int lower = 0;
209         int upper = s->points_written - 1;
210         int index = 0;
211         if (count != NULL)
212                 *count = 0;     
213
214         while (upper - lower > 1)
215         {
216                 index = lower + ((upper - lower)/2);
217
218                 // Basically anything with fseek is critical; if we don't make it critical the sensor thread may alter data at a random point in the file!
219                 // CRITICAL SECTION (May need to rethink how this is done, but I can't see how to do it without fseek :S)
220                 // Regarding the suggestion that we have 2 file pointers; one for reading and one for writing:
221                 // That seems like it will work... but we will have to be very careful and test it first
222                 pthread_mutex_lock(&s->mutex);
223                         fseek(s->file, index*sizeof(DataPoint), SEEK_SET);
224                         int amount_read = fread(&d, sizeof(DataPoint), 1, s->file);
225                 pthread_mutex_unlock(&s->mutex);
226                 
227                 if (amount_read != 1)
228                 {
229                         Fatal("Couldn't read single data point from sensor %d", s->id);
230                 }
231
232                 if (d.time_stamp > time_stamp)
233                 {
234                         upper = index;
235                 }
236                 else if (d.time_stamp < time_stamp)
237                 {
238                         lower = index;
239                 }
240                 if (count != NULL)
241                         *count += 1;
242         }
243
244         if (found != NULL)
245                 *found = d;
246
247         return index;
248         
249 }
250
251 /**
252  * Print sensor data between two indexes in the file, using a given format
253  * @param s - Sensor to use
254  * @param start - Start index
255  * @param end - End index
256  * @param output_type - JSON, CSV or TSV output format
257  */
258 void PrintData(Sensor * s, int start, int end, OutputType output_type)
259 {
260         DataPoint buffer[SENSOR_QUERYBUFSIZ];
261         int index = start;
262
263         if (output_type == JSON)
264         {
265                 FCGI_JSONValue("[");
266         }
267
268
269         while (index < end)
270         {
271                 int to_read = end - index;
272                 if (to_read > SENSOR_QUERYBUFSIZ)
273                 {
274                         to_read = SENSOR_QUERYBUFSIZ;
275                 }
276
277                 int amount_read = 0;
278                 // CRITICAL SECTION
279                 pthread_mutex_lock(&(s->mutex));
280
281                         fseek(s->file, index*sizeof(DataPoint), SEEK_SET);
282                         amount_read = fread(buffer, sizeof(DataPoint), to_read, s->file);
283
284                 pthread_mutex_unlock(&(s->mutex));
285                 // End critical section
286
287                 if (amount_read != to_read)
288                 {
289                         Fatal("Failed to read %d DataPoints from sensor %d; read %d instead", to_read, s->id, amount_read);
290                 }
291
292                 // Print the data
293                 for (int i = 0; i < amount_read; ++i)
294                 {
295                         //TODO: Reformat?
296                         switch (output_type)
297                         {
298                                 case JSON:
299                                         FCGI_JSONValue("[%f, %f]", buffer[i].time_stamp, buffer[i].value);
300                                         if (i+1 < amount_read)
301                                                 FCGI_JSONValue(",");
302                                         break;
303                                 case CSV:
304                                         FCGI_PrintRaw("%f,%f\n", buffer[i].time_stamp, buffer[i].value);
305                                         break;
306                                 case TSV:
307                                 default:
308                                         FCGI_PrintRaw("%f\t%f\n", buffer[i].time_stamp, buffer[i].value);
309                                         break;
310                         }
311                 }
312                 index += amount_read;
313         }
314
315         if (output_type == JSON)
316         {
317                 FCGI_JSONValue("]");
318         }
319 }
320
321 /**
322  * Fill buffer with most recent sensor data
323  * TODO: This may be obselete; remove?
324  * @param s - Sensor to use
325  * @param buffer - Buffer to fill
326  * @param bufsiz - Size of buffer to fill
327  * @returns The number of DataPoints actually read
328  */
329 int Sensor_Query(Sensor * s, DataPoint * buffer, int bufsiz)
330 {
331         int amount_read = 0;
332         //CRITICAL SECTION (Don't access file while sensor thread is writing to it!)
333         pthread_mutex_lock(&(s->mutex));
334                 
335                 fseek(s->file, -bufsiz*sizeof(DataPoint), SEEK_END);
336                 amount_read = fread(buffer, sizeof(DataPoint), bufsiz, s->file);
337                 //Log(LOGDEBUG, "Read %d data points", amount_read);            
338         pthread_mutex_unlock(&(s->mutex));
339         return amount_read;
340 }
341
342 /**
343  * Get a Sensor given an ID string
344  * @param id_str ID string
345  * @returns Sensor* identified by the string; NULL on error
346  */
347 Sensor * Sensor_Identify(const char * id_str)
348 {
349         char * end;
350         // Parse string as integer
351         int id = strtol(id_str, &end, 10);
352         if (*end != '\0')
353         {
354                 return NULL;
355         }
356         // Bounds check
357         if (id < 0 || id >= NUMSENSORS)
358                 return NULL;
359
360
361         Log(LOGDEBUG, "Sensor \"%s\" identified", g_sensor_names[id]);
362         return g_sensors+id;
363 }
364
365 /**
366  * Handle a request to the sensor module
367  * @param context - The context to work in
368  * @param params - Parameters passed
369  * TODO: Seriously need to write more helper functions and decrease the size of this function!
370  */
371 void Sensor_Handler(FCGIContext *context, char * params)
372 {
373         StatusCodes status = STATUS_OK;
374
375         OutputType output_type = JSON;
376         
377
378
379         const char * key; const char * value;
380
381         Sensor * sensor = NULL;
382
383         struct timeval now;
384         gettimeofday(&now, NULL);
385
386         double start_time = -1;
387         double end_time = -1;
388         double current_time = (now.tv_sec - g_options.start_time.tv_sec) + 1e-6*(now.tv_usec - g_options.start_time.tv_usec);
389         bool seek_time = false;
390         bool points_specified = false;
391         int query_size = SENSOR_QUERYBUFSIZ;
392         int start_index = -1;
393         int end_index = -1;
394
395
396         while ((params = FCGI_KeyPair(params, &key, &value)) != NULL)
397         {
398                 Log(LOGDEBUG, "Got key=%s and value=%s", key, value);
399                 if (strcmp(key, "id") == 0)
400                 {
401                         if (sensor != NULL)
402                         {
403                                 Log(LOGERR, "Only one sensor id should be specified");
404                                 status = STATUS_ERROR;
405                                 break;
406                         }
407                         if (*value == '\0')
408                         {
409                                 Log(LOGERR, "No id specified.");
410                                 status = STATUS_ERROR;
411                                 break;
412                         }
413
414                         sensor = Sensor_Identify(value);
415                         if (sensor == NULL)
416                         {
417                                 Log(LOGERR, "Invalid sensor id: %s", value);
418                                 status = STATUS_ERROR;
419                                 break;
420                         }
421                 }
422                 else if (strcmp(key, "format") == 0)
423                 {
424                         if (strcmp(value, "json") == 0)
425                                 output_type = JSON;
426                         else if (strcmp(value, "csv") == 0)
427                                 output_type = CSV;
428                         else if (strcmp(value, "tsv") == 0)
429                                 output_type = TSV;                      
430                 }
431                 else if (strcmp(key, "points") == 0)
432                 {
433                         points_specified = true;
434                         if (strcmp(value, "all") == 0)
435                         {
436                                 query_size = sensor->points_written;
437                         }
438                         else
439                         {
440                                 char * end;
441                                 query_size = strtol(value, &end, 10);
442                                 if (*end != '\0')
443                                 {
444                                         Log(LOGERR, "Require \"all\" or an integer value: %s = %s", key, value);
445                                         status = STATUS_ERROR;
446                                         break;
447                                 }
448                         }
449                         
450                 }
451                 else if (strcmp(key, "start_time") == 0)
452                 {
453                         seek_time = true;
454                         char * end;
455                         start_time = strtod(value, &end);
456                         if (*end != '\0')
457                         {
458                                 Log(LOGERR, "Require a double: %s = %s", key, value);
459                                 status = STATUS_ERROR;
460                                 break;
461                         }                       
462
463                         // Treat negative values as being relative to the current time
464                         if (start_time < 0)
465                         {
466                                 start_time = current_time + start_time;
467                         }
468                         start_time = floor(start_time);
469                 }
470                 else if (strcmp(key, "end_time") == 0)
471                 {
472                         seek_time = true;
473                         char * end;
474                         end_time = strtod(value, &end);
475                         if (*end != '\0')
476                         {
477                                 Log(LOGERR, "Require a double: %s = %s", key, value);
478                                 status = STATUS_ERROR;
479                                 break;
480                         }       
481
482                         // Treat negative values as being relative to the current time
483                         if (end_time < 0)
484                         {
485                                 end_time = current_time + end_time;
486                         }               
487                         end_time = ceil(end_time);
488                 }
489                 // For backward compatability:
490                 else if (strcmp(key, "dump") == 0)
491                 {
492                         output_type = TSV;
493                         query_size = sensor->points_written+1;
494                 }
495                 else
496                 {
497                         Log(LOGERR, "Unknown key \"%s\" (value = %s)", key, value);
498                         status = STATUS_ERROR;
499                         break;
500                 }               
501         }
502
503         if (status != STATUS_ERROR && sensor == NULL)
504         {
505                 Log(LOGERR, "No valid sensor id given");
506                 status = STATUS_ERROR;
507         }
508
509         if (status == STATUS_ERROR)
510         {
511                 FCGI_RejectJSON(context, "Invalid input parameters");
512                 return;
513         }
514
515
516         if (seek_time)
517         {
518                 if (end_time < 0 && !points_specified)
519                         end_index = sensor->points_written;
520                 else
521                 {
522                         int count = 0; DataPoint d;
523                         end_index = FindTime(sensor, end_time, &count, &d);
524                         Log(LOGDEBUG, "FindTime - Looked for %f; found [%f,%f] after %d iterations; sensor %d, position %d", end_time, d.time_stamp, d.value, count, sensor->id, end_index);
525                 }
526                 if (start_time < 0)
527                         start_time = 0;
528                 else
529                 {
530                         int count = 0; DataPoint d;
531                         start_index = FindTime(sensor, start_time, &count, &d);
532                         Log(LOGDEBUG, "FindTime - Looked for %f; found [%f,%f] after %d iterations; sensor %d, position %d", start_time, d.time_stamp, d.value, count, sensor->id, start_index);
533                 }
534
535                 if (points_specified)
536                         end_index = start_index + query_size;
537         }
538         else
539         {
540                 start_index = sensor->points_written - query_size;
541                 
542                 end_index = sensor->points_written;
543         }
544         
545         if (start_index < 0)
546         {
547                 Log(LOGNOTE, "start_index = %d => Clamped to 0", start_index);
548                 start_index = 0;
549         }
550         if (end_index > sensor->points_written)
551         {
552                 Log(LOGNOTE, "end_index = %d => Clamped to %d", end_index, sensor->points_written);
553                 end_index = sensor->points_written;
554         }
555         
556         switch (output_type)
557         {
558                 case JSON:
559                         FCGI_BeginJSON(context, status);
560                         FCGI_JSONLong("id", sensor->id);
561                         FCGI_JSONKey("data");
562                         PrintData(sensor, start_index, end_index, output_type);
563                         FCGI_EndJSON();
564                         break;
565                 default:
566                         FCGI_PrintRaw("Content-type: text/plain\r\n\r\n");
567                         PrintData(sensor, start_index, end_index, output_type);
568                         //Force download with content-disposition
569                         // Sam: This is cool, but I don't think we should do it
570                         //  - letting the user view it in the browser and then save with their own filename is more flexible
571                         //"Content-disposition: attachment;filename=%d.csv\r\n\r\n", sensor->id);
572                         break;
573         }
574         
575 }
576
577 /**
578  * Setup Sensors, start Sensor polling thread(s)
579  */
580 void Sensor_Spawn()
581 {
582         // start sensor threads
583         for (int i = 0; i < NUMSENSORS; ++i)
584         {
585                 Init(g_sensors+i, i);
586                 pthread_create(&(g_sensors[i].thread), NULL, Sensor_Main, (void*)(g_sensors+i));
587         }
588 }
589
590 /**
591  * Quit Sensor loops
592  */
593 void Sensor_Join()
594 {
595         if (!Thread_Runstate())
596         {
597                 Fatal("This function should not be called before Thread_QuitProgram");
598         }
599         for (int i = 0; i < NUMSENSORS; ++i)
600         {
601                 pthread_join(g_sensors[i].thread, NULL);
602                 Destroy(g_sensors+i);
603         }
604 }

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