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:
@ -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));
|
||||
// Traverse Array
|
||||
for (idx = 0; json_scanf_array_elem(w->user_data, strlen(w->user_data), "", idx, &val) > 0; idx++) {
|
||||
char *t=NULL, *m=NULL;
|
||||
uint16_t t_len=0, m_len=0;
|
||||
char *topic;
|
||||
char *topic, *message;
|
||||
|
||||
LOG(LL_DEBUG, ("Index %d, token [%.*s]", idx, val.len, val.ptr));
|
||||
t=(char*)val.ptr;
|
||||
m=strstr(val.ptr, " ");
|
||||
if (m-val.ptr <= val.len) {
|
||||
t_len=m-t;
|
||||
m++;
|
||||
m_len=val.len-t_len-1;
|
||||
} else {
|
||||
t_len=val.len;
|
||||
m_len=0;
|
||||
m=NULL;
|
||||
if (val.len==0) {
|
||||
LOG(LL_ERROR, ("mqtt element %d is empty token", idx));
|
||||
continue;
|
||||
}
|
||||
if ((topic=malloc(t_len+1))) {
|
||||
memcpy(topic, t, t_len);
|
||||
topic[t_len]=0;
|
||||
LOG(LL_INFO, ("Sending topic='%s', message='%.*s'", topic, m_len, m));
|
||||
mgos_mqtt_pub(topic, m, m_len, 0, false);
|
||||
free(topic);
|
||||
if (json_scanf(val.ptr, val.len, "{topic:%Q, message:%Q}", &topic, &message) != 2) {
|
||||
LOG(LL_ERROR, ("mqtt element %d ('%.*s'), required fields 'topic' and 'message'", idx, val.len, val.ptr));
|
||||
continue;
|
||||
}
|
||||
LOG(LL_INFO, ("Sending topic='%s', message='%s'", topic, message));
|
||||
mgos_mqtt_pub(topic, message, strlen(message), 0, false);
|
||||
widget_network_send();
|
||||
}
|
||||
|
||||
if (topic) free(topic);
|
||||
if (message) free(message);
|
||||
}
|
||||
(void) ev_data;
|
||||
}
|
||||
|
Reference in New Issue
Block a user