An AirVantage layer for MQTT
Diff: AV_MQTT.cpp
- Revision:
- 6:b251f6276497
- Parent:
- 1:7f1a11a70a2b
- Child:
- 7:da5d90052cec
--- a/AV_MQTT.cpp Mon Aug 12 15:33:01 2013 +0000 +++ b/AV_MQTT.cpp Tue Aug 13 12:31:37 2013 +0000 @@ -1,7 +1,8 @@ #include "AV_MQTT.h" +#include "picojson.h" -AV_MQTT::AV_MQTT(char *server, void (*callback)(char *, char*), char *username, char *password, char *id, int port, bool debug): - client(server, callback, id, port, username, password, debug), debug(debug) { +AV_MQTT::AV_MQTT(char *server, void (*callback)(const char *, const char*), char *username, char *password, char *id, int port, bool debug): + niMQTT(server, callback, id, port, username, password, debug) { topic = new char[strlen(username) + 15]; strcpy(topic, username); strcat(topic, "/messages/json"); @@ -16,5 +17,46 @@ strcat(json, "\":[{\"timestamp\":null,\"value\":"); strcat(json, value); strcat(json, "}]}]"); - client.pub(topic, json); + niMQTT::pub(topic, json); +} + +void AV_MQTT::publish_received() { + //remaining length + int remaining_length = decode_remaining_length(); + + // topic + char mqtt_utf8_length[2]; + socket->receive(mqtt_utf8_length, 2); + int utf8_length = mqtt_utf8_length[0] * 256 + mqtt_utf8_length[1]; + + if (debug) printf("PUBLISH Received: %i, %i\r\n", remaining_length, utf8_length); + + char topic[utf8_length + 1]; + socket->receive(topic, utf8_length); + topic[utf8_length] = 0; + + // payload + int message_length = remaining_length - utf8_length - 2; + char message[message_length + 1]; + socket->receive(message, message_length); + message[message_length] = 0; + + waiting_new_packet = true; + + call_callback(topic, message); +// ^^^^^ only 5 characters that differs from niMQTT::publish_received... TODO +} + +void AV_MQTT::call_callback(const char *topic, const char *message) { + picojson::value v; + picojson::parse(v, message, message + strlen(message)); + + picojson::array a = v.get<picojson::array>()[0].get("write").get<picojson::array>(); //[0].get("mbed_mqtt_example.led_settings").to_str().c_str()); + + for (picojson::array::iterator i = a.begin(); i != a.end(); ++i) { + picojson::object& o = i->get<picojson::object>(); + for (picojson::object::iterator it = o.begin(); it != o.end(); ++it) { + callback(it->first.c_str(), it->second.to_str().c_str()); + } + } } \ No newline at end of file