Commit 02042c85 authored by Pim Schellart's avatar Pim Schellart
Browse files

Move client to separate repository.

parents
Pipeline #490 skipped
The MIT License (MIT)
Copyright (c) 2016 Daniel Stenberg
Copyright (c) 2016 Pim Schellart
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
CFLAGS = -Wall
example_client: example_client.o cJSON.o
cc $(CFLAGS) -o example_client example_client.o cJSON.o -lcurl -lm
example_client.o: example_client.c
cc $(CFLAGS) -c example_client.c
cJSON.o: cJSON.c CJSON.h
cc $(CFLAGS) -c cJSON.c
clean:
rm example_client example_client.o cJSON.o
This diff is collapsed.
/*
Copyright (c) 2009 Dave Gamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
/* cJSON Types: */
#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON {
struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
int type; /* The type of the item, as above. */
char *valuestring; /* The item's string, if type==cJSON_String */
int valueint; /* The item's number, if type==cJSON_Number */
double valuedouble; /* The item's number, if type==cJSON_Number */
char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
typedef struct cJSON_Hooks {
void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} cJSON_Hooks;
/* Supply malloc, realloc and free functions to cJSON */
extern void cJSON_InitHooks(cJSON_Hooks* hooks);
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char *cJSON_Print(cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *cJSON_PrintUnformatted(cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt);
/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize(cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr(void);
/* These calls create a cJSON item of the appropriate type. */
extern cJSON *cJSON_CreateNull(void);
extern cJSON *cJSON_CreateTrue(void);
extern cJSON *cJSON_CreateFalse(void);
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray(void);
extern cJSON *cJSON_CreateObject(void);
/* These utilities create an Array of count items. */
extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
/* Append item to the specified array/object. */
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
extern void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object */
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
extern void cJSON_DeleteItemFromArray(cJSON *array,int which);
extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string);
/* Update array items. */
extern void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem); /* Shifts pre-existing items to the right. */
extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
extern void cJSON_Minify(char *json);
/* Macros for creating things quickly. */
#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))
#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val))
#define cJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val))
#ifdef __cplusplus
}
#endif
#endif
/**
* 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);
}
curl_global_cleanup();
return 0;
}
The MIT License (MIT)
Copyright (c) 2016 Pim Schellart
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# An example client for the Radboud Radio Lab VLBI Monitor
#
# Copyright (c) 2016 Pim Schellart
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
import vlbi
import pprint
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--facility", nargs='*')
parser.add_argument("-U", "--admin-username", default="admin", help="Username of server admin")
parser.add_argument("-P", "--admin-password", default="admin", help="Password of server admin")
parser.add_argument("--server", help="Server address", default="http://localhost:8000/rpc")
args = parser.parse_args()
client = vlbi.Client(args.server, "RU", args.admin_username, args.admin_password)
result = client.getCurrentRecord(args.facility)
pp = pprint.PrettyPrinter(indent=4)
for r in result:
pp.pprint(r)
# An example client for the Radboud Radio Lab VLBI Monitor
#
# Copyright (c) 2016 Pim Schellart
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""Example:
python timeseries.py -f ALMA -F totalPower -s 2016-01-20T10:13:32.000Z
"""
import vlbi
import numpy as np
import datetime
import matplotlib.pyplot as plt
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--facility")
parser.add_argument("-F", "--field")
parser.add_argument("-s", "--start-time")
parser.add_argument("-e", "--end-time")
parser.add_argument("-U", "--admin-username", default="admin", help="Username of server admin")
parser.add_argument("-P", "--admin-password", default="admin", help="Password of server admin")
parser.add_argument("--server", help="Server address", default="http://localhost:8000/rpc")
args = parser.parse_args()
client = vlbi.Client(args.server, "RU", args.admin_username, args.admin_password)
start_time = None
if args.start_time:
start_time = datetime.datetime.strptime(args.start_time, "%Y-%m-%dT%H:%M:%S.%fZ")
end_time = None
if args.end_time:
end_time = datetime.datetime.strptime(args.end_time, "%Y-%m-%dT%H:%M:%S.%fZ")
ts = client.getSingleFieldTimeseries(args.facility, args.field, start_time, end_time)
N = len(ts)
x = np.zeros((N, 2))
for i in range(len(ts)):
d = datetime.datetime.strptime(ts[i]["time"], "%Y-%m-%dT%H:%M:%S.%fZ")
x[i, 0] = int(d.strftime("%s"))
x[i, 1] = ts[i]["value"]
plt.plot(x[:, 0], x[:, 1])
plt.xlabel("Time [s]")
plt.ylabel(args.field)
plt.show()
# An example client for the Radboud Radio Lab VLBI Monitor
#
# Copyright (c) 2016 Pim Schellart
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
import random
import time
import datetime
import sys
import vlbi
if len(sys.argv) < 2:
print "Usage: simulated_client.py observatory"
sys.exit(1)
username = "admin"
password = "admin"
facility = sys.argv[1]
client = vlbi.Client("http://localhost:8000/rpc", facility, username, password)
observatory_coordinates = {"ALMA": "-23.02900-067.75500",
"APEX": "-23.00578-067.75917",
"LMT": "+18.98583-097.31472",
"SMTO": "+32.70161-109.89124",
"SMA": "+19.82428-155.47797",
"IRAM_PdB": "+44.63389+005.90792",
"IRAM_PV": "+37.06616-003.39272",
"SPT": "-89.98000-024.80000",
"CARMA": "+37.28040-118.14166"}
i = 0
while True:
now = datetime.datetime.utcnow()
plus = now + datetime.timedelta(seconds=10)
snow = now.isoformat('T') + 'Z'
splus = plus.isoformat('T') + 'Z'
metadata = {}
metadata["observatoryCoordinates"] = {"time": snow, "value": observatory_coordinates[sys.argv[1]]}
metadata["systemTemperature"] = {"time": snow, "value": random.random()}
metadata["oscillatorFrequencyOffset"] = {"time": snow, "value": random.random()}
metadata["observingMode"] = {"time": snow, "value": "VLBI"}
# metadata["currentPointing"] = {"time": snow, "value": random.random()}
metadata["currentlySelectedSource"] = {"time": snow, "value": "Sgr A*"}
metadata["oscillatorFrequencyOffset"] = {"time": snow, "value": random.random()}
metadata["systemTemperature"] = {"time": snow, "value": random.random()}
metadata["totalPower"] = {"time": snow, "value": random.random()}
metadata["maser"] = {"time": snow, "value": random.choice((True, False))}
metadata["maser.clockOffset"] = {"time": snow, "value": random.random()}
metadata["maser.vacPumpCurrent"] = {"time": snow, "value": random.random()}
metadata["maser.clockOffset"] = {"time": snow, "value": random.random()}
metadata["maser.vacPumpCurrent"] = {"time": snow, "value": random.random()}
metadata["maser.onAcPower"] = {"time": snow, "value": random.choice((True, False))}
metadata["maser.lock"] = {"time": snow, "value": random.choice((True, False))}
metadata["maser.chamberTemperature"] = {"time": snow, "value": random.random()}
metadata["polarization"] = {"time": snow, "value": "L/R"}
metadata["polarization.qwpInserted"] = {"time": snow, "value": random.choice((True, False))}
metadata["phasing"] = {"time": snow, "value": random.choice((True, False))}
metadata["phasing.status"] = {"time": snow, "value": random.choice((True, False))}
metadata["phasing.efficiency"] = {"time": snow, "value": random.random()}
metadata["phasing.referenceAntenna"] = {"time": snow, "value": int(100*random.random())}
metadata["r2dbe"] = {"time": snow, "value": random.choice((True, False))}
metadata["r2dbe.status"] = {"time": snow, "value": random.choice((True, False))}
metadata["r2dbe.states"] = {"time": snow, "value": "unknown"}
metadata["mark6"] = {"time": snow, "value": random.choice((True, False))}
metadata["mark6.status"] = {"time": snow, "value": random.choice((True, False))}
metadata["mark6.moduleNames"] = {"time": snow, "value": "unknown"}
metadata["mark6.nofDisks"] = {"time": snow, "value": int(36*random.random())}