Giter Club home page Giter Club logo

espmqttclient's People

Contributors

ahamid-ha avatar corny avatar davidbeauchamp avatar dralisz82 avatar drc38 avatar edjopato avatar grafspirt avatar manfredbrauchle avatar markreds81 avatar matasju avatar per1234 avatar plapointe6 avatar sixtyfive avatar stephanmeijer avatar tomskopek avatar youknow0 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

espmqttclient's Issues

onConnectionEstablished setting

The onConnectionEstablished setting is removed in the new version. If I need to define two Mqtt objects in the sketch, how do I write onConnectionEstablished code for these two objects? Thank you

URL based MQTT broker

Hello,
I have a remote broker on a private domain with not a fix IP Address.
Maybe it's my fault, but I can't find a solution based on your code, how can I use an PROTOCOL://URL:PORT or PROTOCOL://URL format with your lib.

Keep up the great job! :)

MQTT connection handling only doesn't work

Hello,

I'm trying to use your library without the wifi connection because I want to use the OTA and a fixed ip for my project.

But the connection with mqtt server doesn't work with:
EspMQTTClient ClientMqtt (mqttServerIp, mqttServerPort, mqttUsername, mqttPassword, mqttClientName);

The Wifi connection is ok, because I have access to the NTP server for my project.

If i use the line:
EspMQTTClient ClientMqtt(ssid, password, mqttServerIp, mqttUsername, mqttPassword, mqttClientName, mqttServerPort);
It's work fine, but i have a dynamic IP for my esp8266 and i want a static ip...

Do you have an idea

Best regards

Autoreconnect issue with ESP32

If ESP lose Wifi signal, this lib should try to reconnect. Now connection is lost until I reset ESP.
I think this is very important for IOT devices.

Allow setting the rate of the MQTT_PINGREQ

I'm using the library with a charging MQTT broker, that charges the MQTT_PINGREQ message too. I recommend to make possible, at the application layer, to configure the rate of the MQTT_PINGREQ .
Anyone know where to configure it in the present library version ?

get matched Topic when wildcard used

If I subscribe to a topic with a wildcard:

client.subscribe("test/#", [] (const String & payload)  {
      Serial.println(payload);
  });

How can I get the full topic (without wildcard) of the matched MQTT message?
Is it a missing feature or a missing documentation?

currentMillis and targetMills may not be addressing rollover

I have been having a problem with events either getting dropped or my code not handling them properly. (I am using a NodeMCU ESP32 board.) In digging through EspMQTTClient, I identified one corner-case problem in how currentMillis and targetMills are compared to determine whether the event should fire. (This is within EspMQTTClient::loop()).

Currently, these are compared using
unsigned long currentMillis = millis();
...
if (mDelayedExecutionList[i].targetMillis <= currentMillis)

My thought is to imagine that the time returned by millis as it nears 2^32 or 4294967296 (49 days). First I imagined that the time is 2^32 - 1000 and a new delay got set 10000 ms (10 sec) into the future. At this point, the target would be computed as 9000 ms. As targetMillis <= currentMillis, the event would fire right away.

Now imagine the reverse, an event gets set with targetMillis to 2^32 - 100. Then imagine that the user's work took 200 milliseconds to complete so that currentMillis rolled around to a small number. At this point, targetMillis would be a big number while currentMillis would be small and we would be unlikely to see that event get fired for another 49 days.

Sadly, I can't figure my way out of this conundrum. Comparing the numbers isn't right. Subtracting the two times will always return a positive number (unsigned numbers are like that). It might be useful to not generate events that land within some small delta of the epoch. Or it might be just good to document the limiting condition and let the user decide what to do.

'id' is not captured

void onConnectionEstablished()
{
  for (Light l : lights) {
    String id = l.getId();

    client.subscribe("light/" + id + "/switch", [](const String & payload) {
      if (payload == "ON") {
        turnOn(id);
        client.publish("light/" + id + "/state", "ON");
      } else if (payload == "OFF") {
        turnOn(id);
        client.publish("light/" + id + "/state", "OFF");
      }
    });
  }
}

Probably a stupid question: how can I use variables and class instances from outside the callback in the callback itself?

How to use this library with a wired connection

Hi,
I currently try to get this working on an ESP32-POE from Olimex. But noticed that it only supports wifi enabled connections. Even if you put the non managed connection without SSID. It still check for wifi.status()

Is it possible to enhance this to support for wired connection aswell?

Best regards!

Automatic assigment of client name

in the client section:
EspMQTTClient client(
...
"TestClient" // Client name that uniquely identify your device
);

Is there a way to define "TestClient" as a variable=string+MAC outside the constructor?

I explain. For example I am doing a project called UFO and I have 30 devices that I want to connect, but I don't want to make up 30 names for each one. I would like to change ''TestClient" for a variable = string + MAC, where string would be for example UFO and MAC would be the device's MAC address and thus obtain something like: NAME = "UFO:5ACF7F0B98D8''.

So the string would tell me which project my device is related to and the MAC would give me a client name that uniquely identify my device.

THANKS.

SimpleMQTTClient example won't compile for ESP32

