moringaman
4/9/2015 - 6:51 PM

Use MQTT to send/recieve JSON using an Arduino with Ethernet!

Use MQTT to send/recieve JSON using an Arduino with Ethernet!



#include <SPI.h>
#include <Ethernet.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>


// Update these with values suitable for your network.
IPAddress ip(192, 168, 0, 177);

//you can't have 2 of the same mac on your network!
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

char server[] = "meshblu.octoblu.com";

// UUID and token for Octoblu 
char UUID[]  = "";
char TOKEN[] = "";

EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);

char data[80];
StaticJsonBuffer<200> jsonBuffer;


void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
  char inData[80];

  
 Serial.print("payload: ");
 for(int i =26; i<length; i++){
  // Serial.print((char)payload[i]);
   inData[(i - 26)] = (char)payload[i];
 }
 Serial.println();
 
 JsonObject& root = jsonBuffer.parseObject(inData);  


 // Pull the value from key "VALUE" from the JSON message {"value": 1 , "someOtherValue" : 200}
 int val = root["value"];

// DO SOMETHING WITH THE DATA THAT CAME IN!
 Serial.println(val); 
  
if (val == 1){
  
  digitalWrite(6, HIGH);
  
}else if( val == 0 ){
 
  digitalWrite(6, LOW);
  
}

  
  
}



void setup()
{
  
  Serial.begin(9600);
  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println(F("Failed to configure Ethernet using DHCP"));
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
   char clientId[40] = "mb_";
    strcat(clientId, UUID);
  if (client.connect(clientId, UUID, TOKEN)) {
  
    client.subscribe(UUID);
  }
  
  
  pinMode(6, OUTPUT);
}




void loop()
{

  
  
  // Format your message to Octoblu here as JSON
  // Include commas between each added element. 

 String value = "\"number\": " + String(analogRead(A0)) ;
 String value2 = ", \"word\": \"Hello World\" " ;
 
 // Add both value together to send as one string. 
  value = value + value2;
  
  
  // This sends off your payload. 
  String payload = "{ \"devices\": \"*\",\"payload\": {" + value + "}}";
  payload.toCharArray(data, (payload.length() + 1));
  client.publish("message", data);
  delay(500);
  client.loop();
}