example_client.c 7.65 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/**
 * An example client for the Radboud Radio Lab VLBI Monitor
 *
 * This file is based on https://curl.haxx.se/libcurl/c/simplepost.html
 * from the CURL project.
 *
 * Copyright (c) 1998 Daniel Stenberg
 * Copyright (c) 2016 Pim Schellart
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <curl/curl.h>
#include "cJSON.h"

#define SERVER_URL "http://localhost:8000/rpc"
#define USERNAME "admin"
#define PASSWORD "admin"

struct Input {
    const char *readptr;
    long sizeleft;
};

static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp)
{
    struct Input *input = (struct Input *)userp;

    if(size*nmemb < 1)
        return 0;

    if(input->sizeleft) {
        *(char *)ptr = input->readptr[0]; /* copy one single byte */
        input->readptr++;                 /* advance pointer */
        input->sizeleft--;                /* less data left */
        return 1;                        /* we return 1 byte at a time! */
    }

    return 0;                          /* no more data left to deliver */
}

struct Output {
    char *memory;
    size_t size;
};

static size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp)
{
    size_t realsize = size * nmemb;
    struct Output *mem = (struct Output *)userp;

    mem->memory = realloc(mem->memory, mem->size + realsize + 1);
    if(mem->memory == NULL) {
        /* out of memory! */ 
        printf("not enough memory (realloc returned NULL)\n");
        return 0;
    }

    memcpy(&(mem->memory[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;

    return realsize;
}

int main(void)
{
    cJSON *root, *header, *metadata, *field, *record, *auth, *params, *records, *request, *error;
    char *errmsg, *json, *data;
    CURL *curl;
    CURLcode res;
    
    /* You probably want to implement options in a different way */
    int maser = 1;
    int slewStatus = 0;

    time_t now;
    time_t later;
    char snow[32];
    char slater[32];
    struct tm* tm_info;

    /* Current time as ISO8601 formatted string */
    time(&now);
    tm_info = gmtime(&now);
    strftime(snow, 32, "%Y-%m-%dT%H:%M:%S.00000Z", tm_info);

    later = now + 60;
    tm_info = gmtime(&later);
    strftime(slater, 32, "%Y-%m-%dT%H:%M:%S.00000Z", tm_info);

    struct Input input;
    struct Output chunk;

    /* Generate input JSON record */
    record = cJSON_CreateObject();
    cJSON_AddItemToObject(record, "header", header=cJSON_CreateObject());

    cJSON_AddStringToObject(header, "time", snow);
    cJSON_AddStringToObject(header, "facility", "SMTO");
    cJSON_AddStringToObject(header, "username", "SMTO");

    cJSON_AddItemToObject(record, "metadata", metadata=cJSON_CreateObject());

    cJSON_AddItemToObject(metadata, "observatoryCoordinates", field=cJSON_CreateObject());
    cJSON_AddStringToObject(field, "time", snow);
    cJSON_AddStringToObject(field, "value", "+32.70161-109.89124");

    cJSON_AddItemToObject(metadata, "totalPower", field=cJSON_CreateObject());
    cJSON_AddStringToObject(field, "time", snow);
    cJSON_AddNumberToObject(field, "value", 0.323523);

    cJSON_AddItemToObject(metadata, "slewStatus", field=cJSON_CreateObject());
    cJSON_AddStringToObject(field, "time", snow);
    if (slewStatus) {
        cJSON_AddTrueToObject(field, "value");
    } else {
        cJSON_AddFalseToObject(field, "value");
    }

    cJSON_AddItemToObject(metadata, "maser", field=cJSON_CreateObject());
    cJSON_AddStringToObject(field, "time", snow);
    if (maser) {
        cJSON_AddTrueToObject(field, "value");
    } else {
        cJSON_AddFalseToObject(field, "value");
    }

    cJSON_AddItemToObject(metadata, "maser.chamberTemperature", field=cJSON_CreateObject());
    cJSON_AddStringToObject(field, "time", snow);
    cJSON_AddStringToObject(field, "expires", slater);
    cJSON_AddNumberToObject(field, "value", 0.23513);

    /* Print JSON record (just for debug, remove later) */
    /*
    json = cJSON_Print(record);
    printf("%s\n", json);
    */

    /* Generate JSON RPC request */
    request = cJSON_CreateObject();

    cJSON_AddStringToObject(request, "jsonrpc", "2.0");

    cJSON_AddItemToObject(request, "auth", auth=cJSON_CreateObject());
    cJSON_AddStringToObject(auth, "username", USERNAME);
    cJSON_AddStringToObject(auth, "password", PASSWORD);
    cJSON_AddStringToObject(auth, "facility", "SMTO");

    cJSON_AddStringToObject(request, "method", "updateRecords");

    cJSON_AddItemToObject(request, "params", params=cJSON_CreateObject());
    cJSON_AddItemToObject(params, "records", records=cJSON_CreateArray());
    cJSON_AddItemToArray(records, record);

    cJSON_AddNumberToObject(request, "id", 0);

    /* Print JSON request (just for debug, remove later) */
    printf("sending JSON request:\n");
    printf("------------------------------------------\n");
    json = cJSON_Print(request);
    printf("%s\n", json);
    printf("------------------------------------------\n");

    /* Now print unformatted JSON to buffer for transfer */
    data = cJSON_PrintUnformatted(request);

    /* Initialize input and output structs */
    input.readptr = data;
    input.sizeleft = (long)strlen(data);

    chunk.memory = malloc(1);  /* will be grown as needed by the realloc above */ 
    chunk.size = 0;    /* no data at this point */ 

    /* In windows, this will init the winsock stuff */
    res = curl_global_init(CURL_GLOBAL_DEFAULT);
    /* Check for errors */
    if(res != CURLE_OK) {
        fprintf(stderr, "curl_global_init() failed: %s\n",
                curl_easy_strerror(res));
        return 1;
    }

    /* get a curl handle */
    curl = curl_easy_init();
    if(curl) {
        /* First set the URL that is about to receive our POST. */
        curl_easy_setopt(curl, CURLOPT_URL, SERVER_URL);

        /* Now specify we want to POST data */
        curl_easy_setopt(curl, CURLOPT_POST, 1L);

        /* we want to use our own read function */
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);

        /* pointer to pass to our read function */
        curl_easy_setopt(curl, CURLOPT_READDATA, &input);

        /* send all data to this function  */ 
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

        /* we pass our 'chunk' struct to the callback function */ 
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

        /* get verbose debug output please */
        /* curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); */

        /* Set the expected POST size. If you want to POST large amounts of data,
           consider CURLOPT_POSTFIELDSIZE_LARGE */
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, input.sizeleft);

        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);

        /* Check for errors in HTTP transfer */
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        } else {
            /* Check for errors reported by server (expected to be in JSON RPC format */
            root = cJSON_Parse(chunk.memory);
            if (root != NULL) {
                error = cJSON_GetObjectItem(root, "error");
                if (error != NULL) {
                    errmsg = cJSON_GetObjectItem(error, "message")->valuestring;
                    printf("ERROR: %s\n", errmsg);
                } else {
                    printf("success!\n");
                }
            }
        }

        /* always cleanup */
        curl_easy_cleanup(curl);
    }
Pim Schellart's avatar
Pim Schellart committed
239
240
    free(chunk.memory);
    cJSON_Delete(record);
241
242
243
    curl_global_cleanup();
    return 0;
}