plapointe6,

I found your project today, installed version 1.5.0 of the library using the Arduino library manager, and have tried to run the simple example.

Here are the compiler messages when I have the Arduino compiler warnings set to all.

Arduino: 1.8.9 (Mac OS X), Board: "NodeMCU-32S, 40MHz, 921600"

Build options changed, rebuilding all
In file included from /Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/EspMQTTClient.h:22:0,
from /Users/macbookpro/Documents/Arduino/EspMQTTClient-master/examples/SimpleMQTTClient/SimpleMQTTClient.ino:8:
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h:31:46: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
void setup(WebServer* server, char* path = "/", char* username = "", char* password = "")
^
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h:31:68: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
void setup(WebServer* server, char* path = "/", char* username = "", char* password = "")
^
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h:31:89: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
void setup(WebServer* server, char* path = "/", char* username = "", char* password = "")
^
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h: In constructor 'ESP32HTTPUpdateServer::ESP32HTTPUpdateServer(bool)':
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h:27:15: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
_username = "";
^
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h:28:15: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
_password = "";
^
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h: In lambda function:
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h:40:24: error: comparison with string literal results in unspecified behaviour [-Werror=address]
if (_username != "" && _password != "" && !_server->authenticate(_username, _password))
^
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h:40:43: error: comparison with string literal results in unspecified behaviour [-Werror=address]
if (_username != "" && _password != "" && !_server->authenticate(_username, _password))
^
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h: In lambda function:
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h:60:26: error: comparison with string literal results in unspecified behaviour [-Werror=address]
if (_username == "" || _password == "" || _server->authenticate(_username, _password))
^
/Users/macbookpro/Documents/Arduino/libraries/EspMQTTClient/src/ESP32HTTPUpdateServer.h:60:45: error: comparison with string literal results in unspecified behaviour [-Werror=address]
if (_username == "" || _password == "" || _server->authenticate(_username, _password))
^
cc1plus: some warnings being treated as errors
Multiple libraries were found for "WiFiClient.h"
Used: /Users/macbookpro/Library/Arduino15/packages/esp32/hardware/esp32/1.0.2/libraries/WiFi
Not used: /Applications/Arduino.app/Contents/Java/libraries/WiFi
exit status 1
Error compiling for board NodeMCU-32S.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Unsubscribe function vs multiple handlers for the topic

The subscribing function allows to have a number of handlers per one topic.
The receiving function works with the same assumption - there can be a number of callback functions (structures) for the same topic, so they all need to be executed.
But the unsubscribing function removes only the first found "subscription" record.
I guess this has to be like:
mTopicSubscriptionList[i] = mTopicSubscriptionList[i + found_counter]; instead of mTopicSubscriptionList[i] = mTopicSubscriptionList[i + 1];
and
mTopicSubscriptionListSize = mTopicSubscriptionListSize - found_counter; instead of mTopicSubscriptionListSize--;.

Or remove this "multiplicity" with topics.

Esp32 mqtt over websocket?

Hi is there any way your code connect mqtt over "ws://" cause this is what I've looked everywhere and found nothing with any library or add-on!

Can you help me with this?

*Ps:
I also ran to some s.hit from espressif called mqtt-clinet.h. That i didn't succed to run it correctly (somehow event handlesr are not implimented !
Im tired of searching and founding literally nothing pensive

espressif/arduino-esp32#3639

Publish fails secretly on too long message

First of all, thanks for the awesome library!

Currently, the return value of the publish call is not handled:

mMqttClient.publish(topic.c_str(), payload.c_str(), retain);

Therefore, in case your message is too long, it will fail secretly.

Would it be possible to either return the status (boolean) in your publish function or mention this failure in the debug message?

HELP:I need more MQTT to receive the information

// Subscribe to "mytopic/test" and display received message to Serial
client.subscribe("mytopic/test/+", [](const String &payload) {
//Serial.println(topic);-------------------->This is the information I need,and more
Serial.println(payload);
});

How do I get more information parameters returned by the MQTT server?
thanks!!!

mqtt disconnecting

I did wonder if I was sufferring from the wifi disconnection issue reported. I was certainly doing somethings you say you shouldn't do (like using delay()).

So, I went back to basics and just used the sample code, but had the executeDelayed() call my function as you posted in the wifi disconnection thread.

While my wifi doesn't disconnect, the mqtt does. This happened only 16 minutes after starting and is very repeatable. Sometimes even quicker.

14:26:28.869 -> Enterered my_function()
14:26:28.869 -> isConnected (1) - isWifiConnected (1) - isMqttConnected (1)
14:26:28.869 -> MQTT << [mytopic/test] This is a message
14:26:28.869 -> Going to sleep now
14:26:38.873 -> Enterered my_function()
14:26:38.873 -> isConnected (1) - isWifiConnected (1) - isMqttConnected (1)
14:26:38.873 -> MQTT << [mytopic/test] This is a message
14:26:38.873 -> Going to sleep now
14:26:38.873 -> MQTT! Lost connection.
14:26:38.873 -> MQTT: Connecting to broker @pi4-4zig ... unable to connect, MQTT_CONNECT_FAILED
14:26:48.870 -> Enterered my_function()
14:26:48.870 -> isConnected (0) - isWifiConnected (1) - isMqttConnected (0)
14:26:48.870 -> Wifi or MQTT not connected!!!
14:26:52.882 -> MQTT: Connecting to broker @pi4-4zig ... unable to connect, MQTT_CONNECT_FAILED
14:27:02.872 -> MQTT: Connecting to broker @pi4-4zig ... unable to connect, MQTT_CONNECT_FAILED

