Skip to content

Instantly share code, notes, and snippets.

@virgilvox
Created April 9, 2015 18:51
Show Gist options
  • Save virgilvox/ffe1cc08a240db9792d3 to your computer and use it in GitHub Desktop.
Save virgilvox/ffe1cc08a240db9792d3 to your computer and use it in GitHub Desktop.
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();
}
@Yash1903
Copy link

hello i'm trying to do save file in Json on ESP8266(NODmcu) using SPIffs but i can't read that file over Mqtt i'm sharing my code below please replay as soon as possible.

#include <ESP8266WiFi.h>
#include <FS.h> //Include File System Headers
#include <ArduinoJson.h>
const char* filename = "/data.json";
#include <SoftwareSerial.h>
#include <PubSubClient.h>
unsigned long stime=65000;
unsigned long Itime=0;
SoftwareSerial s(14,12);

const char* ssid = "LIMELIGHT LAB";
const char* password = "TATA@123";
const char* mqttServer = "vernemq.limelightit.io";
const int mqttPort = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
////////////////////////////////////////////////////////////////////////////////////////////
Serial.begin(9600);
s.begin(115200);
Serial.println();
////////////////////////////////////for WiFI
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}

Serial.println("Connected to the WiFi network");

client.setServer(mqttServer, mqttPort);

while (!client.connected()) {
Serial.println("Connecting to MQTT...");

if (client.connect("ESP8266Client")) {

  Serial.println("connected");

} else {

  Serial.print("failed with state ");
  Serial.print(client.state());
  delay(2000);

}

}
///////////////////////Initialize File System
if(SPIFFS.begin())
{
Serial.println("SPIFFS Initialize....ok");
}
else
{
Serial.println("SPIFFS Initialization...failed");
}

/////////////////////////////////////////// Format File System
if(SPIFFS.format())
{
// Serial.println("File System Formated");
}
else
{
Serial.println("File System Formatting Error");
}

/////////////////////////////////////// / ///Create New File And Write Data to It
//w=Write Open file for writing
File f = SPIFFS.open(filename, "w");

if (!f) {
// Serial.println("file open failed");
}
else
{
//Write data to file
Serial.println("Writing Data to File");
// f.print("This is sample data which is written in file");
f.close(); //Close file
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
}
void loop() {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
int i;
StaticJsonBuffer<300> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(s);

if (root == JsonObject::invalid())
{
return;
}
//Serial.println("JSON received and parsed");

char JSONmessageBuffer[300];
root.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
Serial.println("Sending message to MQTT topic..");
// Serial.println(JSONmessageBuffer);

// if (client.publish("esp/test", JSONmessageBuffer) == true) {
// Serial.println("Success sending message");
// } else {
// Serial.println("Error sending message");
// }

// client.loop();
// Serial.println("-------------");
/////////////////////////////////////////////////////////
File fileToAppend = SPIFFS.open(filename, "a");
//unsigned long rtime=millis();
//Serial.print(rtime);
if(!fileToAppend){
Serial.println("There was an error opening the file for appending");
return;
}

if(fileToAppend.println(JSONmessageBuffer)){
    Serial.println("File content was appended");
} else {
    Serial.println("File append failed");
}

fileToAppend.close();

/////////////////////////Read File data
unsigned long rtime=millis();
if (spiffsActive) {
if (SPIFFS.exists(filename)) {
File f = SPIFFS.open(filename, "r");
if (!f) {
Serial.print("Unable To Open '");
Serial.print(filename);
Serial.println("' for Reading");
Serial.println();
} else {
String s;
Serial.print("Contents of file '");
Serial.print(filename);
Serial.println("'");
Serial.println();
char spif[spift.length() + 1];
spift.toCharArray(spif, spift.length() + 1);
Serial.println(spif);
while (f.position()<f.size())
{
s=f.readStringUntil('\n');
s.trim();
char mssg[s.length() + 1];
s.toCharArray(mssg, s.length() + 1);
// delay(500);
// client.publish(spif, mssg);
delay(500);
Serial.println(mssg);
Serial.println(s);
}
f.close();
SPIFFS.remove(filename);
}
}
}
Itime=rtime;
///////////////////////////////Serializ
char buffer[300];
size_t n = serializeJson(filename, buffer);
if(client.publish("esp/test", buffer, n)==true);{
// if (client.publish("esp/test","/data.json") == true) {
Serial.println("Success sending message");
} else {
Serial.println("Error sending message");
}

client.loop();
Serial.println("-------------");
}
// delay(5000);
//////////////////////////////////////////////////////////////////////////////////////////////
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment