Merge branch 'testing'

This commit is contained in:
Tobias Reisinger 2020-07-01 23:21:36 +02:00
commit e5419ed1fd
54 changed files with 22888 additions and 318 deletions

27
.drone.yml Normal file
View file

@ -0,0 +1,27 @@
kind: pipeline
name: default
workspace:
path: /drone/src
steps:
- name: build
image: serguzim/emgauwa-builder
pull: always
commands:
- mkdir build
- cd build
- cmake ..
- make
- name: gitea_release
image: plugins/gitea-release
settings:
api_key:
from_secret: gitea_token
base_url: https://git.serguzim.me
files:
- build/controller
- build/controller.ini
when:
event: tag

12
.editorconfig Normal file
View file

@ -0,0 +1,12 @@
# EditorConfig is awesome:
https://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4

View file

@ -1,48 +1,54 @@
cmake_minimum_required (VERSION 3.7) cmake_minimum_required (VERSION 3.7)
project(controller) project(controller
VERSION 0.2.2
LANGUAGES C)
add_executable(controller main.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 -luuid)
option(WIRING_PI_DEBUG "Use WiringPi Debugging Tool (OFF)" OFF) option(WIRING_PI_DEBUG "Use WiringPi Debugging Tool (OFF)" OFF)
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99 -Wall -Wextra -Werror -Wpedantic -lwiringPi -lwiringPiDev -luuid -llmdb -g") SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99 -Wpedantic -Werror -Wall -Wextra -ffile-prefix-map=${CMAKE_SOURCE_DIR}/src/=")
string(LENGTH "${CMAKE_SOURCE_DIR}/" SOURCE_PATH_SIZE) set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g -fprofile-arcs -ftest-coverage")
add_definitions("-DSOURCE_PATH_SIZE=${SOURCE_PATH_SIZE}")
if(WIRING_PI_DEBUG) if(WIRING_PI_DEBUG)
message("Showing wiringPi calls as debug") message("Showing wiringPi calls as debug")
add_definitions("-DWIRING_PI_DEBUG") add_definitions("-DWIRING_PI_DEBUG")
endif(WIRING_PI_DEBUG) endif(WIRING_PI_DEBUG)
aux_source_directory(vendor VENDOR_SRC) # vendor first to put their warnings on top aux_source_directory(src/ SRC_DIR)
aux_source_directory(. SRC_DIR) aux_source_directory(src/models MODELS_SRC)
aux_source_directory(models MODELS_SRC) aux_source_directory(src/helpers HELPERS_SRC)
aux_source_directory(helpers HELPERS_SRC) aux_source_directory(src/handlers HANDLERS_SRC)
aux_source_directory(handlers HANDLERS_SRC) aux_source_directory(src/drivers DRIVERS_SRC)
aux_source_directory(drivers DRIVERS_SRC) aux_source_directory(src/runners RUNNERS_SRC)
aux_source_directory(runners RUNNERS_SRC)
configure_file("controller.ini" "controller.ini" COPYONLY) configure_file("controller.ini" "controller.ini" COPYONLY)
configure_file("version.h.in" "version.h" @ONLY)
target_sources(controller PRIVATE ${VENDOR_SRC} ${SRC_DIR} ${MODELS_SRC} ${HELPERS_SRC} ${HANDLERS_SRC} ${DRIVERS_SRC} ${RUNNERS_SRC}) target_sources(controller PRIVATE ${SRC_DIR} ${MODELS_SRC} ${HELPERS_SRC} ${HANDLERS_SRC} ${DRIVERS_SRC} ${RUNNERS_SRC})
target_include_directories(controller PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) 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(run add_custom_target(run
COMMAND ./controller start COMMAND ./controller start
DEPENDS controller DEPENDS controller
WORKING_DIRECTORY ${CMAKE_PROJECT_DIR} WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
) )
add_custom_target(debug add_custom_target(debug
COMMAND valgrind ./controller start COMMAND valgrind ./controller start
DEPENDS controller DEPENDS controller
WORKING_DIRECTORY ${CMAKE_PROJECT_DIR} WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
) )
add_custom_target(debug-full add_custom_target(debug-full
COMMAND valgrind --leak-check=full --show-leak-kinds=all ./controller start COMMAND valgrind --leak-check=full --show-leak-kinds=all ./controller start
DEPENDS controller DEPENDS controller
WORKING_DIRECTORY ${CMAKE_PROJECT_DIR} WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
) )
add_custom_target(docs add_custom_target(docs
COMMAND doxygen COMMAND doxygen

View file

@ -1,6 +1,11 @@
[controller] [controller]
name = new emgauwa device name = new emgauwa device
: 4422 for testing; 4421 for dev-env; 4420 for testing-env; 4419 for prod-env
discovery-port = 4421 discovery-port = 4421
: 1886 for testing; 1885 for dev-env; 1884 for testing-env; 1883 for prod-env
mqtt-port = 1885
relay-count = 10 relay-count = 10
database = controller_db.lmdb database = controller_db.lmdb
log-level = debug log-level = debug
@ -39,11 +44,13 @@ inverted = 1
driver = gpio driver = gpio
pin = 1 pin = 1
inverted = 1 inverted = 1
pulse-duration = 3
[relay-7] [relay-7]
driver = gpio driver = gpio
pin = 0 pin = 0
inverted = 1 inverted = 1
pulse-duration = 3
[relay-8] [relay-8]
driver = gpio driver = gpio

View file

@ -1,89 +0,0 @@
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <uuid/uuid.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <errno.h>
#include <logger.h>
#include <handlers.h>
#include <helpers.h>
#include <mpack.h>
#include <enums.h>
void
handler_discovery(int fd, controller_t *controller)
{
ssize_t bytes_transferred;
uint16_t discovery_answer_port;
struct sockaddr_in si_other;
socklen_t slen = sizeof(si_other);
if((bytes_transferred = recvfrom(fd, &discovery_answer_port, sizeof(discovery_answer_port), 0, (struct sockaddr *) &si_other, &slen)) <= 0)
{
LOG_ERROR("received invalid discovery from %s\n", inet_ntoa(si_other.sin_addr));
return;
}
LOG_INFO("received discovery from %s:%d\n", inet_ntoa(si_other.sin_addr), discovery_answer_port);
if(discovery_answer_port == 0)
{
LOG_ERROR("invalid port received\n");
return;
}
char* payload;
size_t payload_size;
mpack_writer_t writer;
mpack_writer_init_growable(&writer, &payload, &payload_size);
mpack_start_map(&writer, 4);
mpack_write_uint(&writer, DISCOVERY_MAPPING_ID);
mpack_write_bin(&writer, (char*)controller->id, sizeof(uuid_t));
mpack_write_uint(&writer, DISCOVERY_MAPPING_COMMAND_PORT);
mpack_write_u16(&writer, controller->command_port);
mpack_write_uint(&writer, DISCOVERY_MAPPING_RELAY_COUNT);
mpack_write_u8(&writer, controller->relay_count);
mpack_write_uint(&writer, DISCOVERY_MAPPING_NAME);
mpack_write_cstr(&writer, controller->name);
mpack_finish_map(&writer);
// finish writing
if(mpack_writer_destroy(&writer) != mpack_ok)
{
LOG_ERROR("error writing discovery answer payload\n");
return;
}
int fd_answer = helper_connect_tcp_server(inet_ntoa(si_other.sin_addr), discovery_answer_port);
if(fd_answer == -1)
{
LOG_ERROR("error during connecting\n");
free(payload);
return;
}
if((bytes_transferred = send(fd_answer, &payload_size, sizeof(payload_size), 0)) <= 0)
{
LOG_ERROR("error during sending\n");
free(payload);
close(fd_answer);
return;
}
if((bytes_transferred = send(fd_answer, payload, payload_size, 0)) <= 0)
{
LOG_ERROR("error during sending\n");
free(payload);
close(fd_answer);
return;
}
free(payload);
close(fd_answer);
}

View file

@ -1,46 +0,0 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <logger.h>
#include <models/controller.h>
#include <handlers.h>
#include <drivers.h>
#include <enums.h>
#include <helpers.h>
#include <wiringPi.h>
#include <wiring_debug.h>
void
handler_loop(controller_t *controller)
{
time_t timestamp = time(NULL);
struct tm *time_struct = localtime(&timestamp);
LOG_DEBUG("===== IDLE LOOP START =====\n");
for(uint_fast8_t i = 0; i < controller->relay_count; ++i)
{
relay_t *relay = controller->relays[i];
int is_active = 0;
if(relay_is_active(relay, time_struct))
{
LOG_DEBUG("relay %d is active\n", i);
is_active = 1;
}
if(global_config.relay_configs[i].inverted)
{
is_active = !is_active;
}
switch(global_config.relay_configs[i].driver)
{
case RELAY_DRIVER_GPIO:
driver_gpio_set(global_config.relay_configs[i].pin, is_active);
break;
case RELAY_DRIVER_PIFACE:
driver_piface_set(global_config.relay_configs[i].pin, is_active);
break;
default:
LOG_WARN("relay %d is not using a driver\n", i);
}
}
}

View file

@ -1,50 +0,0 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <lmdb.h>
#include <unistd.h>
#include <sys/socket.h>
#include <poll.h>
#include <signal.h>
#include <logger.h>
#include <models/controller.h>
#include <database.h>
#include <config.h>
#include <constants.h>
#include <handlers.h>
#include <drivers.h>
#include <enums.h>
#include <helpers.h>
#include <wiringPi.h>
#include <piFace.h>
#include <wiring_debug.h>
void
handler_poll(struct pollfd *fds, controller_t *controller, MDB_env *mdb_env)
{
/* An event on one of the fds has occurred. */
for(int i = 0; i < POLL_FDS_COUNT; i++) {
if(fds[i].revents & POLLIN)
{
/* data may be read on device number i. */
LOG_DEBUG("fd %i may read data\n", fds[i].fd);
switch(i)
{
case POLL_FDS_DISCOVERY:
handler_discovery(fds[i].fd, controller);
break;
case POLL_FDS_COMMAND:
handler_command(fds[i].fd, controller);
controller_save(controller, mdb_env);
break;
}
}
if(fds[i].revents & POLLHUP)
{
/* A hangup has occurred on device number i. */
LOG_DEBUG("fd %i got closed\n", fds[i].fd);
}
}
}

View file

@ -11,6 +11,7 @@ typedef struct
uint8_t pin; uint8_t pin;
int inverted; int inverted;
relay_driver_t driver; relay_driver_t driver;
uint8_t pulse_duration;
} config_relay_t; } config_relay_t;
typedef struct typedef struct
@ -21,6 +22,7 @@ typedef struct
run_type_t run_type; run_type_t run_type;
char name[MAX_NAME_LENGTH + 1]; char name[MAX_NAME_LENGTH + 1];
uint16_t discovery_port; uint16_t discovery_port;
uint16_t mqtt_port;
uint8_t relay_count; uint8_t relay_count;
config_relay_t *relay_configs; config_relay_t *relay_configs;
} config_t; } config_t;

