Simplify MQTT messaging

Simply add the entire mosquitto message as a JSON entity, not a string.
The simple case now looks like:
      "mqtt": [ {"topic": "/s/cmnd/5C:CF:7F:20:29:6E/Power", "message": "On"} ]

Sending an RPC to Mongoose OS looks like:
      "mqtt": [ {"topic": "esp32_XXXXXX/rpc/Button.Touch", "message": {"args": {"idx":0}}} ]
This commit is contained in:
Pim van Pelt
2018-01-02 00:20:15 +01:00
parent 0ea78abf4c
commit 9dbf9be428

View File

@ -124,30 +124,23 @@ static void widget_default_mqtt_send(struct widget_t *w, void *ev_data) {
// LOG(LL_DEBUG, ("MQTT string: '%s'", (char *)w->user_data)); // LOG(LL_DEBUG, ("MQTT string: '%s'", (char *)w->user_data));
// Traverse Array // Traverse Array
for (idx = 0; json_scanf_array_elem(w->user_data, strlen(w->user_data), "", idx, &val) > 0; idx++) { for (idx = 0; json_scanf_array_elem(w->user_data, strlen(w->user_data), "", idx, &val) > 0; idx++) {
char *t=NULL, *m=NULL; char *topic, *message;
uint16_t t_len=0, m_len=0;
char *topic;
LOG(LL_DEBUG, ("Index %d, token [%.*s]", idx, val.len, val.ptr)); LOG(LL_DEBUG, ("Index %d, token [%.*s]", idx, val.len, val.ptr));
t=(char*)val.ptr; if (val.len==0) {
m=strstr(val.ptr, " "); LOG(LL_ERROR, ("mqtt element %d is empty token", idx));
if (m-val.ptr <= val.len) { continue;
t_len=m-t;
m++;
m_len=val.len-t_len-1;
} else {
t_len=val.len;
m_len=0;
m=NULL;
} }
if ((topic=malloc(t_len+1))) { if (json_scanf(val.ptr, val.len, "{topic:%Q, message:%Q}", &topic, &message) != 2) {
memcpy(topic, t, t_len); LOG(LL_ERROR, ("mqtt element %d ('%.*s'), required fields 'topic' and 'message'", idx, val.len, val.ptr));
topic[t_len]=0; continue;
LOG(LL_INFO, ("Sending topic='%s', message='%.*s'", topic, m_len, m)); }
mgos_mqtt_pub(topic, m, m_len, 0, false); LOG(LL_INFO, ("Sending topic='%s', message='%s'", topic, message));
free(topic); mgos_mqtt_pub(topic, message, strlen(message), 0, false);
widget_network_send(); widget_network_send();
}
if (topic) free(topic);
if (message) free(message);
} }
(void) ev_data; (void) ev_data;
} }