An AirVantage layer for MQTT

Dependencies:   niMQTT picojson

Dependents:   AV_MQTT_example

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers AV_MQTT.cpp Source File

AV_MQTT.cpp

00001 #include "AV_MQTT.h"
00002 #include "picojson.h"
00003 
00004 AV_MQTT::AV_MQTT(char *server, void (*callback)(const char *, const char*), char *username, char *password, char *id, int port, bool debug):
00005     niMQTT(server, callback, id, port, username, password, debug) {
00006     topic = new char[strlen(username) + 15];
00007     strcpy(topic, username);
00008     strcat(topic, "/messages/json");
00009 }
00010 
00011 void AV_MQTT::pub(char *key, char *value) {
00012     int key_length = strlen(key);
00013     int value_length = strlen(value);
00014     char json[key_length + value_length + 36];
00015     strcpy(json, "[{\"");
00016     strcat(json, key);
00017     strcat(json, "\":[{\"timestamp\":null,\"value\":");
00018     strcat(json, value);
00019     strcat(json, "}]}]");
00020     niMQTT::pub(topic, json);
00021 }
00022 
00023 void AV_MQTT::call_callback(const char *topic, const char *message) {
00024     picojson::value v;
00025     picojson::parse(v, message, message + strlen(message));
00026     
00027     picojson::array a = v.get<picojson::array>()[0].get("write").get<picojson::array>(); //[0].get("mbed_mqtt_example.led_settings").to_str().c_str());
00028     
00029     for (picojson::array::iterator i = a.begin(); i != a.end(); ++i) {
00030         picojson::object& o = i->get<picojson::object>();
00031         for (picojson::object::iterator it = o.begin(); it != o.end(); ++it) {
00032             callback(it->first.c_str(), it->second.to_str().c_str());
00033         }
00034     }
00035 }