17
include/connections.h Normal file
View file

@ -0,0 +1,17 @@
#ifndef CONTROLLER_CONNECTIONS_H
#define CONTROLLER_CONNECTIONS_H
#include <mongoose.h>
struct mg_connection*
connection_discovery_bind(struct mg_mgr *mgr);
struct mg_connection*
connection_command_bind(struct mg_mgr *mgr);
struct mg_connection*
connection_mqtt_connect(struct mg_mgr *mgr);
extern struct mg_connection *global_connection_mqtt;
#endif /* CONTROLLER_CONNECTIONS_H */

View file

@ -14,4 +14,6 @@
void void
database_setup(MDB_env **mdb_env, config_t *config); database_setup(MDB_env **mdb_env, config_t *config);
extern MDB_env *global_mdb_env;
#endif /* CONTROLLER_DATABASE_H */ #endif /* CONTROLLER_DATABASE_H */

View file

@ -24,6 +24,7 @@ typedef enum
COMMAND_MAPPING_SCHEDULE_ID = 4, COMMAND_MAPPING_SCHEDULE_ID = 4,
COMMAND_MAPPING_PERIODS_COUNT = 5, COMMAND_MAPPING_PERIODS_COUNT = 5,
COMMAND_MAPPING_PERIODS_BLOB = 6, COMMAND_MAPPING_PERIODS_BLOB = 6,
COMMAND_MAPPING_PULSE_DURATION = 7,
} control_mapping_t; } control_mapping_t;
typedef enum typedef enum
@ -36,6 +37,7 @@ typedef enum
COMMAND_CODE_GET_SCHEDULE = 103, COMMAND_CODE_GET_SCHEDULE = 103,
COMMAND_CODE_SET_RELAY_NAME = 104, COMMAND_CODE_SET_RELAY_NAME = 104,
COMMAND_CODE_GET_RELAY_NAME = 105, COMMAND_CODE_GET_RELAY_NAME = 105,
COMMAND_CODE_PULSE = 200,
} command_code_t; } command_code_t;
typedef enum typedef enum

