An AirVantage layer for MQTT

Dependencies:   niMQTT picojson

Dependents:   AV_MQTT_example

AV_MQTT.cpp

Committer:
Nim65s
Date:
2013-08-13
Revision:
6:b251f6276497
Parent:
1:7f1a11a70a2b
Child:
7:da5d90052cec

File content as of revision 6:b251f6276497:

#include "AV_MQTT.h"
#include "picojson.h"

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");
}

void AV_MQTT::pub(char *key, char *value) {
    int key_length = strlen(key);
    int value_length = strlen(value);
    char json[key_length + value_length + 36];
    strcpy(json, "[{\"");
    strcat(json, key);
    strcat(json, "\":[{\"timestamp\":null,\"value\":");
    strcat(json, value);
    strcat(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());
        }
    }
}