core-legacy/src/status.c

95 lines
1.9 KiB
C
Raw Normal View History

#include <status.h>
#include <logger.h>
relay_t **global_relay_status_list;
void
status_init()
{
global_relay_status_list = relay_get_all();
}
void
status_reload_entry(int relay_id)
{
relay_t **relays = global_relay_status_list;
for(int i = 0; relays[i] != NULL; ++i)
{
if(relays[i]->id != relay_id)
{
continue;
}
int is_on_backup = relays[i]->is_on;
relay_t *updated_relay = relay_get_by_id(relay_id);
relay_free(relays[i]);
relays[i] = updated_relay;
relays[i]->is_on = is_on_backup;
}
}
void
status_update_entry(int relay_id, int is_on)
{
relay_t **relays = global_relay_status_list;
for(int i = 0; relays[i] != NULL; ++i)
{
if(relays[i]->id != relay_id)
{
continue;
}
relays[i]->is_on = is_on;
}
}
static int is_websocket(const struct mg_connection *nc)
{
return nc->flags & MG_F_IS_WEBSOCKET;
}
void
status_broadcast(struct mg_mgr *mgr)
{
struct mg_connection *c;
relay_t **relays = global_relay_status_list;
cJSON *json = relay_list_to_json(relays);
char *json_str = cJSON_Print(json);
size_t json_str_len = strlen(json_str);
for (c = mg_next(mgr, NULL); c != NULL; c = mg_next(mgr, c)) {
if(is_websocket(c))
{
mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, json_str, json_str_len);
}
}
free(json_str);
cJSON_Delete(json);
}
void
status_send(struct mg_connection *c)
{
if(!is_websocket(c))
{
return;
}
relay_t **relays = global_relay_status_list;
cJSON *json = relay_list_to_json(relays);
char *json_str = cJSON_Print(json);
size_t json_str_len = strlen(json_str);
mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, json_str, json_str_len);
free(json_str);
cJSON_Delete(json);
}
void
status_free()
{
relay_free_list(global_relay_status_list);
}