View file

@ -1,7 +1,7 @@
#ifndef CONTROLLER_HANDLERS_H #ifndef CONTROLLER_HANDLERS_H
#define CONTROLLER_HANDLERS_H #define CONTROLLER_HANDLERS_H
#include <poll.h> #include <mongoose.h>
#include <models/controller.h> #include <models/controller.h>
@ -12,7 +12,7 @@
* @param controller Controller to use for answering command * @param controller Controller to use for answering command
*/ */
void void
handler_command(int fd, controller_t *controller); handler_command(struct mg_connection *c, int ev, void *ev_data);
/** /**
* @brief Handle the discovery processing * @brief Handle the discovery processing
@ -21,12 +21,12 @@ handler_command(int fd, controller_t *controller);
* @param controller Controller to use for answering discovery * @param controller Controller to use for answering discovery
*/ */
void void
handler_discovery(int fd, controller_t *controller); handler_discovery(struct mg_connection *c, int ev, void *ev_data);
void void
handler_loop(controller_t *this_controller); handler_mqtt(struct mg_connection *c, int ev, void *ev_data);
void void
handler_poll(struct pollfd *fds, controller_t *controller, MDB_env *mdb_env); handler_loop(struct mg_connection *c_mqtt);
#endif /* CONTROLLER_HANDLERS_H */ #endif /* CONTROLLER_HANDLERS_H */

View file

@ -6,16 +6,15 @@
#include <colors.h> #include <colors.h>
#include <config.h> #include <config.h>
#include <macros.h>
void void
logger_log(FILE *stream, log_level_t level, const char *filename, int line, const char *func, const char *msg, ...); logger_log(FILE *stream, log_level_t level, const char *filename, int line, const char *func, const char *msg, ...);
#define LOG_TRACE(...) logger_log(stdout, LOG_LEVEL_TRACE, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__) #define LOG_TRACE(...) logger_log(stdout, LOG_LEVEL_TRACE, __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#define LOG_DEBUG(...) logger_log(stdout, LOG_LEVEL_DEBUG, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__) #define LOG_DEBUG(...) logger_log(stdout, LOG_LEVEL_DEBUG, __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#define LOG_INFO(...) logger_log(stdout, LOG_LEVEL_INFO , __FILENAME__, __LINE__, __func__, ##__VA_ARGS__) #define LOG_INFO(...) logger_log(stdout, LOG_LEVEL_INFO , __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#define LOG_WARN(...) logger_log(stdout, LOG_LEVEL_WARN , __FILENAME__, __LINE__, __func__, ##__VA_ARGS__) #define LOG_WARN(...) logger_log(stdout, LOG_LEVEL_WARN , __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#define LOG_ERROR(...) logger_log(stderr, LOG_LEVEL_ERROR, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__) #define LOG_ERROR(...) logger_log(stderr, LOG_LEVEL_ERROR, __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#define LOG_FATAL(...) logger_log(stderr, LOG_LEVEL_FATAL, __FILENAME__, __LINE__, __func__, ##__VA_ARGS__) #define LOG_FATAL(...) logger_log(stderr, LOG_LEVEL_FATAL, __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#endif //CONTROLLER_LOGGER_H #endif //CONTROLLER_LOGGER_H