My code is barely more than the sample code :-

/*
  SimpleMQTTClient.ino
  The purpose of this exemple is to illustrate a simple handling of MQTT and Wifi connection.
  Once it connects successfully to a Wifi network and a MQTT broker, it subscribe to a topic and send a message to it.
  It will also send a message delayed 5 seconds later.
*/

#define TIME_TO_SLEEP 10

#include "EspMQTTClient.h"
EspMQTTClient client(
  "SSID",
  "PASSWORD",
  "pi4-4zig",  // MQTT Broker server ip
  "MQTTUsername",   // Can be omitted if not needed
  "MQTTPassword",   // Can be omitted if not needed
  "TestClient",     // Client name that uniquely identify your device
  1883              // The MQTT port, default to 1883. this line can be omitted
);

void setup()
{
  Serial.begin(115200);

  // Optionnal functionnalities of EspMQTTClient : 
  client.enableDebuggingMessages(); // Enable debugging messages sent to serial output
  client.enableHTTPWebUpdater(); // Enable the web updater. User and password default to values of MQTTUsername and MQTTPassword. These can be overrited with enableHTTPWebUpdater("user", "password").
  client.enableLastWillMessage("TestClient/lastwill", "I am going offline");  // You can activate the retain flag by setting the third parameter to true
}

// This function is called once everything is connected (Wifi and MQTT)
// WARNING : YOU MUST IMPLEMENT IT IF YOU USE EspMQTTClient
void onConnectionEstablished()
{
  // Subscribe to "mytopic/test" and display received message to Serial
  client.subscribe("mytopic/test", [](const String & payload) {
    Serial.println(payload);
  });

  // Subscribe to "mytopic/wildcardtest/#" and display received message to Serial
  client.subscribe("mytopic/wildcardtest/#", [](const String & topic, const String & payload) {
    Serial.println(topic + ": " + payload);
  });

  // Publish a message to "mytopic/test"
  client.publish("mytopic/test", "This is a message"); // You can activate the retain flag by setting the third parameter to true

  // Execute delayed instructions
  //client.executeDelayed(5 * 1000, []() {
  //  client.publish("mytopic/test", "This is a message sent 5 seconds later");
  //});
  client.executeDelayed(5 * 1000, my_function);
}

void my_function() {
  Serial.println("Enterered my_function()");
  Serial.print("isConnected (" + String(client.isConnected()) + ")");
  Serial.print(" - isWifiConnected (" + String(client.isWifiConnected()) + ")");
  Serial.println(" - isMqttConnected (" + String(client.isMqttConnected()) + ")");

  // IMPORTANT, protect from spawning multiple delayed instructions when the connection is lost
  if (!client.isConnected()) {
    Serial.println("Wifi or MQTT not connected!!!");
    return;
  }
  client.publish("mytopic/test", "This is a message");
  Serial.println("Going to sleep now");
  
  client.executeDelayed(TIME_TO_SLEEP * 1000, my_function);
}
void loop()
{
  client.loop();
}

Any ideas how I can fix this?

Thanks

client cant get payload

when i publish payload with

