An AirVantage layer for MQTT

Dependencies:   niMQTT picojson

Dependents:   AV_MQTT_example

AV_MQTT.cpp

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

File content as of revision 7:da5d90052cec:

#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::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());
        }
    }
}