View file

@ -107,4 +107,6 @@ controller_free(controller_t *controller);
void void
controller_debug(controller_t *controller); controller_debug(controller_t *controller);
extern controller_t *global_controller;
#endif //CONTROLLER_CONTROLLER_H #endif //CONTROLLER_CONTROLLER_H

View file

@ -11,6 +11,10 @@
typedef struct typedef struct
{ {
uint8_t number; uint8_t number;
int is_on;
int is_on_schedule;
int pulse_timer;
int sent_to_broker;
char name[MAX_NAME_LENGTH + 1]; char name[MAX_NAME_LENGTH + 1];
schedule_t *schedules[7]; schedule_t *schedules[7];
} relay_t; } relay_t;
@ -51,7 +55,7 @@ int
relay_save(relay_t *relay, MDB_env *mdb_env); relay_save(relay_t *relay, MDB_env *mdb_env);
int int
relay_is_active(relay_t *relay, struct tm *time_struct); relay_is_on_schedule(relay_t *relay, struct tm *time_struct);
void void
relay_free(relay_t *relay); relay_free(relay_t *relay);

6277
include/mongoose.h Normal file

File diff suppressed because it is too large Load diff

View file

@ -4,12 +4,13 @@
#include <logger.h> #include <logger.h>
#ifdef WIRING_PI_DEBUG #ifdef WIRING_PI_DEBUG
#define wiringPiSetup() LOG_DEBUG("wiringPi wiringPiSetup()\n") #define LOG_WIRING_PI LOG_TRACE
#define wiringPiSetupSys() LOG_DEBUG("wiringPi wiringPiSetupSys()\n") #define wiringPiSetup() LOG_WIRING_PI("wiringPi wiringPiSetup()\n")
#define pinMode(x,y) LOG_DEBUG("wiringPi pinMode(%d, %d)\n", x, y) #define wiringPiSetupSys() LOG_WIRING_PI("wiringPi wiringPiSetupSys()\n")
#define digitalWrite(x,y) LOG_DEBUG("wiringPi digitalWrite(%d, %d)\n", x, y) #define pinMode(x,y) LOG_WIRING_PI("wiringPi pinMode(%d, %d)\n", x, y)
#define digitalWrite(x,y) LOG_WIRING_PI("wiringPi digitalWrite(%d, %d)\n", x, y)
#define piFaceSetup(x) LOG_DEBUG("wiringPi piFaceSetup(%d)\n", x) #define piFaceSetup(x) LOG_WIRING_PI("wiringPi piFaceSetup(%d)\n", x)
#endif #endif
#endif /* CONTROLLER_WIRING_DEBUG_H */ #endif /* CONTROLLER_WIRING_DEBUG_H */

35
src/connections.c Normal file
View file

@ -0,0 +1,35 @@
#include <stdio.h>
#include <connections.h>
#include <models/controller.h>
#include <config.h>
#include <handlers.h>
struct mg_connection *global_connection_mqtt;
struct mg_connection*
connection_discovery_bind(struct mg_mgr *mgr)
{
char address[100];
sprintf(address, "udp://0.0.0.0:%u", global_controller->discovery_port);
struct mg_connection *c = mg_bind(mgr, address, handler_discovery);
return c;
}
struct mg_connection*
connection_command_bind(struct mg_mgr *mgr)
{
char address[100];
sprintf(address, "tcp://0.0.0.0:%u", global_controller->command_port);
struct mg_connection *c = mg_bind(mgr, address, handler_command);
return c;
}
struct mg_connection*
connection_mqtt_connect(struct mg_mgr *mgr)
{
char address[100];
sprintf(address, "tcp://localhost:%u", global_config.mqtt_port);
struct mg_connection *c = mg_connect(mgr, address, handler_mqtt);
return c;
}

View file