`'{"type":"rawir","rawLr":"9020,4360,738,476,716,1566,744,450,718,1564,718,1564,718,476,718,1564,718,476,716,476,718,1564,718,1564,718,1564,718,476,718,474,718,478,716,478,718,478,716,478,718,476,718,476,718,476,718,1564,692,502,718,476,718,476,718,476,718,456,738,476,716,1566,718,476,718,1564,744,450,718,476,744,1538"}'

the nodemcu cant get the payload .

but when i publish with payload
``'{"type":"rawir","rawLr":""}' then its okay.

whats the problem?

how do i pass a function to subscribe?

Hello
i tryed the example, and it works so far, even if i don't understand whats done at the subscribe stage....
look like some stuff is created on the fly, but i want to regroup the handling of incoming messages in a function, but i don't see how to pass that function to the subscribe....

i looked at the source, and there a MessageReceivedCallbackWithTopic was used, but i didn't found where that thing is declared nor how to use it?

thanks for your help!

Connection to WiFI Access Point (AP) happen once of two in a network with two AP with the same SSID

Dear all

Using the SimpleMQTTClient example provided of your project, in some home network can happen that two or more AP with the same SSID are in place. It is important that the library selects the best AP (the one with the strongest signal). I've noticed, however, that using the https://github.com/espressif/arduino-esp32/archive/master.zip ES32 library and your additional library, it doesn't happen, for example when there are two WiFi Access Point with the same SSID. After the first hw reset of the NINA-W102 SDK the board connects to the AP, after the second no, after the third reset, yes and so on. So your example works once out of two, connecting the board to the WiFi Network

Any idea why this happen and do you suggest any workaround ?

Thanks

Connection to WiFI Access Point happen once of two in a network with two AP

Dear Developer,

I've encountered Wifi connection problems using the library network with a specific SSID. In some home network can happen that two or more AP with the same SSID are in place. There are different scenarios: the two access points (used to extend the communication range) operate in the same frequency band and are connected together with an Ethernet cable (scenario 1), but can happen, more frequently, that they operate in the same frequency band (scenario 2)

Scenario1:
It is important that the library selects the best AP (the one with the strongest signal). I've noticed, however that using the https://github.com/espressif/arduino-esp32/archive/master.zip ES32 library and EspMQTTClient lib, it doesn't happen, and to connect to two Access point with the same SSID, the below example works once out of two (if the Access point operate in two different frequency band (100% reproducibility), After the first hw reset of the NINA-W102 EVK (ESP 32) the board connects the AP, after the second no, after the third reset, yes and so on (two access point which operate in two different frequency band)

Scenario 2:
If the two Access point operate in the same frequency band, , sometime it is not be able to connect to the Wifi network.
See below, for the same example of the Scenario 1, the test report

I think the problem is in the native Wifi.begin method, but I'm not sure.
If there is only one access point in the network no connectivity problem is detected.

Setup
https://github.com/espressif/arduino-esp32/archive/master.zip ES32 HAL
EspMQTTClient lib 1.10.1 version
SimpleMQTTClient example related to the EspMQTTClient

Hw
NINA-W101 EVK, but also ESP6832 board with related HAL

Same situation is seen in the ESP8266 hw

Test report with two access points which operate in the same frequency band with the same SSID. When the WiFi module disconnect it is not able to recover the connectivity.

WEB: Updater ready, open http://device:7c11f525-c2c8-4f04-b09e-68c5c3c4e256.local in your browser and login with username '2UGGED3TVEPBIYJUGY84' and password 'mnuJ7c8myednY27HHzlk3TJOzyXRPXE43Z76UDRC'.
20:34:02.164 -> MQTT: Connecting to broker "mqtt.broker" with client name "xxxxxxx )unable to connect (16.494000s), reason: MQTT_CONNECTION_TIMEOUT
20:34:17.284 -> MQTT: Retrying to connect in 15 seconds.
20:34:17.324 -> MQTT!: Failed MQTT connection count: 1
20:34:32.304 -> MQTT: Connecting to broker "mqtt.thingstream.io" with client name "devicexxxx" ... (31.495000s) - ok. (31.834000s)
20:34:32.624 -> MQTT: Subscribed to [mytopic/test]
20:34:32.624 -> MQTT: Subscribed to [mytopic/wildcardtest/#]
20:34:32.664 -> MQTT << [mytopic/test] This is a message
20:34:33.024 -> MQTT >> [mytopic/test] This is a message
20:34:33.024 -> This is a message
20:34:37.629 -> MQTT << [mytopic/test] This is a message sent 5 seconds later
20:34:37.834 -> MQTT >> [mytopic/test] This is a message sent 5 seconds later
20:34:37.834 -> This is a message sent 5 seconds later
20:34:42.264 -> ets Jun 8 2016 00:22:57
20:34:42.264 ->
20:34:42.264 -> rst:0x1 (POWERON_RESET),boot:0x37 (SPI_FAST_FLASH_BOOT)
20:34:42.264 -> configsip: 0, SPIWP:0xee
20:34:42.264 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
20:34:42.264 -> mode:DIO, clock div:2
20:34:42.264 -> load:0x3fff0018,len:4
20:34:42.264 -> load:0x3fff001c,len:1044
20:34:42.264 -> load:0x40078000,len:10044
20:34:42.264 -> load:0x40080400,len:5872
20:34:42.264 -> entry 0x400806ac
20:34:42.624 -> ⸮
20:34:43.264 -> WiFi: Connecting to Vodafone-27586605 ... (0.651000s)
20:34:43.384 -> WiFi! Connection attempt failed, delay expired. (0.781000s).
20:34:43.864 -> E (1961) wifi: esp_wifi_disconnect 1153 wifi not start
20:34:43.904 ->
20:34:43.904 -> WiFi: Connecting to Vodafone-27586605 ... (1.284000s)
20:35:43.884 -> WiFi! Connection attempt failed, delay expired. (61.285000s).
20:35:43.884 -> E (61962) wifi: esp_wifi_disconnect 1153 wifi not start
20:35:44.404 -> E (62462) wifi: esp_wifi_disconnect 1153 wifi not start

QoS?

Hey any hint on where I can set the QoS to 2? I am hunting for this through the code and libs and a tad lost.

broker returns invalid UTF-8 message if lastwilltopic read from variable

Hi,

probably more of user error than bug :-) I'd like to set the lastwilltopic but I receive an invalid UTF-8 message from mosquitto:

1581849946: Malformed UTF-8 in will topic string from ContactSensor01, disconnecting.

This DOES work;
client.enableLastWillMessage("test", "false", false);

but the example below does not. Why?

char chArTemp[] = "test";
client.enableLastWillMessage(chArTemp, "false", false);

Thanks in advance

loop blocked if MQTT broker no available

Library tested on ESP32 Dev Module.
Very smart and powerful library,but (for me) a big issue:
If the esp32 boot and no broker MQTT available loop is blocked during mqtt server connecting tentative.
During connection mqtt tentative, I use a button that don't react (led stay off or on).
No problem during wifi connection.

Web updater not working

Hello I have implemented a sketch based on the example

I enabled the HttpWeb Updater, I went to http://mqttclient.local and I enter the mqtt user and password and the screen to upload the binary appears.

I choose the binary click on update and it says "Update Success! Rebooting...", but after reboot the behavior is the same as if the binary didnt change at all

If I take the device and upload the code via serial the change gets reflected. (I tried setting a blinking led or changing the blink rate, the change only reflects when flashing over serial)

#include "EspMQTTClient.h"

#define LED 2

EspMQTTClient client(
  "MySSID",
  "MyPWD",
  "192.168.x.xx",  // MQTT Broker server ip
  "user",   // Can be omitted if not needed
  "password",   // Can be omitted if not needed
  "mqttclient",      // Client name that uniquely identify your device
  1883              // The MQTT port, default to 1883. this line can be omitted
);

void setup()
{
   pinMode(LED, OUTPUT);
  client.enableHTTPWebUpdater(); // Enable the web updater. User and password default to values of MQTTUsername and MQTTPassword. 
}

void loop()
{
  client.loop();
  delay(500);
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level);
  delay(500);
  digitalWrite(LED, LOW);   // turn the LED on (HIGH is the voltage level);
}

Connect to MQTT broker with hostname instead of IP address

Hello,

I am trying to connect to my MQTT server hosted on my Raspberry Pi. Since it is hosted on a private network, I would like to connect to the MQTT server with the RPI hostname (raspberrypi.local). I know I can manually write its IP address but it is not very convenient in my case (if the IP address of the RPI changes).

I was able to ping the "raspberrypi.local" hostname from a MacBook, so I know it's available on my private network.

Is there any way I can connect with the hostname with this library?

The code for creating the client :
client = new EspMQTTClient( "ssid", "password", "raspberrypi.local", "rpi", 1883 );

And the Serial Monitor :
MQTT: Connecting to broker @raspberrypi.local ... unable to connect, MQTT_CONNECT_FAILED

Thanks!

128 byte payload limit

Anything over 128 bytes in the MQTT payload causes the system to fail.

Is there a way to raise this limit?

attachInterrupt Error

I used this code with the old version, "attachInterrupt(digitalPinToInterrupt(Int_Pin), IntCallback, RISING);" cars only Compile and run fine.
However, after the latest update, the compiled code caused repeated restarts on my esp8266.
`attachInterrupt(digitalPinToInterrupt(Int_Pin), IntCallback, RISING);

void IntCallback()
{
KeyInt = 0;
attachInterrupt(digitalPinToInterrupt(Key_Pin), KeyCallback, RISING);
}

void KeyCallback()
{
KeyInt += 1; //Another program handles the KeyInt variable
}
`

Please help me. thank you

Solving the problem with connecting to Wi-Fi

Hello!
I had problems connecting to the network via Wi-Fi.
The solution was to add the WiFi.waitForConnectResult () function to the void EspMQTTClient :: connectToWifi () method.
Now it works for me like this:

void EspMQTTClient :: connectToWifi ()
{
WiFi.mode (WIFI_STA);
WiFi.begin (mWifiSsid.c_str (), mWifiPassword.c_str ());

if (mEnableSerialLogs)
Serial.printf ("\ nConnection to% s", mWifiSsid.c_str ());

WiFi.waitForConnectResult ();

mLastWifiConnectionMillis = millis ();
}

Best regards, Peter

WLAN connection bug on some Fritz!Box routers with ESP32 hardware

Hello,
there is a rather nasty bug with the WLAN connection when trying to connect to a Fritz!Box router with an ESP32: the connection always fails on the first connection attempt an only works after trying a second time.
This is not a bug in your code in itself, but one rather deep inside the ESP32 librarys. However, EspMQTTClient is also suffering from it. At the moment there is only a workaround that you could maybe implement in EspMQTTClient?
I tried with a local copy of your library an it works for me at least:

// ================== Private functions ====================-

void EspMQTTClient::connectToWifi()
{
  WiFi.mode(WIFI_STA);
  #ifdef ESP32
    WiFi.setHostname(mMqttClientName);
  #else
    WiFi.hostname(mMqttClientName);
  #endif
  WiFi.begin(mWifiSsid, mWifiPassword);

  if (mEnableSerialLogs)
    Serial.printf("\nWiFi: Connecting to %s ", mWifiSsid);

  #ifdef ESP32
  // Workaround to a rather nasty BUG with Fritz!Box routers from AVM, where only every other WLAN connection attempt is working.
  // So we will try up to 3 times.
  int tryCount = 0;
  while (WiFi.status() != WL_CONNECTED && tryCount <= 12)
  {
    Serial.print(".");
    tryCount++;
    delay(500);
    if (WiFi.status() == WL_CONNECT_FAILED && (tryCount % 4 == 0))
    {
      WiFi.begin(mWifiSsid, mWifiPassword);
    }
  }
  Serial.println();
  #endif

  mLastWifiConnectionAttemptMillis = millis();
}

see also here: ESP32 WiFi.begin works only every second time - workaround

More sig changes?

So looks like there are more sig changes and I cannot pass in WiFi.macAddress() as the client name anymore. Any thoughts on how to make this work?

Subscribing to topics with wildcards never triggers callback

I just discovered if you wish to subscribe to a topic using wildcards, the check to pull the callback out of the subscription list only looks for exact equivalence so it will never fire.

e.g. espmqtt client subs to my/test/topic/+, another client pubs to my/test/topic/bug; in EspMQTTClient::mqttMessageReceivedCallback, mTopicSubscriptionList[i].topic will contain my/test/topic/+, and topic will contain my/test/topic/bug.

ArduinoOTA compatability with EspMqttClient

Hi,

I've been trying to integrate or make it work alongside but I've been encountering some errors and resets, and can't seem to figure it out. Maybe someone else got it working (ArduinoOTA and EspMqttClient) together?

The error:

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0018,len:4
load:0x3fff001c,len:1100
load:0x40078000,len:9232
load:0x40080400,len:6412
entry 0x400806a8
/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/freertos/queue.c:1442 (xQueueGenericReceive)- assert failed!
abort() was called at PC 0x40088b35 on core 0

Backtrace: 0x4008c774:0x3ffe38e0 0x4008c9a5:0x3ffe3900 0x40088b35:0x3ffe3920 0x400ff736:0x3ffe3960 0x400ffa12:0x3ffe3980 0x400ef57c:0x3ffe39a0 0x400ef5e5:0x3ffe39c0 0x40101b7e:0x3ffe39e0 0x40100838:0x3ffe3a00 0x400ee256:0x3ffe3a40 0x4014c6d2:0x3ffe3a60 0x4014c7c9:0x3ffe3aa0 0x40120fbb:0x3ffe3ad0 0x400d205d:0x3ffe3b20 0x400d1a67:0x3ffe3ba0 0x400d7b53:0x3ffe3bd0 0x40082c8f:0x3ffe3bf0 0x40082e94:0x3ffe3c20 0x40078f2b:0x3ffe3c40 0x40078f91:0x3ffe3c70 0x40078f9c:0x3ffe3ca0 0x40079165:0x3ffe3cc0 0x400806da:0x3ffe3df0 0x40007c31:0x3ffe3eb0 0x4000073d:0x3ffe3f20

Rebooting...

Or maybe you use something else for OTA updates? The WebUploader works great, but i wish to use it with platformio upload.

Possibility to set static IP address

Hello,

by initializing EspMQTTClient with wifi SSID and password it would be great when I could also associate a static IP to it for monitoring cases.

Is this a huge thing to implement?

mqtt server disconnected and never reconnected after working for a day

**I have used this wonderful library for my Relay (Mqtt control via Android APP).

I am just working fine, but when i woke up in the morning, the mqtt does not work from my app.

I have checked the app connection with pc mqtt.fx and is running fine.

I have Arduino OTA support added, so i can update the code, and the esp8266 works again.
But next morning, same problem.

What could be the problem. (There's no problem in the sketch (see below))**

`#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include "EspMQTTClient.h"

#define DEBUG false

EspMQTTClient client(
"MY_SSID",
"MY_PASSWORD",
"broker.hivemq.com", // MQTT Broker server ip
"", // Can be omitted if not needed
"", // Can be omitted if not needed
"TestClientxxx", // Client name that uniquely identify your device
1883 // The MQTT port, default to 1883. this line can be omitted
);

// Relay On or Off (1 or 0)
#define TOPIC "/feedsxyz/relayon"
//Status of the Relay
#define TOPIC1 "/feedsxyz/relaystatus"
//Time Relay is on (Secs)
#define TOPIC2 "/feedsxyz/relaytime"
//Time Esp is Running (Mins)
#define TOPIC3 "/feedsxyz/runtime"

long timer1 = 0;
long timer2 = 0;
long timer3 = 0;
long sec1 = 0;
unsigned long runtime = 0;

#define RELAY 13

void setup() {

pinMode(RELAY, OUTPUT);
digitalWrite(RELAY, LOW);

if (DEBUG) Serial.begin(115200);
delay(10);

ArduinoOTA.setHostname("Motor");
ArduinoOTA.begin();

// Optionnal functionnalities of EspMQTTClient :
client.enableDebuggingMessages(DEBUG); // Enable debugging messages sent to serial output
//client.enableHTTPWebUpdater(); // Enable the web updater. User and password default to values of MQTTUsername and MQTTPassword. These can be overrited with enableHTTPWebUpdater("user", "password").
//client.enableLastWillMessage(TOPIC, "0"); // You can activate the retain flag by setting the third parameter to true
}

