Merge branch 'master' of https://github.com/szmoore/MCTX3420.git
[matches/MCTX3420.git] / testing / fastcgi-approach / main.c
1 #define _BSD_SOURCE
2 #include "common.h"
3 #include "fastcgi.h"
4 #include <time.h>
5
6 typedef struct Data {
7         pthread_t sensors;
8         pthread_mutex_t mutex;
9         volatile int sensor_value;
10 } Data;
11
12 void Handler_Sensors(void *arg, char *params) 
13 {
14         const char *key, *value;
15         char buf[5];
16         Data *data = (Data*) arg;
17         
18         //Begin a request only when you know the final result
19         //E.g whether OK or not.
20         FCGI_BeginJSON(STATUS_OK, "sensors");
21         while ((params = FCGI_KeyPair(params, &key, &value))) {
22                 FCGI_BuildJSON(key, value);
23         }
24         pthread_mutex_lock(&(data->mutex));
25         snprintf(buf, 128, "%d", data->sensor_value);
26         FCGI_BuildJSON("sensor_value", buf); 
27         pthread_mutex_unlock(&(data->mutex));
28         FCGI_EndJSON();
29 }
30
31 void *SensorsLoop(void *arg) {
32         Data *data = (Data*) arg;
33         srand(time(NULL));
34         //Csection
35         while(1) {
36                 pthread_mutex_lock(&(data->mutex));
37                 data->sensor_value = rand() % 1024;
38                 pthread_mutex_unlock(&(data->mutex));
39                 usleep(200*1000); //200ms
40         }
41 }
42
43 int main(int argc, char *argv[]) {
44         Data data = {0};
45         pthread_mutex_init(&(data.mutex), NULL);
46         //data.mutex = PTHREAD_MUTEX_INITIALIZER;
47         
48 //      pthread_create(&data.sensors, NULL, SensorsLoop, &data);
49         FCGI_RequestLoop(&data);
50 }

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