@ -11,12 +11,29 @@
#include <errno.h> #include <errno.h>
#include <logger.h> #include <logger.h>
#include <database.h>
#include <handlers.h> #include <handlers.h>
#include <helpers.h> #include <helpers.h>
#include <enums.h> #include <enums.h>
#include <mpack.h> #include <mpack.h>
#include <models/schedule.h> #include <models/schedule.h>
static void
handler_command_pulse(mpack_node_t map, controller_t *controller)
{
uint8_t relay_num = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_RELAY_NUM));
relay_t *target_relay = controller->relays[relay_num];
(void)target_relay;
uint8_t duration = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_PULSE_DURATION));
if(duration == 0)
{
duration = global_config.relay_configs[relay_num].pulse_duration;
}
target_relay->pulse_timer = duration;
}
static void static void
handler_command_set_name(mpack_node_t map, controller_t *controller) handler_command_set_name(mpack_node_t map, controller_t *controller)
{ {
@ -68,36 +85,22 @@ handler_command_set_relay_name(mpack_node_t map, controller_t *controller)
} }
void void
handler_command(int fd, controller_t *controller) handler_command(struct mg_connection *c, int ev, void *ev_data)
{ {
struct sockaddr_storage their_addr; (void)ev_data;
socklen_t addr_size; if(ev != MG_EV_RECV)
int client_fd; {
return;
addr_size = sizeof(their_addr); }
uint32_t payload_length = *((uint32_t*)c->recv_mbuf.buf);
if((client_fd = accept(fd, (struct sockaddr *) &their_addr, &addr_size)) < 0) LOG_DEBUG("payload_length %d\n", payload_length);
if(c->recv_mbuf.len < payload_length + sizeof(payload_length))
{ {
LOG_ERROR("could not accept client: %s\n", strerror(errno));
return; return;
} }
uint32_t payload_length; char *payload = c->recv_mbuf.buf + sizeof(payload_length);
if(recv(client_fd, &payload_length, sizeof(payload_length), 0) <= 0)
{
LOG_ERROR("unable to receive header: %s\n", strerror(errno));
return;
}
void *payload = malloc((payload_length + 1));
ssize_t bytes_transferred;
if((bytes_transferred = recv(client_fd, payload, payload_length, 0)) <= 0)
{
LOG_ERROR("unable to receive payload: %s\n", strerror(errno));
return;
}
mpack_tree_t tree; mpack_tree_t tree;
mpack_tree_init_data(&tree, payload, payload_length); mpack_tree_init_data(&tree, payload, payload_length);
@ -115,20 +118,23 @@ handler_command(int fd, controller_t *controller)
case COMMAND_CODE_GET_ID: case COMMAND_CODE_GET_ID:
break; break;
case COMMAND_CODE_SET_NAME: case COMMAND_CODE_SET_NAME:
handler_command_set_name(root, controller); handler_command_set_name(root, global_controller);
break; break;
case COMMAND_CODE_GET_NAME: case COMMAND_CODE_GET_NAME:
break; break;
case COMMAND_CODE_SET_SCHEDULE: case COMMAND_CODE_SET_SCHEDULE:
handler_command_set_schedule(root, controller); handler_command_set_schedule(root, global_controller);
break; break;
case COMMAND_CODE_GET_SCHEDULE: case COMMAND_CODE_GET_SCHEDULE:
break; break;
case COMMAND_CODE_SET_RELAY_NAME: case COMMAND_CODE_SET_RELAY_NAME:
handler_command_set_relay_name(root, controller); handler_command_set_relay_name(root, global_controller);
break; break;
case COMMAND_CODE_GET_RELAY_NAME: case COMMAND_CODE_GET_RELAY_NAME:
break; break;
case COMMAND_CODE_PULSE:
handler_command_pulse(root, global_controller);
break;
default: default:
LOG_ERROR("received invalid command\n"); LOG_ERROR("received invalid command\n");
} }
@ -137,6 +143,5 @@ handler_command(int fd, controller_t *controller)
{ {
LOG_WARN("error when destroying mpack tree\n"); LOG_WARN("error when destroying mpack tree\n");
} }
free(payload); controller_save(global_controller, global_mdb_env);
close(client_fd);
} }

95
src/handlers/discovery.c Normal file
View file

@ -0,0 +1,95 @@
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <uuid/uuid.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <errno.h>
#include <logger.h>
#include <mongoose.h>
#include <handlers.h>
#include <helpers.h>
#include <mpack.h>
#include <enums.h>
void
handler_discovery(struct mg_connection *c, int ev, void *ev_data)
{
(void)ev_data;
if(ev == MG_EV_RECV)
{
uint16_t discovery_answer_port;
char ip_buf[32];
mg_conn_addr_to_str(c, ip_buf, sizeof(ip_buf), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_REMOTE);
if(c->recv_mbuf.len != sizeof(discovery_answer_port))
{
LOG_ERROR("received invalid discovery from %s\n", ip_buf);
return;
}
discovery_answer_port = *((uint16_t*)c->recv_mbuf.buf);
LOG_INFO("received discovery from %s:%d\n", ip_buf, discovery_answer_port);
if(discovery_answer_port == 0)
{
LOG_ERROR("invalid port received\n");
return;
}
char* payload;
size_t payload_size;
mpack_writer_t writer;
mpack_writer_init_growable(&writer, &payload, &payload_size);
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_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_uint(&writer, DISCOVERY_MAPPING_NAME);
mpack_write_cstr(&writer, global_controller->name);
mpack_finish_map(&writer);
// finish writing
if(mpack_writer_destroy(&writer) != mpack_ok)
{
LOG_ERROR("error writing discovery answer payload\n");
return;
}
size_t bytes_transferred;
int fd_answer = helper_connect_tcp_server(ip_buf, discovery_answer_port);
if(fd_answer == -1)
{
LOG_ERROR("error during connecting\n");
free(payload);
return;
}
if((bytes_transferred = send(fd_answer, &payload_size, sizeof(payload_size), 0)) <= 0)
{
LOG_ERROR("error during sending\n");
free(payload);
close(fd_answer);
return;
}
if((bytes_transferred = send(fd_answer, payload, payload_size, 0)) <= 0)
{
LOG_ERROR("error during sending\n");
free(payload);
close(fd_answer);
return;
}
free(payload);
}
}