void loop() {
ArduinoOTA.handle();
client.loop();

// Send ESP Runtime Every Minute
if (((millis() - timer3 ) / 1000) >= 60) {
timer3 = millis();
runtime=runtime+1;
client.publish(TOPIC3, (String(runtime)));
}

//Send Motor Status Every 5 Secs
if (((millis() - timer2 ) / 1000) >= 5) {
timer2 = millis();

client.publish(TOPIC1, (digitalRead(RELAY) == HIGH) ? "1" : "0");

}

//Relay Safety (Relay Off After 2 Hours of ON Time Max)
if (((millis() - timer1 ) / 1000) >= 5) {
timer1 = millis();

if (digitalRead(RELAY) == HIGH) {
  sec1 = sec1 + 5;
client.publish(TOPIC2, String(sec1));
} else {
  sec1 = 0;
}
if (sec1 >= 7200) {
  sec1 = 0;
  digitalWrite(RELAY, LOW);
  delay(100);
  client.publish(TOPIC1, "0");
}

}
}

void onConnectionEstablished()
{
// Subscribe to "mytopic/test" and display received message to Serial
client.subscribe(TOPIC, [](const String & payload) {

//Convert String to Char*
char buffer[20];
payload.toCharArray(buffer, 20);

//Convert Char* to Int
int n;
n = atoi(buffer);

//Relay On or Off
if (n == 1)digitalWrite(RELAY, HIGH); else digitalWrite(RELAY, LOW);

if (DEBUG) Serial.println(payload);

if (DEBUG) Serial.println(n);

// Publish a Relay Status
client.publish(TOPIC1, (n == 1) ? "1" : "0");

});

}`

Version 1.10 in Arduino Library Fails

Versions 1.08 and 1.09 compile and work well (thanks!), but 1.10 fails with:

/Users/foo/Documents/Arduino/libraries/EspMQTTClient/src/EspMQTTClient.cpp: In member function 'void EspMQTTClient::loop()':
/Users/foo/Documents/Arduino/libraries/EspMQTTClient/src/EspMQTTClient.cpp:272:13: error: 'class EspClass' has no member named 'reset'
         ESP.reset();

Make Wifi connection status public

Could it be possible to add public methods to access mWifiConnected and mMqttConnected?

it would be useful in order to show status information when wifi is connected but the broker is not.

RFE, please support wildcards (i.e., # and +)

Hi, since the underlying PubSubClient (by knolleary) does support wildcards could it be possible to support them also in this lib?
Currently if I subscribe to a wildcard topic such as "root/sub/#" the subscription succeeds but no callback is called.
Thank you

Client fails to connect to broker if WLAN connect fails in first client.loop() call

It took me some time to isolate the root cause the last days. For unknown reasons I was only able to connect to the broker in every second boot of my ESP32. I instrumented the client with some debug statements and finally found out this test does not handle a WLAN setup and no retry is executed.

I commented out the test such that a connect was executed all the time when there is no connection and then my ESP was able to connect to the broker all the time.

I'm sure the if statement handles some retry and cannot be commented out.

I use Arduino 1.8.13.

See following debug log when there is no issue

19:34:32.495 -> WiFi: LOOP
19:34:32.528 -> WiFi: NOT CONNECTED
19:34:32.528 -> WiFi: RETRY
19:34:32.561 -> WiFi: MyWLAN 0 0 - 
19:34:32.561 -> 
19:34:32.561 -> WiFi: CONNECTTO 
19:34:32.594 -> 
19:34:32.594 -> WiFi: CONNECTTO 
19:34:32.627 -> 
19:34:32.627 -> WiFi: CONNECTTO status 6
19:34:32.627 -> 
19:34:32.627 -> WiFi: Connecting to MyWLAN ... 
19:34:33.291 -> [ 1655 ms ] IR: 30024  Full: 65535  Visible: 35511  Lux: -1.000000
19:34:33.357 -> MQTT! publish failed, is the message too long ?
19:34:34.286 -> WiFi: LOOP
19:34:34.286 -> WiFi: CONNECTED
19:34:34.319 -> WiFi: Connected, ip : 192.168.0.116
19:34:34.352 -> MQTT: Connecting to broker @192.168.0.12 ... ok.
19:34:34.418 -> MQTT << [mytopic/test] This is a message
19:34:35.048 -> [ 3404 ms ] IR: 41531  Full: 65535  Visible: 24004  Lux: -1.000000
19:34:35.114 -> MQTT << [/dawn/sensor/2] 41531;65535;24004;-1.000000```

See following log when the connection request fails

