REFACTOR
This commit is contained in:
parent
0460b2e9f7
commit
176483d72f
59 changed files with 11 additions and 45 deletions
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -1,7 +1,7 @@
|
|||
build/
|
||||
docs/
|
||||
|
||||
tests/testing_tmp/
|
||||
tests/testing_bak/
|
||||
test/testing_tmp/
|
||||
test/testing_bak/
|
||||
|
||||
include/migrations/*.sql.h
|
||||
|
|
|
|||
|
|
@ -1,26 +1,25 @@
|
|||
cmake_minimum_required (VERSION 3.7)
|
||||
project(core)
|
||||
|
||||
add_executable(core main.c)
|
||||
add_executable(core src/main.c)
|
||||
|
||||
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99 -Wpedantic -Werror -Wall -Wextra -luuid -lsqlite3 -ffile-prefix-map=${CMAKE_SOURCE_DIR}/=/")
|
||||
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99 -Wpedantic -Werror -Wall -Wextra -luuid -lsqlite3 -ffile-prefix-map=${CMAKE_SOURCE_DIR}/src/=")
|
||||
|
||||
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g -fprofile-arcs -ftest-coverage")
|
||||
|
||||
add_definitions("-DMG_ENABLE_EXTRA_ERRORS_DESC")
|
||||
|
||||
aux_source_directory(vendor VENDOR_SRC) # vendor first to put their warnings on top
|
||||
aux_source_directory(. SRC_DIR)
|
||||
aux_source_directory(models MODELS_SRC)
|
||||
aux_source_directory(helpers HELPERS_SRC)
|
||||
aux_source_directory(handlers HANDLERS_SRC)
|
||||
aux_source_directory(endpoints ENDPOINTS_SRC)
|
||||
aux_source_directory(src/ SRC_DIR)
|
||||
aux_source_directory(src/models MODELS_SRC)
|
||||
aux_source_directory(src/helpers HELPERS_SRC)
|
||||
aux_source_directory(src/handlers HANDLERS_SRC)
|
||||
aux_source_directory(src/endpoints ENDPOINTS_SRC)
|
||||
|
||||
configure_file("core.ini" "core.ini" COPYONLY)
|
||||
|
||||
add_dependencies(core migrations)
|
||||
|
||||
target_sources(core PRIVATE ${VENDOR_SRC} ${SRC_DIR} ${HANDLERS_SRC} ${HELPERS_SRC} ${MODELS_SRC} ${ENDPOINTS_SRC})
|
||||
target_sources(core PRIVATE ${SRC_DIR} ${HANDLERS_SRC} ${HELPERS_SRC} ${MODELS_SRC} ${ENDPOINTS_SRC})
|
||||
target_include_directories(core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
|
||||
target_include_directories(core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/vendor)
|
||||
|
||||
|
|
@ -53,7 +52,7 @@ add_custom_target(docs
|
|||
add_custom_target(test
|
||||
COMMAND ./run_tests.sh ${CMAKE_BINARY_DIR}/core "dev"
|
||||
DEPENDS core
|
||||
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/tests
|
||||
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/test
|
||||
)
|
||||
add_custom_target(coverage
|
||||
COMMAND gcovr -s --root ${CMAKE_SOURCE_DIR} -e ${CMAKE_SOURCE_DIR}/vendor --html-details ${CMAKE_BINARY_DIR}/coverage.html --html-title "Emgauwa Core Coverage" ${CMAKE_BINARY_DIR}/CMakeFiles/core.dir
|
||||
|
|
|
|||
15
enums.h
15
enums.h
|
|
@ -1,15 +0,0 @@
|
|||
#ifndef CORE_ENUM_H
|
||||
#define CORE_ENUM_H
|
||||
|
||||
enum control_mapping
|
||||
{
|
||||
COMMAND_MAPPING_CODE = 0,
|
||||
COMMAND_MAPPING_NAME = 1,
|
||||
COMMAND_MAPPING_RELAY_NUM = 2,
|
||||
COMMAND_MAPPING_SCHEDULES_ARRAY = 3,
|
||||
COMMAND_MAPPING_SCHEDULE_ID = 4,
|
||||
COMMAND_MAPPING_PERIODS_COUNT = 5,
|
||||
COMMAND_MAPPING_PERIODS_BLOB = 6,
|
||||
};
|
||||
|
||||
#endif /* CORE_ENUM_H */
|
||||
130
include/argparse.h
Normal file
130
include/argparse.h
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
/**
|
||||
* Copyright (C) 2012-2015 Yecheng Fu <cofyc.jackson at gmail dot com>
|
||||
* All rights reserved.
|
||||
*
|
||||
* Use of this source code is governed by a MIT-style license that can be found
|
||||
* in the LICENSE file.
|
||||
*/
|
||||
#ifndef ARGPARSE_H
|
||||
#define ARGPARSE_H
|
||||
|
||||
/* For c++ compatibility */
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
struct argparse;
|
||||
struct argparse_option;
|
||||
|
||||
typedef int argparse_callback (struct argparse *self,
|
||||
const struct argparse_option *option);
|
||||
|
||||
enum argparse_flag {
|
||||
ARGPARSE_STOP_AT_NON_OPTION = 1,
|
||||
};
|
||||
|
||||
enum argparse_option_type {
|
||||
/* special */
|
||||
ARGPARSE_OPT_END,
|
||||
ARGPARSE_OPT_GROUP,
|
||||
/* options with no arguments */
|
||||
ARGPARSE_OPT_BOOLEAN,
|
||||
ARGPARSE_OPT_BIT,
|
||||
/* options with arguments (optional or required) */
|
||||
ARGPARSE_OPT_INTEGER,
|
||||
ARGPARSE_OPT_FLOAT,
|
||||
ARGPARSE_OPT_STRING,
|
||||
};
|
||||
|
||||
enum argparse_option_flags {
|
||||
OPT_NONEG = 1, /* disable negation */
|
||||
};
|
||||
|
||||
/**
|
||||
* argparse option
|
||||
*
|
||||
* `type`:
|
||||
* holds the type of the option, you must have an ARGPARSE_OPT_END last in your
|
||||
* array.
|
||||
*
|
||||
* `short_name`:
|
||||
* the character to use as a short option name, '\0' if none.
|
||||
*
|
||||
* `long_name`:
|
||||
* the long option name, without the leading dash, NULL if none.
|
||||
*
|
||||
* `value`:
|
||||
* stores pointer to the value to be filled.
|
||||
*
|
||||
* `help`:
|
||||
* the short help message associated to what the option does.
|
||||
* Must never be NULL (except for ARGPARSE_OPT_END).
|
||||
*
|
||||
* `callback`:
|
||||
* function is called when corresponding argument is parsed.
|
||||
*
|
||||
* `data`:
|
||||
* associated data. Callbacks can use it like they want.
|
||||
*
|
||||
* `flags`:
|
||||
* option flags.
|
||||
*/
|
||||
struct argparse_option {
|
||||
enum argparse_option_type type;
|
||||
const char short_name;
|
||||
const char *long_name;
|
||||
void *value;
|
||||
const char *help;
|
||||
argparse_callback *callback;
|
||||
intptr_t data;
|
||||
int flags;
|
||||
};
|
||||
|
||||
/**
|
||||
* argpparse
|
||||
*/
|
||||
struct argparse {
|
||||
// user supplied
|
||||
const struct argparse_option *options;
|
||||
const char *const *usages;
|
||||
int flags;
|
||||
const char *description; // a description after usage
|
||||
const char *epilog; // a description at the end
|
||||
// internal context
|
||||
int argc;
|
||||
const char **argv;
|
||||
const char **out;
|
||||
int cpidx;
|
||||
const char *optvalue; // current option value
|
||||
};
|
||||
|
||||
// built-in callbacks
|
||||
int argparse_help_cb(struct argparse *self,
|
||||
const struct argparse_option *option);
|
||||
|
||||
// built-in option macros
|
||||
#define OPT_END() { ARGPARSE_OPT_END, 0, NULL, NULL, 0, NULL, 0, 0 }
|
||||
#define OPT_BOOLEAN(...) { ARGPARSE_OPT_BOOLEAN, __VA_ARGS__ }
|
||||
#define OPT_BIT(...) { ARGPARSE_OPT_BIT, __VA_ARGS__ }
|
||||
#define OPT_INTEGER(...) { ARGPARSE_OPT_INTEGER, __VA_ARGS__ }
|
||||
#define OPT_FLOAT(...) { ARGPARSE_OPT_FLOAT, __VA_ARGS__ }
|
||||
#define OPT_STRING(...) { ARGPARSE_OPT_STRING, __VA_ARGS__ }
|
||||
#define OPT_GROUP(h) { ARGPARSE_OPT_GROUP, 0, NULL, NULL, h, NULL, 0, 0 }
|
||||
#define OPT_HELP() OPT_BOOLEAN('h', "help", NULL, \
|
||||
"show this help message and exit", \
|
||||
argparse_help_cb, 0, OPT_NONEG)
|
||||
|
||||
int argparse_init(struct argparse *self, struct argparse_option *options,
|
||||
const char *const *usages, int flags);
|
||||
void argparse_describe(struct argparse *self, const char *description,
|
||||
const char *epilog);
|
||||
int argparse_parse(struct argparse *self, int argc, const char **argv);
|
||||
void argparse_usage(struct argparse *self);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
293
include/cJSON.h
Normal file
293
include/cJSON.h
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
/*
|
||||
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
|
||||
|
||||
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
|
||||
|
||||
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
|
||||
#define __WINDOWS__
|
||||
#endif
|
||||
|
||||
#ifdef __WINDOWS__
|
||||
|
||||
/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
|
||||
|
||||
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
|
||||
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
|
||||
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
|
||||
|
||||
For *nix builds that support visibility attribute, you can define similar behavior by
|
||||
|
||||
setting default visibility to hidden by adding
|
||||
-fvisibility=hidden (for gcc)
|
||||
or
|
||||
-xldscope=hidden (for sun cc)
|
||||
to CFLAGS
|
||||
|
||||
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
|
||||
|
||||
*/
|
||||
|
||||
#define CJSON_CDECL __cdecl
|
||||
#define CJSON_STDCALL __stdcall
|
||||
|
||||
/* export symbols by default, this is necessary for copy pasting the C and header file */
|
||||
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
|
||||
#define CJSON_EXPORT_SYMBOLS
|
||||
#endif
|
||||
|
||||
#if defined(CJSON_HIDE_SYMBOLS)
|
||||
#define CJSON_PUBLIC(type) type CJSON_STDCALL
|
||||
#elif defined(CJSON_EXPORT_SYMBOLS)
|
||||
#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
|
||||
#elif defined(CJSON_IMPORT_SYMBOLS)
|
||||
#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
|
||||
#endif
|
||||
#else /* !__WINDOWS__ */
|
||||
#define CJSON_CDECL
|
||||
#define CJSON_STDCALL
|
||||
|
||||
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
|
||||
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
|
||||
#else
|
||||
#define CJSON_PUBLIC(type) type
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* project version */
|
||||
#define CJSON_VERSION_MAJOR 1
|
||||
#define CJSON_VERSION_MINOR 7
|
||||
#define CJSON_VERSION_PATCH 13
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
/* cJSON Types: */
|
||||
#define cJSON_Invalid (0)
|
||||
#define cJSON_False (1 << 0)
|
||||
#define cJSON_True (1 << 1)
|
||||
#define cJSON_NULL (1 << 2)
|
||||
#define cJSON_Number (1 << 3)
|
||||
#define cJSON_String (1 << 4)
|
||||
#define cJSON_Array (1 << 5)
|
||||
#define cJSON_Object (1 << 6)
|
||||
#define cJSON_Raw (1 << 7) /* raw json */
|
||||
|
||||
#define cJSON_IsReference 256
|
||||
#define cJSON_StringIsConst 512
|
||||
|
||||
/* The cJSON structure: */
|
||||
typedef struct cJSON
|
||||
{
|
||||
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
|
||||
struct cJSON *next;
|
||||
struct cJSON *prev;
|
||||
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
|
||||
struct cJSON *child;
|
||||
|
||||
/* The type of the item, as above. */
|
||||
int type;
|
||||
|
||||
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
|
||||
char *valuestring;
|
||||
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
|
||||
int valueint;
|
||||
/* The item's number, if type==cJSON_Number */
|
||||
double valuedouble;
|
||||
|
||||
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
|
||||
char *string;
|
||||
} cJSON;
|
||||
|
||||
typedef struct cJSON_Hooks
|
||||
{
|
||||
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
|
||||
void *(CJSON_CDECL *malloc_fn)(size_t sz);
|
||||
void (CJSON_CDECL *free_fn)(void *ptr);
|
||||
} cJSON_Hooks;
|
||||
|
||||
typedef int cJSON_bool;
|
||||
|
||||
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
|
||||
* This is to prevent stack overflows. */
|
||||
#ifndef CJSON_NESTING_LIMIT
|
||||
#define CJSON_NESTING_LIMIT 1000
|
||||
#endif
|
||||
|
||||
/* returns the version of cJSON as a string */
|
||||
CJSON_PUBLIC(const char*) cJSON_Version(void);
|
||||
|
||||
/* Supply malloc, realloc and free functions to cJSON */
|
||||
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
|
||||
|
||||
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
|
||||
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length);
|
||||
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
|
||||
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated);
|
||||
|
||||
/* Render a cJSON entity to text for transfer/storage. */
|
||||
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
|
||||
/* Render a cJSON entity to text for transfer/storage without any formatting. */
|
||||
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const 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 */
|
||||
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
|
||||
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
|
||||
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
|
||||
/* Delete a cJSON entity and all subentities. */
|
||||
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
|
||||
|
||||
/* Returns the number of items in an array (or object). */
|
||||
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
|
||||
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
|
||||
/* Get item "string" from object. Case insensitive. */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const 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. */
|
||||
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
|
||||
|
||||
/* Check item type and return its value */
|
||||
CJSON_PUBLIC(char *) cJSON_GetStringValue(cJSON *item);
|
||||
CJSON_PUBLIC(double) cJSON_GetNumberValue(cJSON *item);
|
||||
|
||||
/* These functions check the type of an item */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
|
||||
|
||||
/* These calls create a cJSON item of the appropriate type. */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
|
||||
/* raw json */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
|
||||
|
||||
/* Create a string where valuestring references a string so
|
||||
* it will not be freed by cJSON_Delete */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
|
||||
/* Create an object/array that only references it's elements so
|
||||
* they will not be freed by cJSON_Delete */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
|
||||
|
||||
/* These utilities create an Array of count items.
|
||||
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
|
||||
|
||||
/* Append item to the specified array/object. */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(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.
|
||||
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
|
||||
* writing to `item->string` */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
|
||||
/* 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. */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
|
||||
|
||||
/* Remove/Detach items from Arrays/Objects. */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
|
||||
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
|
||||
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
|
||||
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
|
||||
|
||||
/* Update array items. */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
|
||||
|
||||
/* Duplicate a cJSON item */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool 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. */
|
||||
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
|
||||
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
|
||||
|
||||
/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
|
||||
* The input pointer json cannot point to a read-only address area, such as a string constant,
|
||||
* but should point to a readable and writable adress area. */
|
||||
CJSON_PUBLIC(void) cJSON_Minify(char *json);
|
||||
|
||||
/* Helper functions for creating and adding items to an object at the same time.
|
||||
* They return the added item or NULL on failure. */
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
|
||||
|
||||
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
|
||||
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
|
||||
/* helper for the cJSON_SetNumberValue macro */
|
||||
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
|
||||
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
|
||||
/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */
|
||||
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring);
|
||||
|
||||
/* Macro for iterating over an array or object */
|
||||
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
|
||||
|
||||
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
|
||||
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
|
||||
CJSON_PUBLIC(void) cJSON_free(void *object);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
547
include/confini.h
Normal file
547
include/confini.h
Normal file
|
|
@ -0,0 +1,547 @@
|
|||
/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*- */
|
||||
|
||||
/**
|
||||
|
||||
@file confini.h
|
||||
@brief libconfini header
|
||||
@author Stefano Gioffré
|
||||
@copyright GNU General Public License, version 3 or any later version
|
||||
@version 1.14.0
|
||||
@date 2016-2020
|
||||
@see https://madmurphy.github.io/libconfini
|
||||
|
||||
**/
|
||||
|
||||
|
||||
#ifndef _LIBCONFINI_HEADER_
|
||||
#define _LIBCONFINI_HEADER_
|
||||
|
||||
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* PRIVATE (HEADER-SCOPED) MACROS */
|
||||
|
||||
|
||||
#define __INIFORMAT_TABLE_CB_FIELDS__(NAME, OFFSET, SIZE, DEFVAL) \
|
||||
unsigned char NAME:SIZE;
|
||||
#define __INIFORMAT_TABLE_CB_DEFAULT__(NAME, OFFSET, SIZE, DEFVAL) DEFVAL,
|
||||
#define __INIFORMAT_TABLE_CB_ZERO__(NAME, OFFSET, SIZE, DEFVAL) 0,
|
||||
#define _LIBCONFINI_INIFORMAT_TYPE_ \
|
||||
struct IniFormat { INIFORMAT_TABLE_AS(__INIFORMAT_TABLE_CB_FIELDS__) }
|
||||
#define _LIBCONFINI_DEFAULT_FORMAT_ \
|
||||
{ INIFORMAT_TABLE_AS(__INIFORMAT_TABLE_CB_DEFAULT__) }
|
||||
#define _LIBCONFINI_UNIXLIKE_FORMAT_ \
|
||||
{ INIFORMAT_TABLE_AS(__INIFORMAT_TABLE_CB_ZERO__) }
|
||||
|
||||
|
||||
|
||||
/* PUBLIC MACROS */
|
||||
|
||||
|
||||
/**
|
||||
@brief Calls a user-given macro (that accepts four arguments) for each row
|
||||
of the table
|
||||
**/
|
||||
/*
|
||||
NOTE: The following table and the order of its rows **define** (and link
|
||||
together) both the #IniFormat and #IniFormatNum data types declared in this
|
||||
header
|
||||
*/
|
||||
#define INIFORMAT_TABLE_AS(_____) /* IniFormat table *\
|
||||
|
||||
NAME BIT SIZE DEFAULT
|
||||
*/\
|
||||
_____( delimiter_symbol, 0, 7, INI_EQUALS ) \
|
||||
_____( case_sensitive, 7, 1, false )/*
|
||||
*/\
|
||||
_____( semicolon_marker, 8, 2, INI_DISABLED_OR_COMMENT ) \
|
||||
_____( hash_marker, 10, 2, INI_DISABLED_OR_COMMENT ) \
|
||||
_____( section_paths, 12, 2, INI_ABSOLUTE_AND_RELATIVE ) \
|
||||
_____( multiline_nodes, 14, 2, INI_MULTILINE_EVERYWHERE )/*
|
||||
*/\
|
||||
_____( no_single_quotes, 16, 1, false ) \
|
||||
_____( no_double_quotes, 17, 1, false ) \
|
||||
_____( no_spaces_in_names, 18, 1, false ) \
|
||||
_____( implicit_is_not_empty, 19, 1, false ) \
|
||||
_____( do_not_collapse_values, 20, 1, false ) \
|
||||
_____( preserve_empty_quotes, 21, 1, false ) \
|
||||
_____( disabled_after_space, 22, 1, false ) \
|
||||
_____( disabled_can_be_implicit, 23, 1, false )
|
||||
|
||||
|
||||
|
||||
/**
|
||||
@brief Checks whether a format does **not** support escape sequences
|
||||
**/
|
||||
#define INIFORMAT_HAS_NO_ESC(FORMAT) \
|
||||
(FORMAT.multiline_nodes == INI_NO_MULTILINE && \
|
||||
FORMAT.no_double_quotes && FORMAT.no_single_quotes)
|
||||
|
||||
|
||||
|
||||
/* PUBLIC TYPEDEFS */
|
||||
|
||||
|
||||
/**
|
||||
@brief 24-bit bitfield representing the format of an INI file (INI
|
||||
dialect)
|
||||
**/
|
||||
typedef _LIBCONFINI_INIFORMAT_TYPE_ IniFormat;
|
||||
|
||||
|
||||
/**
|
||||
@brief Global statistics about an INI file
|
||||
**/
|
||||
typedef struct IniStatistics {
|
||||
const IniFormat format;
|
||||
const size_t bytes;
|
||||
const size_t members;
|
||||
} IniStatistics;
|
||||
|
||||
|
||||
/**
|
||||
@brief Dispatch of a single INI node
|
||||
**/
|
||||
typedef struct IniDispatch {
|
||||
const IniFormat format;
|
||||
uint8_t type;
|
||||
char * data;
|
||||
char * value;
|
||||
const char * append_to;
|
||||
size_t d_len;
|
||||
size_t v_len;
|
||||
size_t at_len;
|
||||
size_t dispatch_id;
|
||||
} IniDispatch;
|
||||
|
||||
|
||||
/**
|
||||
@brief The unique ID of an INI format (24-bit maximum)
|
||||
**/
|
||||
typedef uint32_t IniFormatNum;
|
||||
|
||||
|
||||
/**
|
||||
@brief Callback function for handling an #IniStatistics structure
|
||||
**/
|
||||
typedef int (* IniStatsHandler) (
|
||||
IniStatistics * statistics,
|
||||
void * user_data
|
||||
);
|
||||
|
||||
|
||||
/**
|
||||
@brief Callback function for handling an #IniDispatch structure
|
||||
**/
|
||||
typedef int (* IniDispHandler) (
|
||||
IniDispatch * dispatch,
|
||||
void * user_data
|
||||
);
|
||||
|
||||
|
||||
/**
|
||||
@brief Callback function for handling an INI string belonging to a
|
||||
sequence of INI strings
|
||||
**/
|
||||
typedef int (* IniStrHandler) (
|
||||
char * ini_string,
|
||||
size_t string_length,
|
||||
size_t string_num,
|
||||
IniFormat format,
|
||||
void * user_data
|
||||
);
|
||||
|
||||
|
||||
/**
|
||||
@brief Callback function for handling a selected fragment of an INI string
|
||||
**/
|
||||
typedef int (* IniSubstrHandler) (
|
||||
const char * ini_string,
|
||||
size_t fragm_offset,
|
||||
size_t fragm_length,
|
||||
size_t fragm_num,
|
||||
IniFormat format,
|
||||
void * user_data
|
||||
);
|
||||
|
||||
|
||||
|
||||
/* PUBLIC FUNCTIONS */
|
||||
|
||||
|
||||
extern int strip_ini_cache (
|
||||
register char * const ini_source,
|
||||
const size_t ini_length,
|
||||
const IniFormat format,
|
||||
const IniStatsHandler f_init,
|
||||
const IniDispHandler f_foreach,
|
||||
void * const user_data
|
||||
);
|
||||
|
||||
|
||||
extern int load_ini_file (
|
||||
FILE * const ini_file,
|
||||
const IniFormat format,
|
||||
const IniStatsHandler f_init,
|
||||
const IniDispHandler f_foreach,
|
||||
void * const user_data
|
||||
);
|
||||
|
||||
|
||||
extern int load_ini_path (
|
||||
const char * const path,
|
||||
const IniFormat format,
|
||||
const IniStatsHandler f_init,
|
||||
const IniDispHandler f_foreach,
|
||||
void * const user_data
|
||||
);
|
||||
|
||||
|
||||
extern bool ini_string_match_ss (
|
||||
const char * const simple_string_a,
|
||||
const char * const simple_string_b,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern bool ini_string_match_si (
|
||||
const char * const simple_string,
|
||||
const char * const ini_string,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern bool ini_string_match_ii (
|
||||
const char * const ini_string_a,
|
||||
const char * const ini_string_b,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern bool ini_array_match (
|
||||
const char * const ini_string_a,
|
||||
const char * const ini_string_b,
|
||||
const char delimiter,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern size_t ini_unquote (
|
||||
char * const ini_string,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern size_t ini_string_parse (
|
||||
char * const ini_string,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern size_t ini_array_get_length (
|
||||
const char * const ini_string,
|
||||
const char delimiter,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern int ini_array_foreach (
|
||||
const char * const ini_string,
|
||||
const char delimiter,
|
||||
const IniFormat format,
|
||||
const IniSubstrHandler f_foreach,
|
||||
void * const user_data
|
||||
);
|
||||
|
||||
|
||||
extern size_t ini_array_shift (
|
||||
const char ** const ini_strptr,
|
||||
const char delimiter,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern size_t ini_array_collapse (
|
||||
char * const ini_string,
|
||||
const char delimiter,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern char * ini_array_break (
|
||||
char * const ini_string,
|
||||
const char delimiter,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern char * ini_array_release (
|
||||
char ** const ini_strptr,
|
||||
const char delimiter,
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern int ini_array_split (
|
||||
char * const ini_string,
|
||||
const char delimiter,
|
||||
const IniFormat format,
|
||||
const IniStrHandler f_foreach,
|
||||
void * const user_data
|
||||
);
|
||||
|
||||
|
||||
extern void ini_global_set_lowercase_mode (
|
||||
const bool lowercase
|
||||
);
|
||||
|
||||
|
||||
extern void ini_global_set_implicit_value (
|
||||
char * const implicit_value,
|
||||
const size_t implicit_v_len
|
||||
);
|
||||
|
||||
|
||||
extern IniFormatNum ini_fton (
|
||||
const IniFormat format
|
||||
);
|
||||
|
||||
|
||||
extern IniFormat ini_ntof (
|
||||
const IniFormatNum format_id
|
||||
);
|
||||
|
||||
|
||||
extern int ini_get_bool (
|
||||
const char * const ini_string,
|
||||
const int when_fail
|
||||
);
|
||||
|
||||
|
||||
|
||||
/* PUBLIC LINKS */
|
||||
|
||||
|
||||
extern int (* const ini_get_int) (
|
||||
const char * ini_string
|
||||
);
|
||||
|
||||
|
||||
extern long int (* const ini_get_lint) (
|
||||
const char * ini_string
|
||||
);
|
||||
|
||||
|
||||
extern long long int (* const ini_get_llint) (
|
||||
const char * ini_string
|
||||
);
|
||||
|
||||
|
||||
extern double (* const ini_get_double) (
|
||||
const char * ini_string
|
||||
);
|
||||
|
||||
|
||||
/**
|
||||
@brief Legacy support, soon to be replaced with a `float` data type --
|
||||
please **do not use `ini_get_float()`!**
|
||||
**/
|
||||
#define ini_get_float \
|
||||
_Pragma("GCC warning \"function `ini_get_float()` is deprecated for parsing a `double` data type; use `ini_get_double()` instead\"") \
|
||||
ini_get_double
|
||||
|
||||
|
||||
|
||||
/* PUBLIC CONSTANTS AND VARIABLES */
|
||||
|
||||
|
||||
/**
|
||||
@brief Error mask (flags not present in user-generated interruptions)
|
||||
**/
|
||||
#define CONFINI_ERROR 252
|
||||
|
||||
|
||||
/**
|
||||
@brief Error codes
|
||||
**/
|
||||
enum ConfiniInterruptNo {
|
||||
CONFINI_SUCCESS = 0, /**< There have been no interruptions, everything
|
||||
went well [value=0] **/
|
||||
CONFINI_IINTR = 1, /**< Interrupted by the user during `f_init()`
|
||||
[value=1] **/
|
||||
CONFINI_FEINTR = 2, /**< Interrupted by the user during `f_foreach()`
|
||||
[value=2] **/
|
||||
CONFINI_ENOENT = 4, /**< File inaccessible [value=4] **/
|
||||
CONFINI_ENOMEM = 5, /**< Error allocating virtual memory [value=5] **/
|
||||
CONFINI_EIO = 6, /**< Error reading the file [value=6] **/
|
||||
CONFINI_EOOR = 7, /**< Out-of-range error: callbacks are more than
|
||||
expected [value=7] **/
|
||||
CONFINI_EBADF = 8, /**< The stream specified is not a seekable stream
|
||||
[value=8] **/
|
||||
CONFINI_EFBIG = 9, /**< File too large [value=9] **/
|
||||
CONFINI_EROADDR = 10 /**< Address is read-only [value=10] **/
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
@brief INI node types
|
||||
**/
|
||||
enum IniNodeType {
|
||||
INI_UNKNOWN = 0, /**< This is a node impossible to categorize
|
||||
[value=0] **/
|
||||
INI_VALUE = 1, /**< Not used by **libconfini** (values are
|
||||
dispatched together with keys) -- but
|
||||
available for user's implementations
|
||||
[value=1] **/
|
||||
INI_KEY = 2, /**< This is a key [value=2] **/
|
||||
INI_SECTION = 3, /**< This is a section or a section path
|
||||
[value=3] **/
|
||||
INI_COMMENT = 4, /**< This is a comment [value=4] **/
|
||||
INI_INLINE_COMMENT = 5, /**< This is an inline comment [value=5] **/
|
||||
INI_DISABLED_KEY = 6, /**< This is a disabled key [value=6] **/
|
||||
INI_DISABLED_SECTION = 7 /**< This is a disabled section path
|
||||
[value=7] **/
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
@brief Common array and key-value delimiters (but a delimiter may also be
|
||||
any other ASCII character not present in this list)
|
||||
**/
|
||||
enum IniDelimiters {
|
||||
INI_ANY_SPACE = 0, /**< In multi-line INIs:
|
||||
`/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`, in
|
||||
non-multi-line INIs: `/[\t \v\f])+/` **/
|
||||
INI_EQUALS = '=', /**< Equals character (`=`) **/
|
||||
INI_COLON = ':', /**< Colon character (`:`) **/
|
||||
INI_DOT = '.', /**< Dot character (`.`) **/
|
||||
INI_COMMA = ',' /**< Comma character (`,`) **/
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
@brief Possible values of #IniFormat::semicolon_marker and
|
||||
#IniFormat::hash_marker (i.e., meaning of `/\s+;/` and `/\s+#/` in
|
||||
respect to a format)
|
||||
**/
|
||||
enum IniCommentMarker {
|
||||
INI_DISABLED_OR_COMMENT = 0, /**< This marker opens a comment or a
|
||||
disabled entry **/
|
||||
INI_ONLY_COMMENT = 1, /**< This marker opens a comment **/
|
||||
INI_IGNORE = 2, /**< This marker opens a comment that has
|
||||
been marked for deletion and must not
|
||||
be dispatched or counted **/
|
||||
INI_IS_NOT_A_MARKER = 3 /**< This is not a marker at all, but a
|
||||
normal character instead **/
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
@brief Possible values of #IniFormat::section_paths
|
||||
**/
|
||||
enum IniSectionPaths {
|
||||
INI_ABSOLUTE_AND_RELATIVE = 0, /**< Section paths starting with a dot
|
||||
express nesting to the current parent,
|
||||
to root otherwise **/
|
||||
INI_ABSOLUTE_ONLY = 1, /**< Section paths starting with a dot will
|
||||
be cleaned of their leading dot and
|
||||
appended to root **/
|
||||
INI_ONE_LEVEL_ONLY = 2, /**< Format supports sections, but the dot
|
||||
does not express nesting and is not a
|
||||
meta-character **/
|
||||
INI_NO_SECTIONS = 3 /**< Format does *not* support sections --
|
||||
`/\[[^\]]*\]/g`, if any, will be
|
||||
treated as keys! **/
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
@brief Possible values of #IniFormat::multiline_nodes
|
||||
**/
|
||||
enum IniMultiline {
|
||||
INI_MULTILINE_EVERYWHERE = 0, /**< Comments, section paths and keys
|
||||
-- disabled or not -- are allowed
|
||||
to be multi-line **/
|
||||
INI_BUT_COMMENTS = 1, /**< Only section paths and keys --
|
||||
disabled or not -- are allowed to
|
||||
be multi-line **/
|
||||
INI_BUT_DISABLED_AND_COMMENTS = 2, /**< Only active section paths and
|
||||
active keys are allowed to be
|
||||
multi-line **/
|
||||
INI_NO_MULTILINE = 3 /**< Multi-line escape sequences are
|
||||
disabled **/
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
@brief A model format for standard INI files
|
||||
**/
|
||||
static const IniFormat INI_DEFAULT_FORMAT = _LIBCONFINI_DEFAULT_FORMAT_;
|
||||
|
||||
|
||||
/**
|
||||
@brief A model format for Unix-like .conf files (where space characters
|
||||
are delimiters between keys and values)
|
||||
**/
|
||||
/* All fields are set to `0` here. */
|
||||
static const IniFormat INI_UNIXLIKE_FORMAT = _LIBCONFINI_UNIXLIKE_FORMAT_;
|
||||
|
||||
|
||||
/**
|
||||
@brief If set to `true`, key and section names in case-insensitive INI
|
||||
formats will be dispatched lowercase, verbatim otherwise (default
|
||||
value: `false`)
|
||||
**/
|
||||
extern bool INI_GLOBAL_LOWERCASE_MODE;
|
||||
|
||||
|
||||
/**
|
||||
@brief Value to be assigned to implicit keys (default value: `NULL`)
|
||||
**/
|
||||
extern char * INI_GLOBAL_IMPLICIT_VALUE;
|
||||
|
||||
|
||||
/**
|
||||
@brief Length of the value assigned to implicit keys (default value: `0`)
|
||||
**/
|
||||
extern size_t INI_GLOBAL_IMPLICIT_V_LEN;
|
||||
|
||||
|
||||
|
||||
/* CLEAN THE PRIVATE ENVIRONMENT */
|
||||
|
||||
|
||||
#undef _LIBCONFINI_UNIXLIKE_FORMAT_
|
||||
#undef _LIBCONFINI_DEFAULT_FORMAT_
|
||||
#undef _LIBCONFINI_INIFORMAT_TYPE_
|
||||
#undef __INIFORMAT_TABLE_CB_ZERO__
|
||||
#undef __INIFORMAT_TABLE_CB_DEFAULT__
|
||||
#undef __INIFORMAT_TABLE_CB_FIELDS__
|
||||
|
||||
|
||||
|
||||
/* END OF `_LIBCONFINI_HEADER_` */
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* EOF */
|
||||
|
||||
6277
include/mongoose.h
Normal file
6277
include/mongoose.h
Normal file
File diff suppressed because it is too large
Load diff
7151
include/mpack.h
Normal file
7151
include/mpack.h
Normal file
File diff suppressed because it is too large
Load diff
384
src/argparse.c
Normal file
384
src/argparse.c
Normal file
|
|
@ -0,0 +1,384 @@
|
|||
/**
|
||||
* Copyright (C) 2012-2015 Yecheng Fu <cofyc.jackson at gmail dot com>
|
||||
* All rights reserved.
|
||||
*
|
||||
* Use of this source code is governed by a MIT-style license that can be found
|
||||
* in the LICENSE file.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include "argparse.h"
|
||||
|
||||
#define OPT_UNSET 1
|
||||
#define OPT_LONG (1 << 1)
|
||||
|
||||
static const char *
|
||||
prefix_skip(const char *str, const char *prefix)
|
||||
{
|
||||
size_t len = strlen(prefix);
|
||||
return strncmp(str, prefix, len) ? NULL : str + len;
|
||||
}
|
||||
|
||||
static int
|
||||
prefix_cmp(const char *str, const char *prefix)
|
||||
{
|
||||
for (;; str++, prefix++)
|
||||
if (!*prefix) {
|
||||
return 0;
|
||||
} else if (*str != *prefix) {
|
||||
return (unsigned char)*prefix - (unsigned char)*str;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
argparse_error(struct argparse *self, const struct argparse_option *opt,
|
||||
const char *reason, int flags)
|
||||
{
|
||||
(void)self;
|
||||
if (flags & OPT_LONG) {
|
||||
fprintf(stderr, "error: option `--%s` %s\n", opt->long_name, reason);
|
||||
} else {
|
||||
fprintf(stderr, "error: option `-%c` %s\n", opt->short_name, reason);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
static int
|
||||
argparse_getvalue(struct argparse *self, const struct argparse_option *opt,
|
||||
int flags)
|
||||
{
|
||||
const char *s = NULL;
|
||||
if (!opt->value)
|
||||
goto skipped;
|
||||
switch (opt->type) {
|
||||
case ARGPARSE_OPT_BOOLEAN:
|
||||
if (flags & OPT_UNSET) {
|
||||
*(int *)opt->value = *(int *)opt->value - 1;
|
||||
} else {
|
||||
*(int *)opt->value = *(int *)opt->value + 1;
|
||||
}
|
||||
if (*(int *)opt->value < 0) {
|
||||
*(int *)opt->value = 0;
|
||||
}
|
||||
break;
|
||||
case ARGPARSE_OPT_BIT:
|
||||
if (flags & OPT_UNSET) {
|
||||
*(int *)opt->value &= ~opt->data;
|
||||
} else {
|
||||
*(int *)opt->value |= opt->data;
|
||||
}
|
||||
break;
|
||||
case ARGPARSE_OPT_STRING:
|
||||
if (self->optvalue) {
|
||||
*(const char **)opt->value = self->optvalue;
|
||||
self->optvalue = NULL;
|
||||
} else if (self->argc > 1) {
|
||||
self->argc--;
|
||||
*(const char **)opt->value = *++self->argv;
|
||||
} else {
|
||||
argparse_error(self, opt, "requires a value", flags);
|
||||
}
|
||||
break;
|
||||
case ARGPARSE_OPT_INTEGER:
|
||||
errno = 0;
|
||||
if (self->optvalue) {
|
||||
*(int *)opt->value = strtol(self->optvalue, (char **)&s, 0);
|
||||
self->optvalue = NULL;
|
||||
} else if (self->argc > 1) {
|
||||
self->argc--;
|
||||
*(int *)opt->value = strtol(*++self->argv, (char **)&s, 0);
|
||||
} else {
|
||||
argparse_error(self, opt, "requires a value", flags);
|
||||
}
|
||||
if (errno)
|
||||
argparse_error(self, opt, strerror(errno), flags);
|
||||
if (s[0] != '\0')
|
||||
argparse_error(self, opt, "expects an integer value", flags);
|
||||
break;
|
||||
case ARGPARSE_OPT_FLOAT:
|
||||
errno = 0;
|
||||
if (self->optvalue) {
|
||||
*(float *)opt->value = strtof(self->optvalue, (char **)&s);
|
||||
self->optvalue = NULL;
|
||||
} else if (self->argc > 1) {
|
||||
self->argc--;
|
||||
*(float *)opt->value = strtof(*++self->argv, (char **)&s);
|
||||
} else {
|
||||
argparse_error(self, opt, "requires a value", flags);
|
||||
}
|
||||
if (errno)
|
||||
argparse_error(self, opt, strerror(errno), flags);
|
||||
if (s[0] != '\0')
|
||||
argparse_error(self, opt, "expects a numerical value", flags);
|
||||
break;
|
||||
default:
|
||||
assert(0);
|
||||
}
|
||||
|
||||
skipped:
|
||||
if (opt->callback) {
|
||||
return opt->callback(self, opt);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
argparse_options_check(const struct argparse_option *options)
|
||||
{
|
||||
for (; options->type != ARGPARSE_OPT_END; options++) {
|
||||
switch (options->type) {
|
||||
case ARGPARSE_OPT_END:
|
||||
case ARGPARSE_OPT_BOOLEAN:
|
||||
case ARGPARSE_OPT_BIT:
|
||||
case ARGPARSE_OPT_INTEGER:
|
||||
case ARGPARSE_OPT_FLOAT:
|
||||
case ARGPARSE_OPT_STRING:
|
||||
case ARGPARSE_OPT_GROUP:
|
||||
continue;
|
||||
default:
|
||||
fprintf(stderr, "wrong option type: %d", options->type);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int
|
||||
argparse_short_opt(struct argparse *self, const struct argparse_option *options)
|
||||
{
|
||||
for (; options->type != ARGPARSE_OPT_END; options++) {
|
||||
if (options->short_name == *self->optvalue) {
|
||||
self->optvalue = self->optvalue[1] ? self->optvalue + 1 : NULL;
|
||||
return argparse_getvalue(self, options, 0);
|
||||
}
|
||||
}
|
||||
return -2;
|
||||
}
|
||||
|
||||
static int
|
||||
argparse_long_opt(struct argparse *self, const struct argparse_option *options)
|
||||
{
|
||||
for (; options->type != ARGPARSE_OPT_END; options++) {
|
||||
const char *rest;
|
||||
int opt_flags = 0;
|
||||
if (!options->long_name)
|
||||
continue;
|
||||
|
||||
rest = prefix_skip(self->argv[0] + 2, options->long_name);
|
||||
if (!rest) {
|
||||
// negation disabled?
|
||||
if (options->flags & OPT_NONEG) {
|
||||
continue;
|
||||
}
|
||||
// only OPT_BOOLEAN/OPT_BIT supports negation
|
||||
if (options->type != ARGPARSE_OPT_BOOLEAN && options->type !=
|
||||
ARGPARSE_OPT_BIT) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (prefix_cmp(self->argv[0] + 2, "no-")) {
|
||||
continue;
|
||||
}
|
||||
rest = prefix_skip(self->argv[0] + 2 + 3, options->long_name);
|
||||
if (!rest)
|
||||
continue;
|
||||
opt_flags |= OPT_UNSET;
|
||||
}
|
||||
if (*rest) {
|
||||
if (*rest != '=')
|
||||
continue;
|
||||
self->optvalue = rest + 1;
|
||||
}
|
||||
return argparse_getvalue(self, options, opt_flags | OPT_LONG);
|
||||
}
|
||||
return -2;
|
||||
}
|
||||
|
||||
int
|
||||
argparse_init(struct argparse *self, struct argparse_option *options,
|
||||
const char *const *usages, int flags)
|
||||
{
|
||||
memset(self, 0, sizeof(*self));
|
||||
self->options = options;
|
||||
self->usages = usages;
|
||||
self->flags = flags;
|
||||
self->description = NULL;
|
||||
self->epilog = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
argparse_describe(struct argparse *self, const char *description,
|
||||
const char *epilog)
|
||||
{
|
||||
self->description = description;
|
||||
self->epilog = epilog;
|
||||
}
|
||||
|
||||
int
|
||||
argparse_parse(struct argparse *self, int argc, const char **argv)
|
||||
{
|
||||
self->argc = argc - 1;
|
||||
self->argv = argv + 1;
|
||||
self->out = argv;
|
||||
|
||||
argparse_options_check(self->options);
|
||||
|
||||
for (; self->argc; self->argc--, self->argv++) {
|
||||
const char *arg = self->argv[0];
|
||||
if (arg[0] != '-' || !arg[1]) {
|
||||
if (self->flags & ARGPARSE_STOP_AT_NON_OPTION) {
|
||||
goto end;
|
||||
}
|
||||
// if it's not option or is a single char '-', copy verbatim
|
||||
self->out[self->cpidx++] = self->argv[0];
|
||||
continue;
|
||||
}
|
||||
// short option
|
||||
if (arg[1] != '-') {
|
||||
self->optvalue = arg + 1;
|
||||
switch (argparse_short_opt(self, self->options)) {
|
||||
case -1:
|
||||
break;
|
||||
case -2:
|
||||
goto unknown;
|
||||
}
|
||||
while (self->optvalue) {
|
||||
switch (argparse_short_opt(self, self->options)) {
|
||||
case -1:
|
||||
break;
|
||||
case -2:
|
||||
goto unknown;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// if '--' presents
|
||||
if (!arg[2]) {
|
||||
self->argc--;
|
||||
self->argv++;
|
||||
break;
|
||||
}
|
||||
// long option
|
||||
switch (argparse_long_opt(self, self->options)) {
|
||||
case -1:
|
||||
break;
|
||||
case -2:
|
||||
goto unknown;
|
||||
}
|
||||
continue;
|
||||
|
||||
unknown:
|
||||
fprintf(stderr, "error: unknown option `%s`\n", self->argv[0]);
|
||||
argparse_usage(self);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
end:
|
||||
memmove(self->out + self->cpidx, self->argv,
|
||||
self->argc * sizeof(*self->out));
|
||||
self->out[self->cpidx + self->argc] = NULL;
|
||||
|
||||
return self->cpidx + self->argc;
|
||||
}
|
||||
|
||||
void
|
||||
argparse_usage(struct argparse *self)
|
||||
{
|
||||
if (self->usages) {
|
||||
fprintf(stdout, "Usage: %s\n", *self->usages++);
|
||||
while (*self->usages && **self->usages)
|
||||
fprintf(stdout, " or: %s\n", *self->usages++);
|
||||
} else {
|
||||
fprintf(stdout, "Usage:\n");
|
||||
}
|
||||
|
||||
// print description
|
||||
if (self->description)
|
||||
fprintf(stdout, "%s\n", self->description);
|
||||
|
||||
fputc('\n', stdout);
|
||||
|
||||
const struct argparse_option *options;
|
||||
|
||||
// figure out best width
|
||||
size_t usage_opts_width = 0;
|
||||
size_t len;
|
||||
options = self->options;
|
||||
for (; options->type != ARGPARSE_OPT_END; options++) {
|
||||
len = 0;
|
||||
if ((options)->short_name) {
|
||||
len += 2;
|
||||
}
|
||||
if ((options)->short_name && (options)->long_name) {
|
||||
len += 2; // separator ", "
|
||||
}
|
||||
if ((options)->long_name) {
|
||||
len += strlen((options)->long_name) + 2;
|
||||
}
|
||||
if (options->type == ARGPARSE_OPT_INTEGER) {
|
||||
len += strlen("=<int>");
|
||||
}
|
||||
if (options->type == ARGPARSE_OPT_FLOAT) {
|
||||
len += strlen("=<flt>");
|
||||
} else if (options->type == ARGPARSE_OPT_STRING) {
|
||||
len += strlen("=<str>");
|
||||
}
|
||||
len = (len + 3) - ((len + 3) & 3);
|
||||
if (usage_opts_width < len) {
|
||||
usage_opts_width = len;
|
||||
}
|
||||
}
|
||||
usage_opts_width += 4; // 4 spaces prefix
|
||||
|
||||
options = self->options;
|
||||
for (; options->type != ARGPARSE_OPT_END; options++) {
|
||||
size_t pos = 0;
|
||||
int pad = 0;
|
||||
if (options->type == ARGPARSE_OPT_GROUP) {
|
||||
fputc('\n', stdout);
|
||||
fprintf(stdout, "%s", options->help);
|
||||
fputc('\n', stdout);
|
||||
continue;
|
||||
}
|
||||
pos = fprintf(stdout, " ");
|
||||
if (options->short_name) {
|
||||
pos += fprintf(stdout, "-%c", options->short_name);
|
||||
}
|
||||
if (options->long_name && options->short_name) {
|
||||
pos += fprintf(stdout, ", ");
|
||||
}
|
||||
if (options->long_name) {
|
||||
pos += fprintf(stdout, "--%s", options->long_name);
|
||||
}
|
||||
if (options->type == ARGPARSE_OPT_INTEGER) {
|
||||
pos += fprintf(stdout, "=<int>");
|
||||
} else if (options->type == ARGPARSE_OPT_FLOAT) {
|
||||
pos += fprintf(stdout, "=<flt>");
|
||||
} else if (options->type == ARGPARSE_OPT_STRING) {
|
||||
pos += fprintf(stdout, "=<str>");
|
||||
}
|
||||
if (pos <= usage_opts_width) {
|
||||
pad = usage_opts_width - pos;
|
||||
} else {
|
||||
fputc('\n', stdout);
|
||||
pad = usage_opts_width;
|
||||
}
|
||||
fprintf(stdout, "%*s%s\n", pad + 2, "", options->help);
|
||||
}
|
||||
|
||||
// print epilog
|
||||
if (self->epilog)
|
||||
fprintf(stdout, "%s\n", self->epilog);
|
||||
}
|
||||
|
||||
int
|
||||
argparse_help_cb(struct argparse *self, const struct argparse_option *option)
|
||||
{
|
||||
(void)option;
|
||||
argparse_usage(self);
|
||||
exit(0);
|
||||
}
|
||||
3074
src/cJSON.c
Normal file
3074
src/cJSON.c
Normal file
File diff suppressed because it is too large
Load diff
141
src/command.c
Normal file
141
src/command.c
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <command.h>
|
||||
#include <mpack.h>
|
||||
#include <logger.h>
|
||||
#include <helpers.h>
|
||||
#include <enums.h>
|
||||
#include <models/controller.h>
|
||||
|
||||
int
|
||||
command_set_relay_schedule(relay_t *relay)
|
||||
{
|
||||
controller_t *controller = controller_get_by_id(relay->controller_id);
|
||||
if(!controller)
|
||||
{
|
||||
LOG_ERROR("couldn't find controller\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
char* payload;
|
||||
size_t payload_size;
|
||||
mpack_writer_t writer;
|
||||
mpack_writer_init_growable(&writer, &payload, &payload_size);
|
||||
|
||||
// 3 = code, relay num, relay name, schedules(array)
|
||||
mpack_start_map(&writer, 3);
|
||||
|
||||
mpack_write_uint(&writer, COMMAND_MAPPING_CODE);
|
||||
mpack_write_u8(&writer, COMMAND_CODE_SET_SCHEDULE);
|
||||
|
||||
mpack_write_uint(&writer, COMMAND_MAPPING_RELAY_NUM);
|
||||
mpack_write_u8(&writer, relay->number);
|
||||
|
||||
mpack_write_uint(&writer, COMMAND_MAPPING_SCHEDULES_ARRAY);
|
||||
// 7 = days of week
|
||||
mpack_start_array(&writer, 7);
|
||||
for(int i = 0; i < 7; ++i)
|
||||
{
|
||||
uint16_t *periods_blob = schedule_periods_to_blob(relay->schedules[i]);
|
||||
uint16_t periods_count = periods_blob[0];
|
||||
|
||||
// 3 = code, relaynum, schedules(array)
|
||||
mpack_start_map(&writer, 3);
|
||||
|
||||
mpack_write_uint(&writer, COMMAND_MAPPING_PERIODS_COUNT);
|
||||
mpack_write_u16(&writer, periods_count);
|
||||
|
||||
mpack_write_uint(&writer, COMMAND_MAPPING_SCHEDULE_ID);
|
||||
mpack_write_bin(&writer, (char*)relay->schedules[0]->uid, sizeof(uuid_t));
|
||||
|
||||
mpack_write_uint(&writer, COMMAND_MAPPING_PERIODS_BLOB);
|
||||
// periods + 1 to skip length in periods[0]
|
||||
// periods_count * 2 because each uint16_t is a timestamp. 2 are start and end
|
||||
mpack_write_bin(&writer, (char*)(periods_blob + 1), sizeof(uint16_t) * periods_count * 2);
|
||||
|
||||
mpack_finish_map(&writer);
|
||||
|
||||
free(periods_blob);
|
||||
}
|
||||
mpack_finish_array(&writer);
|
||||
|
||||
mpack_finish_map(&writer);
|
||||
|
||||
// finish writing
|
||||
if (mpack_writer_destroy(&writer) != mpack_ok)
|
||||
{
|
||||
LOG_ERROR("an error occurred encoding the data");
|
||||
controller_free(controller);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int result = command_send(controller, COMMAND_CODE_SET_SCHEDULE, payload, payload_size);
|
||||
|
||||
controller_free(controller);
|
||||
free(payload);
|
||||
return result;
|
||||
}
|
||||
|
||||
int
|
||||
command_set_controller_name(controller_t *controller)
|
||||
{
|
||||
char* payload;
|
||||
size_t payload_size;
|
||||
mpack_writer_t writer;
|
||||
mpack_writer_init_growable(&writer, &payload, &payload_size);
|
||||
|
||||
// write the example on the msgpack homepage
|
||||
mpack_start_map(&writer, 2);
|
||||
|
||||
mpack_write_uint(&writer, COMMAND_MAPPING_CODE);
|
||||
mpack_write_u8(&writer, COMMAND_CODE_SET_NAME);
|
||||
|
||||
mpack_write_uint(&writer, COMMAND_MAPPING_NAME);
|
||||
mpack_write_cstr(&writer, controller->name);
|
||||
|
||||
mpack_finish_map(&writer);
|
||||
|
||||
// finish writing
|
||||
if (mpack_writer_destroy(&writer) != mpack_ok)
|
||||
{
|
||||
LOG_ERROR("an error occurred encoding the data");
|
||||
return 1;
|
||||
}
|
||||
|
||||
int result = command_send(controller, COMMAND_CODE_SET_NAME, payload, payload_size);
|
||||
|
||||
free(payload);
|
||||
return result;
|
||||
}
|
||||
|
||||
int
|
||||
command_send(controller_t *controller, int command_code, char *payload, uint32_t payload_size)
|
||||
{
|
||||
LOG_DEBUG("commanding %d\n", command_code);
|
||||
|
||||
int bytes_transferred;
|
||||
|
||||
int fd_controller = helper_connect_tcp_server(controller->ip, controller->port);
|
||||
|
||||
if(fd_controller == -1)
|
||||
{
|
||||
LOG_ERROR("can't open command socket %s:%d\n", controller->ip, controller->port);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if((bytes_transferred = send(fd_controller, &payload_size, sizeof(payload_size), 0)) <= 0)
|
||||
{
|
||||
LOG_ERROR("error during sending size\n");
|
||||
return 1;
|
||||
}
|
||||
if((bytes_transferred = send(fd_controller, payload, payload_size, 0)) <= 0)
|
||||
{
|
||||
LOG_ERROR("error during sending\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
close(fd_controller);
|
||||
return 0;
|
||||
}
|
||||
98
src/config.c
Normal file
98
src/config.c
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <logger.h>
|
||||
#include <config.h>
|
||||
|
||||
config_t global_config;
|
||||
|
||||
#define CONFINI_IS_KEY(SECTION, KEY) \
|
||||
(ini_array_match(SECTION, disp->append_to, '.', disp->format) && \
|
||||
ini_string_match_ii(KEY, disp->data, disp->format))
|
||||
|
||||
int
|
||||
config_load_log_level(IniDispatch *disp, config_t *config)
|
||||
{
|
||||
if(strcasecmp(disp->value, "trace") == 0)
|
||||
{
|
||||
config->log_level = LOG_LEVEL_TRACE;
|
||||
return 0;
|
||||
}
|
||||
if(strcasecmp(disp->value, "debug") == 0)
|
||||
{
|
||||
config->log_level = LOG_LEVEL_DEBUG;
|
||||
return 0;
|
||||
}
|
||||
if(strcasecmp(disp->value, "info") == 0)
|
||||
{
|
||||
config->log_level = LOG_LEVEL_INFO;
|
||||
return 0;
|
||||
}
|
||||
if(strcasecmp(disp->value, "warn") == 0)
|
||||
{
|
||||
config->log_level = LOG_LEVEL_WARN;
|
||||
return 0;
|
||||
}
|
||||
if(strcasecmp(disp->value, "error") == 0)
|
||||
{
|
||||
config->log_level = LOG_LEVEL_ERROR;
|
||||
return 0;
|
||||
}
|
||||
if(strcasecmp(disp->value, "fatal") == 0)
|
||||
{
|
||||
config->log_level = LOG_LEVEL_FATAL;
|
||||
return 0;
|
||||
}
|
||||
LOG_WARN("invalid log-level '%s'\n", disp->value);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
config_load(IniDispatch *disp, void *config_void)
|
||||
{
|
||||
config_t *config = (config_t*)config_void;
|
||||
|
||||
if(disp->type == INI_KEY)
|
||||
{
|
||||
if(CONFINI_IS_KEY("core", "server-port"))
|
||||
{
|
||||
strcpy(config->server_port, disp->value);
|
||||
return 0;
|
||||
}
|
||||
if(CONFINI_IS_KEY("core", "database"))
|
||||
{
|
||||
strcpy(config->database, disp->value);
|
||||
return 0;
|
||||
}
|
||||
if(CONFINI_IS_KEY("core", "not-found-file"))
|
||||
{
|
||||
strcpy(config->not_found_file, disp->value);
|
||||
return 0;
|
||||
}
|
||||
if(CONFINI_IS_KEY("core", "not-found-file-type"))
|
||||
{
|
||||
strcpy(config->not_found_file_type, disp->value);
|
||||
return 0;
|
||||
}
|
||||
if(CONFINI_IS_KEY("core", "not-found-content"))
|
||||
{
|
||||
strcpy(config->not_found_content, disp->value);
|
||||
return 0;
|
||||
}
|
||||
if(CONFINI_IS_KEY("core", "not-found-content-type"))
|
||||
{
|
||||
strcpy(config->not_found_content_type, disp->value);
|
||||
return 0;
|
||||
}
|
||||
if(CONFINI_IS_KEY("core", "log-level"))
|
||||
{
|
||||
return config_load_log_level(disp, config);
|
||||
}
|
||||
if(CONFINI_IS_KEY("core", "discovery-port"))
|
||||
{
|
||||
config->discovery_port = atoi(disp->value);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
5016
src/confini.c
Normal file
5016
src/confini.c
Normal file
File diff suppressed because it is too large
Load diff
67
src/database.c
Normal file
67
src/database.c
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include <logger.h>
|
||||
#include <database.h>
|
||||
|
||||
#include <migrations/0.sql.h>
|
||||
|
||||
sqlite3 *global_database;
|
||||
|
||||
int
|
||||
database_migrate()
|
||||
{
|
||||
uint16_t version_num = 0;
|
||||
int s, rc;
|
||||
sqlite3_stmt *stmt;
|
||||
sqlite3_prepare_v2(global_database, "SELECT version_num FROM meta LIMIT 1;", -1, &stmt, NULL);
|
||||
s = sqlite3_step(stmt);
|
||||
if (s == SQLITE_ROW)
|
||||
{
|
||||
version_num = sqlite3_column_int(stmt, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
version_num = 0;
|
||||
}
|
||||
|
||||
uint16_t new_version_num = version_num;
|
||||
char* err_msg;
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
switch(version_num)
|
||||
{
|
||||
case 0:
|
||||
LOG_INFO("migrating LEVEL 0\n");
|
||||
rc = sqlite3_exec(global_database, (const char *)sql_migration_0_sql, NULL, NULL, &err_msg);
|
||||
if(rc != 0)
|
||||
{
|
||||
LOG_FATAL("couldn't migrate LEVEL 0 (%s)\n", err_msg);
|
||||
break;
|
||||
}
|
||||
new_version_num = 1;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if(version_num == 0)
|
||||
{
|
||||
sqlite3_prepare_v2(global_database, "INSERT INTO meta (version_num) VALUES (?1);", -1, &stmt, NULL);
|
||||
}
|
||||
else
|
||||
{
|
||||
sqlite3_prepare_v2(global_database, "UPDATE meta SET version_num=?1;", -1, &stmt, NULL);
|
||||
}
|
||||
sqlite3_bind_int(stmt, 1, new_version_num);
|
||||
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc != SQLITE_DONE)
|
||||
{
|
||||
LOG_FATAL("couldn't write new schema version");
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc != SQLITE_DONE;
|
||||
}
|
||||
91
src/endpoint.c
Normal file
91
src/endpoint.c
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
#include <logger.h>
|
||||
#include <cJSON.h>
|
||||
#include <mongoose.h>
|
||||
#include <macros.h>
|
||||
#include <endpoint.h>
|
||||
|
||||
void
|
||||
endpoint_func_index(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)args;
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
(void)response;
|
||||
|
||||
response->status_code = 0;
|
||||
|
||||
mg_serve_http(nc, hm, global_config.http_server_opts);
|
||||
}
|
||||
|
||||
void
|
||||
endpoint_func_not_found(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)args;
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
if(access(global_config.not_found_file, R_OK) != -1)
|
||||
{
|
||||
struct mg_str mime_type = mg_mk_str(global_config.not_found_file_type);
|
||||
response->status_code = 0;
|
||||
mg_http_serve_file(nc, hm, global_config.not_found_file, mime_type, mg_mk_str(""));
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_DEBUG("404 file not found\n");
|
||||
response->status_code = 404;
|
||||
response->content_type = global_config.not_found_content_type;
|
||||
response->content_length = strlen(global_config.not_found_content);
|
||||
response->content = global_config.not_found_content;
|
||||
response->alloced_content = false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void
|
||||
endpoint_response_text(endpoint_response_t *response, int status_code, const char *content, int content_length)
|
||||
{
|
||||
if(content == NULL)
|
||||
{
|
||||
content = "";
|
||||
content_length = 0;
|
||||
}
|
||||
|
||||
response->status_code = status_code;
|
||||
response->content_type = "text/plain";
|
||||
if(content_length >= 0)
|
||||
{
|
||||
response->content_length = content_length;
|
||||
response->alloced_content = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
response->content_length = strlen(content);
|
||||
response->alloced_content = true;
|
||||
}
|
||||
response->content = content;
|
||||
}
|
||||
|
||||
void
|
||||
endpoint_response_json(endpoint_response_t *response, int status_code, const cJSON *json_root)
|
||||
{
|
||||
if(json_root != NULL)
|
||||
{
|
||||
char *json_str = cJSON_Print(json_root);
|
||||
if (json_str != NULL)
|
||||
{
|
||||
response->status_code = status_code;
|
||||
response->content_type = "application/json";
|
||||
response->content_length = strlen(json_str);
|
||||
response->content = json_str;
|
||||
response->alloced_content = true;
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
LOG_ERROR("failed to print schedule json\n");
|
||||
|
||||
static const char content[] = "failed to print json";
|
||||
endpoint_response_text(response, status_code, content, STRLEN(content));
|
||||
}
|
||||
30
src/endpoints/api_v1_controllers.c
Normal file
30
src/endpoints/api_v1_controllers.c
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_controllers.h>
|
||||
#include <logger.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/controller.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_controllers_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)args;
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
controller_t** all_controllers = controller_get_all();
|
||||
|
||||
cJSON *json = cJSON_CreateArray();
|
||||
|
||||
for(int i = 0; all_controllers[i] != NULL; ++i)
|
||||
{
|
||||
cJSON *json_controller = controller_to_json(all_controllers[i]);
|
||||
|
||||
cJSON_AddItemToArray(json, json_controller);
|
||||
}
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
controller_free_list(all_controllers);
|
||||
}
|
||||
194
src/endpoints/api_v1_controllers_STR.c
Normal file
194
src/endpoints/api_v1_controllers_STR.c
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
#include <arpa/inet.h>
|
||||
|
||||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <command.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_controllers.h>
|
||||
#include <logger.h>
|
||||
#include <models/controller.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_controllers_STR_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
uuid_t target_uid;
|
||||
if(uuid_parse(args[0].value.v_str, target_uid))
|
||||
{
|
||||
LOG_DEBUG("failed to unparse uid\n");
|
||||
|
||||
static const char content[] = "given id was invalid";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
controller_t* controller = controller_get_by_uid(target_uid);
|
||||
|
||||
if(!controller)
|
||||
{
|
||||
LOG_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str);
|
||||
|
||||
static const char content[] = "no controller for id found";
|
||||
endpoint_response_text(response, 404, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json = controller_to_json(controller);
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
controller_free(controller);
|
||||
}
|
||||
|
||||
void
|
||||
api_v1_controllers_STR_PUT(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
uuid_t target_uid;
|
||||
if(uuid_parse(args[0].value.v_str, target_uid))
|
||||
{
|
||||
LOG_DEBUG("failed to unparse uid\n");
|
||||
|
||||
static const char content[] = "given id was invalid";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
controller_t* controller = controller_get_by_uid(target_uid);
|
||||
|
||||
if(!controller)
|
||||
{
|
||||
LOG_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str);
|
||||
|
||||
static const char content[] = "no controller for id found";
|
||||
endpoint_response_text(response, 404, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json = cJSON_ParseWithLength(hm->body.p, hm->body.len);
|
||||
|
||||
if(json == NULL)
|
||||
{
|
||||
static const char content[] = "no valid json was supplied";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
controller_free(controller);
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json_name = cJSON_GetObjectItemCaseSensitive(json, "name");
|
||||
if(json_name)
|
||||
{
|
||||
if(cJSON_IsString(json_name) && json_name->valuestring)
|
||||
{
|
||||
strncpy(controller->name, json_name->valuestring, MAX_NAME_LENGTH);
|
||||
controller->name[MAX_NAME_LENGTH] = '\0';
|
||||
}
|
||||
else
|
||||
{
|
||||
static const char content[] = "the given name is no valid string";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
cJSON_Delete(json);
|
||||
controller_free(controller);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
cJSON *json_ip = cJSON_GetObjectItemCaseSensitive(json, "ip");
|
||||
if(json_ip)
|
||||
{
|
||||
if(cJSON_IsString(json_ip) && json_ip->valuestring)
|
||||
{
|
||||
unsigned char buf[sizeof(struct in_addr)];
|
||||
if(inet_pton(AF_INET, json_ip->valuestring, buf))
|
||||
{
|
||||
strncpy(controller->ip, json_ip->valuestring, IP_LENGTH);
|
||||
controller->ip[IP_LENGTH] = '\0';
|
||||
}
|
||||
else
|
||||
{
|
||||
static const char content[] = "the given ip address is no valid IPv4 address";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
cJSON_Delete(json);
|
||||
controller_free(controller);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
static const char content[] = "the given ip address is no valid string";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
cJSON_Delete(json);
|
||||
controller_free(controller);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if(controller_save(controller))
|
||||
{
|
||||
LOG_ERROR("failed to save controller\n");
|
||||
controller_free(controller);
|
||||
cJSON_Delete(json);
|
||||
|
||||
static const char content[] = "failed to save controller to database";
|
||||
endpoint_response_text(response, 500, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON_Delete(json);
|
||||
json = controller_to_json(controller);
|
||||
|
||||
command_set_controller_name(controller);
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
controller_free(controller);
|
||||
}
|
||||
|
||||
void
|
||||
api_v1_controllers_STR_DELETE(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
const char *target_uid_str = args[0].value.v_str;
|
||||
|
||||
uuid_t target_uid;
|
||||
if(uuid_parse(target_uid_str, target_uid))
|
||||
{
|
||||
LOG_DEBUG("failed to unparse uid\n");
|
||||
|
||||
static const char content[] = "given id was invalid";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
controller_t* controller = controller_get_by_uid(target_uid);
|
||||
|
||||
if(!controller)
|
||||
{
|
||||
LOG_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str);
|
||||
|
||||
static const char content[] = "no controller for id found";
|
||||
endpoint_response_text(response, 404, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
if(controller_remove(controller))
|
||||
{
|
||||
LOG_ERROR("failed to remove controller from database\n");
|
||||
|
||||
static const char content[] = "failed to remove controller from database";
|
||||
endpoint_response_text(response, 500, content, STRLEN(content));
|
||||
}
|
||||
else
|
||||
{
|
||||
endpoint_response_text(response, 200, "", 0);
|
||||
}
|
||||
controller_free(controller);
|
||||
return;
|
||||
}
|
||||
51
src/endpoints/api_v1_controllers_STR_relays.c
Normal file
51
src/endpoints/api_v1_controllers_STR_relays.c
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_controllers.h>
|
||||
#include <logger.h>
|
||||
#include <models/controller.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_controllers_STR_relays_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
uuid_t target_uid;
|
||||
if(uuid_parse(args[0].value.v_str, target_uid))
|
||||
{
|
||||
LOG_DEBUG("failed to unparse uid\n");
|
||||
|
||||
static const char content[] = "given id was invalid";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
controller_t* controller = controller_get_by_uid(target_uid);
|
||||
|
||||
if(!controller)
|
||||
{
|
||||
LOG_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str);
|
||||
|
||||
static const char content[] = "no controller for id found";
|
||||
endpoint_response_text(response, 404, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
relay_t** all_relays = relay_get_by_controller_id(controller->id);
|
||||
|
||||
cJSON *json = cJSON_CreateArray();
|
||||
|
||||
for(int i = 0; all_relays[i] != NULL; ++i)
|
||||
{
|
||||
cJSON *json_relay = relay_to_json(all_relays[i]);
|
||||
|
||||
cJSON_AddItemToArray(json, json_relay);
|
||||
}
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
relay_free_list(all_relays);
|
||||
controller_free(controller);
|
||||
}
|
||||
231
src/endpoints/api_v1_controllers_STR_relays_INT.c
Normal file
231
src/endpoints/api_v1_controllers_STR_relays_INT.c
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <command.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_controllers.h>
|
||||
#include <logger.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/controller.h>
|
||||
#include <models/relay.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_controllers_STR_relays_INT_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
uuid_t target_uid;
|
||||
if(uuid_parse(args[0].value.v_str, target_uid))
|
||||
{
|
||||
LOG_DEBUG("failed to unparse uid\n");
|
||||
|
||||
static const char content[] = "given id was invalid";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
controller_t* controller = controller_get_by_uid(target_uid);
|
||||
|
||||
if(!controller)
|
||||
{
|
||||
LOG_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str);
|
||||
|
||||
static const char content[] = "no controller for id found";
|
||||
endpoint_response_text(response, 404, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
relay_t* relay = relay_get_for_controller(controller->id, args[1].value.v_int);
|
||||
|
||||
if(!relay)
|
||||
{
|
||||
LOG_DEBUG("could not find a relay with num %d for controller '%s'\n", args[1].value.v_int, args[0].value.v_str);
|
||||
|
||||
static const char content[] = "no relay for this controller found";
|
||||
endpoint_response_text(response, 404, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json = relay_to_json(relay);
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
relay_free(relay);
|
||||
controller_free(controller);
|
||||
}
|
||||
|
||||
void
|
||||
api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
uuid_t target_uid;
|
||||
if(uuid_parse(args[0].value.v_str, target_uid))
|
||||
{
|
||||
LOG_DEBUG("failed to unparse uid\n");
|
||||
|
||||
static const char content[] = "given id was invalid";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
controller_t* controller = controller_get_by_uid(target_uid);
|
||||
|
||||
if(!controller)
|
||||
{
|
||||
LOG_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str);
|
||||
|
||||
static const char content[] = "no controller for id found";
|
||||
endpoint_response_text(response, 404, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
relay_t* relay = relay_get_for_controller(controller->id, args[1].value.v_int);
|
||||
|
||||
if(!relay)
|
||||
{
|
||||
relay = malloc(sizeof(relay_t));
|
||||
relay->id = 0;
|
||||
relay->number = args[1].value.v_int;
|
||||
snprintf(relay->name, MAX_NAME_LENGTH, "Relay %d", relay->number);
|
||||
relay->name[MAX_NAME_LENGTH] = '\0';
|
||||
relay->controller_id = controller->id;
|
||||
|
||||
uuid_t tmp_uuid;
|
||||
memset(tmp_uuid, 0, sizeof(uuid_t));
|
||||
memcpy(tmp_uuid, "off", 3);
|
||||
|
||||
for(int i = 0; i < 7; ++i)
|
||||
{
|
||||
relay->schedules[i] = schedule_get_by_uid(tmp_uuid);
|
||||
}
|
||||
time_t timestamp = time(NULL);
|
||||
struct tm *time_struct = localtime(×tamp);
|
||||
relay->active_schedule = relay->schedules[helper_get_weekday(time_struct)];
|
||||
}
|
||||
|
||||
cJSON *json = cJSON_ParseWithLength(hm->body.p, hm->body.len);
|
||||
|
||||
if(json == NULL)
|
||||
{
|
||||
static const char content[] = "no valid json was supplied";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json_name = cJSON_GetObjectItemCaseSensitive(json, "name");
|
||||
if(cJSON_IsString(json_name) && json_name->valuestring)
|
||||
{
|
||||
strncpy(relay->name, json_name->valuestring, MAX_NAME_LENGTH);
|
||||
relay->name[MAX_NAME_LENGTH] = '\0';
|
||||
}
|
||||
|
||||
|
||||
cJSON *json_schedule;
|
||||
cJSON *json_schedules = cJSON_GetObjectItemCaseSensitive(json, "schedules");
|
||||
|
||||
if(cJSON_GetArraySize(json_schedules) == 7)
|
||||
{
|
||||
int schedule_position = 0;
|
||||
cJSON_ArrayForEach(json_schedule, json_schedules)
|
||||
{
|
||||
cJSON *json_schedule_uid = cJSON_GetObjectItemCaseSensitive(json_schedule, "id");
|
||||
if(!cJSON_IsString(json_schedule_uid) || (json_schedule_uid->valuestring == NULL))
|
||||
{
|
||||
LOG_DEBUG("schedules[%d] is missing uid\n", schedule_position);
|
||||
cJSON_Delete(json);
|
||||
|
||||
static const char content[] = "at least one schedule is missing an id";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
uuid_t target_uid;
|
||||
if(schedule_uid_parse(json_schedule_uid->valuestring, target_uid))
|
||||
{
|
||||
LOG_DEBUG("schedules[%d] has bad uid\n", schedule_position);
|
||||
cJSON_Delete(json);
|
||||
|
||||
static const char content[] = "at least one schedule has a bad id";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
schedule_free(relay->schedules[schedule_position]);
|
||||
relay->schedules[schedule_position] = schedule_get_by_uid_or_off(target_uid);
|
||||
|
||||
++schedule_position;
|
||||
}
|
||||
}
|
||||
|
||||
cJSON *json_active_schedule = cJSON_GetObjectItemCaseSensitive(json, "active_schedule");
|
||||
if(cJSON_IsObject(json_active_schedule))
|
||||
{
|
||||
cJSON *json_active_schedule_uid = cJSON_GetObjectItemCaseSensitive(json_active_schedule, "id");
|
||||
if(cJSON_IsString(json_active_schedule_uid) && json_active_schedule_uid->valuestring)
|
||||
{
|
||||
time_t timestamp = time(NULL);
|
||||
struct tm *time_struct = localtime(×tamp);
|
||||
int day_of_week = helper_get_weekday(time_struct);
|
||||
|
||||
schedule_free(relay->schedules[day_of_week]);
|
||||
|
||||
uuid_t target_uid;
|
||||
if(schedule_uid_parse(json_active_schedule_uid->valuestring, target_uid))
|
||||
{
|
||||
LOG_DEBUG("active_schedule has bad uid\n");
|
||||
cJSON_Delete(json);
|
||||
|
||||
static const char content[] = "active_schedule has a bad id";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
relay->schedules[day_of_week] = schedule_get_by_uid_or_off(target_uid);
|
||||
}
|
||||
}
|
||||
|
||||
if(relay_save(relay))
|
||||
{
|
||||
LOG_ERROR("failed to save relay\n");
|
||||
free(controller);
|
||||
cJSON_Delete(json);
|
||||
|
||||
static const char content[] = "failed to save relay to database";
|
||||
endpoint_response_text(response, 500, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json_tag;
|
||||
cJSON *json_tags = cJSON_GetObjectItemCaseSensitive(json, "tags");
|
||||
if(cJSON_IsArray(json_tags))
|
||||
{
|
||||
junction_tag_remove_for_relay(relay->id);
|
||||
}
|
||||
cJSON_ArrayForEach(json_tag, json_tags)
|
||||
{
|
||||
if(!cJSON_IsString(json_tag) || (json_tag->valuestring == NULL))
|
||||
{
|
||||
LOG_DEBUG("invalid tag in tags\n");
|
||||
continue;
|
||||
}
|
||||
const char *tag = json_tag->valuestring;
|
||||
int tag_id = tag_get_id(tag);
|
||||
if(tag_id == 0)
|
||||
{
|
||||
tag_save(tag_id, tag);
|
||||
tag_id = tag_get_id(tag);
|
||||
}
|
||||
junction_tag_insert(tag_id, relay->id, 0);
|
||||
}
|
||||
|
||||
cJSON_Delete(json);
|
||||
json = relay_to_json(relay);
|
||||
|
||||
command_set_relay_schedule(relay);
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
relay_free(relay);
|
||||
controller_free(controller);
|
||||
}
|
||||
309
src/endpoints/api_v1_controllers_discover.c
Normal file
309
src/endpoints/api_v1_controllers_discover.c
Normal file
|
|
@ -0,0 +1,309 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_controllers.h>
|
||||
#include <models/controller.h>
|
||||
#include <logger.h>
|
||||
#include <mpack.h>
|
||||
|
||||
#define DISCOVERY_TIMEOUT_MS 2000
|
||||
|
||||
typedef enum
|
||||
{
|
||||
DISCOVERY_MAPPING_ID = 0,
|
||||
DISCOVERY_MAPPING_NAME = 1,
|
||||
DISCOVERY_MAPPING_COMMAND_PORT = 2,
|
||||
DISCOVERY_MAPPING_RELAY_COUNT = 3,
|
||||
} discovery_mapping_t;
|
||||
|
||||
static int
|
||||
bind_tcp_server(const char *addr, const char *port, int max_client_backlog)
|
||||
{
|
||||
struct addrinfo hints, *res;
|
||||
int fd;
|
||||
int status;
|
||||
|
||||
memset(&hints, 0, sizeof hints);
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
hints.ai_flags = AI_PASSIVE;
|
||||
|
||||
if ((status = getaddrinfo(addr, port, &hints, &res)) != 0)
|
||||
{
|
||||
LOG_ERROR("error getting address info: %s\n", gai_strerror(status));
|
||||
}
|
||||
|
||||
fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
|
||||
|
||||
if ((status = bind(fd, res->ai_addr, res->ai_addrlen)) == -1)
|
||||
{
|
||||
LOG_ERROR("error binding socket: %s\n", status);
|
||||
freeaddrinfo(res);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if ((status = listen(fd, max_client_backlog)) == -1)
|
||||
{
|
||||
LOG_ERROR("error setting up listener: %s\n", status);
|
||||
freeaddrinfo(res);
|
||||
return -1;
|
||||
}
|
||||
|
||||
freeaddrinfo(res);
|
||||
|
||||
return fd;
|
||||
}
|
||||
|
||||
static int
|
||||
get_server_port(int fd)
|
||||
{
|
||||
if(fd == -1)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
struct sockaddr_in sin;
|
||||
socklen_t addr_len = sizeof(sin);
|
||||
if(getsockname(fd, (struct sockaddr *)&sin, &addr_len) == 0)
|
||||
{
|
||||
return ntohs(sin.sin_port);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int
|
||||
send_udp_broadcast(const char *addr, uint16_t port, void *message, size_t length)
|
||||
{
|
||||
struct sockaddr_in their_addr;
|
||||
int fd;
|
||||
|
||||
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
|
||||
{
|
||||
LOG_ERROR("error creating socket\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
int broadcast = 1;
|
||||
if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast) < 0)
|
||||
{
|
||||
LOG_ERROR("error setting broadcast\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
memset(&their_addr, 0, sizeof(their_addr));
|
||||
their_addr.sin_family = AF_INET;
|
||||
their_addr.sin_port = htons(port);
|
||||
their_addr.sin_addr.s_addr = inet_addr(addr);
|
||||
|
||||
if(sendto(fd, message, length, 0, (struct sockaddr *)&their_addr, sizeof(their_addr)) < 0)
|
||||
{
|
||||
LOG_ERROR("error sending broadcast (%d): '%s'\n", errno, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
close(fd);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
api_v1_controllers_discover_POST(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)nc;
|
||||
(void)hm;
|
||||
int discover_server_socket = bind_tcp_server("0.0.0.0", "0", 20);
|
||||
int discover_server_port = get_server_port(discover_server_socket);
|
||||
|
||||
if(discover_server_port == -1)
|
||||
{
|
||||
LOG_ERROR("failed to get server port for discovery\n");
|
||||
static const char content[] = "";
|
||||
response->status_code = 500;
|
||||
response->content_type = "text/plain";
|
||||
response->content_length = STRLEN(content);;
|
||||
response->content = content;
|
||||
response->alloced_content = false;
|
||||
return;
|
||||
}
|
||||
|
||||
int16_t payload[1];
|
||||
payload[0] = discover_server_port;
|
||||
|
||||
if(send_udp_broadcast("255.255.255.255", global_config.discovery_port, payload, sizeof(payload)) < 0)
|
||||
{
|
||||
LOG_ERROR("failed to send UDP broadcast\n");
|
||||
static const char content[] = "";
|
||||
response->status_code = 500;
|
||||
response->content_type = "text/plain";
|
||||
response->content_length = STRLEN(content);;
|
||||
response->content = content;
|
||||
response->alloced_content = false;
|
||||
return;
|
||||
}
|
||||
|
||||
struct sockaddr_storage their_addr;
|
||||
socklen_t addr_size;
|
||||
int client_fd, s_ret;
|
||||
fd_set accept_fds;
|
||||
struct timeval timeout;
|
||||
|
||||
uint8_t discover_answer_buf[1];
|
||||
|
||||
controller_t **known_controllers = controller_get_all();
|
||||
|
||||
while(true)
|
||||
{
|
||||
addr_size = sizeof(their_addr);
|
||||
|
||||
FD_ZERO(&accept_fds);
|
||||
FD_SET(discover_server_socket, &accept_fds); // NOLINT(hicpp-signed-bitwise)
|
||||
|
||||
timeout.tv_sec = DISCOVERY_TIMEOUT_MS / 1000;
|
||||
timeout.tv_usec = (DISCOVERY_TIMEOUT_MS % 1000) * 1000;
|
||||
|
||||
s_ret = select(discover_server_socket + 1, &accept_fds, NULL, NULL, &timeout);
|
||||
if(s_ret == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
if((client_fd = accept(discover_server_socket, (struct sockaddr *) &their_addr, &addr_size)) < 0)
|
||||
{
|
||||
LOG_ERROR("error accepting client %s\n", strerror(errno));
|
||||
continue;
|
||||
}
|
||||
|
||||
size_t payload_length;
|
||||
|
||||
if(recv(client_fd, &payload_length, sizeof(payload_length), 0) <= 0)
|
||||
{
|
||||
LOG_ERROR("error receiving header from client\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
char *answer_payload = (char*)malloc((payload_length));
|
||||
ssize_t bytes_transferred;
|
||||
|
||||
if((bytes_transferred = recv(client_fd, answer_payload, payload_length, 0)) <= 0)
|
||||
{
|
||||
LOG_ERROR("error receiving payload from client\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
struct sockaddr_in addr;
|
||||
socklen_t client_addr_size = sizeof(struct sockaddr_in);
|
||||
if(getpeername(client_fd, (struct sockaddr *)&addr, &client_addr_size) != 0)
|
||||
{
|
||||
|
||||
LOG_ERROR("error receiving payload from client\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
uuid_t discovered_id;
|
||||
|
||||
mpack_tree_t tree;
|
||||
mpack_tree_init_data(&tree, answer_payload, payload_length);
|
||||
mpack_tree_parse(&tree);
|
||||
mpack_node_t root = mpack_tree_root(&tree);
|
||||
|
||||
memcpy(discovered_id, mpack_node_data(mpack_node_map_uint(root, DISCOVERY_MAPPING_ID)), sizeof(uuid_t));
|
||||
|
||||
uint16_t discovered_command_port = mpack_node_u16(mpack_node_map_uint(root, DISCOVERY_MAPPING_COMMAND_PORT));
|
||||
uint8_t discovered_relay_count = mpack_node_u8(mpack_node_map_uint(root, DISCOVERY_MAPPING_RELAY_COUNT));
|
||||
const char *discovered_name = mpack_node_str(mpack_node_map_uint(root, DISCOVERY_MAPPING_NAME));
|
||||
size_t discovered_name_len = mpack_node_strlen(mpack_node_map_uint(root, DISCOVERY_MAPPING_NAME));
|
||||
|
||||
if(discovered_name_len > MAX_NAME_LENGTH)
|
||||
{
|
||||
discovered_name_len = MAX_NAME_LENGTH;
|
||||
}
|
||||
|
||||
bool found_discovered_in_list = 0;
|
||||
|
||||
for(int i = 0; known_controllers[i] != NULL; i++)
|
||||
{
|
||||
if(!found_discovered_in_list)
|
||||
{
|
||||
if(uuid_compare(known_controllers[i]->uid, discovered_id) == 0)
|
||||
{
|
||||
known_controllers[i]->active = 1;
|
||||
strncpy(known_controllers[i]->name, discovered_name, discovered_name_len);
|
||||
known_controllers[i]->name[discovered_name_len] = '\0';
|
||||
known_controllers[i]->port = discovered_command_port;
|
||||
known_controllers[i]->relay_count = discovered_relay_count;
|
||||
|
||||
controller_save(known_controllers[i]);
|
||||
controller_free(known_controllers[i]);
|
||||
|
||||
found_discovered_in_list = 1;
|
||||
known_controllers[i] = known_controllers[i + 1];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
known_controllers[i] = known_controllers[i + 1];
|
||||
}
|
||||
}
|
||||
|
||||
if(!found_discovered_in_list)
|
||||
{
|
||||
controller_t *discovered_controller = malloc(sizeof(controller_t));
|
||||
discovered_controller->id = 0;
|
||||
strcpy(discovered_controller->ip, inet_ntoa(addr.sin_addr));
|
||||
memcpy(discovered_controller->uid, discovered_id, sizeof(uuid_t));
|
||||
strncpy(discovered_controller->name, discovered_name, discovered_name_len);
|
||||
discovered_controller->name[discovered_name_len] = '\0';
|
||||
discovered_controller->relay_count = discovered_relay_count;
|
||||
discovered_controller->port = discovered_command_port;
|
||||
discovered_controller->active = 1;
|
||||
|
||||
controller_save(discovered_controller);
|
||||
|
||||
// TODO get relays during discovery and don't create empty ones
|
||||
relay_t **discovered_relays = malloc(sizeof(relay_t*) * (discovered_controller->relay_count + 1));
|
||||
for(int i = 0; i < discovered_controller->relay_count; ++i)
|
||||
{
|
||||
relay_t *new_relay = malloc(sizeof(relay_t));
|
||||
new_relay->id = 0;
|
||||
sprintf(new_relay->name, "Relay %d", i + 1);
|
||||
new_relay->number = i;
|
||||
new_relay->controller_id = discovered_controller->id;
|
||||
|
||||
uuid_t tmp_uuid;
|
||||
memset(tmp_uuid, 0, sizeof(uuid_t));
|
||||
memcpy(tmp_uuid, "off", 3);
|
||||
|
||||
for(int i = 0; i < 7; ++i)
|
||||
{
|
||||
new_relay->schedules[i] = schedule_get_by_uid(tmp_uuid);
|
||||
}
|
||||
time_t timestamp = time(NULL);
|
||||
struct tm *time_struct = localtime(×tamp);
|
||||
new_relay->active_schedule = new_relay->schedules[helper_get_weekday(time_struct)];
|
||||
|
||||
relay_save(new_relay);
|
||||
|
||||
discovered_relays[i] = new_relay;
|
||||
}
|
||||
discovered_relays[discovered_controller->relay_count] = NULL;
|
||||
discovered_controller->relays = discovered_relays;
|
||||
|
||||
controller_free(discovered_controller);
|
||||
}
|
||||
mpack_tree_destroy(&tree);
|
||||
free(answer_payload);
|
||||
|
||||
discover_answer_buf[0] = 0; // TODO add discovery return codes
|
||||
send(client_fd, discover_answer_buf, sizeof(uint8_t), 0);
|
||||
close(client_fd);
|
||||
}
|
||||
}
|
||||
for(int i = 0; known_controllers[i] != NULL; i++)
|
||||
{
|
||||
known_controllers[i]->active = false;
|
||||
controller_save(known_controllers[i]);
|
||||
LOG_DEBUG("lost: %s\n", known_controllers[i]->name);
|
||||
}
|
||||
controller_free_list(known_controllers);
|
||||
|
||||
api_v1_controllers_GET(nc, hm, args, response);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue