network/http_server/requests/json_generator.c

/*
* EVALUATION AND USE OF THIS SOFTWARE IS SUBJECT TO THE TERMS AND
* CONDITIONS OF THE CONTROLLING LICENSE AGREEMENT FOUND AT LICENSE.md
* IN THIS SDK. IF YOU DO NOT AGREE TO THE LICENSE TERMS AND CONDITIONS,
* PLEASE RETURN ALL SOURCE FILES TO SILICON LABORATORIES.
* (c) Copyright 2018, Silicon Laboratories Inc. All rights reserved.
*/
#include "gos.h"
#include "common.h"
#define JSON_START "{\"gpios\":["
#define JSON_END "]}"
/*************************************************************************************************
* This handles a GET request which returns a JSON formatted response.
* The response data has chunked encoding
* GET http://<domain>/json_generator
*
* Response:
* {
* "gpios" :
* [
* { "gpio0" : 1 },
* { "gpio2" : 1 },
* ...
* ]
* }
*/
gos_result_t json_generator_request(const gos_hs_request_t *request, const char *arg)
{
gos_result_t result;
// -1 length means 'chunked' encoded response
if (GOS_FAILED(result, gos_hs_write_reply_header(request, "application/json", -1, GOS_HS_RESPONSE_FLAG_NONE)))
{
goto exit;
}
else if (GOS_FAILED(result, gos_hs_write_chunked_data(request, JSON_START, sizeof(JSON_START)-1, false)))
{
goto exit;
}
for (gos_gpio_t gpio = GOS_GPIO_0; gpio < GOS_GPIO_MAX; ++gpio)
{
char buffer[32];
int len = sprintf(buffer, "{\"gpio%d\": %d},", gpio, gos_gpio_get(gpio));
// if this is the last gpio then don't add trailing comma
if (gpio + 1 == GOS_GPIO_MAX)
{
--len;
}
if (GOS_FAILED(result, gos_hs_write_chunked_data(request, buffer, len, false)))
{
goto exit;
}
}
if (GOS_FAILED(result, gos_hs_write_chunked_data(request, JSON_END, sizeof(JSON_END)-1, true)))
{
goto exit;
}
exit:
return result;
}