9:36:26.883 -> WiFi: LOOP
19:36:26.916 -> WiFi: NOT CONNECTED
19:36:26.916 -> WiFi: RETRY
19:36:26.949 -> WiFi: MyWLAN 0 0 - 
19:36:26.949 -> 
19:36:26.949 -> WiFi: CONNECTTO 
19:36:26.983 -> 
19:36:26.983 -> WiFi: CONNECTTO 
19:36:27.016 -> 
19:36:27.016 -> WiFi: CONNECTTO status 6
19:36:27.016 -> 
19:36:27.016 -> WiFi: Connecting to MyWLAN ... 
19:36:27.647 -> [ 1631 ms ] IR: 34954  Full: 65535  Visible: 30581  Lux: -1.000000
19:36:27.713 -> MQTT! publish failed, is the message too long ?
19:36:28.642 -> WiFi: LOOP
19:36:28.675 -> WiFi: NOT CONNECTED
19:36:28.675 -> WiFi: RETRY
19:36:28.708 -> WiFi: MyWLAN 909 0 - 
19:36:29.372 -> [ 3353 ms ] IR: 33892  Full: 65535  Visible: 31643  Lux: -1.000000
19:36:29.438 -> MQTT! publish failed, is the message too long ?
19:36:30.367 -> WiFi: LOOP
19:36:30.400 -> WiFi: NOT CONNECTED
19:36:30.400 -> WiFi: RETRY
19:36:30.434 -> WiFi: MyWLAN 909 0 - 
19:36:31.096 -> [ 5075 ms ] IR: 33773  Full: 65535  Visible: 31762  Lux: -1.000000
...

EspMQTTClient dynamic configuration

Hey. I have a good start of your class EspMQTTClient on the esp8266 platform .But I would like to have to adjust the connection settings after reading the SD card.Please tell me how can I change the connection settings to WIFI and MQTT broker in the code of the setup function?

(ESP01 and ESP12E) Disconnects Permanently from Broker after some Hour/Day (And FIX)

I have a Water Pump, Street Light, Other Hardware working with esp8266 (Different Models) (This Library).

It runs and blinks led light every 2 seconds (for activity tracking).

They run 24x7 in my house without any issue. But after a day or so , it does not listens my mqtt commands (But esp is running, check using activity Led)
I'm using broker.hivemq.com with different clientid's

I added a fix (Reset Esp8266 when mqtt is disconnected for 2 minutes).

It works very good , now it don't quit mqtt broker permanently ( Several Days have passed ).

Here's the fix , if you run your board for 24x7, then you should add it to your sketch.

Fix:

Either use this library 's ajaybnl-fix commit, or:

**Define timer4 variable as unsigned long, interror as int,
Add to loop:

if ((millis() - timer4) >= 15000) {
timer4 = millis();
if(!client.isConnected()) interror++; else interror=0;
if(interror>4) ESP.reset();
}

Problem Fixed.

Deep sleep reconnect issue with ESP32 and a solution

Edit: added ESP8266 part.

I had trouble to get ESP32 connected after adding "esp_deep_sleep_start();" to the "loop(){...}".

This could be related to #51

The problem I found was, that in the libraries loop() function no test for "NOT been connected" was made first.
So the first loop call will always fail to connect.

Therefor I added this "if..." (naively, without looking into the rest of this function) to:

void EspMQTTClient::loop()
{
  unsigned long currentMillis = millis();

  if (WiFi.status() != WL_CONNECTED)
  {
    connectToWifi();
  }
  

The connectToWifi() had some stability problems with ESP32:

void EspMQTTClient::connectToWifi()
{
  WiFi.mode(WIFI_STA);
#ifdef ESP32
  WiFi.setHostname(mMqttClientName);
#else
  WiFi.hostname(mMqttClientName);
#endif

  if (mEnableSerialLogs)
    Serial.printf("\nWiFi: Connecting to %s .", mWifiSsid);

#ifdef ESP32
  int tryCount = 0;
  bool myWiFiFirstConnect = true;
  wl_status_t state = WiFi.status();
  while (state != WL_CONNECTED && tryCount <= 5)
  {
    tryCount++;

    if (state == WL_NO_SHIELD || state != WL_CONNECTED) {
      if (mEnableSerialLogs) Serial.println("Connecting WiFi");

      WiFi.mode(WIFI_STA);
      WiFi.begin(mWifiSsid, mWifiPassword);
      vTaskDelay (250);

    } else if (state == WL_CONNECT_FAILED) {  // WiFi.begin has failed (AUTH_FAIL)
      if (mEnableSerialLogs) Serial.println("Disconnecting WiFi");

      WiFi.disconnect(true);

    } else if (state == WL_DISCONNECTED) {  // WiFi.disconnect was done or Router.WiFi got out of range
      if (!myWiFiFirstConnect) {  // Report only once
        myWiFiFirstConnect = true;

        if (mEnableSerialLogs) Serial.println("WiFi disconnected");
      }
    }

    state = WiFi.status();
  }
  if (mEnableSerialLogs) {
    if (state == WL_CONNECTED) {
      Serial.print(" -> Connected: IP ");
      Serial.println(WiFi.localIP());
    } else {
      Serial.printf(" -> NOT Connected\n");
    }
  }
#else
  WiFi.begin(mWifiSsid, mWifiPassword);
#endif

  mLastWifiConnectionAttemptMillis = millis();
}

I didn't make a PR since I did not test ESP8266.

This solution works perfectly for me with ESP32 with deep sleep.

For copycats: Please always download the latest IDE, board library and mqtt libs (PubSub 2.8 works for me). This is very important for fixing this error.

Thank you for the nice & slim library!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.