diff --git a/CMakeLists.txt b/CMakeLists.txt index 49b059d..c1f96a6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,13 +1,13 @@ cmake_minimum_required (VERSION 3.7) project(controller - VERSION 0.2.10 + VERSION 0.3.0 LANGUAGES C) add_executable(controller src/main.c) target_link_libraries(controller -lwiringPi) target_link_libraries(controller -lwiringPiDev) -target_link_libraries(controller -llmdb) +target_link_libraries(controller -lsqlite3) target_link_libraries(controller -luuid) option(WIRING_PI_DEBUG "Use WiringPi Debugging Tool (OFF)" OFF) @@ -30,14 +30,22 @@ aux_source_directory(src/drivers DRIVERS_SRC) aux_source_directory(src/runners RUNNERS_SRC) aux_source_directory(vendor VENDOR_SRC) +add_dependencies(controller sql) + configure_file("controller.ini" "controller.ini" COPYONLY) configure_file("version.h.in" "version.h" @ONLY) + target_sources(controller PRIVATE ${SRC_DIR} ${MODELS_SRC} ${HELPERS_SRC} ${HANDLERS_SRC} ${DRIVERS_SRC} ${RUNNERS_SRC} ${VENDOR_SRC}) target_include_directories(controller PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) target_include_directories(controller PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/vendor) target_include_directories(controller PRIVATE ${CMAKE_BINARY_DIR}) +add_custom_target(sql + COMMAND ./compile_sql.sh + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} +) + add_custom_target(run COMMAND ./controller start DEPENDS controller diff --git a/compile_sql.sh b/compile_sql.sh new file mode 100755 index 0000000..18fe323 --- /dev/null +++ b/compile_sql.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env sh + +to_header () { + if [ -f ./include/sql/$1.h ] + then + if [ -z $(find ./sql/$1.sql -newer ./include/sql/$1.h -print) ] + then + return + fi + fi + echo "Compiling $1" + xxd -i sql/$1.sql | sed 's/\([0-9a-f]\)$/\0, 0x00/' > ./include/sql/$1.h +} + +cd "$(dirname "$0")"; + +migration_num=0; + +while [ -f ./sql/migration_$migration_num.sql ] +do + if [ -f ./include/migrations/$migration_num.sql.h ] + then + if [ -z $(find ./sql/migration_$migration_num.sql -newer ./include/sql/migration_$migration_num.h -print) ] + then + migration_num=$((migration_num+1)) + continue + fi + fi + to_header "migration_$migration_num" + migration_num=$((migration_num+1)) +done + +cd $PWD; diff --git a/controller.ini b/controller.ini index b1abf21..dfec8e3 100644 --- a/controller.ini +++ b/controller.ini @@ -10,7 +10,7 @@ mqtt-host = localhost relay-count = 10 relays-init = 1 -database = controller_db.lmdb +database = controller.sqlite log-level = debug log-file = stdout diff --git a/include/database.h b/include/database.h index d24bf3c..6408d9c 100644 --- a/include/database.h +++ b/include/database.h @@ -1,19 +1,40 @@ #ifndef CONTROLLER_DATABASE_H #define CONTROLLER_DATABASE_H -#include +#include + +extern sqlite3 *global_database; -/** - * @brief Setup lmdb database enviroment - * - * Creates, sets max dbs and opens an MDB_env instance. - * Will return on success, but exit program on failure. - * - * @param mdb_env Source variable will be set to new MDB_env - */ void -database_setup(MDB_env **mdb_env, config_t *config); +database_init(); -extern MDB_env *global_mdb_env; +void +database_free(); + +void +database_migrate(); + + +int +database_transaction_begin(); + +void +database_transaction_commit(); + +void +database_transaction_rollback(); + + +int +database_helper_get_id(sqlite3_stmt *stmt); + +int* +database_helper_get_ids(sqlite3_stmt *stmt); + +char* +database_helper_get_string(sqlite3_stmt *stmt); + +char** +database_helper_get_strings(sqlite3_stmt *stmt); #endif /* CONTROLLER_DATABASE_H */ diff --git a/include/enums.h b/include/enums.h index e57a627..032622a 100644 --- a/include/enums.h +++ b/include/enums.h @@ -15,31 +15,6 @@ typedef enum DISCOVERY_MAPPING_RELAY_COUNT = 3, } discovery_mapping_t; -typedef enum -{ - COMMAND_MAPPING_CODE = 0, - COMMAND_MAPPING_NAME = 1, - COMMAND_MAPPING_RELAY_NUM = 2, - COMMAND_MAPPING_SCHEDULES_ARRAY = 3, - COMMAND_MAPPING_SCHEDULE_ID = 4, - COMMAND_MAPPING_PERIODS_COUNT = 5, - COMMAND_MAPPING_PERIODS_BLOB = 6, - COMMAND_MAPPING_PULSE_DURATION = 7, -} control_mapping_t; - -typedef enum -{ - COMMAND_CODE_GET_TIME = 1, - COMMAND_CODE_GET_ID = 2, - COMMAND_CODE_SET_NAME = 100, - COMMAND_CODE_GET_NAME = 101, - COMMAND_CODE_SET_SCHEDULE = 102, - COMMAND_CODE_GET_SCHEDULE = 103, - COMMAND_CODE_SET_RELAY_NAME = 104, - COMMAND_CODE_GET_RELAY_NAME = 105, - COMMAND_CODE_PULSE = 200, -} command_code_t; - typedef enum { RELAY_DRIVER_NONE, diff --git a/include/macros.h b/include/macros.h index 9e8f597..63a0b93 100644 --- a/include/macros.h +++ b/include/macros.h @@ -1,13 +1,6 @@ #ifndef CONTROLLER_MACROS_H #define CONTROLLER_MACROS_H -#include -#include +#define STRLEN(s) ((sizeof(s)/sizeof(s[0])) - sizeof(s[0])) -#ifndef SOURCE_PATH_SIZE - #define SOURCE_PATH_SIZE 0 -#endif - -#define __FILENAME__ (__FILE__ + SOURCE_PATH_SIZE) - -#endif //CONTROLLER_MACROS_H +#endif /* CONTROLLER_MACROS_H */ diff --git a/include/models/controller.h b/include/models/controller.h index 96c9282..1cf4fad 100644 --- a/include/models/controller.h +++ b/include/models/controller.h @@ -13,10 +13,12 @@ */ typedef struct { + int id; + /** * @brief A unique UUID for this controller */ - uuid_t id; + uuid_t uid; /** * @brief The name of this controller * @@ -27,14 +29,7 @@ typedef struct * @brief The command port the controller was bound to */ uint16_t command_port; - /** - * @brief The discovery port the controller receives broadcasts on - */ - uint16_t discovery_port; - /** - * @brief Amount of relays available to this controller - */ - uint8_t relay_count; + relay_t **relays; } controller_t; @@ -71,7 +66,7 @@ controller_create(void); * @return A loaded or new instance of controller or NULL on database error */ controller_t* -controller_load(MDB_env *mdb_env); +controller_load(); /** * @brief Save a controller to the database @@ -82,7 +77,7 @@ controller_load(MDB_env *mdb_env); * @return Indicator to show success (0) or failure (!0) */ int -controller_save(controller_t *controller, MDB_env *mdb_env); +controller_save(); /** * @brief Sets a name to a controller. diff --git a/include/models/junction_relay_schedule.h b/include/models/junction_relay_schedule.h new file mode 100644 index 0000000..3a1eccb --- /dev/null +++ b/include/models/junction_relay_schedule.h @@ -0,0 +1,13 @@ +#ifndef CONTROLLER_MODELS_JUNCTION_RELAY_SCHEDULE_H +#define CONTROLLER_MODELS_JUNCTION_RELAY_SCHEDULE_H + +int +junction_relay_schedule_insert(uint8_t weekday, int relay_id, int schedule_id); + +int +junction_relay_schedule_remove_for_relay(int relay_id); + +int +junction_relay_schedule_insert_weekdays(int relay_id, int *schedule_ids); + +#endif /* CONTROLLER_MODELS_JUNCTION_RELAY_SCHEDULE_H */ diff --git a/include/models/period.h b/include/models/period.h index 3c87544..b264ce0 100644 --- a/include/models/period.h +++ b/include/models/period.h @@ -10,10 +10,7 @@ typedef struct uint16_t end; } period_t; -period_t* -period_create(uint16_t start, uint16_t end); - int -period_includes_time(period_t *period, struct tm *time_struct); +period_includes_time(period_t period, struct tm *time_struct); #endif /* CONTROLLER_PERIOD_H */ diff --git a/include/models/relay.h b/include/models/relay.h index c2efd58..6ffb258 100644 --- a/include/models/relay.h +++ b/include/models/relay.h @@ -10,6 +10,7 @@ typedef struct { + int id; uint8_t number; int is_on; int is_on_schedule; @@ -33,26 +34,14 @@ relay_create(uint8_t number); void relay_set_name(relay_t *relay, const char *name); -/** - * @brief Load a relay for database or create a new one - * - * @param mdb_env An opened MDB_env to load from - * - * @return A loaded or new instance of relay - */ relay_t* -relay_load(MDB_env *mdb_env, uint8_t num); +relay_load(uint8_t number); -/** - * @brief Save a relay to the database - * - * @param relay Instance of a relay - * @param mdb_env Already created MDB_env - * - * @return Indicator to show success (0) or failure (!0) - */ int -relay_save(relay_t *relay, MDB_env *mdb_env); +relay_save(relay_t *relay); + +void +relay_reload_schedules(relay_t *relay); int relay_is_on_schedule(relay_t *relay, struct tm *time_struct); diff --git a/include/models/schedule.h b/include/models/schedule.h index 69f6d81..3455e4c 100644 --- a/include/models/schedule.h +++ b/include/models/schedule.h @@ -9,10 +9,11 @@ typedef struct { - uuid_t id; + int id; + uuid_t uid; uint8_t weekday; uint16_t length; - period_t **periods; + period_t *periods; } schedule_t; /** @@ -25,13 +26,16 @@ typedef enum } db_key_schedule_e; schedule_t* -schedule_create(uuid_t id, uint8_t weekday, uint16_t length, uint16_t *periods_blob); - -schedule_t* -schedule_load(MDB_env *mdb_env, uint8_t relay_num, uint8_t weekday); +schedule_create(uuid_t uid, uint16_t length, uint16_t *periods_blob); int -schedule_save(schedule_t *schedule, uint8_t relay_num, MDB_env *mdb_env); +schedule_save(schedule_t *schedule); + +schedule_t* +schedule_get_by_uid(uuid_t uid); + +schedule_t** +schedule_get_relay_weekdays(int relay_id); uint16_t* schedule_periods_to_blob(schedule_t *schedule); @@ -39,7 +43,16 @@ schedule_periods_to_blob(schedule_t *schedule); void schedule_free(schedule_t *schedule); +void +schedule_free_list(schedule_t **schedules_list); + void schedule_debug(schedule_t *schedule); +int +schedule_uid_parse(const char *uid_str, uuid_t result); + +void +schedule_uid_unparse(const uuid_t uid, char *result); + #endif /* CONTROLLER_SCHEDULE_H */ diff --git a/include/runners.h b/include/runners.h index ce74bd2..1eecf37 100644 --- a/include/runners.h +++ b/include/runners.h @@ -6,6 +6,6 @@ #include void -runner_test(controller_t *controller); +runner_test(); #endif /* CONTROLLER_RUNNERS_H */ diff --git a/include/sql/.gitkeep b/include/sql/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/include/sql/migration_0.h b/include/sql/migration_0.h new file mode 100644 index 0000000..fc2ea85 --- /dev/null +++ b/include/sql/migration_0.h @@ -0,0 +1,96 @@ +unsigned char sql_migration_0_sql[] = { + 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x20, 0x74, 0x61, 0x62, 0x6c, 0x65, + 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x73, + 0x0a, 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x64, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x49, 0x4e, 0x54, 0x45, 0x47, 0x45, 0x52, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x50, + 0x52, 0x49, 0x4d, 0x41, 0x52, 0x59, 0x20, 0x4b, 0x45, 0x59, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x41, + 0x55, 0x54, 0x4f, 0x49, 0x4e, 0x43, 0x52, 0x45, 0x4d, 0x45, 0x4e, 0x54, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x75, 0x69, 0x64, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x42, 0x4c, 0x4f, 0x42, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4e, 0x4f, 0x54, 0x20, 0x4e, + 0x55, 0x4c, 0x4c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x55, 0x4e, 0x49, 0x51, 0x55, 0x45, 0x2c, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x56, 0x41, 0x52, 0x43, + 0x48, 0x41, 0x52, 0x28, 0x31, 0x32, 0x38, 0x29, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x5f, 0x70, 0x6f, + 0x72, 0x74, 0x20, 0x20, 0x20, 0x20, 0x49, 0x4e, 0x54, 0x45, 0x47, 0x45, + 0x52, 0x0a, 0x29, 0x3b, 0x0a, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, + 0x20, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x72, 0x65, 0x6c, 0x61, 0x79, + 0x73, 0x0a, 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6e, 0x75, 0x6d, 0x62, + 0x65, 0x72, 0x20, 0x20, 0x49, 0x4e, 0x54, 0x45, 0x47, 0x45, 0x52, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x50, 0x52, 0x49, 0x4d, 0x41, 0x52, 0x59, 0x20, 0x4b, 0x45, 0x59, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x4e, 0x4f, 0x54, 0x20, 0x4e, 0x55, 0x4c, 0x4c, 0x2c, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x20, 0x20, 0x20, 0x56, 0x41, + 0x52, 0x43, 0x48, 0x41, 0x52, 0x28, 0x31, 0x32, 0x38, 0x29, 0x0a, 0x29, + 0x3b, 0x0a, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x20, 0x74, 0x61, + 0x62, 0x6c, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, + 0x73, 0x0a, 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x64, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x49, 0x4e, 0x54, 0x45, 0x47, 0x45, 0x52, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x50, 0x52, 0x49, 0x4d, 0x41, 0x52, 0x59, 0x20, 0x4b, 0x45, 0x59, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x41, 0x55, 0x54, 0x4f, 0x49, 0x4e, 0x43, 0x52, 0x45, 0x4d, 0x45, 0x4e, + 0x54, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x75, 0x69, 0x64, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x42, 0x4c, 0x4f, 0x42, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4e, 0x4f, 0x54, 0x20, + 0x4e, 0x55, 0x4c, 0x4c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x55, 0x4e, 0x49, 0x51, 0x55, 0x45, 0x2c, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x20, 0x20, + 0x20, 0x56, 0x41, 0x52, 0x43, 0x48, 0x41, 0x52, 0x28, 0x31, 0x32, 0x38, + 0x29, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x70, 0x65, 0x72, 0x69, 0x6f, + 0x64, 0x73, 0x20, 0x42, 0x4c, 0x4f, 0x42, 0x0a, 0x29, 0x3b, 0x0a, 0x0a, + 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x20, 0x74, 0x61, 0x62, 0x6c, 0x65, + 0x20, 0x6a, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, + 0x6c, 0x61, 0x79, 0x5f, 0x73, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, + 0x0a, 0x28, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x77, 0x65, 0x65, 0x6b, 0x64, + 0x61, 0x79, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x53, + 0x4d, 0x41, 0x4c, 0x4c, 0x49, 0x4e, 0x54, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x4e, 0x4f, 0x54, 0x20, 0x4e, 0x55, 0x4c, 0x4c, + 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x6c, 0x61, 0x79, 0x5f, + 0x69, 0x64, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x49, 0x4e, + 0x54, 0x45, 0x47, 0x45, 0x52, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x52, 0x45, 0x46, 0x45, 0x52, 0x45, 0x4e, 0x43, 0x45, 0x53, + 0x20, 0x72, 0x65, 0x6c, 0x61, 0x79, 0x73, 0x20, 0x28, 0x69, 0x64, 0x29, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4f, 0x4e, 0x20, + 0x44, 0x45, 0x4c, 0x45, 0x54, 0x45, 0x20, 0x43, 0x41, 0x53, 0x43, 0x41, + 0x44, 0x45, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x73, 0x63, 0x68, 0x65, + 0x64, 0x75, 0x6c, 0x65, 0x5f, 0x69, 0x64, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x49, 0x4e, 0x54, 0x45, 0x47, 0x45, 0x52, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x44, 0x45, 0x46, 0x41, 0x55, 0x4c, 0x54, 0x20, + 0x31, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x52, 0x45, + 0x46, 0x45, 0x52, 0x45, 0x4e, 0x43, 0x45, 0x53, 0x20, 0x73, 0x63, 0x68, + 0x65, 0x64, 0x75, 0x6c, 0x65, 0x73, 0x20, 0x28, 0x69, 0x64, 0x29, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4f, 0x4e, 0x20, 0x44, + 0x45, 0x4c, 0x45, 0x54, 0x45, 0x20, 0x53, 0x45, 0x54, 0x20, 0x44, 0x45, + 0x46, 0x41, 0x55, 0x4c, 0x54, 0x0a, 0x29, 0x3b, 0x0a, 0x0a, 0x49, 0x4e, + 0x53, 0x45, 0x52, 0x54, 0x20, 0x49, 0x4e, 0x54, 0x4f, 0x20, 0x73, 0x63, + 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x73, 0x20, 0x28, 0x75, 0x69, 0x64, + 0x2c, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x20, 0x70, 0x65, 0x72, 0x69, + 0x6f, 0x64, 0x73, 0x29, 0x20, 0x56, 0x41, 0x4c, 0x55, 0x45, 0x53, 0x20, + 0x28, 0x78, 0x27, 0x36, 0x66, 0x36, 0x36, 0x36, 0x36, 0x30, 0x30, 0x30, + 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, + 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x27, + 0x2c, 0x20, 0x27, 0x6f, 0x66, 0x66, 0x27, 0x2c, 0x20, 0x78, 0x27, 0x30, + 0x30, 0x27, 0x29, 0x3b, 0x0a, 0x49, 0x4e, 0x53, 0x45, 0x52, 0x54, 0x20, + 0x49, 0x4e, 0x54, 0x4f, 0x20, 0x73, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, + 0x65, 0x73, 0x20, 0x28, 0x75, 0x69, 0x64, 0x2c, 0x20, 0x6e, 0x61, 0x6d, + 0x65, 0x2c, 0x20, 0x70, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x73, 0x29, 0x20, + 0x56, 0x41, 0x4c, 0x55, 0x45, 0x53, 0x20, 0x28, 0x78, 0x27, 0x36, 0x66, + 0x36, 0x65, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, + 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, + 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x27, 0x2c, 0x20, 0x20, 0x27, 0x6f, + 0x6e, 0x27, 0x2c, 0x20, 0x78, 0x27, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, + 0x30, 0x30, 0x39, 0x46, 0x30, 0x35, 0x27, 0x29, 0x3b, 0x0a, 0x00 +}; +unsigned int sql_migration_0_sql_len = 1114; diff --git a/sql/migration_0.sql b/sql/migration_0.sql new file mode 100644 index 0000000..922c002 --- /dev/null +++ b/sql/migration_0.sql @@ -0,0 +1,47 @@ +create table controllers +( + id INTEGER + PRIMARY KEY + AUTOINCREMENT, + uid BLOB + NOT NULL + UNIQUE, + name VARCHAR(128), + command_port INTEGER +); + +create table relays +( + number INTEGER + PRIMARY KEY + NOT NULL, + name VARCHAR(128) +); + +create table schedules +( + id INTEGER + PRIMARY KEY + AUTOINCREMENT, + uid BLOB + NOT NULL + UNIQUE, + name VARCHAR(128), + periods BLOB +); + +create table junction_relay_schedule +( + weekday SMALLINT + NOT NULL, + relay_id INTEGER + REFERENCES relays (id) + ON DELETE CASCADE, + schedule_id INTEGER + DEFAULT 1 + REFERENCES schedules (id) + ON DELETE SET DEFAULT +); + +INSERT INTO schedules (uid, name, periods) VALUES (x'6f666600000000000000000000000000', 'off', x'00'); +INSERT INTO schedules (uid, name, periods) VALUES (x'6f6e0000000000000000000000000000', 'on', x'010000009F05'); diff --git a/src/connections.c b/src/connections.c index 7b886aa..f32c062 100644 --- a/src/connections.c +++ b/src/connections.c @@ -11,7 +11,7 @@ struct mg_connection* connection_discovery_bind(struct mg_mgr *mgr) { char address[32]; - sprintf(address, "udp://0.0.0.0:%u", global_controller->discovery_port); + sprintf(address, "udp://0.0.0.0:%u", global_config.discovery_port); struct mg_connection *c = mg_bind(mgr, address, handler_discovery); return c; } diff --git a/src/database.c b/src/database.c index ea41e00..1b6b36e 100644 --- a/src/database.c +++ b/src/database.c @@ -1,32 +1,264 @@ -#include +#include +#include #include -#include -#include +#include #include -#include -#include +#include + +#include + +sqlite3 *global_database; +static int in_transaction; void -database_setup(MDB_env **mdb_env, config_t *config) +database_init() { - int err; - - if(mdb_env_create(mdb_env) != 0) + int rc = sqlite3_open(global_config.database, &global_database); + + if(rc) { - LOGGER_CRIT("Can't create mdb handle"); + LOGGER_CRIT("can't open database: %s\n", sqlite3_errmsg(global_database)); exit(1); } - if((err = mdb_env_set_maxdbs(*mdb_env, MDB_MAXDBS)) != 0) - { - LOGGER_CRIT("mdb_env_set_maxdbs error %s\n", mdb_strerror(err)); - exit(1); - } + database_migrate(); - if(mdb_env_open(*mdb_env, config->database, MDB_NOSUBDIR, 0700) != 0) - { - LOGGER_CRIT("Can't open mdb file"); - exit(1); - } + sqlite3_exec(global_database, "PRAGMA foreign_keys = ON", 0, 0, 0); + in_transaction = 0; +} + +void +database_free() +{ + sqlite3_close(global_database); +} + +void +database_migrate() +{ + uint16_t version_num = 0; + int s, rc; + sqlite3_stmt *stmt; + sqlite3_prepare_v2(global_database, "PRAGMA user_version;", -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: + LOGGER_INFO("migrating LEVEL 0\n"); + rc = sqlite3_exec(global_database, (const char *)sql_migration_0_sql, NULL, NULL, &err_msg); + if(rc) + { + LOGGER_CRIT("couldn't migrate LEVEL 0 (%s)\n", err_msg); + exit(1); + } + new_version_num = 1; + default: + break; + } + + char pragma_query[32]; + sprintf(pragma_query, "PRAGMA user_version=%d;", new_version_num); + sqlite3_exec(global_database, pragma_query, 0, 0, 0); + LOGGER_DEBUG("storing new user_version %d\n", new_version_num); + + return; +} + +int +database_transaction_begin() +{ + if(!in_transaction) + { + LOGGER_DEBUG("beginning transaction\n"); + sqlite3_exec(global_database, "BEGIN TRANSACTION;", NULL, NULL, NULL); + in_transaction = 1; + return 1; + } + return 0; +} + +void +database_transaction_commit() +{ + LOGGER_DEBUG("commiting transaction\n"); + sqlite3_exec(global_database, "COMMIT TRANSACTION;", NULL, NULL, NULL); + in_transaction = 0; +} + +void +database_transaction_rollback() +{ + LOGGER_DEBUG("rolling back transaction\n"); + sqlite3_exec(global_database, "ROLLBACK TRANSACTION;", NULL, NULL, NULL); + in_transaction = 0; +} + +int +database_helper_get_id(sqlite3_stmt *stmt) +{ + int result = 0; + + for(;;) + { + int s; + + s = sqlite3_step(stmt); + if (s == SQLITE_ROW) + { + result = sqlite3_column_int(stmt, 0); + } + else + { + if (s == SQLITE_DONE) + { + break; + } + else + { + LOGGER_ERR("error selecting id from database: %s\n", sqlite3_errstr(s)); + sqlite3_finalize(stmt); + return 0; + } + } + } + + sqlite3_finalize(stmt); + + return result; +} + +int* +database_helper_get_ids(sqlite3_stmt *stmt) +{ + int *result = malloc(sizeof(int)); + int new_id; + + int row = 0; + + for(;;) + { + 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++; + + result = (int*)realloc(result, sizeof(int) * (row + 1)); + result[row - 1] = new_id; + } + } + else + { + if (s == SQLITE_DONE) + { + break; + } + else + { + LOGGER_ERR("error selecting ids from database: %s\n", sqlite3_errstr(s)); + sqlite3_finalize(stmt); + return NULL; + } + } + } + + sqlite3_finalize(stmt); + result[row] = 0; + + return result; +} + +char* +database_helper_get_string(sqlite3_stmt *stmt) +{ + char *result = NULL; + + for(;;) + { + int s; + + s = sqlite3_step(stmt); + if (s == SQLITE_ROW) + { + const char *found_string = (const char *)sqlite3_column_text(stmt, 0); + result = (char*)malloc(sizeof(char) * (strlen(found_string) + 1)); + strcpy(result, found_string); + } + else + { + if (s == SQLITE_DONE) + { + break; + } + else + { + LOGGER_ERR("error selecting string from database: %s\n", sqlite3_errstr(s)); + sqlite3_finalize(stmt); + return NULL; + } + } + } + + sqlite3_finalize(stmt); + + return result; +} + +char** +database_helper_get_strings(sqlite3_stmt *stmt) +{ + char **result = malloc(sizeof(char*)); + + int row = 0; + + for(;;) + { + int s; + + s = sqlite3_step(stmt); + if (s == SQLITE_ROW) + { + const char *new_string = (const char *)sqlite3_column_text(stmt, 0); + int new_string_len = strlen(new_string); + row++; + + result = (char**)realloc(result, sizeof(char*) * (row + 1)); + result[row - 1] = malloc(sizeof(char) * (new_string_len + 1)); + strcpy(result[row - 1], new_string); + } + else + { + if(s == SQLITE_DONE) + { + break; + } + else + { + LOGGER_ERR("error selecting strings from database: %s\n", sqlite3_errstr(s)); + break; + } + } + } + sqlite3_finalize(stmt); + result[row] = NULL; + return result; } diff --git a/src/handlers/command.c b/src/handlers/command.c index c72c4bd..ae15e86 100644 --- a/src/handlers/command.c +++ b/src/handlers/command.c @@ -14,16 +14,52 @@ #include #include #include -#include #include +#include +#include #include +#include + +typedef enum +{ + COMMAND_CODE_CONTROLLER_ID_GET = 0, + COMMAND_CODE_CONTROLLER_TIME_GET = 1, + COMMAND_CODE_CONTROLLER_NAME_SET = 2, + COMMAND_CODE_CONTROLLER_NAME_GET = 3, + + COMMAND_CODE_RELAY_SCHEDULES_SET = 100, + COMMAND_CODE_RELAY_SCHEDULES_GET = 101, + COMMAND_CODE_RELAY_NAME_SET = 102, + COMMAND_CODE_RELAY_NAME_GET = 103, + COMMAND_CODE_RELAY_PULSE = 200, + + COMMAND_CODE_SCHEDULE_UPDATE = 300 +} command_code_t; + +typedef enum +{ + COMMAND_MAPPING_CODE = 0, + COMMAND_MAPPING_NAME = 1, + COMMAND_MAPPING_RELAY_NUM = 2, + COMMAND_MAPPING_SCHEDULES_ARRAY = 3, + COMMAND_MAPPING_SCHEDULE_ID = 4, + COMMAND_MAPPING_PERIODS_COUNT = 5, + COMMAND_MAPPING_PERIODS_BLOB = 6, + COMMAND_MAPPING_PULSE_DURATION = 7, +} control_mapping_t; static void -handler_command_pulse(mpack_node_t map, controller_t *controller) +handler_command_relay_pulse(mpack_node_t map) { - int relay_num = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_RELAY_NUM)); + uint8_t relay_num = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_RELAY_NUM)); - relay_t *target_relay = controller->relays[relay_num]; + if(relay_num > global_config.relay_count) + { + LOGGER_WARNING("relay %d is not available (relay count: %d\n", relay_num, global_config.relay_count); + return; + } + + relay_t *target_relay = global_controller->relays[relay_num]; (void)target_relay; int duration = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_PULSE_DURATION)); @@ -36,56 +72,92 @@ handler_command_pulse(mpack_node_t map, controller_t *controller) } static void -handler_command_set_name(mpack_node_t map, controller_t *controller) +handler_command_controller_name_set(mpack_node_t map) { char name_buffer[MAX_NAME_LENGTH + 1]; mpack_node_copy_cstr(mpack_node_map_uint(map, COMMAND_MAPPING_NAME), name_buffer, MAX_NAME_LENGTH + 1); - controller_set_name(controller, name_buffer); + controller_set_name(global_controller, name_buffer); LOGGER_DEBUG("setting new name %s for controller\n", name_buffer); + controller_save(); } static void -handler_command_set_schedule(mpack_node_t map, controller_t *controller) +handler_command_relay_name_set(mpack_node_t map) { uint8_t relay_num = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_RELAY_NUM)); - LOGGER_DEBUG("setting schedules for relay %d\n", relay_num); + const char *relay_name = mpack_node_str(mpack_node_map_uint(map, COMMAND_MAPPING_NAME)); - relay_t *target_relay = controller->relays[relay_num]; + if(relay_num > global_config.relay_count) + { + LOGGER_WARNING("relay %d is not available (relay count: %d\n", relay_num, global_config.relay_count); + return; + } + relay_set_name(global_controller->relays[relay_num], relay_name); + relay_debug(global_controller->relays[relay_num]); + LOGGER_DEBUG("setting new name %s for relay %d\n", relay_name, relay_num); + relay_save(global_controller->relays[relay_num]); +} + +static void +handler_command_schedule_update(mpack_node_t map) +{ + uuid_t schedule_uid; + memcpy(schedule_uid, mpack_node_data(mpack_node_map_uint(map, COMMAND_MAPPING_SCHEDULE_ID)), sizeof(uuid_t)); + + uint16_t periods_count = mpack_node_u16(mpack_node_map_uint(map, COMMAND_MAPPING_PERIODS_COUNT)); + uint16_t *periods = (uint16_t*)mpack_node_bin_data(mpack_node_map_uint(map, COMMAND_MAPPING_PERIODS_BLOB)); + + schedule_t *schedule = schedule_get_by_uid(schedule_uid); + + schedule_t *new_schedule = schedule_create(schedule_uid, periods_count, periods); + + if(schedule) + { + new_schedule->id = schedule->id; + } + schedule_save(new_schedule); + schedule_free(schedule); + schedule_free(new_schedule); +} + +static void +handler_command_relay_schedules_set(mpack_node_t map) +{ + uint8_t relay_num = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_RELAY_NUM)); + + if(relay_num > global_config.relay_count) + { + LOGGER_WARNING("relay %d is not available (relay count: %d\n", relay_num, global_config.relay_count); + return; + } + + LOGGER_DEBUG("setting schedules for relay %d\n", relay_num); + relay_t *target_relay = global_controller->relays[relay_num]; + + database_transaction_begin(); + + junction_relay_schedule_remove_for_relay(target_relay->id); mpack_node_t schedules_array = mpack_node_map_uint(map, COMMAND_MAPPING_SCHEDULES_ARRAY); for(int i = 0; i < 7; ++i) { - mpack_node_t schedules_map = mpack_node_array_at(schedules_array, i); + mpack_node_t schedule_map = mpack_node_array_at(schedules_array, i); - uuid_t schedule_id; - memcpy(schedule_id, mpack_node_data(mpack_node_map_uint(schedules_map, COMMAND_MAPPING_SCHEDULE_ID)), sizeof(uuid_t)); + handler_command_schedule_update(schedule_map); - uint16_t periods_count = mpack_node_u16(mpack_node_map_uint(schedules_map, COMMAND_MAPPING_PERIODS_COUNT)); - uint16_t *periods = (uint16_t*)mpack_node_bin_data(mpack_node_map_uint(schedules_map, COMMAND_MAPPING_PERIODS_BLOB)); + uuid_t schedule_uid; + memcpy(schedule_uid, mpack_node_data(mpack_node_map_uint(schedule_map, COMMAND_MAPPING_SCHEDULE_ID)), sizeof(uuid_t)); - if(target_relay->schedules[i]) - { - schedule_free(target_relay->schedules[i]); - } - target_relay->schedules[i] = schedule_create(schedule_id, i, periods_count, periods); + schedule_t *schedule = schedule_get_by_uid(schedule_uid); + + junction_relay_schedule_insert(i, target_relay->id, schedule->id); } + relay_reload_schedules(target_relay); relay_debug(target_relay); -} -static void -handler_command_set_relay_name(mpack_node_t map, controller_t *controller) -{ - uint8_t relay_num = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_RELAY_NUM)); - const char *relay_name = mpack_node_str(mpack_node_map_uint(map, COMMAND_MAPPING_NAME)); - - if(relay_num < controller->relay_count) - { - relay_set_name(controller->relays[relay_num], relay_name); - } - relay_debug(controller->relays[relay_num]); - LOGGER_DEBUG("setting new name %s for relay %d\n", relay_name, relay_num); + database_transaction_commit(); } void @@ -110,33 +182,36 @@ handler_command(struct mg_connection *c, int ev, void *ev_data) mpack_tree_parse(&tree); mpack_node_t root = mpack_tree_root(&tree); - uint8_t command_code = mpack_node_u8(mpack_node_map_uint(root, COMMAND_MAPPING_CODE)); + uint16_t command_code = mpack_node_u8(mpack_node_map_uint(root, COMMAND_MAPPING_CODE)); LOGGER_DEBUG("received command %d\n", command_code); switch(command_code) { - case COMMAND_CODE_GET_TIME: + case COMMAND_CODE_CONTROLLER_ID_GET: break; - case COMMAND_CODE_GET_ID: + case COMMAND_CODE_CONTROLLER_TIME_GET: break; - case COMMAND_CODE_SET_NAME: - handler_command_set_name(root, global_controller); + case COMMAND_CODE_CONTROLLER_NAME_SET: + handler_command_controller_name_set(root); break; - case COMMAND_CODE_GET_NAME: + case COMMAND_CODE_CONTROLLER_NAME_GET: break; - case COMMAND_CODE_SET_SCHEDULE: - handler_command_set_schedule(root, global_controller); + case COMMAND_CODE_RELAY_SCHEDULES_SET: + handler_command_relay_schedules_set(root); break; - case COMMAND_CODE_GET_SCHEDULE: + case COMMAND_CODE_RELAY_SCHEDULES_GET: break; - case COMMAND_CODE_SET_RELAY_NAME: - handler_command_set_relay_name(root, global_controller); + case COMMAND_CODE_RELAY_NAME_SET: + handler_command_relay_name_set(root); break; - case COMMAND_CODE_GET_RELAY_NAME: + case COMMAND_CODE_RELAY_NAME_GET: break; - case COMMAND_CODE_PULSE: - handler_command_pulse(root, global_controller); + case COMMAND_CODE_RELAY_PULSE: + handler_command_relay_pulse(root); + break; + case COMMAND_CODE_SCHEDULE_UPDATE: + handler_command_schedule_update(root); break; default: LOGGER_ERR("received invalid command\n"); @@ -146,5 +221,4 @@ handler_command(struct mg_connection *c, int ev, void *ev_data) { LOGGER_WARNING("error when destroying mpack tree\n"); } - controller_save(global_controller, global_mdb_env); } diff --git a/src/handlers/discovery.c b/src/handlers/discovery.c index 4f7ec5c..db95e08 100644 --- a/src/handlers/discovery.c +++ b/src/handlers/discovery.c @@ -49,11 +49,11 @@ handler_discovery(struct mg_connection *c, int ev, void *ev_data) mpack_start_map(&writer, 4); mpack_write_uint(&writer, DISCOVERY_MAPPING_ID); - mpack_write_bin(&writer, (char*)global_controller->id, sizeof(uuid_t)); + mpack_write_bin(&writer, (char*)global_controller->uid, sizeof(uuid_t)); mpack_write_uint(&writer, DISCOVERY_MAPPING_COMMAND_PORT); mpack_write_u16(&writer, global_controller->command_port); mpack_write_uint(&writer, DISCOVERY_MAPPING_RELAY_COUNT); - mpack_write_u8(&writer, global_controller->relay_count); + mpack_write_u8(&writer, global_config.relay_count); mpack_write_uint(&writer, DISCOVERY_MAPPING_NAME); mpack_write_cstr(&writer, global_controller->name); mpack_finish_map(&writer); diff --git a/src/handlers/loop.c b/src/handlers/loop.c index b13e45b..76a5999 100644 --- a/src/handlers/loop.c +++ b/src/handlers/loop.c @@ -19,7 +19,7 @@ handler_loop(struct mg_connection *c_mqtt) char topic_buf[100]; char payload_buf[2]; char controller_uid[UUID_STR_LEN]; - uuid_unparse(global_controller->id, controller_uid); + uuid_unparse(global_controller->uid, controller_uid); struct tm time_last, time_now; time_t timestamp; @@ -28,7 +28,7 @@ handler_loop(struct mg_connection *c_mqtt) localtime_r(×tamp, &time_last); timestamp = time(NULL); localtime_r(×tamp, &time_now); - for(uint_fast8_t i = 0; i < global_controller->relay_count; ++i) + for(uint_fast8_t i = 0; i < global_config.relay_count; ++i) { relay_t *relay = global_controller->relays[i]; int is_on = 0; diff --git a/src/main.c b/src/main.c index 883efb8..cd998b6 100644 --- a/src/main.c +++ b/src/main.c @@ -24,8 +24,6 @@ #include config_t global_config; -controller_t *global_controller; -MDB_env *global_mdb_env; static struct mg_mgr mgr; @@ -39,7 +37,7 @@ terminate(int signum) //mg_mgr_free(&mgr); LOGGER_DEBUG("closing database\n"); - mdb_env_close(global_mdb_env); + database_free(); LOGGER_DEBUG("freeing global controller\n"); controller_free(global_controller); @@ -114,13 +112,19 @@ main(int argc, const char** argv) } - /******************** SETUP DATABASE, SOCKETS AND THIS CONTROLLER ********************/ + /******************** INIT DATABASE, SOCKETS AND THIS CONTROLLER ********************/ mg_mgr_init(&mgr, NULL); - database_setup(&global_mdb_env, &global_config); + database_init(); - global_controller = controller_load(global_mdb_env); + global_controller = controller_load(); + if(!global_controller) + { + global_controller = controller_create(); + + controller_save(); + } connection_discovery_bind(&mgr); connection_mqtt_connect(&mgr); @@ -128,7 +132,7 @@ main(int argc, const char** argv) global_controller->command_port = helper_get_port(c_command->sock); - controller_save(global_controller, global_mdb_env); + controller_save(); helper_drop_privileges(); @@ -139,7 +143,7 @@ main(int argc, const char** argv) int piface_setup = 0; - for(uint_fast8_t i = 0; i < global_controller->relay_count; ++i) + for(uint_fast8_t i = 0; i < global_config.relay_count; ++i) { int relay_default = global_config.relay_configs[i].init; if(relay_default == -1) diff --git a/src/models/controller.c b/src/models/controller.c index f44aa21..58c1554 100644 --- a/src/models/controller.c +++ b/src/models/controller.c @@ -4,29 +4,213 @@ #include #include +#include #include -#include +#include #include #include +#include + +controller_t *global_controller; + +static int +db_update_insert(controller_t *controller, sqlite3_stmt *stmt) +{ + LOGGER_DEBUG("saving controller '%s' into database (id: %d)\n", controller->name, controller->id); + 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_int(stmt, 4, controller->command_port); + + 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 'i': // id + new_controller->id = sqlite3_column_int(stmt, i); + break; + case 'c': // command_port + new_controller->command_port = sqlite3_column_int(stmt, i); + break; + case 'n': // name + strncpy(new_controller->name, (const char*)sqlite3_column_text(stmt, i), 127); + 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 = malloc(sizeof(relay_t) * global_config.relay_count); + uint8_t i; + for(i = 0; i < global_config.relay_count; ++i) + { + new_controller->relays[i] = relay_load(new_controller->id); + if(!new_controller->relays[i]) + { + new_controller->relays[i] = relay_create(i); + } + } + return new_controller; +} + +static controller_t** +controller_db_select(sqlite3_stmt *stmt) +{ + controller_t **all_controllers = malloc(sizeof(controller_t*)); + + int row = 0; + + for(;;) + { + 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 + { + LOGGER_ERR("error selecting controllers from database: %s\n", sqlite3_errstr(s)); + break; + } + } + } + sqlite3_finalize(stmt); + all_controllers[row] = NULL; + return all_controllers; +} + +int +controller_save() +{ + int opened_transaction = database_transaction_begin(); + + sqlite3_stmt *stmt; + if(global_controller->id) + { + sqlite3_prepare_v2(global_database, "UPDATE controllers set uid = ?2, name = ?3, command_port = ?4 WHERE id = ?1;", -1, &stmt, NULL); + } + else + { + sqlite3_prepare_v2(global_database, "INSERT INTO controllers(uid, name, command_port) values (?2, ?3, ?4);", -1, &stmt, NULL); + } + + int result = db_update_insert(global_controller, stmt); + + if(result) + { + if(global_controller->id) + { + LOGGER_ERR("error inserting data: %s\n", sqlite3_errmsg(global_database)); + } + else + { + LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database)); + } + + if(opened_transaction) + { + database_transaction_rollback(); + } + } + else + { + if(!global_controller->id) + { + global_controller->id = sqlite3_last_insert_rowid(global_database); + } + + if(opened_transaction) + { + database_transaction_commit(); + } + } + + return result; +} + +controller_t* +controller_load() +{ + LOGGER_DEBUG("getting controller from database\n"); + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT * FROM controllers LIMIT 1;", -1, &stmt, NULL); + + controller_t **sql_result = controller_db_select(stmt); + + controller_t *result = sql_result[0]; + free(sql_result); + 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; +} controller_t* controller_create(void) { controller_t *new_controller = malloc(sizeof(*new_controller)); - uuid_generate(new_controller->id); + new_controller->id = 0; + uuid_generate(new_controller->uid); strncpy(new_controller->name, global_config.name, MAX_NAME_LENGTH); new_controller->name[MAX_NAME_LENGTH] = '\0'; new_controller->command_port = 0; - new_controller->discovery_port = global_config.discovery_port; - new_controller->relay_count = global_config.relay_count; - new_controller->relays = malloc(sizeof(relay_t) * new_controller->relay_count); + new_controller->relays = malloc(sizeof(relay_t) * global_config.relay_count); uint8_t i; - for(i = 0; i < new_controller->relay_count; ++i) + for(i = 0; i < global_config.relay_count; ++i) { - new_controller->relays[i] = relay_create(i); + new_controller->relays[i] = relay_load(new_controller->id); + if(!new_controller->relays[i]) + { + new_controller->relays[i] = relay_create(i); + } } return new_controller; @@ -42,7 +226,7 @@ controller_set_name(controller_t *controller, const char *name) void controller_free(controller_t *controller) { - for(int i = 0; i < controller->relay_count; ++i) + for(int i = 0; i < global_config.relay_count; ++i) { relay_free(controller->relays[i]); } @@ -59,13 +243,11 @@ controller_debug(controller_t *controller) return; } char uuid_str[37]; - uuid_unparse(controller->id, uuid_str); - LOGGER_DEBUG("(1/5) %s @ %p\n", uuid_str, (void*)controller); - LOGGER_DEBUG("(2/5) name: %s\n", controller->name); - LOGGER_DEBUG("(3/5) command_port: %5d discovery_port: %5d\n", controller->command_port, controller->discovery_port); - LOGGER_DEBUG("(4/5) relay count: %3d\n", controller->relay_count); - LOGGER_DEBUG("(5/5) relays @ %p:\n", (void*)controller->relays); - for(int i = 0; i < controller->relay_count; ++i) + uuid_unparse(controller->uid, uuid_str); + LOGGER_DEBUG("(1/3) %s @ %p\n", uuid_str, (void*)controller); + LOGGER_DEBUG("(2/3) name: %s\n", controller->name); + LOGGER_DEBUG("(3/3) relays @ %p:\n", (void*)controller->relays); + for(int i = 0; i < global_config.relay_count; ++i) { relay_debug(controller->relays[i]); } diff --git a/src/models/controller_load.c b/src/models/controller_load.c deleted file mode 100644 index 0b9da30..0000000 --- a/src/models/controller_load.c +++ /dev/null @@ -1,86 +0,0 @@ -#include -#include -#include -#include -#include - -#include -#include - -static void -controller_load_single(MDB_txn *mdb_txn, MDB_dbi mdb_dbi, db_key_controller_e key_controller, MDB_val *value) -{ - int err; - MDB_val key; - - key.mv_size = sizeof(db_key_controller_e); - key.mv_data = &key_controller; - - if((err = mdb_get(mdb_txn, mdb_dbi, &key, value)) != 0) - { - LOGGER_ERR("mdb_get error %s\n", mdb_strerror(err)); - exit(1); - } -} - -controller_t* -controller_load(MDB_env *mdb_env) -{ - int err; - MDB_txn *mdb_txn; - MDB_dbi mdb_dbi; - - controller_t *new_controller; - - LOGGER_DEBUG("loading controller\n"); - - if((err = mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn)) != 0) - { - LOGGER_ERR("mdb_txn_begin error %s\n", mdb_strerror(err)); - return NULL; - } - if((err = mdb_dbi_open(mdb_txn, "controller", 0, &mdb_dbi)) != 0) - { - switch(err) - { - case MDB_NOTFOUND: - LOGGER_INFO("no controller found in db. creating new one\n"); - mdb_txn_abort(mdb_txn); - new_controller = controller_create(); - controller_save(new_controller, mdb_env); - return new_controller; - default: - LOGGER_ERR("mdb_txn_begin error %s\n", mdb_strerror(err)); - return NULL; - } - } - - new_controller = malloc(sizeof(controller_t)); - - MDB_val value; - - controller_load_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_ID, &value); - memmove(new_controller->id, (uuid_t*)value.mv_data, sizeof(uuid_t)); - - controller_load_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_NAME, &value); - strncpy(new_controller->name, (char*)value.mv_data, MAX_NAME_LENGTH); - new_controller->name[MAX_NAME_LENGTH] = '\0'; - - controller_load_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_COMMAND_PORT, &value); - new_controller->command_port = ((uint16_t*)value.mv_data)[0]; - - controller_load_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_DISCOVERY_PORT, &value); - new_controller->discovery_port = ((uint16_t*)value.mv_data)[0]; - - new_controller->relay_count = global_config.relay_count; - - mdb_txn_abort(mdb_txn); // transaction is read only - - new_controller->relays = malloc(sizeof(relay_t*) * new_controller->relay_count); - for(uint8_t i = 0; i < new_controller->relay_count; i++) - { - new_controller->relays[i] = relay_load(mdb_env, i); - } - - return new_controller; -} diff --git a/src/models/controller_save.c b/src/models/controller_save.c deleted file mode 100644 index 59457f8..0000000 --- a/src/models/controller_save.c +++ /dev/null @@ -1,91 +0,0 @@ -#include -#include -#include -#include -#include - -#include -#include - -int -controller_save_single(MDB_txn *mdb_txn, MDB_dbi mdb_dbi, db_key_controller_e key_controller, MDB_val value) -{ - int err; - - MDB_val key; - key.mv_size = sizeof(db_key_controller_e); - key.mv_data = &key_controller; - - if((err = mdb_put(mdb_txn, mdb_dbi, &key, &value, 0)) != 0) - { - LOGGER_ERR("mdb_put error %s\n", mdb_strerror(err)); - mdb_txn_abort(mdb_txn); - return 1; - } - return 0; -} - -int -controller_save(controller_t *controller, MDB_env *mdb_env) -{ - int err; - - MDB_txn *mdb_txn; - MDB_dbi mdb_dbi; - MDB_val value; - - LOGGER_DEBUG("saving controller\n"); - - if((err = mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn)) != 0) - { - LOGGER_ERR("mdb_txn_begin error %s\n", mdb_strerror(err)); - exit(1); - } - - if((err = mdb_dbi_open(mdb_txn, "controller", MDB_CREATE, &mdb_dbi)) != 0) - { - LOGGER_ERR("mdb_dbi_open error %s\n", mdb_strerror(err)); - exit(1); - } - - value.mv_size = sizeof(uuid_t); - value.mv_data = controller->id; - if(controller_save_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_ID, value)) - { - LOGGER_ERR("failed to save ID\n"); - return 1; - } - - value.mv_size = sizeof(char) * (strlen(controller->name) + 1); - value.mv_data = controller->name; - if(controller_save_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_NAME, value)) - { - LOGGER_ERR("failed to save name\n"); - return 1; - } - - value.mv_size = sizeof(controller->command_port); - value.mv_data = &controller->command_port; - if(controller_save_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_COMMAND_PORT, value)) - { - LOGGER_ERR("failed to save command port\n"); - return 1; - } - - value.mv_size = sizeof(controller->discovery_port); - value.mv_data = &controller->discovery_port; - if(controller_save_single(mdb_txn, mdb_dbi, DB_KEY_CONTROLLER_DISCOVERY_PORT, value)) - { - LOGGER_ERR("failed to save discovery port\n"); - return 1; - } - - mdb_txn_commit(mdb_txn); - - for(uint8_t i = 0; i < controller->relay_count; ++i) - { - relay_save(controller->relays[i], mdb_env); - } - - return 0; -} diff --git a/src/models/junction_relay_schedule.c b/src/models/junction_relay_schedule.c new file mode 100644 index 0000000..fca0ffd --- /dev/null +++ b/src/models/junction_relay_schedule.c @@ -0,0 +1,90 @@ +#include +#include +#include +#include + +#include +#include +#include +#include + +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) + { + LOGGER_ERR("error inserting data: %s", sqlite3_errmsg(global_database)); + return false; + } + + sqlite3_finalize(stmt); + + return true; +} + +int +junction_relay_schedule_insert_weekdays(int relay_id, int *schedule_ids) +{ + int rc; + sqlite3_stmt *stmt; + + static const char query_base[] = "INSERT INTO junction_relay_schedule (weekday, schedule_id, relay_id) VALUES"; + static const char query_extender[] = " (?, ?, ?)"; + + size_t query_len = STRLEN(query_base) + (7 * (STRLEN(query_extender) + 1)) + 1; + char *query = malloc(sizeof(char) * query_len + 1); + strncpy(query, query_base, query_len); + query_len -= STRLEN(query_base); + for(int i = 0; i < 7; ++i) + { + strncat(query, query_extender, query_len); + query_len -= STRLEN(query_extender); + char *query_divider = (i < 7 - 1) ? "," : ";"; + strncat(query, query_divider, query_len); + query_len -= 1; + } + + sqlite3_prepare_v2(global_database, query, -1, &stmt, NULL); + + for(int i = 0; i < 7; ++i) + { + sqlite3_bind_int(stmt, i * 3 + 1, i); + sqlite3_bind_int(stmt, i * 3 + 2, schedule_ids[i]); + sqlite3_bind_int(stmt, i * 3 + 3, relay_id); + } + + rc = sqlite3_step(stmt); + if (rc != SQLITE_DONE) + { + LOGGER_ERR("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; +} diff --git a/src/models/period.c b/src/models/period.c index d3a7369..8ad53c4 100644 --- a/src/models/period.c +++ b/src/models/period.c @@ -4,21 +4,11 @@ #include #include -period_t* -period_create(uint16_t start, uint16_t end) -{ - period_t *new_period = malloc(sizeof(period_t)); - new_period->start = start; - new_period->end = end; - - return new_period; -} - int -period_includes_time(period_t *period, struct tm *time_struct) +period_includes_time(period_t period, struct tm *time_struct) { - uint16_t start = period->start; - uint16_t end = period->end; + uint16_t start = period.start; + uint16_t end = period.end; time_t timestamp = time_struct->tm_hour * 60; timestamp += time_struct->tm_min; diff --git a/src/models/relay.c b/src/models/relay.c index 9469200..317f575 100644 --- a/src/models/relay.c +++ b/src/models/relay.c @@ -4,7 +4,173 @@ #include #include +#include #include +#include + +static int +db_update_insert(relay_t *relay, sqlite3_stmt *stmt) +{ + LOGGER_DEBUG("saving relay '%s' into database (id: %d)\n", relay->name, relay->id); + 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); + + 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)); + new_relay->is_on = 0; + + for(int i = 0; i < sqlite3_column_count(stmt); i++) + { + const char *name = sqlite3_column_name(stmt, i); + switch(name[0]) + { + 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) + { + LOGGER_ERR("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 + + 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 + { + LOGGER_ERR("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) +{ + int opened_transaction = database_transaction_begin(); + + 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) + { + LOGGER_ERR("error inserting data: %s\n", sqlite3_errmsg(global_database)); + } + else + { + LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database)); + } + + if(opened_transaction) + { + database_transaction_rollback(); + } + } + else + { + if(relay->id == 0) + { + relay->id = sqlite3_last_insert_rowid(global_database); + } + + LOGGER_DEBUG("cleaning relay_schedule junction\n"); + junction_relay_schedule_remove_for_relay(relay->id); + + LOGGER_DEBUG("rebuilding relay_schedule junction\n"); + int schedule_ids[7]; + for(int i = 0; i < 7; ++i) + { + schedule_ids[i] = relay->schedules[i]->id; + } + junction_relay_schedule_insert_weekdays(relay->id, schedule_ids); + + if(opened_transaction) + { + database_transaction_commit(); + } + } + + return result; +} + relay_t* relay_create(uint8_t number) @@ -25,12 +191,52 @@ relay_create(uint8_t number) for(int i = 0; i < 7; ++i) { - new_relay->schedules[i] = schedule_create(off_id, i, 0, NULL); + new_relay->schedules[i] = schedule_get_by_uid(off_id); } return new_relay; } +relay_t* +relay_load(uint8_t number) +{ + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT * FROM relays WHERE number = ?1;", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, number); + + relay_t **sql_result = relay_db_select(stmt); + + relay_t *result = sql_result[0]; + free(sql_result); + + return result; +} + +void +relay_reload_schedules(relay_t *relay) +{ + schedule_t **schedules = schedule_get_relay_weekdays(relay->id); + for(int i = 0; i < 7; ++i) + { + if(schedules[i] == NULL) + { + LOGGER_ERR("got only %d/7 schedules for relay_id %d\n", i, relay->id); + relay_free(relay); + schedule_free_list(schedules); + return; + } + } + + + for(int i = 0; i < 7; ++i) + { + schedule_free(relay->schedules[i]); + relay->schedules[i] = schedules[i]; + } + free(schedules); // don't free list, because contents are kept in relay->schedules +} + void relay_set_name(relay_t *relay, const char *name) { diff --git a/src/models/relay_load.c b/src/models/relay_load.c deleted file mode 100644 index 8186092..0000000 --- a/src/models/relay_load.c +++ /dev/null @@ -1,95 +0,0 @@ -#include -#include -#include -#include -#include - -#include -#include - -static int -relay_load_single(MDB_txn *mdb_txn, MDB_dbi mdb_dbi, db_key_relay_e key_relay, uint8_t relay_num, MDB_val *value) -{ - int err; - - size_t key_size = sizeof(db_key_relay_e) + sizeof(uint8_t); - uint8_t *key_data = malloc(key_size); - uint8_t *key_data_writer = key_data; - memmove(key_data_writer, &relay_num, sizeof(uint8_t)); - key_data_writer += sizeof(uint8_t); - memmove(key_data_writer, &key_relay, sizeof(db_key_relay_e)); - - MDB_val key; - key.mv_size = key_size; - key.mv_data = key_data; - - if((err = mdb_get(mdb_txn, mdb_dbi, &key, value)) != 0) - { - LOGGER_ERR("mdb_get error %s\n", mdb_strerror(err)); - mdb_txn_abort(mdb_txn); - free(key_data); - return 1; - } - free(key_data); - return 0; -} - -relay_t* -relay_load(MDB_env *mdb_env, uint8_t num) -{ - int err; - MDB_txn *mdb_txn; - MDB_dbi mdb_dbi; - - relay_t *new_relay; - - LOGGER_DEBUG("loading relay %d\n", num); - - if((err = mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn)) != 0) - { - LOGGER_ERR("mdb_txn_begin error %s\n", mdb_strerror(err)); - return relay_create(num); - } - - if((err = mdb_dbi_open(mdb_txn, "relays", 0, &mdb_dbi)) != 0) - { - switch(err) - { - case MDB_NOTFOUND: - LOGGER_INFO("no relay for num %d found in db. returning new one (no relays db)\n", num); - mdb_txn_abort(mdb_txn); - return relay_create(num); - default: - LOGGER_ERR("mdb_txn_begin error %s\n", mdb_strerror(err)); - return relay_create(num); - } - } - - new_relay = malloc(sizeof(relay_t)); - new_relay->number = num; - - new_relay->is_on = -1; - new_relay->is_on_schedule = -1; - new_relay->pulse_timer = 0; - new_relay->sent_to_broker = 0; - - MDB_val value; - - if((err = relay_load_single(mdb_txn, mdb_dbi, DB_KEY_RELAY_NAME, num, &value)) != 0) - { - LOGGER_INFO("no relay for num %d found in db. returning new one\n", num); - mdb_txn_abort(mdb_txn); // transaction is read only - return relay_create(num); - } - strncpy(new_relay->name, (char*)value.mv_data, MAX_NAME_LENGTH); - new_relay->name[MAX_NAME_LENGTH] = '\0'; - - mdb_txn_abort(mdb_txn); // transaction is read only - - for(int i = 0; i < 7; ++i) - { - new_relay->schedules[i] = schedule_load(mdb_env, num, i); - } - - return new_relay; -} diff --git a/src/models/relay_save.c b/src/models/relay_save.c deleted file mode 100644 index 86b4714..0000000 --- a/src/models/relay_save.c +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include -#include -#include -#include - -#include -#include - -static int -relay_save_single(MDB_txn *mdb_txn, MDB_dbi mdb_dbi, db_key_relay_e key_relay, uint8_t relay_num, MDB_val value) -{ - int err; - - size_t key_size = sizeof(db_key_relay_e) + sizeof(uint8_t); - uint8_t *key_data = malloc(key_size); - uint8_t *key_data_writer = key_data; - memmove(key_data_writer, &relay_num, sizeof(uint8_t)); - key_data_writer += sizeof(uint8_t); - memmove(key_data_writer, &key_relay, sizeof(db_key_relay_e)); - - MDB_val key; - key.mv_size = key_size; - key.mv_data = key_data; - - if((err = mdb_put(mdb_txn, mdb_dbi, &key, &value, 0)) != 0) - { - LOGGER_ERR("mdb_put error %s\n", mdb_strerror(err)); - mdb_txn_abort(mdb_txn); - free(key_data); - return 1; - } - free(key_data); - return 0; -} - -int -relay_save(relay_t *relay, MDB_env *mdb_env) -{ - int err; - - MDB_txn *mdb_txn; - MDB_dbi mdb_dbi; - MDB_val value; - - LOGGER_DEBUG("saving relay %d\n", relay->number); - - if((err = mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn)) != 0) - { - LOGGER_ERR("mdb_txn_begin error %s\n", mdb_strerror(err)); - exit(1); - } - - if((err = mdb_dbi_open(mdb_txn, "relays", MDB_CREATE, &mdb_dbi)) != 0) - { - LOGGER_ERR("mdb_dbi_open error %s\n", mdb_strerror(err)); - exit(1); - } - - value.mv_size = sizeof(char) * (strlen(relay->name) + 1); - value.mv_data = relay->name; - if(relay_save_single(mdb_txn, mdb_dbi, DB_KEY_RELAY_NAME, relay->number, value)) - { - LOGGER_ERR("failed to save name\n"); - return 1; - } - - mdb_txn_commit(mdb_txn); - - for(int i = 0; i < 7; ++i) - { - schedule_save(relay->schedules[i], relay->number, mdb_env); - } - - return 0; -} diff --git a/src/models/schedule.c b/src/models/schedule.c index 8485444..188358e 100644 --- a/src/models/schedule.c +++ b/src/models/schedule.c @@ -2,29 +2,203 @@ #include #include +#include #include +#include + +static int +db_update_insert(schedule_t *schedule, sqlite3_stmt *stmt) +{ + char uuid_str[UUID_STR_LEN]; + uuid_unparse(schedule->uid, uuid_str); + LOGGER_DEBUG("saving schedule '%s' into database (id: %d)\n", uuid_str, schedule->id); + + 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_blob(stmt, 3, 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 'p': // periods + periods_blob = sqlite3_column_blob(stmt, i); + 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; + + for(;;) + { + 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 + { + LOGGER_ERR("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) +{ + int opened_transaction = database_transaction_begin(); + + sqlite3_stmt *stmt; + if(schedule->id) + { + sqlite3_prepare_v2(global_database, "UPDATE schedules SET uid = ?2, periods = ?3 WHERE id=?1;", -1, &stmt, NULL); + } + else + { + sqlite3_prepare_v2(global_database, "INSERT INTO schedules(uid, periods) values (?2, ?3);", -1, &stmt, NULL); + } + + int result = db_update_insert(schedule, stmt); + + if(result) + { + if(schedule->id) + { + LOGGER_ERR("error inserting data: %s\n", sqlite3_errmsg(global_database)); + } + else + { + LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database)); + } + + if(opened_transaction) + { + database_transaction_rollback(); + } + } + else + { + if(!schedule->id) + { + schedule->id = sqlite3_last_insert_rowid(global_database); + } + + if(opened_transaction) + { + database_transaction_commit(); + } + } + + return result; +} + +schedule_t** +schedule_get_relay_weekdays(int relay_id) +{ + LOGGER_DEBUG("getting schedules [relay_id=%d] from database\n", 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_create(uuid_t id, uint8_t weekday, uint16_t length, uint16_t *periods_blob) +schedule_get_by_uid(uuid_t uid) +{ + char uuid_str[UUID_STR_LEN]; + schedule_uid_unparse(uid, uuid_str); + LOGGER_DEBUG("getting schedule [uid=%s] from database\n", uuid_str); + 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_create(uuid_t uid, uint16_t length, uint16_t *periods_blob) { schedule_t *new_schedule = malloc(sizeof(schedule_t)); - memmove(new_schedule->id, id, sizeof(uuid_t)); - - new_schedule->weekday = weekday; + memmove(new_schedule->uid, uid, sizeof(uuid_t)); new_schedule->length = length; new_schedule->periods = NULL; if(length) { - new_schedule->periods = malloc(sizeof(period_t*) * length); + new_schedule->periods = malloc(sizeof(period_t) * length); for(uint16_t i = 0; i < length; ++i) { - uint16_t start = periods_blob[0 + (i * 2)]; - uint16_t end = periods_blob[1 + (i * 2)]; - new_schedule->periods[i] = period_create(start, end); + new_schedule->periods[i].start = periods_blob[0 + (i * 2)]; + new_schedule->periods[i].end = periods_blob[1 + (i * 2)]; } } @@ -40,24 +214,77 @@ schedule_periods_to_blob(schedule_t *schedule) for(uint16_t i = 0; i < schedule->length; ++i) { - periods_blob[1 + (i * 2)] = schedule->periods[i]->start; - periods_blob[2 + (i * 2)] = schedule->periods[i]->end; + periods_blob[1 + (i * 2)] = schedule->periods[i].start; + periods_blob[2 + (i * 2)] = schedule->periods[i].end; } return periods_blob; } +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); +} + void schedule_free(schedule_t *schedule) { - for(uint16_t i = 0; i < schedule->length; ++i) - { - free(schedule->periods[i]); - } 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); +} + void schedule_debug(schedule_t *schedule) { @@ -67,7 +294,7 @@ schedule_debug(schedule_t *schedule) return; } char uuid_str[UUID_STR_LEN]; - uuid_unparse(schedule->id, uuid_str); + uuid_unparse(schedule->uid, uuid_str); LOGGER_DEBUG("(1/3) %s @ %p\n", uuid_str, (void*)schedule); LOGGER_DEBUG("(2/4) period count: %3d\n", schedule->length); LOGGER_DEBUG("(3/4) weekday: %3d\n", schedule->weekday); @@ -81,10 +308,10 @@ schedule_debug(schedule_t *schedule) sprintf( periods_debug_str + (13 * i), "%02d:%02d-%02d:%02d, ", - schedule->periods[i]->start / 60, - schedule->periods[i]->start % 60, - schedule->periods[i]->end / 60, - schedule->periods[i]->end % 60 + schedule->periods[i].start / 60, + schedule->periods[i].start % 60, + schedule->periods[i].end / 60, + schedule->periods[i].end % 60 ); } diff --git a/src/models/schedule_load.c b/src/models/schedule_load.c deleted file mode 100644 index ccfde1a..0000000 --- a/src/models/schedule_load.c +++ /dev/null @@ -1,98 +0,0 @@ -#include -#include -#include -#include -#include - -#include -#include - -static int -schedule_load_single(MDB_txn *mdb_txn, MDB_dbi mdb_dbi, db_key_schedule_e key_schedule, uint8_t relay_num, uint8_t weekday, MDB_val *value) -{ - int err; - - size_t key_size = sizeof(db_key_schedule_e) + (2 * sizeof(uint8_t)); - uint8_t *key_data = malloc(key_size); - uint8_t *key_data_writer = key_data; - memmove(key_data_writer, &relay_num, sizeof(uint8_t)); - key_data_writer += sizeof(uint8_t); - memmove(key_data_writer, &weekday, sizeof(uint8_t)); - key_data_writer += sizeof(uint8_t); - memmove(key_data_writer, &key_schedule, sizeof(db_key_schedule_e)); - - MDB_val key; - key.mv_size = key_size; - key.mv_data = key_data; - - if((err = mdb_get(mdb_txn, mdb_dbi, &key, value)) != 0) - { - LOGGER_ERR("mdb_get error %s\n", mdb_strerror(err)); - mdb_txn_abort(mdb_txn); - free(key_data); - return 1; - } - free(key_data); - return 0; -} - -schedule_t* -schedule_load(MDB_env *mdb_env, uint8_t relay_num, uint8_t weekday) -{ - int err; - MDB_txn *mdb_txn; - MDB_dbi mdb_dbi; - - schedule_t *new_schedule; - - uuid_t off_id; - memset(off_id, 0, sizeof(uuid_t)); - memcpy(off_id, "off", 3); - - LOGGER_DEBUG("loading schedule %d for relay %d\n", weekday, relay_num); - - if((err = mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn)) != 0) - { - LOGGER_ERR("mdb_txn_begin error %s\n", mdb_strerror(err)); - return schedule_create(off_id, weekday, 0, NULL); - } - - if((err = mdb_dbi_open(mdb_txn, "schedules", 0, &mdb_dbi)) != 0) - { - switch(err) - { - case MDB_NOTFOUND: - LOGGER_INFO("no schedule db found in db. returning new one (no schedules db)\n"); - mdb_txn_abort(mdb_txn); - break; - default: - LOGGER_ERR("mdb_txn_begin error %s\n", mdb_strerror(err)); - } - return schedule_create(off_id, weekday, 0, NULL); - } - - MDB_val value; - - if((err = schedule_load_single(mdb_txn, mdb_dbi, DB_KEY_SCHEDULE_ID, relay_num, weekday, &value)) != 0) - { - LOGGER_INFO("no schedule for relay %d and weekday %d found in db. returning new one\n", relay_num, weekday); - mdb_txn_abort(mdb_txn); // transaction is read only - return schedule_create(off_id, weekday, 0, NULL); - } - uuid_t *schedule_id = (uuid_t*)value.mv_data; - - if((err = schedule_load_single(mdb_txn, mdb_dbi, DB_KEY_SCHEDULE_PERIODS, relay_num, weekday, &value)) != 0) - { - LOGGER_INFO("no schedule for relay %d and weekday %d found in db. returning new one\n", relay_num, weekday); - mdb_txn_abort(mdb_txn); // transaction is read only - return schedule_create(off_id, weekday, 0, NULL); - } - uint16_t schedule_periods_length = ((uint16_t*)value.mv_data)[0]; - uint16_t *schedule_periods = ((uint16_t*)value.mv_data) + 1; - - new_schedule = schedule_create(*schedule_id, weekday, schedule_periods_length, schedule_periods); - - mdb_txn_abort(mdb_txn); // transaction is read only - - return new_schedule; -} diff --git a/src/models/schedule_save.c b/src/models/schedule_save.c deleted file mode 100644 index c742c7a..0000000 --- a/src/models/schedule_save.c +++ /dev/null @@ -1,88 +0,0 @@ -#include -#include -#include -#include -#include - -#include -#include -#include - -static int -schedule_save_single(MDB_txn *mdb_txn, MDB_dbi mdb_dbi, db_key_schedule_e key_schedule, uint8_t relay_num, uint8_t weekday, MDB_val value) -{ - int err; - - size_t key_size = sizeof(db_key_schedule_e) + (2 * sizeof(uint8_t)); - uint8_t *key_data = malloc(key_size); - uint8_t *key_data_writer = key_data; - memmove(key_data_writer, &relay_num, sizeof(uint8_t)); - key_data_writer += sizeof(uint8_t); - memmove(key_data_writer, &weekday, sizeof(uint8_t)); - key_data_writer += sizeof(uint8_t); - memmove(key_data_writer, &key_schedule, sizeof(db_key_schedule_e)); - - MDB_val key; - key.mv_size = key_size; - key.mv_data = key_data; - - if((err = mdb_put(mdb_txn, mdb_dbi, &key, &value, 0)) != 0) - { - LOGGER_ERR("mdb_put error %s\n", mdb_strerror(err)); - mdb_txn_abort(mdb_txn); - free(key_data); - return 1; - } - free(key_data); - return 0; -} - -int -schedule_save(schedule_t *schedule, uint8_t relay_num, MDB_env *mdb_env) -{ - char uuid_str[37]; - uuid_unparse(schedule->id, uuid_str); - int err; - - MDB_txn *mdb_txn; - MDB_dbi mdb_dbi; - MDB_val value; - - LOGGER_DEBUG("saving schedule %d for relay %d\n", schedule->weekday, relay_num); - - if((err = mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn)) != 0) - { - LOGGER_ERR("mdb_txn_begin error %s\n", mdb_strerror(err)); - exit(1); - } - - if((err = mdb_dbi_open(mdb_txn, "schedules", MDB_CREATE, &mdb_dbi)) != 0) - { - LOGGER_ERR("mdb_dbi_open error %s\n", mdb_strerror(err)); - exit(1); - } - - value.mv_size = sizeof(uuid_t); - value.mv_data = schedule->id; - if(schedule_save_single(mdb_txn, mdb_dbi, DB_KEY_SCHEDULE_ID, relay_num, schedule->weekday, value)) - { - LOGGER_ERR("failed to save ID\n"); - return 1; - } - - // save periods blob - uint16_t *periods_blob = schedule_periods_to_blob(schedule); - value.mv_size = sizeof(uint16_t) * ((periods_blob[0] * 2) + 1); - value.mv_data = periods_blob; - if(schedule_save_single(mdb_txn, mdb_dbi, DB_KEY_SCHEDULE_PERIODS, relay_num, schedule->weekday, value)) - { - free(periods_blob); - LOGGER_ERR("failed to save periods\n"); - return 1; - } - free(periods_blob); - - mdb_txn_commit(mdb_txn); - - return 0; -} diff --git a/src/runners/test.c b/src/runners/test.c index f2cd2ce..2eec714 100644 --- a/src/runners/test.c +++ b/src/runners/test.c @@ -6,10 +6,10 @@ #include void -runner_test(controller_t *controller) +runner_test() { // from x down to 0 to turn all relays off in the end - for(uint_fast8_t i = 0; i < controller->relay_count; ++i) + for(uint_fast8_t i = 0; i < global_config.relay_count; ++i) { for(int test_run = 2; test_run >= 0; --test_run) {