7a9ab161019d6d7c0882fda74bb2a8f39a44cf62
[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
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                 FILE * file = fopen(s->filename, "rb");
29                 if (file == NULL)
30                 {
31                         Log(LOGWARN, "Couldn't open file \"%s\" mode rb - %s", s->filename, strerror(errno));                   
32                 }
33                 else
34                 {
35                         fseek(file, 0, SEEK_SET);
36                         rewind(file);
37                         amount_read = fread(&buffer, sizeof(DataPoint), QUERY_BUFSIZ, file);
38                         s->read_offset += amount_read;
39                         Log(LOGDEBUG, "Read %d data points; offset now at %d", amount_read, s->read_offset);
40                         
41                         fclose(file);
42                 }
43
44         pthread_mutex_unlock(&(s->mutex));
45         //End critical section
46
47         // So... we have a buffer
48         // I guess we'll want to JSON it or something?
49         // Just print it out for now
50         for (int i = 0; i < amount_read; ++i)
51         {
52                 printf("%f\t%f\n", buffer[i].time, buffer[i].value);
53         }
54
55         // Will want to handle case where there actually wasn't anything new to respond with
56         // (In case we have a sensor that is slower than the rate of jQuery requests)
57         if (amount_read == 0)
58         {
59                 Log(LOGWARN, "No data points read from sensor%s file");
60                 printf("# No data\n");
61         }
62 }
63
64 /**
65  * Test function to simulate responding to HTTP requests
66  * @param args - IGNORED (void* required to pass function to pthread_create)
67  * @returns NULL (void* required to pass function to pthread_create)
68  */
69 void * Query_Main(void * args)
70 {
71         while (true) //TODO: Exit condition
72         {
73                 
74                 for (int i = 0; i < NUMSENSORS; ++i)
75                 {
76                         printf("# Sensor %d\n", i);
77                         QuerySensor(i);
78                         printf("\n");   
79                 }
80                 usleep(REQUEST_RATE);
81         }
82 }

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