88
src/handlers/loop.c Normal file
View file

@ -0,0 +1,88 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <uuid/uuid.h>
#include <logger.h>
#include <models/controller.h>
#include <handlers.h>
#include <drivers.h>
#include <enums.h>
#include <helpers.h>
#include <wiringPi.h>
#include <wiring_debug.h>
void
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);
struct tm time_last, time_now;
time_t timestamp;
timestamp = time(NULL) - 1;
localtime_r(&timestamp, &time_last);
timestamp = time(NULL);
localtime_r(&timestamp, &time_now);
LOG_TRACE("===== IDLE LOOP START =====\n");
for(uint_fast8_t i = 0; i < global_controller->relay_count; ++i)
{
relay_t *relay = global_controller->relays[i];
int is_on = 0;
int is_on_schedule = relay_is_on_schedule(relay, &time_now);
if(relay->is_on_schedule != is_on_schedule && relay->is_on_schedule != -1)
{
relay->pulse_timer = global_config.relay_configs[i].pulse_duration;
}
if(is_on_schedule && !global_config.relay_configs[i].pulse_duration)
{
is_on = 1;
}
if(relay->pulse_timer > 0)
{
is_on = 1;
--relay->pulse_timer;
}
if(is_on)
{
LOG_DEBUG("relay %d is active\n", i);
}
if(relay->is_on != is_on)
{
relay->sent_to_broker = 0;
}
if(!relay->sent_to_broker && c_mqtt)
{
sprintf(topic_buf, "controller/%s/relay/%u", controller_uid, i);
sprintf(payload_buf, "%u", is_on);
mg_mqtt_publish(c_mqtt, topic_buf, 0, MG_MQTT_QOS(0), payload_buf, strlen(payload_buf));
relay->sent_to_broker = 1;
}
relay->is_on = is_on;
relay->is_on_schedule = is_on_schedule;
if(global_config.relay_configs[i].inverted)
{
is_on = !is_on;
}
switch(global_config.relay_configs[i].driver)
{
case RELAY_DRIVER_GPIO:
driver_gpio_set(global_config.relay_configs[i].pin, is_on);
break;
case RELAY_DRIVER_PIFACE:
driver_piface_set(global_config.relay_configs[i].pin, is_on);
break;
default:
LOG_WARN("relay %d is not using a driver\n", i);
}
}
}

43
src/handlers/mqtt.c Normal file
View file

@ -0,0 +1,43 @@
#include <logger.h>
#include <handlers.h>
#include <connections.h>
#include <models/controller.h>
void
handler_mqtt(struct mg_connection *nc, int ev, void *p) {
struct mg_mqtt_message *msg = (struct mg_mqtt_message *) p;
(void) nc;
switch (ev)
{
case MG_EV_CONNECT:
{
struct mg_send_mqtt_handshake_opts opts;
memset(&opts, 0, sizeof(opts));
// TODO add password
mg_set_protocol_mqtt(nc);
mg_send_mqtt_handshake_opt(nc, global_controller->name, opts);
break;
}
case MG_EV_MQTT_CONNACK:
if(msg->connack_ret_code != MG_EV_MQTT_CONNACK_ACCEPTED)
{
LOG_INFO("Got MQTT connection error: %d\n", msg->connack_ret_code);
break;
}
if(!global_connection_mqtt)
{
LOG_DEBUG("connected to MQTT server\n");
global_connection_mqtt = nc;
}
break;
case MG_EV_CLOSE:
if(global_connection_mqtt)
{
LOG_DEBUG("disconnected from MQTT server\n");
}
global_connection_mqtt = NULL;
break;
}
}

View file

