Created
October 19, 2018 17:26
-
-
Save cpq/07bdab15977ce4182e586a5c157dfba5 to your computer and use it in GitHub Desktop.
config via shadow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "mgos.h" | |
#include "mgos_rpc.h" | |
#include "mgos_shadow.h" | |
static void report_state_to_the_shadow(void) { | |
const struct mgos_conf_entry *schema = | |
mgos_conf_find_schema_entry("KEY", mgos_config_schema()); | |
struct mbuf mb; | |
mbuf_init(&mb, 0); | |
mgos_conf_emit_cb(&mgos_sys_config, NULL, schema, false, &mb, NULL, NULL); | |
mgos_shadow_updatef(0, "{KEY: %.*s, uptime: %.2f}", (int) mb.len, mb.buf, | |
(float) mgos_uptime()); | |
mbuf_free(&mb); | |
} | |
// When we're connected to the shadow, report our current state. | |
// This may generate shadow delta on the cloud, and the cloud will push | |
// it down to us. | |
static void connected_cb(int ev, void *ev_data, void *userdata) { | |
report_state_to_the_shadow(); | |
(void) ev; | |
(void) ev_data; | |
(void) userdata; | |
} | |
// Handle shadow delta. | |
static void delta_cb(int ev, void *ev_data, void *userdata) { | |
struct mg_str *delta = (struct mg_str *) ev_data; | |
struct json_token t = JSON_INVALID_TOKEN; | |
LOG(LL_INFO, ("GOT DELTA: [%.*s]", (int) delta->len, delta->p)); | |
if (json_scanf(delta->p, delta->len, "{KEY: %T}", &t) == 1) { | |
const struct mgos_conf_entry *schema = | |
mgos_conf_find_schema_entry("KEY", mgos_config_schema()); | |
struct mg_str s = mg_mk_str_n(t.ptr, t.len); | |
bool res = mgos_conf_parse(s, "*", schema, &mgos_sys_config); | |
if (res) { | |
save_cfg(&mgos_sys_config, NULL); | |
LOG(LL_INFO, ("DELTA applied")); | |
} else { | |
LOG(LL_INFO, ("Error in config, DELTA NOT applied")); | |
} | |
} else { | |
LOG(LL_ERROR, ("Unexpected delta, looking for {KEY: ...}")); | |
} | |
(void) ev; | |
(void) userdata; | |
} | |
static void my_timer_cb(void *arg) { | |
report_state_to_the_shadow(); | |
(void) arg; | |
} | |
enum mgos_app_init_result mgos_app_init(void) { | |
mgos_event_add_handler(MGOS_SHADOW_UPDATE_DELTA, delta_cb, NULL); | |
mgos_event_add_handler(MGOS_SHADOW_CONNECTED, connected_cb, NULL); | |
mgos_set_timer(1000, MGOS_TIMER_REPEAT, my_timer_cb, NULL); | |
return MGOS_APP_INIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment