MQTT subscription - mqtt

Can someone help me with this code?
The goal is to trigger a Led when the value of the payload is > 1000.
It is a MQTT subscribtion code based on the esp8266mqtt PubSub client example. I will use it for a subscribyion of a topic from a CO2sensor
I've tried to modify a part of it but I think it has yo do something with the kind of datatype or a wrong condition?
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char *ssid = "xxx";
const char *password = "xxx";
const char *mqtt_server = "xxxx";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
int led = D4;
void setup_wifi()
{
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if value of C02 is above 1000
i = atoi (payload); //convert string to integer
if ( i > 1000) // comparison
{
digitalWrite(led, HIGH); // Turn the LED on
}
else
{
digitalWrite(led, LOW); // Turn the LED off
}
}
void reconnect()
{
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic", "Test");
// ... and resubscribe
client.subscribe("my/sensors/co2");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
pinMode(led, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
}
Kind regards
Hi, This is what I publish:
void pubMessage() {
char message[16];
snprintf(message, sizeof(message), "%d", co2);
client.publish("my/sensors/co2", message);
delay(30000);

First you are casting the first byte of payload to a char.
Since it's just the first byte, it has a max value of 256.
Second you are comparing that 1 bytes value to the string '1000'
Without knowing exactly what you are publishing it is very hard to tell you how to fix it.
If you are publishing a string representing the number then you will need to parse it first with atoi() then do the comparison to the integer 1000 not the string.
If it is a byte value then you will need to read the correct value from the incoming byte array before doing the comparison.

Related

Blue ESP8266-12e tx light staying on

I have some code I have been putting on an ESP8266-12e board. Until recently it always worked fine. Now though when I finish uploading the code the blue light on the ESP8266-12e is staying on. I have tried it on two different board and the blue light stay on on both. I can't figure out what I changed in the code.
I have decided to put it up and have everyone look at it and let me know what I may be missing.
I hope someone can find something.
My code:
//NodeMCU 1.0 (ESP-12E Module constant connect)
#include <ESP8266WiFi.h>
#include <FS.h> //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
//MQTT stuff
#define AIO_SERVER "go,here"
#define AIO_SERVERPORT SSSS // 8883 for MQTTS
#define AIO_USERNAME "FFFFFF"
#define AIO_KEY "XXXXXXXXXXXXXXXXXXXXXXX"
int tripper = 1;
#define MQTT_CONN_KEEPALIVE 18000000
#define LED3 16
//NEW AUTOCONNECT
const byte numChars = 32;
char receivedChars[numChars];
char Password[36]="";
char apiKey[16]="";
char apiKey2[32]="";
char channelKey[16];
char channelKey2[16];
String channelKey21= "&";
byte pinState = LOW;
char ssid[] = "";
char pass[] = "";
String Label = "";
String TOTAL = "";
uint32_t m=0;
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe trip2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/trip");
Adafruit_MQTT_Publish move1 = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/motion");
/*************************** Error Reporting *********************************/
Adafruit_MQTT_Subscribe errors = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/errors");
Adafruit_MQTT_Subscribe throttle = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/throttle");
//NEW AUTOCONNECT
int LED2 = 13;
int MOVEMENT = 5;
//send ssid/pass
String f;
//mqtt
char temperature[]="000";
String level;
String battery;
String trip;
String date;
int addr = 0;
//END NEW AUTOCONNECT
void MQTT_connect();
void setup() {
Serial.begin(115200);
pinMode(MOVEMENT,OUTPUT);
digitalWrite(MOVEMENT,LOW);
pinMode(D5,OUTPUT);
digitalWrite(D5,LOW);
pinMode(LED3,OUTPUT);
digitalWrite(LED3,LOW);
pinMode(LED2,INPUT);
Serial.println(F("Adafruit MQTT demo"));
//NEW AUTOCONNECT
WiFiManager wifiManager;
// put your setup code here, to run once:
WiFiManagerParameter customAPIKey("apiKey", "Time Zone #", apiKey, 16);
wifiManager.addParameter(&customAPIKey);
wifiManager.autoConnect("FloWT2");
Serial.println("Connected");
strcpy(apiKey,customAPIKey.getValue());
EEPROM.begin(512); //Initialize EEPROM
EEPROM.write(addr, 'A'); //Write character A
addr++; //Increment address
EEPROM.write(addr, 'B'); //Write character A
String www = apiKey;
Serial.print("www");
Serial.print (www);
for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
{
EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
}
EEPROM.commit();
delay (2000);
if (WiFi.status() == WL_DISCONNECTED) {
wifiManager.autoConnect("FloWT2");
delay(60000);}
if (WiFi.status() == WL_CONNECTED) { Serial.println("Connected");
delay(1000);
//get time zone
EEPROM.begin(512);
Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it
Serial.print(char(EEPROM.read(addr))); //Read from address 0x00
addr++; //Increment address
Serial.print(char(EEPROM.read(addr))); //Read from address 0x01
addr++; //Increment address
Serial.println(char(EEPROM.read(addr))); //Read from address 0x02
//Read string from eeprom
String www;
//Here we dont know how many bytes to read it is better practice to use some terminating character
//Lets do it manually www.circuits4you.com total length is 20 characters
for(int i=0;i<16;i++)
{
www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F
}
Serial.println("this");
Serial.print(www);
Serial.println("IP address: "); Serial.println(WiFi.localIP());
// Setup MQTT subscription for onoff feed
mqtt.subscribe(&trip2);
// Setup MQTT subscriptions for throttle & error messages
mqtt.subscribe(&throttle);
mqtt.subscribe(&errors);
WiFiClient client;
delay(2000);
Serial.printf("SSID: %s\n", WiFi.SSID().c_str());
Serial.printf("SSID: %s\n", WiFi.psk().c_str());
String ssidString = WiFi.SSID().c_str();
String pskString = WiFi.psk().c_str();
f = String('<')+String("Hi")+String(',')+String(ssidString)+String(',')+String(pskString)+String(',')+String(www)+String('>');
delay (1000);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
}
client.stop();
}
void loop() {
MQTT_connect();
uint32_t m=0;
Serial.print(F("\nSending motion val "));
Serial.print(m);
Serial.print("...");
if (! move1.publish(m)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
long state = digitalRead(LED2);
if(state == HIGH) {
m = 1;
Serial.print(F("\nSending motion val "));
Serial.print(m);
Serial.print("...");
digitalWrite(MOVEMENT,HIGH);
delay(1000);
digitalWrite(MOVEMENT,LOW);
if (! move1.publish(m)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
}
else{
}
// this is our 'wait for incoming subscription packets' busy subloop
// try to spend your time here
//12e
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(5000))) {
if (subscription == &trip2) {
Serial.print(F("Got onoff: "));
Serial.println((char *)trip2.lastread);
uint16_t sliderval = atoi((char *)trip2.lastread);
//THIS IS FOR LATCHING RELAY TURN ON D5 HIGH THEN OFF AFTER 1 SECOND
//NEXt TURN D6 HIGH THEN OFF AFTER A SECONDS
if((sliderval ==0)&&(tripper == 1)){
digitalWrite(D5,HIGH);
delay(1000);
digitalWrite(D5,LOW);
tripper = 2;
Serial.print(tripper);
Serial.print("tripped");
}
else if(sliderval == 50){
}
else if((sliderval == 100)&&(tripper == 2)){
digitalWrite(LED3,HIGH);
delay(1000);
digitalWrite(LED3,LOW);
tripper = 1;
Serial.print(tripper);
Serial.print("tripped2");
}
} else if(subscription == &errors) {
Serial.print(F("ERROR: "));
Serial.println((char *)errors.lastread);
} else if(subscription == &throttle) {
Serial.println((char *)throttle.lastread);
}
}
}
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!");
}
I hope it is not toooo long.
Anyway I hope someone can find my problem. Everything works ok with the blue light on it is just know supposed to be that I can tell.
When I upload another code it doesn't stay on so it has to be in the code.
I will keep looking.
THANKS
So I got the blue light to go off. Instead of pinMode(D4,INPUT); and digitalWrite(D4,LOW); D4 is pin 16 which is the wake pin. So I had to define it thus #define LED3 16 and then pinMode(LED3,INPUT); and digitalWrite(LED3,LOW); I will change my original code to reflect these changes.

ESP8266 - Setting Wifi Credentials programmatically and then checking they are valid, and then change them if they are not (without reset)

I have an NodeMCU chip that needs to connect to my home wifi and post an http request. I use the chip in WIFI_STA_AP mode as I need the chip to both accept requests via http and issue requests by http.
I do not want to hard-code my home's SSID/Password into the chip, so I have written some code that places the ESP (NodeMCU) into AP mode, receives the SSID/Pass via an http request and saves it on EEPROM.
This works great.
In the code below, onTestWifi() is called when I call http://192.168.4.1/test_wifi?wifi_ssid=mySsid&wifi_password=myPassword. The ssid and password are provided to the WiFi.begin() function. However, if I accidentally type in the wrong password and use it in WiFi.begin(), the connection will always fail until reset the chip and then insert the correct password.
What am I missing? Is it possible to change the ESP's wifi credentials programmatically, without having to reset the chip? Resetting the chip causes the client (in the case, an iPhone app) to disconnect from the chip and this breaks the entire program flow.
Here's the experimentation code I am using:
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
Serial.println("");
delay(100);
Serial.println("Starting...");
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("APSSID");
IPAddress ip = WiFi.softAPIP();
server.on("/test_wifi", onTestWifi);
server.begin();
yield();
}
void onTestWifi()
{
char ssid[30] = "";
char password[30] = "";
for (int i = 0; i < server.args(); i++)
{
String n = server.argName(i);
String v = server.arg(i);
if (n == "wifi_ssid")
v.toCharArray(ssid, 30);
else if (n == "wifi_password")
v.toCharArray(password, 30);
yield();
}
Serial.print("Connecting to: ");
Serial.print(ssid);
Serial.print(" ");
Serial.println(password);
delay(100);
WiFi.begin(ssid, password);
yield();
int counter = 0;
while (WiFi.status() != WL_CONNECTED && counter < 10)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++counter);
Serial.print(' ');
}
if (WiFi.status() != WL_CONNECTED)
{ // Failed to connect.
Serial.println("Connection failed!");
}
else {
Serial.println("Connection succeeded!");
}
yield();
}
void loop() {
server.handleClient();
}```
OK, so I figured it out. Had to add the line WiFi.disconnect(true) in the onTestWifi() function. Apparently it disconnects from the network and erases the credentials. This stuff is very poorly documented and I wasted days on it.
I hope someone finds it useful.
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
Serial.println("");
delay(100);
Serial.println("Starting...");
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("APSSID");
IPAddress ip = WiFi.softAPIP();
server.on("/test_wifi", onTestWifi);
server.begin();
yield();
}
void onTestWifi()
{
char ssid[30] = "";
char password[30] = "";
for (int i = 0; i < server.args(); i++)
{
String n = server.argName(i);
String v = server.arg(i);
if (n == "wifi_ssid")
v.toCharArray(ssid, 30);
else if (n == "wifi_password")
v.toCharArray(password, 30);
yield();
}
Serial.print("Connecting to: ");
Serial.print(ssid);
Serial.print(" ");
Serial.println(password);
delay(100);
WiFi.begin(ssid, password);
yield();
int counter = 0;
while (WiFi.status() != WL_CONNECTED && counter < 10)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++counter);
Serial.print(' ');
}
if (WiFi.status() != WL_CONNECTED)
{ // Failed to connect.
Serial.println("Connection failed!");
}
else {
Serial.println("Connection succeeded!");
}
WiFi.disconnect(true); // <--- Added this line
yield();
}
void loop() {
server.handleClient();
}

MQTT NodeMCU servo can react only on decimal array payload

I'm creating a fish feeder with SG90 servo and NodeMCU
I used this sketch:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
// Update these with values suitable for your network.
const char* ssid = "your_wifi_hotspot";
const char* password = "your_wifi_password";
const char* mqtt_server = "broker.mqttdashboard.com";
//const char* mqtt_server = "iot.eclipse.org";
Servo myservo; // create servo object to control a servo
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(100);
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Command from MQTT broker is : [");
Serial.print(topic);
for(int i=0;i<length;i++)
{
if((int)payload[i]>194||(int)payload[i]<0)
break;
myservo.write((int)payload[i]); // tell servo to go to position in variable '(int)payload[i]'
}
}//end callback
void reconnect() {
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
//if you MQTT broker has clientID,username and password
//please change following line to if (client.connect(clientId,userName,passWord))
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
//once connected to MQTT broker, subscribe command if any
client.subscribe("OsoyooCommand");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 6 seconds before retrying
delay(6000);
}
}
} //end reconnect()
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
myservo.attach(D1); // attaches the servo on pin D1 to the servo object
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
The servo is working when I use MQTTBox in order to send a payload as "Decimal Array", it is however is giving me a hard time when I send payload as JSON string.
If I send "Decimal Array" 1 it does turn Servo to position 1, however if I simply send 1 as a payload as a string it moves Servo to position 49.
If I send payload as 2 it moves to position 50.
If I send payload as 10 then position is 4948
looks like position of 1 and position of 0 at the same time.
My ultimate goal is to send those payloads via HomeAssistant which are sent as string or JSON, however I don't find a correct solution at the moment.
I would highly appreciate any help or solution.
MQTT payloads are UTF-8 encoded so the Arduino PubSubClient library treats the payload as an array of uint8_t.
If you want to send and receive JSON then you can use the ArduinoJson library to parse a JSON payload. So assuming a JSON payload like:
{
"position": 123
}
Then you can implement a callback such as:
#include <ArduinoJson.h>
// Assuming a fixed sized JSON buffer
StaticJsonBuffer<200> jsonBuffer;
void callback(char* topic, byte* payload, unsigned int length)
{
JsonObject& root = jsonBuffer.parseObject(payload);
if (root.success() && root.is<JsonObject>())
{
int position = root.as<JsonObject>().get<int>("position");
myservo.write(position);
}
}
Looks like the motor is taking the position of the ASCII equivalent of the number when you send it as a string.
i.e.
ASCII equivalent of the character '1' in 49 in decimal
ASCII equivalent of the character '2' in 50 in decimal
Try sending the character 'a', the motor will go to 97.
If you want to send a string, you will have to change the following code:
for(int i=0;i<length;i++)
{
if((int)payload[i]>194||(int)payload[i]<0)
break;
myservo.write((int)payload[i]); // tell servo to go to position in variable '(int)payload[i]'
}
to:
int location=String((char*)payload).toInt()
if((location>194)||(location<0))
return;
myservo.write(location);

Arduino ESP8266 01 MQTT Raspberry pi

I want to use ESP 8266 01 and arduino uno as client in MQTT. The code For ESP8266 01 is successfully compiled and I'M getting errors in Arduino uno
The error is 'messageTemp' was not declared in this scope
Amd also I have a thought of using stm32xx in client.
If I compile for that
exit status 1
ISO C++ forbids comparison between pointer and integer [-fpermissive]
above is the error I'm getting
1)ESP code
// Loading the ESP8266WiFi library and the PubSubClient library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* mqtt_server = "YOUR_RPi_IP_Address";
// Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
if(topic=="home/office/esp1/gpio2"){
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
// digitalWrite(ledGPIO2, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
// digitalWrite(ledGPIO2, LOW);
Serial.print("Off");
}
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("home/office/esp1/gpio2");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Code for Arduino UNO
void setup(){
Serial.begin(9600);
pinMode(12, OUTPUT);
digitalWrite(12, HIGH);
String messageTemp;
}
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
}
void loop ()
{
if (Serial.available()){
char topic = Serial.read();
{
if (topic=="home/office/esp1/gpio2")
{
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
digitalWrite(12, HIGH);
Serial.print("On");
}
else if(messageTemp == "0")
{
digitalWrite(12, LOW);
Serial.print("Off");
}
}}}}
ESP code doesn't look the whole source code you provided. In case of Arduino UNO, if you're intending to use messageTemp as a global variable, then you need to declare it only one time outside of functions. In the above code, you declared it twice in setup() and callback(), then those are considered as local variables. Even in loop(), there's no declaration, this should create the compile error.

The ESP8266 is not connecting to MQTT broker hivemq

I have a simple code in which I am trying to connect to HiveMQ open broker and subscribe to a topic to listen to incoming messages.
here is the code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char *ssid = "P9Inct"; // cannot be longer than 32 characters!
const char *pass = "P9inct123*"; //
const char *mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char *mqtt_user = "testUser";
const char *mqtt_pass = "abc123";
const char *mqtt_client_name = "12312312332212";
#define BUFFER_SIZE 100
String incoming="";
String did="";
String state="";
// Update these with values suitable for your network.
//IPAddress server(172, 16, 0, 2);
String DEVID="8581870006";//"6931108641";//old
WiFiClient wclient;
PubSubClient client(wclient, mqtt_server,mqtt_port);
void callback(const MQTT::Publish& pub) {
// handle message arrived
Serial.print(pub.topic());
Serial.print(" => ");
if (pub.has_stream()) {
uint8_t buf[BUFFER_SIZE];
int read;
while (read = pub.payload_stream()->read(buf, BUFFER_SIZE)) {
Serial.write(buf, read);
}
pub.payload_stream()->stop();
Serial.println("");
} else
Serial.println(pub.payload_string());
////////////////////////////////////////////
incoming=String(pub.payload_string());
Serial.println(pub.payload_string());
Serial.println(incoming);
}
void setup() {
// Setup console
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
Serial.println("Connecting to MQTT server");
if (client.connect(MQTT::Connect(mqtt_client_name)
.set_auth(mqtt_user, mqtt_pass))) {
Serial.println("Connected to MQTT server");
client.set_callback(callback);
client.subscribe("diy/1"+DEVID);
} else {
Serial.println("Could not connect to MQTT server");
}
}
if (client.connected())
client.loop();
}
}
WiFi connection is working fine but, communication via broker is not working and it always gives the message "Could not connect to MQTT server". How to make esp8266 work with HiveMQ broker. The dashboard of borker is
http://www.mqtt-dashboard.com/
So, you are connected. You have unnecessary print line in your loop. Try to adapt on this :
/* Incoming data callback. */
void callback(char* topic, byte* payload, unsigned int length)
{
char payloadStr[length + 1];
memset(payloadStr, 0, length + 1);
strncpy(payloadStr, (char*)payload, length);
Serial.printf("Topic : [%s]\n", topic);
Serial.printf("Payload : %s\n", payloadStr);
}
void performConnect()
{
uint16_t connectionDelay = 5000;
while (!client.connected())
{
if (client.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_KEY))
{
Serial.printf("Connected to Broker.\n");
client.subscribe("diy/1"+DEVID);
}
else
{
Serial.printf("MQTT Connect failed, rc = %d\n", client.state());
Serial.printf("Trying again in %d msec.\n", connectionDelay);
delay(connectionDelay);
}
}
}
void loop()
{
if (!client.connected())
{
performConnect();
}
client.loop();
}

Resources