Merge pull request #15 from jtanx/master
[matches/MCTX3420.git] / server / query.c
1 /**
2  * @file query.c
3  * @purpose Temporary file to run a test thread that will query a sensors thread
4  * Code will probably be combined with Jeremy's FastCGI API
5  */
6
7
8
9 #include "query.h"
10
11 #include "sensor.h"
12 #include "log.h"
13
14 static DataPoint buffer[QUERY_BUFSIZ];
15
16 /**
17  * Query sensor with id
18  * @param id - The index of the sensor in g_sensors
19  */
20 void QuerySensor(int id) //TODO: This code will form the SensorHandler FastCGI function (I think?)
21 {
22         Sensor * s = g_sensors+id;
23
24         int amount_read = 0;
25         //CRITICAL SECTION (Don't access file while sensor thread is writing to it!)
26         pthread_mutex_lock(&(s->mutex));
27
28                 fseek(s->file, -QUERY_BUFSIZ*sizeof(DataPoint), SEEK_END);
29                 amount_read = fread(&buffer, sizeof(DataPoint), QUERY_BUFSIZ, s->file);
30                 Log(LOGDEBUG, "Read %d data points", amount_read);
31                 
32         pthread_mutex_unlock(&(s->mutex));
33         //End critical section
34
35         // So... we have a buffer
36         // I guess we'll want to JSON it or something?
37         // Just print it out for now
38         for (int i = 0; i < amount_read; ++i)
39         {
40                 printf("%f\t%f\n", buffer[i].time, buffer[i].value);
41         }
42
43         // Will want to handle case where there actually wasn't anything new to respond with
44         // (In case we have a sensor that is slower than the rate of jQuery requests)
45         if (amount_read == 0)
46         {
47                 Log(LOGWARN, "No data points read from sensor%s file");
48                 printf("# No data\n");
49         }
50 }
51
52 /**
53  * Test function to simulate responding to HTTP requests
54  * @param args - IGNORED (void* required to pass function to pthread_create)
55  * @returns NULL (void* required to pass function to pthread_create)
56  */
57 void * Query_Main(void * args)
58 {
59         while (true) //TODO: Exit condition
60         {
61                 
62                 for (int i = 0; i < NUMSENSORS; ++i)
63                 {
64                         printf("# Sensor %d\n", i);
65                         QuerySensor(i);
66                         printf("\n");   
67                 }
68                 usleep(REQUEST_RATE);
69         }
70 }

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