REFACTOR
This commit is contained in:
parent
0460b2e9f7
commit
176483d72f
59 changed files with 11 additions and 45 deletions
src
argparse.ccJSON.ccommand.cconfig.cconfini.cdatabase.cendpoint.c
endpoints
api_v1_controllers.capi_v1_controllers_STR.capi_v1_controllers_STR_relays.capi_v1_controllers_STR_relays_INT.capi_v1_controllers_discover.capi_v1_relays.capi_v1_relays_tag_STR.capi_v1_schedules.capi_v1_schedules_STR.capi_v1_schedules_list.capi_v1_schedules_tag_STR.capi_v1_tags.c
handlers
helpers
logger.cmain.cmodels
mongoose.cmpack.crouter.c
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);
|
||||
}
|
31
src/endpoints/api_v1_relays.c
Normal file
31
src/endpoints/api_v1_relays.c
Normal file
|
@ -0,0 +1,31 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_relays.h>
|
||||
#include <logger.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/relay.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_relays_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)args;
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
relay_t** all_relays = relay_get_all();
|
||||
|
||||
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);
|
||||
}
|
47
src/endpoints/api_v1_relays_tag_STR.c
Normal file
47
src/endpoints/api_v1_relays_tag_STR.c
Normal file
|
@ -0,0 +1,47 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_relays.h>
|
||||
#include <logger.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/relay.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_relays_tag_STR_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
int tag_id = tag_get_id(args[0].value.v_str);
|
||||
int *relays_ids = junction_tag_get_relays_for_tag_id(tag_id);
|
||||
if(relays_ids == NULL)
|
||||
{
|
||||
LOG_ERROR("failed to load relays for tag from database\n");
|
||||
|
||||
static const char content[] = "failed to load relays for tag from database";
|
||||
endpoint_response_text(response, 500, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json = cJSON_CreateArray();
|
||||
|
||||
for(int i = 0; relays_ids[i] != 0; ++i)
|
||||
{
|
||||
relay_t* relay = relay_get_by_id(relays_ids[i]);
|
||||
|
||||
if(!relay)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
cJSON *json_relay = relay_to_json(relay);
|
||||
|
||||
cJSON_AddItemToArray(json, json_relay);
|
||||
|
||||
relay_free(relay);
|
||||
}
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
free(relays_ids);
|
||||
}
|
176
src/endpoints/api_v1_schedules.c
Normal file
176
src/endpoints/api_v1_schedules.c
Normal file
|
@ -0,0 +1,176 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_schedules.h>
|
||||
#include <logger.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/schedule.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_schedules_POST(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)args;
|
||||
(void)nc;
|
||||
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 == NULL))
|
||||
{
|
||||
LOG_DEBUG("no name for schedule provided\n");
|
||||
cJSON_Delete(json);
|
||||
|
||||
static const char content[] = "no name for schedule provided";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
cJSON *json_periods = cJSON_GetObjectItemCaseSensitive(json, "periods");
|
||||
if(!cJSON_IsArray(json_periods))
|
||||
{
|
||||
LOG_DEBUG("no periods for schedule provided\n");
|
||||
cJSON_Delete(json);
|
||||
|
||||
static const char content[] = "no periods for schedule provided";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json_tag;
|
||||
cJSON *json_tags = cJSON_GetObjectItemCaseSensitive(json, "tags");
|
||||
cJSON_ArrayForEach(json_tag, json_tags)
|
||||
{
|
||||
if(!cJSON_IsString(json_tag) || (json_tag->valuestring == NULL))
|
||||
{
|
||||
LOG_DEBUG("invalid tag in tags\n");
|
||||
cJSON_Delete(json);
|
||||
|
||||
static const char content[] = "invalid tag in tags";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
schedule_t *new_schedule = malloc(sizeof(schedule_t));
|
||||
|
||||
new_schedule->id = 0;
|
||||
uuid_generate(new_schedule->uid);
|
||||
|
||||
strncpy(new_schedule->name, json_name->valuestring, MAX_NAME_LENGTH);
|
||||
new_schedule->name[MAX_NAME_LENGTH] = '\0';
|
||||
|
||||
int periods_count = cJSON_GetArraySize(json_periods);
|
||||
new_schedule->periods = malloc(sizeof(period_t) * periods_count);
|
||||
|
||||
int periods_valid = 0;
|
||||
|
||||
cJSON *json_period;
|
||||
cJSON_ArrayForEach(json_period, json_periods)
|
||||
{
|
||||
cJSON *json_period_start = cJSON_GetObjectItemCaseSensitive(json_period, "start");
|
||||
cJSON *json_period_end = cJSON_GetObjectItemCaseSensitive(json_period, "end");
|
||||
|
||||
if(!cJSON_IsString(json_period_start) || (json_period_start->valuestring == NULL))
|
||||
{
|
||||
LOG_DEBUG("period is missing start\n");
|
||||
cJSON_Delete(json);
|
||||
schedule_free(new_schedule);
|
||||
|
||||
static const char content[] = "one period is missing a start";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
if(!cJSON_IsString(json_period_end) || (json_period_end->valuestring == NULL))
|
||||
{
|
||||
LOG_DEBUG("period is missing end\n");
|
||||
cJSON_Delete(json);
|
||||
schedule_free(new_schedule);
|
||||
|
||||
static const char content[] = "one period is missing an end";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
uint16_t start;
|
||||
uint16_t end;
|
||||
if(period_helper_parse_hhmm(json_period_start->valuestring, &start))
|
||||
{
|
||||
LOG_DEBUG("couldn't parse start '%s'\n", json_period_start->valuestring);
|
||||
cJSON_Delete(json);
|
||||
schedule_free(new_schedule);
|
||||
|
||||
static const char content[] = "the start for one period is invalid";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
if(period_helper_parse_hhmm(json_period_end->valuestring, &end))
|
||||
{
|
||||
LOG_DEBUG("couldn't parse end '%s'\n", json_period_end->valuestring);
|
||||
cJSON_Delete(json);
|
||||
schedule_free(new_schedule);
|
||||
|
||||
static const char content[] = "the end for one period is invalid";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
new_schedule->periods[periods_valid].start = start;
|
||||
new_schedule->periods[periods_valid].end = end;
|
||||
++periods_valid;
|
||||
}
|
||||
|
||||
new_schedule->periods_count = periods_valid;
|
||||
|
||||
schedule_save(new_schedule);
|
||||
|
||||
junction_tag_remove_for_schedule(new_schedule->id);
|
||||
|
||||
json_tags = cJSON_GetObjectItemCaseSensitive(json, "tags");
|
||||
cJSON_ArrayForEach(json_tag, json_tags)
|
||||
{
|
||||
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, 0, new_schedule->id);
|
||||
}
|
||||
|
||||
cJSON_Delete(json);
|
||||
json = schedule_to_json(new_schedule);
|
||||
|
||||
endpoint_response_json(response, 201, json);
|
||||
cJSON_Delete(json);
|
||||
schedule_free(new_schedule);
|
||||
}
|
||||
|
||||
void
|
||||
api_v1_schedules_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)args;
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
schedule_t** all_schedules = schedule_get_all();
|
||||
|
||||
cJSON *json = cJSON_CreateArray();
|
||||
|
||||
for(int i = 0; all_schedules[i] != NULL; ++i)
|
||||
{
|
||||
cJSON *json_schedule = schedule_to_json(all_schedules[i]);
|
||||
|
||||
cJSON_AddItemToArray(json, json_schedule);
|
||||
}
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
schedule_free_list(all_schedules);
|
||||
}
|
238
src/endpoints/api_v1_schedules_STR.c
Normal file
238
src/endpoints/api_v1_schedules_STR.c
Normal file
|
@ -0,0 +1,238 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_schedules.h>
|
||||
#include <logger.h>
|
||||
#include <command.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/junction_relay_schedule.h>
|
||||
#include <models/schedule.h>
|
||||
#include <models/relay.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_schedules_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(schedule_uid_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;
|
||||
}
|
||||
|
||||
schedule_t* schedule = schedule_get_by_uid(target_uid);
|
||||
|
||||
if(!schedule)
|
||||
{
|
||||
LOG_DEBUG("could not find a schedule for uid '%s'\n", args[0].value.v_str);
|
||||
|
||||
static const char content[] = "no schedule for id found";
|
||||
endpoint_response_text(response, 404, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json = schedule_to_json(schedule);
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
schedule_free(schedule);
|
||||
}
|
||||
|
||||
void
|
||||
api_v1_schedules_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(schedule_uid_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;
|
||||
}
|
||||
|
||||
schedule_t* schedule = schedule_get_by_uid(target_uid);
|
||||
|
||||
if(!schedule)
|
||||
{
|
||||
LOG_DEBUG("could not find a schedule for uid '%s'\n", args[0].value.v_str);
|
||||
|
||||
static const char content[] = "no schedule 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));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json_name = cJSON_GetObjectItemCaseSensitive(json, "name");
|
||||
if(cJSON_IsString(json_name) && json_name->valuestring)
|
||||
{
|
||||
strncpy(schedule->name, json_name->valuestring, MAX_NAME_LENGTH);
|
||||
schedule->name[MAX_NAME_LENGTH] = '\0';
|
||||
}
|
||||
|
||||
if(!schedule_is_protected(schedule))
|
||||
{
|
||||
cJSON *json_period;
|
||||
cJSON *json_periods = cJSON_GetObjectItemCaseSensitive(json, "periods");
|
||||
|
||||
int periods_count = cJSON_GetArraySize(json_periods);
|
||||
free(schedule->periods);
|
||||
schedule->periods = malloc(sizeof(period_t) * periods_count);
|
||||
|
||||
int periods_valid = 0;
|
||||
|
||||
cJSON_ArrayForEach(json_period, json_periods)
|
||||
{
|
||||
cJSON *json_period_start = cJSON_GetObjectItemCaseSensitive(json_period, "start");
|
||||
cJSON *json_period_end = cJSON_GetObjectItemCaseSensitive(json_period, "end");
|
||||
|
||||
if(!cJSON_IsString(json_period_start) || (json_period_start->valuestring == NULL))
|
||||
{
|
||||
LOG_DEBUG("period is missing start\n");
|
||||
continue;
|
||||
}
|
||||
if(!cJSON_IsString(json_period_end) || (json_period_end->valuestring == NULL))
|
||||
{
|
||||
LOG_DEBUG("period is missing end\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
uint16_t start;
|
||||
uint16_t end;
|
||||
if(period_helper_parse_hhmm(json_period_start->valuestring, &start))
|
||||
{
|
||||
LOG_DEBUG("couldn't parse start '%s'\n", json_period_start->valuestring);
|
||||
continue;
|
||||
}
|
||||
if(period_helper_parse_hhmm(json_period_end->valuestring, &end))
|
||||
{
|
||||
LOG_DEBUG("couldn't parse end '%s'\n", json_period_end->valuestring);
|
||||
continue;
|
||||
}
|
||||
|
||||
schedule->periods[periods_valid].start = start;
|
||||
schedule->periods[periods_valid].end = end;
|
||||
++periods_valid;
|
||||
}
|
||||
|
||||
schedule->periods_count = periods_valid;
|
||||
}
|
||||
|
||||
if(schedule_save(schedule))
|
||||
{
|
||||
LOG_ERROR("failed to save schedule\n");
|
||||
free(schedule);
|
||||
cJSON_Delete(json);
|
||||
|
||||
static const char content[] = "failed to save schedule to database";
|
||||
endpoint_response_text(response, 500, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
relay_t **relays = relay_get_with_schedule(schedule->id);
|
||||
for(int i = 0; relays[i] != NULL; ++i)
|
||||
{
|
||||
command_set_relay_schedule(relays[i]);
|
||||
}
|
||||
|
||||
cJSON *json_tag;
|
||||
cJSON *json_tags = cJSON_GetObjectItemCaseSensitive(json, "tags");
|
||||
if(cJSON_IsArray(json_tags))
|
||||
{
|
||||
junction_tag_remove_for_schedule(schedule->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, 0, schedule->id);
|
||||
}
|
||||
|
||||
cJSON_Delete(json);
|
||||
json = schedule_to_json(schedule);
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
relay_free_list(relays);
|
||||
schedule_free(schedule);
|
||||
}
|
||||
|
||||
void
|
||||
api_v1_schedules_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(schedule_uid_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;
|
||||
}
|
||||
|
||||
schedule_t* schedule = schedule_get_by_uid(target_uid);
|
||||
|
||||
if(!schedule)
|
||||
{
|
||||
LOG_DEBUG("could not find a schedule for uid '%s'\n", args[0].value.v_str);
|
||||
|
||||
static const char content[] = "no schedule for id found";
|
||||
endpoint_response_text(response, 404, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
if(schedule_is_protected(schedule))
|
||||
{
|
||||
static const char content[] = "target schedule is protected";
|
||||
endpoint_response_text(response, 403, content, STRLEN(content));
|
||||
|
||||
schedule_free(schedule);
|
||||
return;
|
||||
}
|
||||
|
||||
if(schedule_remove(schedule))
|
||||
{
|
||||
LOG_ERROR("failed to remove schedule from database\n");
|
||||
|
||||
static const char content[] = "failed to remove schedule from database";
|
||||
endpoint_response_text(response, 500, content, STRLEN(content));
|
||||
}
|
||||
else
|
||||
{
|
||||
endpoint_response_text(response, 200, "", 0);
|
||||
}
|
||||
schedule_free(schedule);
|
||||
return;
|
||||
}
|
155
src/endpoints/api_v1_schedules_list.c
Normal file
155
src/endpoints/api_v1_schedules_list.c
Normal file
|
@ -0,0 +1,155 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_schedules.h>
|
||||
#include <logger.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/schedule.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_schedules_list_POST(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)args;
|
||||
(void)nc;
|
||||
cJSON *json_list = cJSON_ParseWithLength(hm->body.p, hm->body.len);
|
||||
|
||||
|
||||
cJSON *json;
|
||||
cJSON_ArrayForEach(json, json_list)
|
||||
{
|
||||
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 == NULL))
|
||||
{
|
||||
LOG_DEBUG("no name for schedule provided\n");
|
||||
cJSON_Delete(json_list);
|
||||
|
||||
static const char content[] = "no name for schedule provided";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
cJSON *json_periods = cJSON_GetObjectItemCaseSensitive(json, "periods");
|
||||
if(!cJSON_IsArray(json_periods))
|
||||
{
|
||||
LOG_DEBUG("no periods for schedule provided\n");
|
||||
cJSON_Delete(json_list);
|
||||
|
||||
static const char content[] = "no periods for schedule provided";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json_tag;
|
||||
cJSON *json_tags = cJSON_GetObjectItemCaseSensitive(json, "tags");
|
||||
cJSON_ArrayForEach(json_tag, json_tags)
|
||||
{
|
||||
if(!cJSON_IsString(json_tag) || (json_tag->valuestring == NULL))
|
||||
{
|
||||
LOG_DEBUG("invalid tag in tags\n");
|
||||
cJSON_Delete(json_list);
|
||||
|
||||
static const char content[] = "invalid tag in tags";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
schedule_t *new_schedule = malloc(sizeof(schedule_t));
|
||||
|
||||
new_schedule->id = 0;
|
||||
uuid_generate(new_schedule->uid);
|
||||
|
||||
strncpy(new_schedule->name, json_name->valuestring, MAX_NAME_LENGTH);
|
||||
new_schedule->name[MAX_NAME_LENGTH] = '\0';
|
||||
|
||||
int periods_count = cJSON_GetArraySize(json_periods);
|
||||
new_schedule->periods = malloc(sizeof(period_t) * periods_count);
|
||||
|
||||
int periods_valid = 0;
|
||||
|
||||
cJSON *json_period;
|
||||
cJSON_ArrayForEach(json_period, json_periods)
|
||||
{
|
||||
cJSON *json_period_start = cJSON_GetObjectItemCaseSensitive(json_period, "start");
|
||||
cJSON *json_period_end = cJSON_GetObjectItemCaseSensitive(json_period, "end");
|
||||
|
||||
if(!cJSON_IsString(json_period_start) || (json_period_start->valuestring == NULL))
|
||||
{
|
||||
LOG_DEBUG("period is missing start\n");
|
||||
cJSON_Delete(json_list);
|
||||
schedule_free(new_schedule);
|
||||
|
||||
static const char content[] = "one period is missing a start";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
if(!cJSON_IsString(json_period_end) || (json_period_end->valuestring == NULL))
|
||||
{
|
||||
LOG_DEBUG("period is missing end\n");
|
||||
cJSON_Delete(json_list);
|
||||
schedule_free(new_schedule);
|
||||
|
||||
static const char content[] = "one period is missing an end";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
uint16_t start;
|
||||
uint16_t end;
|
||||
if(period_helper_parse_hhmm(json_period_start->valuestring, &start))
|
||||
{
|
||||
LOG_DEBUG("couldn't parse start '%s'\n", json_period_start->valuestring);
|
||||
cJSON_Delete(json_list);
|
||||
schedule_free(new_schedule);
|
||||
|
||||
static const char content[] = "the start for one period is invalid";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
if(period_helper_parse_hhmm(json_period_end->valuestring, &end))
|
||||
{
|
||||
LOG_DEBUG("couldn't parse end '%s'\n", json_period_end->valuestring);
|
||||
cJSON_Delete(json_list);
|
||||
schedule_free(new_schedule);
|
||||
|
||||
static const char content[] = "the end for one period is invalid";
|
||||
endpoint_response_text(response, 400, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
new_schedule->periods[periods_valid].start = start;
|
||||
new_schedule->periods[periods_valid].end = end;
|
||||
++periods_valid;
|
||||
}
|
||||
|
||||
new_schedule->periods_count = periods_valid;
|
||||
|
||||
schedule_save(new_schedule);
|
||||
|
||||
junction_tag_remove_for_schedule(new_schedule->id);
|
||||
|
||||
json_tags = cJSON_GetObjectItemCaseSensitive(json, "tags");
|
||||
cJSON_ArrayForEach(json_tag, json_tags)
|
||||
{
|
||||
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, 0, new_schedule->id);
|
||||
}
|
||||
schedule_free(new_schedule);
|
||||
}
|
||||
|
||||
cJSON_Delete(json_list);
|
||||
api_v1_schedules_GET(nc, hm, args, response);;
|
||||
}
|
47
src/endpoints/api_v1_schedules_tag_STR.c
Normal file
47
src/endpoints/api_v1_schedules_tag_STR.c
Normal file
|
@ -0,0 +1,47 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_schedules.h>
|
||||
#include <logger.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/schedule.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_schedules_tag_STR_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
int tag_id = tag_get_id(args[0].value.v_str);
|
||||
int *schedules_ids = junction_tag_get_schedules_for_tag_id(tag_id);
|
||||
if(schedules_ids == NULL)
|
||||
{
|
||||
LOG_ERROR("failed to load schedules for tag from database\n");
|
||||
|
||||
static const char content[] = "failed to load schedules for tag from database";
|
||||
endpoint_response_text(response, 500, content, STRLEN(content));
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON *json = cJSON_CreateArray();
|
||||
|
||||
for(int i = 0; schedules_ids[i] != 0; ++i)
|
||||
{
|
||||
schedule_t* schedule = schedule_get_by_id(schedules_ids[i]);
|
||||
|
||||
if(!schedule)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
cJSON *json_schedule = schedule_to_json(schedule);
|
||||
|
||||
cJSON_AddItemToArray(json, json_schedule);
|
||||
|
||||
schedule_free(schedule);
|
||||
}
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
free(schedules_ids);
|
||||
}
|
35
src/endpoints/api_v1_tags.c
Normal file
35
src/endpoints/api_v1_tags.c
Normal file
|
@ -0,0 +1,35 @@
|
|||
#include <cJSON.h>
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <endpoints/api_v1_tags.h>
|
||||
#include <logger.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
void
|
||||
api_v1_tags_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
|
||||
{
|
||||
(void)args;
|
||||
(void)hm;
|
||||
(void)nc;
|
||||
|
||||
char** all_tags = tag_get_all();
|
||||
|
||||
cJSON *json = cJSON_CreateArray();
|
||||
|
||||
for(int i = 0; all_tags[i] != NULL; ++i)
|
||||
{
|
||||
cJSON *json_tag = cJSON_CreateString(all_tags[i]);
|
||||
if (json_tag == NULL)
|
||||
{
|
||||
LOG_DEBUG("failed to add tag from string '%s'\n", all_tags[i]);
|
||||
free(all_tags[i]);
|
||||
continue;
|
||||
}
|
||||
cJSON_AddItemToArray(json, json_tag);
|
||||
free(all_tags[i]);
|
||||
}
|
||||
|
||||
endpoint_response_json(response, 200, json);
|
||||
cJSON_Delete(json);
|
||||
free(all_tags);
|
||||
}
|
134
src/handlers/connection.c
Normal file
134
src/handlers/connection.c
Normal file
|
@ -0,0 +1,134 @@
|
|||
#include <string.h>
|
||||
|
||||
#include <macros.h>
|
||||
#include <constants.h>
|
||||
#include <mongoose.h>
|
||||
#include <logger.h>
|
||||
#include <router.h>
|
||||
#include <handlers.h>
|
||||
|
||||
#define HEADERS_FMT "Content-Type: %s"
|
||||
|
||||
// -2 for "%s" -1 for \0
|
||||
#define HEADERS_FMT_LEN (sizeof(HEADERS_FMT) - 3)
|
||||
|
||||
static char*
|
||||
add_extra_headers(char *extra_headers)
|
||||
{
|
||||
char *result;
|
||||
size_t std_headers_len = strlen(global_config.http_server_opts.extra_headers);
|
||||
if(extra_headers == NULL)
|
||||
{
|
||||
result = malloc(sizeof(char) * (std_headers_len + 1));
|
||||
strcpy(result, global_config.http_server_opts.extra_headers);
|
||||
return result;
|
||||
}
|
||||
|
||||
result = malloc(sizeof(char) * (std_headers_len + strlen(extra_headers) + 3));
|
||||
sprintf(result, "%s\r\n%s", global_config.http_server_opts.extra_headers, extra_headers);
|
||||
return result;
|
||||
}
|
||||
|
||||
static void
|
||||
send_response(struct mg_connection *nc, endpoint_response_t *response)
|
||||
{
|
||||
if(response->status_code)
|
||||
{
|
||||
char *response_headers = malloc(sizeof(char) * (HEADERS_FMT_LEN + strlen(response->content_type) + 1));
|
||||
sprintf(response_headers, HEADERS_FMT, response->content_type);
|
||||
|
||||
char *extra_headers = add_extra_headers(response_headers);
|
||||
mg_send_head(nc, response->status_code, response->content_length, extra_headers);
|
||||
mg_printf(nc, "%s", response->content);
|
||||
|
||||
free(response_headers);
|
||||
free(extra_headers);
|
||||
|
||||
if(response->alloced_content)
|
||||
{
|
||||
free((char*)response->content);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
handler_connection(struct mg_connection *nc, int ev, void *p)
|
||||
{
|
||||
if (ev == MG_EV_HTTP_REQUEST)
|
||||
{
|
||||
struct http_message *hm = (struct http_message *) p;
|
||||
LOG_TRACE("new http %.*s request for %.*s\n", hm->method.len, hm->method.p, hm->uri.len, hm->uri.p);
|
||||
|
||||
endpoint_t *endpoint = router_find_endpoint(hm->uri.p, hm->uri.len, &hm->method);
|
||||
|
||||
endpoint_response_t response;
|
||||
static const char content[] = "the server did not create a response";
|
||||
endpoint_response_text(&response, 500, content, STRLEN(content));
|
||||
|
||||
if(!endpoint)
|
||||
{
|
||||
/* Normalize path - resolve "." and ".." (in-place). */
|
||||
if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
|
||||
mg_http_send_error(nc, 400, global_config.http_server_opts.extra_headers);
|
||||
return;
|
||||
}
|
||||
char *request_file_org = malloc(sizeof(char) * hm->uri.len);
|
||||
strncpy(request_file_org, hm->uri.p + 1, hm->uri.len);
|
||||
request_file_org[hm->uri.len - 1] = '\0';
|
||||
|
||||
char *request_file = request_file_org;
|
||||
while(request_file[0] == '/')
|
||||
{
|
||||
++request_file;
|
||||
}
|
||||
|
||||
LOG_DEBUG("%s\n", request_file);
|
||||
int access_result = access(request_file, R_OK);
|
||||
free(request_file_org);
|
||||
if(access_result != -1)
|
||||
{
|
||||
response.status_code = 0;
|
||||
mg_serve_http(nc, hm, global_config.http_server_opts);
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
endpoint = router_get_not_found_endpoint();
|
||||
}
|
||||
}
|
||||
|
||||
if(!endpoint->func)
|
||||
{
|
||||
if(endpoint->method == HTTP_METHOD_OPTIONS)
|
||||
{
|
||||
char options_header[256]; // TODO make more generic
|
||||
sprintf(options_header, "Allow: OPTIONS%s%s%s%s",
|
||||
endpoint->options & HTTP_METHOD_GET ? ", GET" : "",
|
||||
endpoint->options & HTTP_METHOD_POST ? ", POST" : "",
|
||||
endpoint->options & HTTP_METHOD_PUT ? ", PUT" : "",
|
||||
endpoint->options & HTTP_METHOD_DELETE ? ", DELETE" : ""
|
||||
);
|
||||
char *extra_headers = add_extra_headers(options_header);
|
||||
mg_send_head(nc, 204, 0, extra_headers);
|
||||
free(extra_headers);
|
||||
}
|
||||
else
|
||||
{
|
||||
mg_send_head(nc, 501, 0, "Content-Type: text/plain");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
endpoint->func(nc, hm, endpoint->args, &response);
|
||||
send_response(nc, &response);
|
||||
}
|
||||
|
||||
for(int i = 0; i < endpoint->args_count; ++i)
|
||||
{
|
||||
if(endpoint->args[i].type == ENDPOINT_ARG_TYPE_STR)
|
||||
{
|
||||
free((char*)endpoint->args[i].value.v_str);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
39
src/helpers/connect_server.c
Normal file
39
src/helpers/connect_server.c
Normal file
|
@ -0,0 +1,39 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <netdb.h>
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <logger.h>
|
||||
#include <helpers.h>
|
||||
|
||||
int
|
||||
helper_connect_tcp_server(char* host, uint16_t port)
|
||||
{
|
||||
char port_str[6];
|
||||
sprintf(port_str, "%d", port);
|
||||
|
||||
int s, status;
|
||||
struct addrinfo hints, *res;
|
||||
memset(&hints, 0, sizeof hints);
|
||||
hints.ai_family = AF_INET; //set IP Protocol flag (IPv4 or IPv6 - we don't care)
|
||||
hints.ai_socktype = SOCK_STREAM; //set socket flag
|
||||
|
||||
if ((status = getaddrinfo(host, port_str, &hints, &res)) != 0) { //getaddrinfo() will evaluate the given address, using the hints-flags and port, and return an IP address and other server infos
|
||||
LOG_ERROR("getaddrinfo: %s\n", gai_strerror(status));
|
||||
return -1;
|
||||
}
|
||||
|
||||
//res got filled out by getaddrinfo() for us
|
||||
s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); //creating Socket
|
||||
|
||||
if ((status = connect(s, res->ai_addr, res->ai_addrlen)) != 0) {
|
||||
LOG_ERROR("connect() failed\n");
|
||||
freeaddrinfo(res);
|
||||
return -1;
|
||||
}
|
||||
|
||||
freeaddrinfo(res);
|
||||
|
||||
return s;
|
||||
}
|
11
src/helpers/get_weekday.c
Normal file
11
src/helpers/get_weekday.c
Normal file
|
@ -0,0 +1,11 @@
|
|||
#include <time.h>
|
||||
|
||||
#include <helpers.h>
|
||||
|
||||
int
|
||||
helper_get_weekday(const struct tm *time_struct)
|
||||
{
|
||||
int wday_sun_sat = time_struct->tm_wday;
|
||||
int wday_mon_sun = (wday_sun_sat + 6) % 7;
|
||||
return wday_mon_sun;
|
||||
}
|
54
src/helpers/parse_cli.c
Normal file
54
src/helpers/parse_cli.c
Normal file
|
@ -0,0 +1,54 @@
|
|||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include <argparse.h>
|
||||
#include <config.h>
|
||||
#include <logger.h>
|
||||
#include <helpers.h>
|
||||
|
||||
static const char *const usage[] = {
|
||||
"core [options] [[--] args]",
|
||||
"core [options]",
|
||||
NULL,
|
||||
};
|
||||
|
||||
void
|
||||
helper_parse_cli(int argc, const char **argv, config_t *config)
|
||||
{
|
||||
struct argparse_option options[] =
|
||||
{
|
||||
OPT_HELP(),
|
||||
OPT_GROUP("Basic options"),
|
||||
OPT_STRING('c', "config", &config->file, "path to config file", NULL, 0, OPT_NONEG),
|
||||
|
||||
OPT_END(),
|
||||
};
|
||||
|
||||
struct argparse argparse;
|
||||
argparse_init(&argparse, options, usage, 0);
|
||||
argparse_describe(
|
||||
&argparse,
|
||||
"\nA brief description of what the program does and how it works.",
|
||||
"\nAdditional description of the program after the description of the arguments."
|
||||
);
|
||||
argc = argparse_parse(&argparse, argc, argv);
|
||||
|
||||
if(argc == 1)
|
||||
{
|
||||
config->run_type = RUN_TYPE_INVALID;
|
||||
if(strcmp(argv[0], "start") == 0)
|
||||
{
|
||||
config->run_type = RUN_TYPE_START;
|
||||
return;
|
||||
}
|
||||
LOG_FATAL("bad action '%s' given ('start')\n", argv[0]);
|
||||
exit(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_FATAL("no action given ('start')\n");
|
||||
exit(1);
|
||||
}
|
||||
return;
|
||||
}
|
59
src/logger.c
Normal file
59
src/logger.c
Normal file
|
@ -0,0 +1,59 @@
|
|||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <config.h>
|
||||
#include <logger.h>
|
||||
|
||||
#define COLOR_TRACE COLOR_GREEN
|
||||
#define COLOR_DEBUG COLOR_BLUE
|
||||
#define COLOR_INFO COLOR_CYAN
|
||||
#define COLOR_WARN COLOR_YELLOW
|
||||
#define COLOR_ERROR COLOR_RED
|
||||
#define COLOR_FATAL COLOR_MAGENTA
|
||||
|
||||
void
|
||||
logger_log(FILE *stream, log_level_t level, const char *filename, int line, const char *func, const char *msg, ...)
|
||||
{
|
||||
if(global_config.log_level < level)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
switch(level)
|
||||
{
|
||||
case LOG_LEVEL_TRACE:
|
||||
fprintf(stream, COLOR_TRACE "[TRACE] ");
|
||||
break;
|
||||
case LOG_LEVEL_DEBUG:
|
||||
fprintf(stream, COLOR_DEBUG "[DEBUG] ");
|
||||
break;
|
||||
case LOG_LEVEL_INFO:
|
||||
fprintf(stream, COLOR_INFO "[INFO ] ");
|
||||
break;
|
||||
case LOG_LEVEL_WARN:
|
||||
fprintf(stream, COLOR_WARN "[WARN ] ");
|
||||
break;
|
||||
case LOG_LEVEL_ERROR:
|
||||
fprintf(stream, COLOR_ERROR "[ERROR] ");
|
||||
break;
|
||||
case LOG_LEVEL_FATAL:
|
||||
fprintf(stream, COLOR_FATAL "[FATAL] ");
|
||||
break;
|
||||
default:
|
||||
fprintf(stream, COLOR_NONE "[LOG ] ");
|
||||
break;
|
||||
}
|
||||
|
||||
char timestamp_str[32];
|
||||
time_t rawtime;
|
||||
time(&rawtime);
|
||||
strftime(timestamp_str, 32, "%Y-%m-%d %H:%M:%S", localtime(&rawtime));
|
||||
|
||||
fprintf(stream, "%s %s:%d:%s " COLOR_NONE, timestamp_str, filename, line, func);
|
||||
|
||||
va_list args;
|
||||
va_start(args, msg);
|
||||
vfprintf(stream, msg, args);
|
||||
va_end(args);
|
||||
}
|
117
src/main.c
Normal file
117
src/main.c
Normal file
|
@ -0,0 +1,117 @@
|
|||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
|
||||
#include <mongoose.h>
|
||||
#include <router.h>
|
||||
#include <logger.h>
|
||||
#include <config.h>
|
||||
#include <database.h>
|
||||
#include <handlers.h>
|
||||
#include <enums.h>
|
||||
#include <helpers.h>
|
||||
#include <confini.h>
|
||||
#include <models/controller.h>
|
||||
|
||||
static struct mg_mgr mgr;
|
||||
|
||||
static void
|
||||
terminate(int signum)
|
||||
{
|
||||
LOG_INFO("terminating controller (%d)\n", signum);
|
||||
|
||||
mg_mgr_free(&mgr);
|
||||
|
||||
sqlite3_close(global_database);
|
||||
|
||||
router_free();
|
||||
|
||||
exit(signum);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The main function
|
||||
*
|
||||
* @param argc UNUSED
|
||||
* @param argv UNUSED
|
||||
*
|
||||
* @return Statuscode to indicate success (0) or failure (!0)
|
||||
*/
|
||||
int
|
||||
main(int argc, const char** argv)
|
||||
{
|
||||
signal(SIGINT, terminate);
|
||||
signal(SIGABRT, terminate);
|
||||
signal(SIGTERM, terminate);
|
||||
|
||||
|
||||
/******************** LOAD CONFIG ********************/
|
||||
|
||||
global_config.file = "core.ini";
|
||||
strcpy(global_config.not_found_file, "404.html");
|
||||
strcpy(global_config.not_found_file_type, "text/html");
|
||||
strcpy(global_config.not_found_content, "404 - NOT FOUND");
|
||||
strcpy(global_config.not_found_content_type, "text/plain");
|
||||
global_config.log_level = LOG_LEVEL_INFO;
|
||||
|
||||
helper_parse_cli(argc, argv, &global_config);
|
||||
|
||||
FILE * const ini_file = fopen(global_config.file, "rb");
|
||||
if(ini_file == NULL)
|
||||
{
|
||||
LOG_FATAL("config file '%s' was not found\n", global_config.file);
|
||||
exit(1);
|
||||
}
|
||||
if(load_ini_file( ini_file, INI_DEFAULT_FORMAT, NULL, config_load, &global_config))
|
||||
{
|
||||
LOG_FATAL("unable to parse ini file\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
fclose(ini_file);
|
||||
|
||||
memset(&global_config.http_server_opts, 0, sizeof(global_config.http_server_opts));
|
||||
global_config.http_server_opts.document_root = "."; // Serve current directory
|
||||
global_config.http_server_opts.enable_directory_listing = "no";
|
||||
global_config.http_server_opts.extra_headers = "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Headers: *\r\nAccess-Control-Allow-Methods: *";
|
||||
|
||||
|
||||
/******************** SETUP DATABASE ********************/
|
||||
|
||||
int rc = sqlite3_open(global_config.database, &global_database);
|
||||
|
||||
if(rc)
|
||||
{
|
||||
LOG_FATAL("can't open database: %s\n", sqlite3_errmsg(global_database));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if(database_migrate())
|
||||
{
|
||||
terminate(1);
|
||||
}
|
||||
|
||||
sqlite3_exec(global_database, "PRAGMA foreign_keys = ON", 0, 0, 0);
|
||||
|
||||
|
||||
/******************** INIT ROUTER ********************/
|
||||
|
||||
router_init();
|
||||
|
||||
|
||||
/******************** START MAIN LOOP ********************/
|
||||
|
||||
struct mg_connection *c;
|
||||
|
||||
mg_mgr_init(&mgr, NULL);
|
||||
c = mg_bind(&mgr, global_config.server_port, handler_connection);
|
||||
mg_set_protocol_http_websocket(c);
|
||||
|
||||
for (;;)
|
||||
{
|
||||
mg_mgr_poll(&mgr, 1000);
|
||||
}
|
||||
|
||||
terminate(0);
|
||||
}
|
293
src/models/controller.c
Normal file
293
src/models/controller.c
Normal file
|
@ -0,0 +1,293 @@
|
|||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sqlite3.h>
|
||||
|
||||
#include <cJSON.h>
|
||||
#include <logger.h>
|
||||
#include <database.h>
|
||||
#include <models/controller.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
static int
|
||||
db_update_insert(controller_t *controller, sqlite3_stmt *stmt)
|
||||
{
|
||||
int rc;
|
||||
|
||||
sqlite3_bind_int(stmt, 1, controller->id);
|
||||
sqlite3_bind_blob(stmt, 2, controller->uid, sizeof(uuid_t), SQLITE_STATIC);
|
||||
sqlite3_bind_text(stmt, 3, controller->name, -1, SQLITE_STATIC);
|
||||
sqlite3_bind_text(stmt, 4, controller->ip, -1, SQLITE_STATIC);
|
||||
sqlite3_bind_int(stmt, 5, controller->active);
|
||||
sqlite3_bind_int(stmt, 6, controller->port);
|
||||
sqlite3_bind_int(stmt, 7, controller->relay_count);
|
||||
|
||||
rc = sqlite3_step(stmt);
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc != SQLITE_DONE;
|
||||
}
|
||||
static controller_t*
|
||||
controller_db_select_mapper(sqlite3_stmt *stmt)
|
||||
{
|
||||
controller_t *new_controller = malloc(sizeof(controller_t));
|
||||
for(int i = 0; i < sqlite3_column_count(stmt); i++)
|
||||
{
|
||||
const char *name = sqlite3_column_name(stmt, i);
|
||||
switch(name[0])
|
||||
{
|
||||
case 'a': // active
|
||||
new_controller->active = (bool)sqlite3_column_int(stmt, i);
|
||||
break;
|
||||
case 'i':
|
||||
switch(name[1])
|
||||
{
|
||||
case 'd': // id
|
||||
new_controller->id = sqlite3_column_int(stmt, i);
|
||||
break;
|
||||
case 'p': // ip
|
||||
strncpy(new_controller->ip, (const char*)sqlite3_column_text(stmt, i), 16);
|
||||
break;
|
||||
default: // ignore columns not implemented
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 'n': // name
|
||||
strncpy(new_controller->name, (const char*)sqlite3_column_text(stmt, i), 127);
|
||||
break;
|
||||
case 'p': // port
|
||||
new_controller->port = sqlite3_column_int(stmt, i);
|
||||
break;
|
||||
case 'r': // relay_count
|
||||
new_controller->relay_count = sqlite3_column_int(stmt, i);
|
||||
break;
|
||||
case 'u': // uid
|
||||
uuid_copy(new_controller->uid, (const unsigned char*)sqlite3_column_blob(stmt, i));
|
||||
break;
|
||||
default: // ignore columns not implemented
|
||||
break;
|
||||
}
|
||||
}
|
||||
new_controller->relays = relay_get_by_controller_id(new_controller->id);
|
||||
return new_controller;
|
||||
}
|
||||
|
||||
static controller_t**
|
||||
controller_db_select(sqlite3_stmt *stmt)
|
||||
{
|
||||
controller_t **all_controllers = malloc(sizeof(controller_t*));
|
||||
|
||||
int row = 0;
|
||||
|
||||
while(true)
|
||||
{
|
||||
int s;
|
||||
|
||||
s = sqlite3_step(stmt);
|
||||
if (s == SQLITE_ROW)
|
||||
{
|
||||
controller_t *new_controller = controller_db_select_mapper(stmt);
|
||||
row++;
|
||||
|
||||
all_controllers = (controller_t**)realloc(all_controllers, sizeof(controller_t*) * (row + 1));
|
||||
all_controllers[row - 1] = new_controller;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(s == SQLITE_DONE)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("error selecting controllers from database: %s\n", sqlite3_errstr(s));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
all_controllers[row] = NULL;
|
||||
return all_controllers;
|
||||
}
|
||||
|
||||
int
|
||||
controller_save(controller_t *controller)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
if(controller->id)
|
||||
{
|
||||
sqlite3_prepare_v2(global_database, "UPDATE controllers set uid = ?2, name = ?3, ip = ?4, active = ?5, port = ?6, relay_count = ?7 WHERE id = ?1;", -1, &stmt, NULL);
|
||||
}
|
||||
else
|
||||
{
|
||||
sqlite3_prepare_v2(global_database, "INSERT INTO controllers(uid, name, ip, active, port, relay_count) values (?2, ?3, ?4, ?5, ?6, ?7);", -1, &stmt, NULL);
|
||||
}
|
||||
|
||||
int result = db_update_insert(controller, stmt);
|
||||
|
||||
if(result)
|
||||
{
|
||||
if(controller->id)
|
||||
{
|
||||
LOG_ERROR("error inserting data: %s\n", sqlite3_errmsg(global_database));
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("error updating data: %s\n", sqlite3_errmsg(global_database));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if(!controller->id)
|
||||
{
|
||||
controller->id = sqlite3_last_insert_rowid(global_database);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
int
|
||||
controller_remove(controller_t *controller)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
if(!controller->id)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
sqlite3_prepare_v2(global_database, "DELETE FROM controllers WHERE id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, controller->id);
|
||||
|
||||
int rc = sqlite3_step(stmt);
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc != SQLITE_DONE;
|
||||
}
|
||||
|
||||
void
|
||||
controller_free(controller_t *controller)
|
||||
{
|
||||
relay_free_list(controller->relays);
|
||||
free(controller);
|
||||
}
|
||||
|
||||
void
|
||||
controller_free_list(controller_t **controllers)
|
||||
{
|
||||
for(int i = 0; controllers[i] != NULL; ++i)
|
||||
{
|
||||
controller_free(controllers[i]);
|
||||
}
|
||||
free(controllers);
|
||||
}
|
||||
|
||||
cJSON*
|
||||
controller_to_json(controller_t *controller)
|
||||
{
|
||||
cJSON *json = cJSON_CreateObject();
|
||||
|
||||
cJSON *json_name = cJSON_CreateString(controller->name);
|
||||
if(json_name == NULL)
|
||||
{
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "name", json_name);
|
||||
|
||||
char uuid_str[UUID_STR_LEN];
|
||||
uuid_unparse(controller->uid, uuid_str);
|
||||
cJSON *json_id = cJSON_CreateString(uuid_str);
|
||||
if(json_name == NULL)
|
||||
{
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "id", json_id);
|
||||
|
||||
cJSON *json_ip = cJSON_CreateString(controller->ip);
|
||||
if(json_ip == NULL)
|
||||
{
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "ip", json_ip);
|
||||
|
||||
cJSON *json_port = cJSON_CreateNumber(controller->port);
|
||||
if(json_port == NULL)
|
||||
{
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "port", json_port);
|
||||
|
||||
cJSON *json_relay_count = cJSON_CreateNumber(controller->relay_count);
|
||||
if(json_relay_count == NULL)
|
||||
{
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "relay_count", json_relay_count);
|
||||
|
||||
cJSON *json_active = cJSON_CreateBool(controller->active);
|
||||
if(json_active == NULL)
|
||||
{
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "active", json_active);
|
||||
|
||||
relay_t **relays = relay_get_by_controller_id(controller->id);
|
||||
cJSON *json_relays = cJSON_CreateArray();
|
||||
for(int i = 0; relays[i] != NULL; ++i)
|
||||
{
|
||||
cJSON_AddItemToArray(json_relays, relay_to_json(relays[i]));
|
||||
}
|
||||
cJSON_AddItemToObject(json, "relays", json_relays);
|
||||
relay_free_list(relays);
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
controller_t*
|
||||
controller_get_by_id(int id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM controllers WHERE id = ?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, id);
|
||||
|
||||
controller_t **sql_result = controller_db_select(stmt);
|
||||
|
||||
controller_t *result = sql_result[0];
|
||||
free(sql_result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
controller_t*
|
||||
controller_get_by_uid(uuid_t uid)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM controllers WHERE uid = ?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_blob(stmt, 1, uid, sizeof(uuid_t), SQLITE_STATIC);
|
||||
|
||||
controller_t **sql_result = controller_db_select(stmt);
|
||||
|
||||
controller_t *result = sql_result[0];
|
||||
free(sql_result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
controller_t**
|
||||
controller_get_all()
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM controllers;", -1, &stmt, NULL);
|
||||
|
||||
return controller_db_select(stmt);
|
||||
}
|
45
src/models/junction_relay_schedule.c
Normal file
45
src/models/junction_relay_schedule.c
Normal file
|
@ -0,0 +1,45 @@
|
|||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include <models/junction_relay_schedule.h>
|
||||
#include <logger.h>
|
||||
#include <database.h>
|
||||
|
||||
int
|
||||
junction_relay_schedule_insert(uint8_t weekday, int relay_id, int schedule_id)
|
||||
{
|
||||
int rc;
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "INSERT INTO junction_relay_schedule(weekday, schedule_id, relay_id) values (?1, ?2, ?3);", -1, &stmt, NULL);
|
||||
|
||||
sqlite3_bind_int(stmt, 1, weekday);
|
||||
sqlite3_bind_int(stmt, 2, schedule_id);
|
||||
sqlite3_bind_int(stmt, 3, relay_id);
|
||||
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc != SQLITE_DONE)
|
||||
{
|
||||
LOG_ERROR("error inserting data: %s", sqlite3_errmsg(global_database));
|
||||
return false;
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int
|
||||
junction_relay_schedule_remove_for_relay(int relay_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
int rc;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "DELETE FROM junction_relay_schedule WHERE relay_id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, relay_id);
|
||||
rc = sqlite3_step(stmt);
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc == SQLITE_DONE;
|
||||
}
|
194
src/models/junction_tag.c
Normal file
194
src/models/junction_tag.c
Normal file
|
@ -0,0 +1,194 @@
|
|||
#include <stdlib.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include <sqlite3.h>
|
||||
#include <logger.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <database.h>
|
||||
|
||||
int
|
||||
junction_tag_insert(int tag_id, int relay_id, int schedule_id)
|
||||
{
|
||||
int rc;
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "INSERT INTO junction_tag(tag_id, schedule_id, relay_id) values (?1, ?2, ?3);", -1, &stmt, NULL);
|
||||
|
||||
sqlite3_bind_int(stmt, 1, tag_id);
|
||||
|
||||
if(schedule_id)
|
||||
{
|
||||
sqlite3_bind_int(stmt, 2, schedule_id);
|
||||
}
|
||||
else
|
||||
{
|
||||
sqlite3_bind_null(stmt, 2);
|
||||
}
|
||||
|
||||
if(relay_id)
|
||||
{
|
||||
sqlite3_bind_int(stmt, 3, relay_id);
|
||||
}
|
||||
else
|
||||
{
|
||||
sqlite3_bind_null(stmt, 3);
|
||||
}
|
||||
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc != SQLITE_DONE)
|
||||
{
|
||||
printf("ERROR inserting data: %s\n", sqlite3_errmsg(global_database));
|
||||
return false;
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static int*
|
||||
get_ids(sqlite3_stmt *stmt)
|
||||
{
|
||||
int *ids = malloc(sizeof(int));
|
||||
int new_id;
|
||||
|
||||
int row = 0;
|
||||
|
||||
while(true)
|
||||
{
|
||||
int s;
|
||||
|
||||
s = sqlite3_step(stmt);
|
||||
if (s == SQLITE_ROW)
|
||||
{
|
||||
new_id = sqlite3_column_int(stmt, 0);
|
||||
if(new_id != 0) // found row for other target (relay <> schedule)
|
||||
{
|
||||
row++;
|
||||
|
||||
ids = (int*)realloc(ids, sizeof(int) * (row + 1));
|
||||
ids[row - 1] = new_id;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (s == SQLITE_DONE)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("error selecting relays from database: %s\n", sqlite3_errstr(s));
|
||||
sqlite3_finalize(stmt);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
ids[row] = 0;
|
||||
|
||||
return ids;
|
||||
}
|
||||
|
||||
int*
|
||||
junction_tag_get_relays_for_tag_id(int tag_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT relay_id FROM junction_tag WHERE tag_id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, tag_id);
|
||||
|
||||
return get_ids(stmt);
|
||||
}
|
||||
|
||||
int*
|
||||
junction_tag_get_schedules_for_tag_id(int tag_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT schedule_id FROM junction_tag WHERE tag_id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, tag_id);
|
||||
|
||||
return get_ids(stmt);
|
||||
}
|
||||
|
||||
int*
|
||||
junction_tag_get_tags_for_relay_id(int relay_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT tag_id FROM junction_tag WHERE relay_id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, relay_id);
|
||||
|
||||
return get_ids(stmt);
|
||||
}
|
||||
|
||||
int*
|
||||
junction_tag_get_tags_for_schedule_id(int schedule_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT tag_id FROM junction_tag WHERE schedule_id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, schedule_id);
|
||||
|
||||
return get_ids(stmt);
|
||||
}
|
||||
|
||||
int
|
||||
junction_tag_remove(int tag_id, int relay_id, int schedule_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
int rc;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "DELETE FROM junction_tag WHERE tag_id=?1 AND schedule_id=?2 AND relay_id=?3;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, tag_id);
|
||||
sqlite3_bind_int(stmt, 2, schedule_id);
|
||||
sqlite3_bind_int(stmt, 3, relay_id);
|
||||
rc = sqlite3_step(stmt);
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc == SQLITE_DONE;
|
||||
}
|
||||
|
||||
int
|
||||
junction_tag_remove_for_tag(int tag_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
int rc;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "DELETE FROM junction_tag WHERE tag_id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, tag_id);
|
||||
rc = sqlite3_step(stmt);
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc == SQLITE_DONE;
|
||||
}
|
||||
|
||||
int
|
||||
junction_tag_remove_for_relay(int relay_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
int rc;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "DELETE FROM junction_tag WHERE relay_id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, relay_id);
|
||||
rc = sqlite3_step(stmt);
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc == SQLITE_DONE;
|
||||
}
|
||||
|
||||
int
|
||||
junction_tag_remove_for_schedule(int schedule_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
int rc;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "DELETE FROM junction_tag WHERE schedule_id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, schedule_id);
|
||||
rc = sqlite3_step(stmt);
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc == SQLITE_DONE;
|
||||
}
|
46
src/models/period.c
Normal file
46
src/models/period.c
Normal file
|
@ -0,0 +1,46 @@
|
|||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <errno.h>
|
||||
|
||||
#include <models/period.h>
|
||||
|
||||
int
|
||||
period_helper_parse_hhmm(const char *hhmm_str, uint16_t *hhmm)
|
||||
{
|
||||
if(strlen(hhmm_str) != 5)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
if(hhmm_str[2] != ':')
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
for(int i = 0; i < 5; ++i)
|
||||
{
|
||||
if(i != 2)
|
||||
{
|
||||
if(hhmm_str[i] < '0' || hhmm_str[i] > '9')
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uint16_t tmp_h, tmp_m;
|
||||
tmp_h = (uint16_t)strtol(&hhmm_str[0], NULL, 10);
|
||||
tmp_m = (uint16_t)strtol(&hhmm_str[3], NULL, 10);
|
||||
|
||||
if(tmp_h > 24 || tmp_m >= 60)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
if(tmp_h == 24 && tmp_m > 0)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
*hhmm = (tmp_h * 60) + tmp_m;
|
||||
|
||||
return 0;
|
||||
}
|
376
src/models/relay.c
Normal file
376
src/models/relay.c
Normal file
|
@ -0,0 +1,376 @@
|
|||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sqlite3.h>
|
||||
|
||||
#include <cJSON.h>
|
||||
#include <logger.h>
|
||||
#include <database.h>
|
||||
#include <models/relay.h>
|
||||
#include <models/controller.h>
|
||||
#include <models/schedule.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/junction_relay_schedule.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
static int
|
||||
db_update_insert(relay_t *relay, sqlite3_stmt *stmt)
|
||||
{
|
||||
int rc;
|
||||
|
||||
sqlite3_bind_int(stmt, 1, relay->id);
|
||||
sqlite3_bind_int(stmt, 2, relay->number);
|
||||
sqlite3_bind_text(stmt, 3, relay->name, -1, SQLITE_STATIC);
|
||||
sqlite3_bind_int(stmt, 4, relay->controller_id);
|
||||
|
||||
rc = sqlite3_step(stmt);
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc != SQLITE_DONE;
|
||||
}
|
||||
static relay_t*
|
||||
relay_db_select_mapper(sqlite3_stmt *stmt)
|
||||
{
|
||||
relay_t *new_relay = malloc(sizeof(relay_t));
|
||||
for(int i = 0; i < sqlite3_column_count(stmt); i++)
|
||||
{
|
||||
const char *name = sqlite3_column_name(stmt, i);
|
||||
switch(name[0])
|
||||
{
|
||||
case 'c': // controller_id
|
||||
new_relay->controller_id = sqlite3_column_int(stmt, i);
|
||||
break;
|
||||
case 'i':
|
||||
new_relay->id = sqlite3_column_int(stmt, i);
|
||||
break;
|
||||
case 'n':
|
||||
switch(name[1])
|
||||
{
|
||||
case 'a': // name
|
||||
strncpy(new_relay->name, (const char*)sqlite3_column_text(stmt, i), 127);
|
||||
break;
|
||||
case 'u': // number
|
||||
new_relay->number = sqlite3_column_int(stmt, i);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default: // ignore columns not implemented
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
schedule_t **schedules = schedule_get_relay_weekdays(new_relay->id);
|
||||
for(int i = 0; i < 7; ++i)
|
||||
{
|
||||
if(schedules[i] == NULL)
|
||||
{
|
||||
LOG_ERROR("got only %d/7 schedules for relay_id %d\n", i, new_relay->id);
|
||||
relay_free(new_relay);
|
||||
free(schedules);
|
||||
return NULL;
|
||||
}
|
||||
new_relay->schedules[i] = schedules[i];
|
||||
}
|
||||
free(schedules); // don't free list, because contents are kept in relay->schedules
|
||||
|
||||
relay_reload_active_schedule(new_relay);
|
||||
|
||||
return new_relay;
|
||||
}
|
||||
|
||||
static relay_t**
|
||||
relay_db_select(sqlite3_stmt *stmt)
|
||||
{
|
||||
relay_t **all_relays = malloc(sizeof(relay_t*));
|
||||
|
||||
int row = 0;
|
||||
|
||||
while(true)
|
||||
{
|
||||
int s;
|
||||
|
||||
s = sqlite3_step(stmt);
|
||||
if (s == SQLITE_ROW)
|
||||
{
|
||||
relay_t *new_relay = relay_db_select_mapper(stmt);
|
||||
row++;
|
||||
|
||||
all_relays = (relay_t**)realloc(all_relays, sizeof(relay_t*) * (row + 1));
|
||||
all_relays[row - 1] = new_relay;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(s == SQLITE_DONE)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("error selecting relays from database: %s\n", sqlite3_errstr(s));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
all_relays[row] = NULL;
|
||||
return all_relays;
|
||||
}
|
||||
|
||||
int
|
||||
relay_save(relay_t *relay)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
if(relay->id)
|
||||
{
|
||||
sqlite3_prepare_v2(global_database, "UPDATE relays set number = ?2, name = ?3, controller_id = ?4 WHERE id = ?1;", -1, &stmt, NULL);
|
||||
}
|
||||
else
|
||||
{
|
||||
sqlite3_prepare_v2(global_database, "INSERT INTO relays(number, name, controller_id) values (?2, ?3, ?4);", -1, &stmt, NULL);
|
||||
}
|
||||
|
||||
int result = db_update_insert(relay, stmt);
|
||||
|
||||
if(result)
|
||||
{
|
||||
if(relay->id)
|
||||
{
|
||||
LOG_ERROR("error inserting data: %s\n", sqlite3_errmsg(global_database));
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("error updating data: %s\n", sqlite3_errmsg(global_database));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if(relay->id == 0)
|
||||
{
|
||||
relay->id = sqlite3_last_insert_rowid(global_database);
|
||||
}
|
||||
}
|
||||
|
||||
junction_relay_schedule_remove_for_relay(relay->id);
|
||||
for(int i = 0; i < 7; ++i)
|
||||
{
|
||||
junction_relay_schedule_insert(i, relay->id, relay->schedules[i]->id);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
int
|
||||
relay_remove(relay_t *relay)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
if(!relay->id)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
sqlite3_prepare_v2(global_database, "DELETE FROM relays WHERE id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, relay->id);
|
||||
|
||||
int rc = sqlite3_step(stmt);
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc != SQLITE_DONE;
|
||||
}
|
||||
|
||||
void
|
||||
relay_reload_active_schedule(relay_t *relay)
|
||||
{
|
||||
time_t timestamp = time(NULL);
|
||||
struct tm *time_struct = localtime(×tamp);
|
||||
relay->active_schedule = relay->schedules[helper_get_weekday(time_struct)];
|
||||
}
|
||||
|
||||
void
|
||||
relay_free(relay_t *relay)
|
||||
{
|
||||
for(int i = 0; i < 7; ++i)
|
||||
{
|
||||
schedule_free(relay->schedules[i]);
|
||||
}
|
||||
free(relay);
|
||||
}
|
||||
|
||||
void
|
||||
relay_free_list(relay_t **relays)
|
||||
{
|
||||
for(int i = 0; relays[i] != NULL; ++i)
|
||||
{
|
||||
relay_free(relays[i]);
|
||||
}
|
||||
free(relays);
|
||||
}
|
||||
|
||||
cJSON*
|
||||
relay_to_json(relay_t *relay)
|
||||
{
|
||||
relay_reload_active_schedule(relay);
|
||||
|
||||
cJSON *json = cJSON_CreateObject();
|
||||
|
||||
cJSON *json_number = cJSON_CreateNumber(relay->number);
|
||||
if(json_number == NULL)
|
||||
{
|
||||
LOG_DEBUG("failed to make number\n");
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "number", json_number);
|
||||
|
||||
cJSON *json_name = cJSON_CreateString(relay->name);
|
||||
if(json_name == NULL)
|
||||
{
|
||||
LOG_DEBUG("failed to make name\n");
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "name", json_name);
|
||||
|
||||
controller_t *controller = controller_get_by_id(relay->controller_id);
|
||||
if(!controller)
|
||||
{
|
||||
LOG_WARN("failed to get controller\n");
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
char uuid_str[UUID_STR_LEN];
|
||||
uuid_unparse(controller->uid, uuid_str);
|
||||
cJSON *json_controller_id = cJSON_CreateString(uuid_str);
|
||||
if(json_controller_id == NULL)
|
||||
{
|
||||
LOG_DEBUG("failed to make controller id\n");
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "controller_id", json_controller_id);
|
||||
|
||||
controller_free(controller);
|
||||
|
||||
cJSON_AddItemToObject(json, "active_schedule", schedule_to_json(relay->active_schedule));
|
||||
|
||||
cJSON *json_schedules = cJSON_CreateArray();
|
||||
for(int i = 0; i < 7; ++i)
|
||||
{
|
||||
cJSON_AddItemToArray(json_schedules, schedule_to_json(relay->schedules[i]));
|
||||
}
|
||||
cJSON_AddItemToObject(json, "schedules", json_schedules);
|
||||
|
||||
cJSON *json_tags = cJSON_CreateArray();
|
||||
int *tags_ids = junction_tag_get_tags_for_relay_id(relay->id);
|
||||
if(tags_ids != NULL)
|
||||
{
|
||||
for(int i = 0; tags_ids[i] != 0; ++i)
|
||||
{
|
||||
char *tag = tag_get_tag(tags_ids[i]);
|
||||
if(tag == NULL)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
cJSON *json_tag = cJSON_CreateString(tag);
|
||||
if (json_tag == NULL)
|
||||
{
|
||||
LOG_DEBUG("failed to add tag from string '%s'\n", tag);
|
||||
free(tag);
|
||||
continue;
|
||||
}
|
||||
cJSON_AddItemToArray(json_tags, json_tag);
|
||||
free(tag);
|
||||
}
|
||||
free(tags_ids);
|
||||
}
|
||||
cJSON_AddItemToObject(json, "tags", json_tags);
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
relay_t*
|
||||
relay_get_by_id(int id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM relays WHERE id = ?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, id);
|
||||
|
||||
relay_t **sql_result = relay_db_select(stmt);
|
||||
|
||||
relay_t *result = sql_result[0];
|
||||
free(sql_result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
relay_t*
|
||||
relay_get_by_uid(uuid_t uid)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM relays WHERE uid = ?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_blob(stmt, 1, uid, sizeof(uuid_t), SQLITE_STATIC);
|
||||
|
||||
relay_t **sql_result = relay_db_select(stmt);
|
||||
|
||||
relay_t *result = sql_result[0];
|
||||
free(sql_result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
relay_t**
|
||||
relay_get_all()
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM relays;", -1, &stmt, NULL);
|
||||
|
||||
return relay_db_select(stmt);
|
||||
}
|
||||
|
||||
relay_t**
|
||||
relay_get_with_schedule(int schedule_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT DISTINCT relays.* FROM relays INNER JOIN junction_relay_schedule ON relays.id == junction_relay_schedule.relay_id WHERE junction_relay_schedule.schedule_id = ?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, schedule_id);
|
||||
|
||||
return relay_db_select(stmt);
|
||||
}
|
||||
|
||||
relay_t*
|
||||
relay_get_for_controller(int controller_id, int relay_num)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM relays WHERE controller_id = ?1 AND number = ?2;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, controller_id);
|
||||
sqlite3_bind_int(stmt, 2, relay_num);
|
||||
|
||||
relay_t **sql_result = relay_db_select(stmt);
|
||||
|
||||
relay_t *result = sql_result[0];
|
||||
free(sql_result);
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
relay_t**
|
||||
relay_get_by_controller_id(int controller_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM relays WHERE controller_id = ?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, controller_id);
|
||||
|
||||
return relay_db_select(stmt);
|
||||
|
||||
}
|
461
src/models/schedule.c
Normal file
461
src/models/schedule.c
Normal file
|
@ -0,0 +1,461 @@
|
|||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sqlite3.h>
|
||||
|
||||
#include <cJSON.h>
|
||||
#include <logger.h>
|
||||
#include <database.h>
|
||||
#include <models/schedule.h>
|
||||
#include <models/junction_tag.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
static int
|
||||
db_update_insert(schedule_t *schedule, sqlite3_stmt *stmt)
|
||||
{
|
||||
int rc;
|
||||
uint16_t *periods_blob = schedule_periods_to_blob(schedule);
|
||||
int blob_size = (int)sizeof(uint16_t) * ((periods_blob[0] * 2) + 1);
|
||||
|
||||
sqlite3_bind_int(stmt, 1, schedule->id);
|
||||
sqlite3_bind_blob(stmt, 2, schedule->uid, sizeof(uuid_t), SQLITE_STATIC);
|
||||
sqlite3_bind_text(stmt, 3, schedule->name, -1, SQLITE_STATIC);
|
||||
sqlite3_bind_blob(stmt, 4, periods_blob, blob_size, SQLITE_STATIC);
|
||||
|
||||
rc = sqlite3_step(stmt);
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
free(periods_blob);
|
||||
|
||||
return rc != SQLITE_DONE;
|
||||
}
|
||||
static schedule_t*
|
||||
schedule_db_select_mapper(sqlite3_stmt *stmt)
|
||||
{
|
||||
const uint16_t *periods_blob;
|
||||
schedule_t *new_schedule = malloc(sizeof(schedule_t));
|
||||
for(int i = 0; i < sqlite3_column_count(stmt); i++)
|
||||
{
|
||||
const char *name = sqlite3_column_name(stmt, i);
|
||||
switch(name[0])
|
||||
{
|
||||
case 'i': // id
|
||||
new_schedule->id = sqlite3_column_int(stmt, i);
|
||||
break;
|
||||
case 'n': // name
|
||||
strncpy(new_schedule->name, (const char*)sqlite3_column_text(stmt, i), 127);
|
||||
new_schedule->name[127] = '\0';
|
||||
break;
|
||||
case 'p': // periods
|
||||
periods_blob = sqlite3_column_blob(stmt, i);
|
||||
new_schedule->periods_count = periods_blob[0];
|
||||
new_schedule->periods = malloc(sizeof(period_t) * periods_blob[0]);
|
||||
|
||||
for(int i = 0; i < periods_blob[0]; ++i)
|
||||
{
|
||||
new_schedule->periods[i].start = periods_blob[(i * 2) + 1];
|
||||
new_schedule->periods[i].end = periods_blob[(i * 2) + 2];
|
||||
}
|
||||
|
||||
break;
|
||||
case 'u': // uid
|
||||
uuid_copy(new_schedule->uid, (const unsigned char*)sqlite3_column_blob(stmt, i));
|
||||
break;
|
||||
default: // ignore columns not implemented
|
||||
break;
|
||||
}
|
||||
}
|
||||
return new_schedule;
|
||||
}
|
||||
|
||||
static schedule_t**
|
||||
schedule_db_select(sqlite3_stmt *stmt)
|
||||
{
|
||||
schedule_t **all_schedules = malloc(sizeof(schedule_t*));
|
||||
|
||||
int row = 0;
|
||||
|
||||
while(true)
|
||||
{
|
||||
int s;
|
||||
|
||||
s = sqlite3_step(stmt);
|
||||
if (s == SQLITE_ROW)
|
||||
{
|
||||
schedule_t *new_schedule = schedule_db_select_mapper(stmt);
|
||||
row++;
|
||||
|
||||
all_schedules = (schedule_t**)realloc(all_schedules, sizeof(schedule_t*) * (row + 1));
|
||||
all_schedules[row - 1] = new_schedule;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(s == SQLITE_DONE)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("error selecting schedules from database: %s\n", sqlite3_errstr(s));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
all_schedules[row] = NULL;
|
||||
return all_schedules;
|
||||
}
|
||||
|
||||
int
|
||||
schedule_save(schedule_t *schedule)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
if(schedule->id)
|
||||
{
|
||||
sqlite3_prepare_v2(global_database, "UPDATE schedules SET uid = ?2, name = ?3, periods = ?4 WHERE id=?1;", -1, &stmt, NULL);
|
||||
}
|
||||
else
|
||||
{
|
||||
sqlite3_prepare_v2(global_database, "INSERT INTO schedules(uid, name, periods) values (?2, ?3, ?4);", -1, &stmt, NULL);
|
||||
}
|
||||
|
||||
int result = db_update_insert(schedule, stmt);
|
||||
|
||||
if(result)
|
||||
{
|
||||
if(schedule->id)
|
||||
{
|
||||
LOG_ERROR("error inserting data: %s\n", sqlite3_errmsg(global_database));
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("error updating data: %s\n", sqlite3_errmsg(global_database));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if(!schedule->id)
|
||||
{
|
||||
schedule->id = sqlite3_last_insert_rowid(global_database);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
int
|
||||
schedule_remove(schedule_t *schedule)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
if(!schedule->id)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
sqlite3_prepare_v2(global_database, "DELETE FROM schedules WHERE id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, schedule->id);
|
||||
|
||||
int rc = sqlite3_step(stmt);
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc != SQLITE_DONE;
|
||||
}
|
||||
|
||||
int
|
||||
schedule_is_protected(schedule_t *schedule)
|
||||
{
|
||||
uuid_t tmp_uuid;
|
||||
|
||||
memset(tmp_uuid, 0, sizeof(uuid_t));
|
||||
memcpy(tmp_uuid, "off", 3);
|
||||
if(uuid_compare(schedule->uid, tmp_uuid) == 0)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
memset(tmp_uuid, 0, sizeof(uuid_t));
|
||||
memcpy(tmp_uuid, "on", 2);
|
||||
if(uuid_compare(schedule->uid, tmp_uuid) == 0)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
schedule_free(schedule_t *schedule)
|
||||
{
|
||||
free(schedule->periods);
|
||||
free(schedule);
|
||||
}
|
||||
|
||||
void
|
||||
schedule_free_list(schedule_t **schedules)
|
||||
{
|
||||
for(int i = 0; schedules[i] != NULL; ++i)
|
||||
{
|
||||
schedule_free(schedules[i]);
|
||||
}
|
||||
free(schedules);
|
||||
}
|
||||
|
||||
uint16_t*
|
||||
schedule_periods_to_blob(schedule_t *schedule)
|
||||
{
|
||||
uint16_t *blob = malloc(sizeof(uint16_t) * ((schedule->periods_count * 2) + 1));
|
||||
|
||||
blob[0] = schedule->periods_count;
|
||||
|
||||
for(int i = 0; i < schedule->periods_count; i++)
|
||||
{
|
||||
blob[(i * 2) + 1] = schedule->periods[i].start;
|
||||
blob[(i * 2) + 2] = schedule->periods[i].end;
|
||||
}
|
||||
return blob;
|
||||
}
|
||||
|
||||
cJSON*
|
||||
schedule_to_json(schedule_t *schedule)
|
||||
{
|
||||
cJSON *json = cJSON_CreateObject();
|
||||
|
||||
cJSON *json_name = cJSON_CreateString(schedule->name);
|
||||
if(json_name == NULL)
|
||||
{
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "name", json_name);
|
||||
|
||||
char uuid_str[UUID_STR_LEN];
|
||||
schedule_uid_unparse(schedule->uid, uuid_str);
|
||||
cJSON *json_id = cJSON_CreateString(uuid_str);
|
||||
if(json_name == NULL)
|
||||
{
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "id", json_id);
|
||||
|
||||
cJSON *json_periods = cJSON_CreateArray();
|
||||
if(json_periods == NULL)
|
||||
{
|
||||
cJSON_Delete(json);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToObject(json, "periods", json_periods);
|
||||
|
||||
for(int i = 0; i < schedule->periods_count; ++i)
|
||||
{
|
||||
cJSON *json_period = cJSON_CreateObject();
|
||||
if (json_period == NULL)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
char start_str[8], end_str[8];
|
||||
period_t *period = &schedule->periods[i];
|
||||
sprintf(start_str, "%02d:%02d", period->start / 60, period->start % 60);
|
||||
sprintf(end_str, "%02d:%02d", period->end / 60, period->end % 60);
|
||||
|
||||
cJSON *json_period_start = cJSON_CreateString(start_str);
|
||||
if (json_period_start == NULL)
|
||||
{
|
||||
LOG_DEBUG("failed to add start period from string '%s'\n", start_str);
|
||||
cJSON_Delete(json_period);
|
||||
continue;
|
||||
}
|
||||
cJSON_AddItemToObject(json_period, "start", json_period_start);
|
||||
|
||||
cJSON *json_period_end = cJSON_CreateString(end_str);
|
||||
if (json_period_end == NULL)
|
||||
{
|
||||
LOG_DEBUG("failed to add end period from string '%s'\n", end_str);
|
||||
cJSON_Delete(json_period);
|
||||
continue;
|
||||
}
|
||||
cJSON_AddItemToObject(json_period, "end", json_period_end);
|
||||
|
||||
cJSON_AddItemToArray(json_periods, json_period);
|
||||
}
|
||||
|
||||
cJSON *json_tags = cJSON_CreateArray();
|
||||
int *tags_ids = junction_tag_get_tags_for_schedule_id(schedule->id);
|
||||
if(tags_ids != NULL)
|
||||
{
|
||||
for(int i = 0; tags_ids[i] != 0; ++i)
|
||||
{
|
||||
char *tag = tag_get_tag(tags_ids[i]);
|
||||
if(tag == NULL)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
cJSON *json_tag = cJSON_CreateString(tag);
|
||||
if (json_tag == NULL)
|
||||
{
|
||||
LOG_DEBUG("failed to add tag from string '%s'\n", tag);
|
||||
free(tag);
|
||||
continue;
|
||||
}
|
||||
cJSON_AddItemToArray(json_tags, json_tag);
|
||||
free(tag);
|
||||
}
|
||||
free(tags_ids);
|
||||
}
|
||||
cJSON_AddItemToObject(json, "tags", json_tags);
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
schedule_t*
|
||||
schedule_get_by_id_or_off(int id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM schedules WHERE id = ?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, id);
|
||||
|
||||
schedule_t **sql_result = schedule_db_select(stmt);
|
||||
|
||||
schedule_t *result = sql_result[0];
|
||||
free(sql_result);
|
||||
|
||||
if(result)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
uuid_t tmp_uuid;
|
||||
memset(tmp_uuid, 0, sizeof(uuid_t));
|
||||
memcpy(tmp_uuid, "off", 3);
|
||||
|
||||
return schedule_get_by_uid(tmp_uuid);
|
||||
}
|
||||
|
||||
schedule_t*
|
||||
schedule_get_by_id(int id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM schedules WHERE id = ?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, id);
|
||||
|
||||
schedule_t **sql_result = schedule_db_select(stmt);
|
||||
|
||||
schedule_t *result = sql_result[0];
|
||||
free(sql_result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
schedule_t*
|
||||
schedule_get_by_uid_or_off(uuid_t uid)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM schedules WHERE uid = ?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_blob(stmt, 1, uid, sizeof(uuid_t), SQLITE_STATIC);
|
||||
|
||||
schedule_t **sql_result = schedule_db_select(stmt);
|
||||
|
||||
schedule_t *result = sql_result[0];
|
||||
free(sql_result);
|
||||
|
||||
if(result)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
uuid_t tmp_uuid;
|
||||
memset(tmp_uuid, 0, sizeof(uuid_t));
|
||||
memcpy(tmp_uuid, "off", 3);
|
||||
|
||||
return schedule_get_by_uid(tmp_uuid);
|
||||
}
|
||||
|
||||
schedule_t*
|
||||
schedule_get_by_uid(uuid_t uid)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM schedules WHERE uid = ?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_blob(stmt, 1, uid, sizeof(uuid_t), SQLITE_STATIC);
|
||||
|
||||
schedule_t **sql_result = schedule_db_select(stmt);
|
||||
|
||||
schedule_t *result = sql_result[0];
|
||||
free(sql_result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
schedule_t**
|
||||
schedule_get_relay_weekdays(int relay_id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT schedules.* FROM schedules INNER JOIN junction_relay_schedule ON schedules.id == junction_relay_schedule.schedule_id WHERE junction_relay_schedule.relay_id = ?1 ORDER BY junction_relay_schedule.weekday ASC", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, relay_id);
|
||||
|
||||
return schedule_db_select(stmt);
|
||||
}
|
||||
|
||||
schedule_t**
|
||||
schedule_get_all()
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT * FROM schedules;", -1, &stmt, NULL);
|
||||
|
||||
return schedule_db_select(stmt);
|
||||
|
||||
}
|
||||
|
||||
int
|
||||
schedule_uid_parse(const char *uid_str, uuid_t result)
|
||||
{
|
||||
if(strcmp("off", uid_str) == 0)
|
||||
{
|
||||
memset(result, 0, sizeof(uuid_t));
|
||||
memcpy(result, "off", 3);
|
||||
return 0;
|
||||
}
|
||||
if(strcmp("on", uid_str) == 0)
|
||||
{
|
||||
memset(result, 0, sizeof(uuid_t));
|
||||
memcpy(result, "on", 2);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if(uuid_parse(uid_str, result))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
schedule_uid_unparse(const uuid_t uid, char *result)
|
||||
{
|
||||
uuid_t tmp_uuid;
|
||||
|
||||
memset(tmp_uuid, 0, sizeof(uuid_t));
|
||||
memcpy(tmp_uuid, "off", 3);
|
||||
if(uuid_compare(uid, tmp_uuid) == 0)
|
||||
{
|
||||
strcpy(result, "off");
|
||||
return;
|
||||
}
|
||||
|
||||
memset(tmp_uuid, 0, sizeof(uuid_t));
|
||||
memcpy(tmp_uuid, "on", 2);
|
||||
if(uuid_compare(uid, tmp_uuid) == 0)
|
||||
{
|
||||
strcpy(result, "on");
|
||||
return;
|
||||
}
|
||||
|
||||
uuid_unparse(uid, result);
|
||||
}
|
177
src/models/tag.c
Normal file
177
src/models/tag.c
Normal file
|
@ -0,0 +1,177 @@
|
|||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include <logger.h>
|
||||
#include <database.h>
|
||||
#include <models/tag.h>
|
||||
|
||||
int
|
||||
tag_save(int id, const char *tag)
|
||||
{
|
||||
int rc;
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
if(id)
|
||||
{
|
||||
sqlite3_prepare_v2(global_database, "UPDATE tags SET tag = ?2 WHERE id = ?1;", -1, &stmt, NULL);
|
||||
}
|
||||
else
|
||||
{
|
||||
sqlite3_prepare_v2(global_database, "INSERT INTO tags(tag) values (?2);", -1, &stmt, NULL);
|
||||
}
|
||||
|
||||
sqlite3_bind_int(stmt, 1, id);
|
||||
sqlite3_bind_text(stmt, 2, tag, -1, SQLITE_STATIC);
|
||||
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc != SQLITE_DONE)
|
||||
{
|
||||
LOG_ERROR("error saving tag: %s\n", sqlite3_errmsg(global_database));
|
||||
return false;
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
char*
|
||||
tag_get_tag(int id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT tag FROM tags WHERE id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, id);
|
||||
|
||||
char *result = NULL;
|
||||
|
||||
while(1)
|
||||
{
|
||||
int s;
|
||||
|
||||
s = sqlite3_step(stmt);
|
||||
if (s == SQLITE_ROW)
|
||||
{
|
||||
const char *found_tag = (const char *)sqlite3_column_text(stmt, 0);
|
||||
result = (char*)malloc(sizeof(char) * (strlen(found_tag) + 1));
|
||||
strcpy(result, found_tag);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (s == SQLITE_DONE)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("error selecting tags from database: %s\n", sqlite3_errstr(s));
|
||||
sqlite3_finalize(stmt);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
char**
|
||||
tag_get_all()
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT tag FROM tags;", -1, &stmt, NULL);
|
||||
|
||||
char **all_tags = malloc(sizeof(char*));
|
||||
|
||||
int row = 0;
|
||||
|
||||
while(true)
|
||||
{
|
||||
int s;
|
||||
|
||||
s = sqlite3_step(stmt);
|
||||
if (s == SQLITE_ROW)
|
||||
{
|
||||
const char *new_tag = (const char *)sqlite3_column_text(stmt, 0);
|
||||
int new_tag_len = strlen(new_tag);
|
||||
row++;
|
||||
|
||||
all_tags = (char**)realloc(all_tags, sizeof(char*) * (row + 1));
|
||||
all_tags[row - 1] = malloc(sizeof(char) * (new_tag_len + 1));
|
||||
strcpy(all_tags[row - 1], new_tag);
|
||||
}
|
||||
else
|
||||
{
|
||||
if(s == SQLITE_DONE)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("error selecting tags from database: %s\n", sqlite3_errstr(s));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
all_tags[row] = NULL;
|
||||
return all_tags;
|
||||
}
|
||||
|
||||
int
|
||||
tag_get_id(const char *tag)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "SELECT id FROM tags WHERE tag=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_text(stmt, 1, tag, -1, SQLITE_STATIC);
|
||||
|
||||
int result = 0;
|
||||
|
||||
while(1)
|
||||
{
|
||||
int s;
|
||||
|
||||
s = sqlite3_step(stmt);
|
||||
if (s == SQLITE_ROW)
|
||||
{
|
||||
result = sqlite3_column_int(stmt, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (s == SQLITE_DONE)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("error selecting tags from database: %s\n", sqlite3_errstr(s));
|
||||
sqlite3_finalize(stmt);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
int
|
||||
tag_remove(int id)
|
||||
{
|
||||
sqlite3_stmt *stmt;
|
||||
int rc;
|
||||
|
||||
sqlite3_prepare_v2(global_database, "DELETE FROM tags WHERE id=?1;", -1, &stmt, NULL);
|
||||
sqlite3_bind_int(stmt, 1, id);
|
||||
|
||||
rc = sqlite3_step(stmt);
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return rc == SQLITE_DONE;
|
||||
}
|
||||
|
16123
src/mongoose.c
Normal file
16123
src/mongoose.c
Normal file
File diff suppressed because it is too large
Load diff
6440
src/mpack.c
Normal file
6440
src/mpack.c
Normal file
File diff suppressed because it is too large
Load diff
341
src/router.c
Normal file
341
src/router.c
Normal file
|
@ -0,0 +1,341 @@
|
|||
#include <string.h>
|
||||
|
||||
#include <logger.h>
|
||||
#include <router.h>
|
||||
#include <macros.h>
|
||||
#include <endpoint.h>
|
||||
|
||||
#include <endpoints/api_v1_schedules.h>
|
||||
#include <endpoints/api_v1_controllers.h>
|
||||
#include <endpoints/api_v1_relays.h>
|
||||
#include <endpoints/api_v1_tags.h>
|
||||
|
||||
static endpoint_t endpoints[ROUTER_ENDPOINTS_MAX_COUNT];
|
||||
static endpoint_t endpoint_not_found;
|
||||
static int endpoints_registered = 0;
|
||||
static const char delimiter[2] = "/";
|
||||
|
||||
static struct mg_str
|
||||
get_method_str_for_int(int method_int)
|
||||
{
|
||||
if(method_int == HTTP_METHOD_GET)
|
||||
{
|
||||
return mg_mk_str("GET");
|
||||
}
|
||||
if(method_int == HTTP_METHOD_POST)
|
||||
{
|
||||
return mg_mk_str("POST");
|
||||
}
|
||||
if(method_int == HTTP_METHOD_PUT)
|
||||
{
|
||||
return mg_mk_str("PUT");
|
||||
}
|
||||
if(method_int == HTTP_METHOD_DELETE)
|
||||
{
|
||||
return mg_mk_str("DELETE");
|
||||
}
|
||||
if(method_int == HTTP_METHOD_OPTIONS)
|
||||
{
|
||||
return mg_mk_str("OPTIONS");
|
||||
}
|
||||
return mg_mk_str("GET");
|
||||
}
|
||||
|
||||
endpoint_t*
|
||||
router_get_not_found_endpoint()
|
||||
{
|
||||
return &endpoint_not_found;
|
||||
}
|
||||
|
||||
void
|
||||
router_init()
|
||||
{
|
||||
// add 404 endpoint
|
||||
endpoint_not_found.route = NULL;
|
||||
endpoint_not_found.func = endpoint_func_not_found;
|
||||
endpoint_not_found.method = 0;
|
||||
endpoint_not_found.args_count = 0;
|
||||
endpoint_not_found.args = NULL;
|
||||
|
||||
router_register_endpoint("/api/v1/schedules/", HTTP_METHOD_GET, api_v1_schedules_GET);
|
||||
router_register_endpoint("/api/v1/schedules/", HTTP_METHOD_POST, api_v1_schedules_POST);
|
||||
router_register_endpoint("/api/v1/schedules/list/", HTTP_METHOD_POST, api_v1_schedules_list_POST);
|
||||
router_register_endpoint("/api/v1/schedules/{str}", HTTP_METHOD_GET, api_v1_schedules_STR_GET);
|
||||
router_register_endpoint("/api/v1/schedules/{str}", HTTP_METHOD_PUT, api_v1_schedules_STR_PUT);
|
||||
router_register_endpoint("/api/v1/schedules/{str}", HTTP_METHOD_DELETE, api_v1_schedules_STR_DELETE);
|
||||
router_register_endpoint("/api/v1/schedules/tag/{str}", HTTP_METHOD_GET, api_v1_schedules_tag_STR_GET);
|
||||
|
||||
router_register_endpoint("/api/v1/controllers/discover/", HTTP_METHOD_POST, api_v1_controllers_discover_POST);
|
||||
router_register_endpoint("/api/v1/controllers/", HTTP_METHOD_GET, api_v1_controllers_GET);
|
||||
router_register_endpoint("/api/v1/controllers/{str}", HTTP_METHOD_GET, api_v1_controllers_STR_GET);
|
||||
router_register_endpoint("/api/v1/controllers/{str}", HTTP_METHOD_PUT, api_v1_controllers_STR_PUT);
|
||||
router_register_endpoint("/api/v1/controllers/{str}", HTTP_METHOD_DELETE, api_v1_controllers_STR_DELETE);
|
||||
|
||||
router_register_endpoint("/api/v1/controllers/{str}/relays/", HTTP_METHOD_GET, api_v1_controllers_STR_relays_GET);
|
||||
router_register_endpoint("/api/v1/controllers/{str}/relays/{int}", HTTP_METHOD_GET, api_v1_controllers_STR_relays_INT_GET);
|
||||
router_register_endpoint("/api/v1/controllers/{str}/relays/{int}", HTTP_METHOD_PUT, api_v1_controllers_STR_relays_INT_PUT);
|
||||
|
||||
router_register_endpoint("/api/v1/relays/", HTTP_METHOD_GET, api_v1_relays_GET);
|
||||
router_register_endpoint("/api/v1/relays/tag/{str}", HTTP_METHOD_GET, api_v1_relays_tag_STR_GET);
|
||||
|
||||
router_register_endpoint("/api/v1/tags/", HTTP_METHOD_GET, api_v1_tags_GET);
|
||||
}
|
||||
|
||||
endpoint_t*
|
||||
router_register_endpoint(const char *route, int method, endpoint_func_f func)
|
||||
{
|
||||
endpoint_t *options_endpoint = NULL;
|
||||
if(method != HTTP_METHOD_OPTIONS)
|
||||
{
|
||||
struct mg_str method_str = get_method_str_for_int(HTTP_METHOD_OPTIONS);
|
||||
options_endpoint = router_find_endpoint(route, strlen(route), &method_str);
|
||||
if(options_endpoint == NULL)
|
||||
{
|
||||
options_endpoint = router_register_endpoint(route, HTTP_METHOD_OPTIONS, NULL);
|
||||
}
|
||||
else
|
||||
{
|
||||
for(int i = 0; i < options_endpoint->args_count; ++i)
|
||||
{
|
||||
if(options_endpoint->args[i].type == ENDPOINT_ARG_TYPE_STR)
|
||||
{
|
||||
free((char*)options_endpoint->args[i].value.v_str);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(endpoints_registered >= ROUTER_ENDPOINTS_MAX_COUNT)
|
||||
{
|
||||
LOG_ERROR("can't register more than %d endpoints\n", ROUTER_ENDPOINTS_MAX_COUNT);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
endpoint_t *endpoint = &endpoints[endpoints_registered];
|
||||
|
||||
endpoint->full_route = route;
|
||||
endpoint->trailing_slash = 0; // unused because trailing slashes are optional. TODO make option
|
||||
if(route[strlen(route)] == delimiter[0])
|
||||
{
|
||||
endpoint->trailing_slash = 1;
|
||||
}
|
||||
|
||||
int route_parts_count = 1;
|
||||
size_t route_len = strlen(route);
|
||||
|
||||
for(size_t i = 0; i < route_len; ++i)
|
||||
{
|
||||
if(route[i] == delimiter[0] || route[i] == '\0')
|
||||
{
|
||||
++route_parts_count;
|
||||
}
|
||||
}
|
||||
|
||||
// +1 for NULL terminator
|
||||
endpoint->route = malloc(sizeof(char*) * (route_parts_count + 1));
|
||||
endpoint->route_keeper = malloc(sizeof(char) * (route_len + 1));
|
||||
strncpy(endpoint->route_keeper, route, route_len);
|
||||
endpoint->route_keeper[route_len] = '\0';
|
||||
|
||||
int route_part = 0;
|
||||
int route_args_count = 0;
|
||||
|
||||
char *route_token = strtok(endpoint->route_keeper, delimiter);
|
||||
while(route_token)
|
||||
{
|
||||
if(strcmp(route_token, "{int}") == 0)
|
||||
{
|
||||
++route_args_count;
|
||||
}
|
||||
if(strcmp(route_token, "{str}") == 0)
|
||||
{
|
||||
++route_args_count;
|
||||
}
|
||||
endpoint->route[route_part] = route_token;
|
||||
++route_part;
|
||||
route_token = strtok(NULL, delimiter);
|
||||
}
|
||||
endpoint->route[route_part] = NULL;
|
||||
|
||||
endpoint->args_count = route_args_count;
|
||||
endpoint->args = NULL;
|
||||
if(route_args_count)
|
||||
{
|
||||
endpoint->args = malloc(sizeof(endpoint_args_t) * route_args_count);
|
||||
}
|
||||
|
||||
endpoint->func = func;
|
||||
endpoint->method = method;
|
||||
endpoint->options = 0;
|
||||
|
||||
if(options_endpoint)
|
||||
{
|
||||
options_endpoint->options |= method;
|
||||
}
|
||||
|
||||
++endpoints_registered;
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
static int
|
||||
get_method_int_for_str(struct mg_str *method_str)
|
||||
{
|
||||
if(strncmp(method_str->p, "GET", method_str->len) == 0)
|
||||
{
|
||||
return HTTP_METHOD_GET;
|
||||
}
|
||||
if(strncmp(method_str->p, "POST", method_str->len) == 0)
|
||||
{
|
||||
return HTTP_METHOD_POST;
|
||||
}
|
||||
if(strncmp(method_str->p, "PUT", method_str->len) == 0)
|
||||
{
|
||||
return HTTP_METHOD_PUT;
|
||||
}
|
||||
if(strncmp(method_str->p, "DELETE", method_str->len) == 0)
|
||||
{
|
||||
return HTTP_METHOD_DELETE;
|
||||
}
|
||||
if(strncmp(method_str->p, "OPTIONS", method_str->len) == 0)
|
||||
{
|
||||
return HTTP_METHOD_OPTIONS;
|
||||
}
|
||||
return HTTP_METHOD_GET;
|
||||
}
|
||||
|
||||
endpoint_t*
|
||||
router_find_endpoint(const char *uri_str, size_t uri_len, struct mg_str *method_str)
|
||||
{
|
||||
char *uri = malloc(sizeof(char) * (uri_len + 1));
|
||||
strncpy(uri, uri_str, uri_len);
|
||||
uri[uri_len] = '\0';
|
||||
|
||||
int method = get_method_int_for_str(method_str);
|
||||
|
||||
for(int i = 0; i < endpoints_registered; ++i)
|
||||
{
|
||||
if(endpoints[i].method & method)
|
||||
{
|
||||
endpoints[i].possible_route = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
endpoints[i].possible_route = 0;
|
||||
}
|
||||
endpoints[i].args_found = 0;
|
||||
}
|
||||
|
||||
char *uri_token;
|
||||
char *uri_token_save;
|
||||
uri_token = strtok_r(uri, delimiter, &uri_token_save);
|
||||
|
||||
int route_part = 0;
|
||||
|
||||
if(!uri_token)
|
||||
{
|
||||
free(uri);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
while(uri_token)
|
||||
{
|
||||
for(int i = 0; i < endpoints_registered; ++i)
|
||||
{
|
||||
if(!endpoints[i].possible_route)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if(!endpoints[i].route[route_part])
|
||||
{
|
||||
endpoints[i].possible_route = 0;
|
||||
continue;
|
||||
}
|
||||
if(uri_token_save[0] == '\0' && endpoints[i].route[route_part + 1])
|
||||
{
|
||||
endpoints[i].possible_route = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(strcmp(endpoints[i].route[route_part], "{str}") == 0)
|
||||
{
|
||||
endpoints[i].possible_route += 1;
|
||||
|
||||
endpoints[i].args[endpoints[i].args_found].type = ENDPOINT_ARG_TYPE_STR;
|
||||
endpoints[i].args[endpoints[i].args_found].value.v_str = uri_token;
|
||||
++endpoints[i].args_found;
|
||||
continue;
|
||||
}
|
||||
if(strcmp(endpoints[i].route[route_part], "{int}") == 0)
|
||||
{
|
||||
char *endptr;
|
||||
errno = 0;
|
||||
int found_arg_int = strtol(uri_token, &endptr, 10);
|
||||
if(errno || (endptr && *endptr != '\0'))
|
||||
{
|
||||
endpoints[i].possible_route = 0;
|
||||
continue;
|
||||
}
|
||||
endpoints[i].possible_route += 2;
|
||||
|
||||
endpoints[i].args[endpoints[i].args_found].type = ENDPOINT_ARG_TYPE_INT;
|
||||
endpoints[i].args[endpoints[i].args_found].value.v_int = found_arg_int;
|
||||
++endpoints[i].args_found;
|
||||
continue;
|
||||
}
|
||||
if(strcmp(endpoints[i].route[route_part], uri_token) == 0)
|
||||
{
|
||||
endpoints[i].possible_route += 3;
|
||||
continue;
|
||||
}
|
||||
endpoints[i].possible_route = 0;
|
||||
continue;
|
||||
}
|
||||
uri_token = strtok_r(NULL, delimiter, &uri_token_save);
|
||||
++route_part;
|
||||
}
|
||||
|
||||
int best_rating = 0;
|
||||
endpoint_t *best_endpoint = NULL;
|
||||
for(int i = 0; i < endpoints_registered; ++i)
|
||||
{
|
||||
int rating = endpoints[i].possible_route;
|
||||
if(rating > best_rating)
|
||||
{
|
||||
best_endpoint = &endpoints[i];
|
||||
best_rating = best_endpoint->possible_route;
|
||||
}
|
||||
}
|
||||
|
||||
if(best_endpoint == NULL)
|
||||
{
|
||||
free(uri);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
for(int i = 0; i < best_endpoint->args_count; ++i)
|
||||
{
|
||||
if(best_endpoint->args[i].type == ENDPOINT_ARG_TYPE_STR)
|
||||
{
|
||||
char *arg_value_str = malloc(sizeof(char) * (strlen(best_endpoint->args[i].value.v_str) + 1));
|
||||
strcpy(arg_value_str, best_endpoint->args[i].value.v_str);
|
||||
best_endpoint->args[i].value.v_str = arg_value_str;
|
||||
}
|
||||
}
|
||||
free(uri);
|
||||
|
||||
return best_endpoint;
|
||||
}
|
||||
|
||||
void
|
||||
router_free()
|
||||
{
|
||||
for(int i = 0; i < endpoints_registered; ++i)
|
||||
{
|
||||
free(endpoints[i].route_keeper);
|
||||
free(endpoints[i].route);
|
||||
if(endpoints[i].args)
|
||||
{
|
||||
free(endpoints[i].args);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue