I am fairly new to all of this, and have been trying publish Json responses on MQTT. I am having problems with my code as it will publish the first time through the loop, but then i keep getting the "error sending message" response, which I think has to do with how I have converted the long into a character or something of the sorts. Does anyone have any idea on how to fix my code to get it to work?
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
const char* ssid = "ssid";
const char* password = "password";
const char* mqttServer = "mqttServer";
const int mqttPort = 1883;
const char* mqttUser = "mqttUser";
const char* mqttPassword = "mqttPassword";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(9600);
Serial.println();
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("Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void loop() {
// Check WiFi Status
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http; //Object of class HTTPClient
http.begin("http://ipaddress/setup/assistant/alarms");
int httpCode = http.GET();
//Check the returning code
if (httpCode > 0) {
const size_t capacity = JSON_ARRAY_SIZE(0) + JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(2) + 4*JSON_OBJECT_SIZE(3) + 2*JSON_OBJECT_SIZE(5) + 360;
DynamicJsonBuffer jsonBuffer(capacity);
JsonObject& root = jsonBuffer.parseObject(http.getString());
// Parameters
JsonObject& alarm0 = root["alarm"][0];
JsonObject& alarm0_date_pattern = alarm0["date_pattern"];
int alarm0_date_pattern_day = alarm0_date_pattern["day"];
int alarm0_date_pattern_month = alarm0_date_pattern["month"];
int alarm0_date_pattern_year = alarm0_date_pattern["year"];
long alarm0_fire_time = alarm0["fire_time"];
const char* alarm0_id = alarm0["id"];
String alarm0_fire_time_str;
char fire0[50];
Serial.print("Alarm Day:");
Serial.println(alarm0_date_pattern_day);
Serial.print("Alarm Month:");
Serial.println(alarm0_date_pattern_month);
Serial.print("Alarm Year:");
Serial.println(alarm0_date_pattern_year);
Serial.print("Alarm Time:");
Serial.println(alarm0_fire_time);
if (client.publish("esp/test", String(alarm0_fire_time).c_str(),true) == true) {
Serial.println("Success sending message");
}
else {
Serial.println("Error sending message");
}
}
http.end();
}
Serial.println("-------------");
// Delay
delay(60000);
}
Again, super new to this so apologies if this is a super basic question.
Thanks for the help.
I am a super new,too.
I don't know why it doesn't do well.
But I can't understand why there are the words of "http" in your code.
I think that mqtt is not related to 'http'.
So,in the first time,you should do mqtt in a simple sample code.
And,
you can investigate the details of reason why "publish("esp/test", String(alarm0_fire_time).c_str(),true)" says False.
You can investigate it in source codes of publish().
( but it is difficult for a super new to analyze it.)
Best regards,
there should not have HTTP on it.There is a simple MQTT code .
/***************************************************
Adafruit MQTT Library ESP8266 Example
Must use ESP8266 Arduino from:
https://github.com/esp8266/Arduino
Works great with Adafruit's Huzzah ESP board & Feather
----> https://www.adafruit.com/product/2471
----> https://www.adafruit.com/products/2821
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
/************************* WiFi Access Point *********************************/
#define WLAN_SSID ""
#define WLAN_PASS ""
/************************* Adafruit.io Setup *********************************/
#define AIO_SERVER "test.mosquitto.org"
#define AIO_SERVERPORT 1883 // use 8883 for SSL
//#define AIO_USERNAME "username"
//#define AIO_KEY "password"
/************ Global State (you don't need to change this!) ******************/
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT);
Adafruit_MQTT_Publish* photocell;
/****************************** Feeds ***************************************/
// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
//Adafruit_MQTT_Publish photocell= Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "");
// Setup a feed called 'onoff' for subscribing to changes.
//Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff");
/*************************** Sketch Code ************************************/
// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();
void setup() {
Serial.begin(115200);
delay(10);
String s="/feeds/photocell";
char buffer[50];
strcpy(buffer, AIO_SERVER);
strcat(buffer, s.c_str());
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, buffer);
Serial.println(F("Adafruit MQTT demo"));
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
// Setup MQTT subscription for onoff feed.
// mqtt.subsc/ribe(&onoffbutton);
}
uint32_t x=0;
void loop() {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_connect
// function definition further below.
delay(1000);
MQTT_connect();
// String s="/feeds/photocell";
// char buffer[50];
// strcpy(buffer, AIO_USERNAME);
// strcat(buffer, s.c_str());
// Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, buffer);
// this is our 'wait for incoming subscription packets' busy subloop
// try to spend your time here
//
// Adafruit_MQTT_Subscribe *subscription;
// while ((subscription = mqtt.readSubscription(5000))) {
// if (subscription == &onoffbutton) {
// Serial.print(F("Got: "));
// Serial.println((char *)onoffbutton.lastread);
// }
// }
// Now we can publish stuff!
Serial.print(F("\nSending photocell val "));
Serial.print(x);
Serial.print("...");
if (! photocell->publish(x++)) {
Serial.println(F("Failed"));
}
else {
Serial.println(F("OK!"));
}
// ping the server to keep the mqtt connection alive
// NOT required if you are publishing once every KEEPALIVE seconds
/*
if(! mqtt.ping()) {
mqtt.disconnect();
}
*/
}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}