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

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