@ -70,13 +70,21 @@ helper_load_config(IniDispatch *disp, void *config_void)
config->discovery_port = atoi(disp->value); config->discovery_port = atoi(disp->value);
return 0; return 0;
} }
if(CONFINI_IS_KEY("controller", "mqtt-port"))
{
config->mqtt_port = atoi(disp->value);
return 0;
}
if(CONFINI_IS_KEY("controller", "relay-count")) if(CONFINI_IS_KEY("controller", "relay-count"))
{ {
config->relay_count = atoi(disp->value); config->relay_count = atoi(disp->value);
config->relay_configs = malloc(sizeof(config_relay_t) * config->relay_count); config->relay_configs = malloc(sizeof(config_relay_t) * config->relay_count);
for(uint8_t i = 0; i < config->relay_count; ++i) for(uint8_t i = 0; i < config->relay_count; ++i)
{ {
config->relay_configs[i].driver= RELAY_DRIVER_NONE; config->relay_configs[i].driver = RELAY_DRIVER_NONE;
config->relay_configs[i].inverted = 0;
config->relay_configs[i].pin = 0;
config->relay_configs[i].pulse_duration = 0;
} }
LOG_TRACE("config relay-count set to %u\n", config->relay_count); LOG_TRACE("config relay-count set to %u\n", config->relay_count);
return 0; return 0;
@ -94,6 +102,11 @@ helper_load_config(IniDispatch *disp, void *config_void)
config->relay_configs[i].inverted = atoi(disp->value); config->relay_configs[i].inverted = atoi(disp->value);
return 0; return 0;
} }
if(CONFINI_IS_KEY(relay_section_name, "pulse-duration"))
{
config->relay_configs[i].pulse_duration = atoi(disp->value);
return 0;
}
if(CONFINI_IS_KEY(relay_section_name, "driver")) if(CONFINI_IS_KEY(relay_section_name, "driver"))
{ {
if(strcasecmp(disp->value, "gpio") == 0) if(strcasecmp(disp->value, "gpio") == 0)

View file

@ -6,6 +6,7 @@
#include <config.h> #include <config.h>
#include <logger.h> #include <logger.h>
#include <helpers.h> #include <helpers.h>
#include <version.h>
static const char *const usage[] = { static const char *const usage[] = {
"controller [options] [[--] args]", "controller [options] [[--] args]",
@ -20,12 +21,13 @@ static const char *const usage[] = {
void void
helper_parse_cli(int argc, const char **argv, config_t *config) helper_parse_cli(int argc, const char **argv, config_t *config)
{ {
int version = 0;
struct argparse_option options[] = struct argparse_option options[] =
{ {
OPT_HELP(), OPT_HELP(),
OPT_GROUP("Basic options"), OPT_GROUP("Basic options"),
OPT_STRING('c', "config", &config->file, "path to config file", NULL, 0, OPT_NONEG), OPT_STRING('c', "config", &config->file, "path to config file", NULL, 0, OPT_NONEG),
OPT_BOOLEAN('v', "version", &version, "print version", NULL, 0, OPT_NONEG),
OPT_END(), OPT_END(),
}; };
@ -38,6 +40,12 @@ helper_parse_cli(int argc, const char **argv, config_t *config)
); );
argc = argparse_parse(&argparse, argc, argv); argc = argparse_parse(&argparse, argc, argv);
if(version)
{
printf("%s\n", EMGAUWA_CONTROLLER_VERSION);
exit(0);
}
if(argc == 1) if(argc == 1)
{ {
if(strcmp(argv[0], "start") == 0) if(strcmp(argv[0], "start") == 0)

View file

@ -3,15 +3,14 @@
#include <stdio.h> #include <stdio.h>
#include <time.h> #include <time.h>
#include <lmdb.h> #include <lmdb.h>
#include <unistd.h>
#include <sys/socket.h>
#include <poll.h>
#include <signal.h> #include <signal.h>
#include <logger.h> #include <logger.h>
#include <mongoose.h>
#include <models/controller.h> #include <models/controller.h>
#include <database.h> #include <database.h>
#include <config.h> #include <config.h>
#include <connections.h>
#include <constants.h> #include <constants.h>
#include <handlers.h> #include <handlers.h>
#include <drivers.h> #include <drivers.h>
@ -24,26 +23,29 @@
#include <confini.h> #include <confini.h>
config_t global_config; config_t global_config;
controller_t *global_controller;
MDB_env *global_mdb_env;
static MDB_env *mdb_env; static struct mg_mgr mgr;
static controller_t *this_controller;
static struct pollfd poll_fds[POLL_FDS_COUNT];
static void static void
terminate(int signum) terminate(int signum)
{ {
LOG_INFO("terminating controller (%d)\n", signum); LOG_INFO("terminating controller (%d)\n", signum);
for(int i = 0; i < POLL_FDS_COUNT; ++i) // TODO fix mg_mgr_free() causing loop (can't terminate)
{ //LOG_DEBUG("freeing mongoose manager\n");
close(poll_fds[i].fd); //mg_mgr_free(&mgr);
}
mdb_env_close(mdb_env); LOG_DEBUG("closing database\n");
mdb_env_close(global_mdb_env);
controller_free(this_controller); LOG_DEBUG("freeing global controller\n");
controller_free(global_controller);
LOG_DEBUG("freeing database config\n");
free(global_config.database); free(global_config.database);
LOG_DEBUG("freeing relay configs config\n");
free(global_config.relay_configs); free(global_config.relay_configs);
exit(signum); exit(signum);
@ -71,6 +73,8 @@ main(int argc, const char** argv)
global_config.file = "controller.ini"; global_config.file = "controller.ini";
global_config.log_level = LOG_LEVEL_INFO; global_config.log_level = LOG_LEVEL_INFO;
global_config.discovery_port = 4421;
global_config.mqtt_port = 1885;
helper_parse_cli(argc, argv, &global_config); helper_parse_cli(argc, argv, &global_config);
@ -93,18 +97,22 @@ main(int argc, const char** argv)
LOG_WARN("this system is not using 8-bit time\n"); LOG_WARN("this system is not using 8-bit time\n");
} }
/******************** SETUP DATABASE AND THIS CONTROLLER ********************/
database_setup(&mdb_env, &global_config); /******************** SETUP DATABASE, SOCKETS AND THIS CONTROLLER ********************/
this_controller = controller_load(mdb_env); mg_mgr_init(&mgr, NULL);
int fd_discovery = helper_open_discovery_socket(this_controller->discovery_port); database_setup(&global_mdb_env, &global_config);
int fd_command = helper_bind_tcp_server("0.0.0.0", this_controller->command_port, 128);
this_controller->command_port = helper_get_port(fd_command); global_controller = controller_load(global_mdb_env);
controller_save(this_controller, mdb_env); connection_discovery_bind(&mgr);
connection_mqtt_connect(&mgr);
struct mg_connection *c_command = connection_command_bind(&mgr);
global_controller->command_port = helper_get_port(c_command->sock);
controller_save(global_controller, global_mdb_env);
/******************** SETUP WIRINGPI ********************/ /******************** SETUP WIRINGPI ********************/
@ -112,7 +120,7 @@ main(int argc, const char** argv)
wiringPiSetup(); wiringPiSetup();
piFaceSetup(PIFACE_GPIO_BASE); piFaceSetup(PIFACE_GPIO_BASE);
for(uint_fast8_t i = 0; i < this_controller->relay_count; ++i) for(uint_fast8_t i = 0; i < global_controller->relay_count; ++i)
{ {
if(global_config.relay_configs[i].driver == RELAY_DRIVER_GPIO) if(global_config.relay_configs[i].driver == RELAY_DRIVER_GPIO)
{ {
@ -121,48 +129,34 @@ main(int argc, const char** argv)
} }
/******************** SETUP SOCKETS ********************/
int timeout_msecs = ACCEPT_TIMEOUT_MSECONDS;
int ret;
/* Open STREAMS device. */
poll_fds[POLL_FDS_DISCOVERY].fd = fd_discovery;
poll_fds[POLL_FDS_DISCOVERY].events = POLLIN;
LOG_DEBUG("setup fd_discovery as %i on index %i\n", fd_discovery, POLL_FDS_DISCOVERY);
poll_fds[POLL_FDS_COMMAND].fd = fd_command;
poll_fds[POLL_FDS_COMMAND].events = POLLIN;
LOG_DEBUG("setup fd_command as %i on index %i\n", fd_command, POLL_FDS_COMMAND);
/******************** CHECK FOR TESTING RUN ********************/ /******************** CHECK FOR TESTING RUN ********************/
if(global_config.run_type == RUN_TYPE_TEST) if(global_config.run_type == RUN_TYPE_TEST)
{ {
runner_test(this_controller); runner_test(global_controller);
terminate(0); terminate(0);
} }
/******************** START MAIN LOOP ********************/ /******************** START MAIN LOOP ********************/
for(;;) time_t timer = time(NULL);
{
ret = poll(poll_fds, POLL_FDS_COUNT, timeout_msecs);
if(ret == 0) for (;;)
{
mg_mgr_poll(&mgr, 200);
if(time(NULL) - timer >= 1)
{ {
handler_loop(this_controller); if(!global_connection_mqtt)
} {
if(ret > 0) connection_mqtt_connect(&mgr);
{ }
handler_poll(poll_fds, this_controller, mdb_env); handler_loop(global_connection_mqtt);
timer = time(NULL);
} }
} }
close(fd_discovery); terminate(0);
mdb_env_close(mdb_env);
return 0; return 0;
} }

View file

@ -14,6 +14,11 @@ relay_create(uint8_t number)
new_relay->number = number; new_relay->number = number;
new_relay->name[0] = '\0'; new_relay->name[0] = '\0';
new_relay->is_on = -1;
new_relay->is_on_schedule = -1;
new_relay->pulse_timer = 0;
new_relay->sent_to_broker = 0;
uuid_t off_id; uuid_t off_id;
memset(off_id, 0, sizeof(uuid_t)); memset(off_id, 0, sizeof(uuid_t));
memcpy(off_id, "off", 3); memcpy(off_id, "off", 3);
@ -34,7 +39,7 @@ relay_set_name(relay_t *relay, const char *name)
} }
int int
relay_is_active(relay_t *relay, struct tm *time_struct) relay_is_on_schedule(relay_t *relay, struct tm *time_struct)
{ {
schedule_t *schedule = relay->schedules[helper_get_weekday(time_struct)]; schedule_t *schedule = relay->schedules[helper_get_weekday(time_struct)];
if(schedule->length == 0) if(schedule->length == 0)

View file

@ -66,6 +66,11 @@ relay_load(MDB_env *mdb_env, uint8_t num)
new_relay = malloc(sizeof(relay_t)); new_relay = malloc(sizeof(relay_t));
new_relay->number = num; 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; MDB_val value;
if((err = relay_load_single(mdb_txn, mdb_dbi, DB_KEY_RELAY_NAME, num, &value)) != 0) if((err = relay_load_single(mdb_txn, mdb_dbi, DB_KEY_RELAY_NAME, num, &value)) != 0)

16123
src/mongoose.c Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,18 +0,0 @@
set(CMAKE_C_COMPILER /usr/bin/arm-none-eabi-gcc)
set(CMAKE_C_COMPILER_WORKS 1)
set(ARM-SYSROOT /usr/arm-none-eabi)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -marm")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mfpu=vfp")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -march=armv6zk+fp")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mcpu=arm1176jzf-s")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mtune=arm1176jzf-s")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --sysroot=${ARM-SYSROOT}" CACHE INTERNAL "" FORCE)
set(CMAKE_C_LINK_FLAGS "${CMAKE_C_LINK_FLAGS} --sysroot=${ARM-SYSROOT}" CACHE INTERNAL "" FORCE)
set(CMAKE_FIND_ROOT_PATH ${ARM-SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

1
version.h.in Normal file
View file

@ -0,0 +1 @@
#define EMGAUWA_CONTROLLER_VERSION "@CMAKE_PROJECT_VERSION@"