GithubHelp home page GithubHelp logo

marvinroger / async-mqtt-client Goto Github PK

View Code? Open in Web Editor NEW
835.0 46.0 263.0 201 KB

📶 An Arduino for ESP8266 asynchronous MQTT client implementation

License: MIT License

C++ 96.95% C 0.16% Makefile 0.21% Python 1.12% Shell 1.57%
mqtt asynchronous arduino client esp8266 esp32

async-mqtt-client's Introduction

Async MQTT client for ESP8266 and ESP32

Build with PlatformIO cpplint

An Arduino for ESP8266 and ESP32 asynchronous MQTT client implementation, built on me-no-dev/ESPAsyncTCP (ESP8266) | me-no-dev/AsyncTCP (ESP32).

Features

  • Compliant with the 3.1.1 version of the protocol
  • Fully asynchronous
  • Subscribe at QoS 0, 1 and 2
  • Publish at QoS 0, 1 and 2
  • SSL/TLS support
  • Available in the PlatformIO registry
  • New: Option to discover the MQTT server by searching for the service _mqtt over the _tcp port.

Requirements, installation and usage

The project is documented in the /docs folder.

async-mqtt-client's People

Contributors

9a4gl avatar adam5wu avatar allanbartley avatar arihantdaga avatar bertmelis avatar bolukan avatar cturqueti avatar cyber-junkie9 avatar davea avatar dudanov avatar endym avatar flaviostutz avatar ivankravets avatar jamesgol avatar jeroenst avatar luebbe avatar marvinroger avatar merlinschumacher avatar pablo2048 avatar rampi avatar rousveiga avatar skorokithakis avatar thijstriemstra avatar timpur avatar uhsl-marcus 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  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

async-mqtt-client's Issues

Esp8266 do not get client_id on start

I'm having issues with conntion to broker. In mosquitto logs I see connection comes from esp8266 but it has null client_id. Esp8266 gets client_id only after several wifi restarts.

Call ESP8266httpUpdate within on_mqtt_publish. Return connection refused

Call ESP8266httpUpdate within on_mqtt_publish. ESP8266httpUpdate returns connection refused. i.e. not able to download firmware. If I call ESP8266httpUpdate within void setup(). It is able to download the firmware.

connection_refuse

Full code is here.
https://github.com/kenpeter/mqtt_esp_http_update_sample/blob/master/phone.txt
https://github.com/kenpeter/mqtt_esp_http_update_sample/blob/master/device.txt

The idea is that the phone.txt fire a json command, then it triggers on_mqtt_publish in device.txt, then it calls ota_update()

connect/disconnect cycle with FullyFeaturedSSL example

I'm trying the FullyFeaturedSSL example. It works with nossl, but when I try the code with ssl I run into the connect/disconnect cycle. The disconnect reason is 0. What could be the TCP problem considering that nossl works?

Sending ping too often

It seems like to logic behind the ping and keepalive is buggy.
No matter hwat keepalive i set, the ping is always send after 6-8 seconds.

I believe the expected behaviour is to send a PINGREQ after keepalive * 1000 * 0.7.

So if I'd set the keepalive to 120 seconds. I would only expect to see a pingreq/pingresp after 84 seconds.

I'm using the homie-esp8266 code for testing. But I also hardcoded the keepalive value in the mqtt-code as 120 also without result.

lastWill and local variable

Hi,
I just wanted to note (for anyone elsehaving the same trouble like me), that passing a topic name in local variable to lastWill method is not going to do any good...
Weird that I'm doing the same with publish and it seems fine.

Does not work

void test() {
    String lastwilltopic='some/topic';

    mqttClient.setKeepAlive(30).setWill(lastwilltopic.c_str(), 2, true, "0"); 
}

Does work

String lastwilltopic='some/topic';
void test() {
    mqttClient.setKeepAlive(30).setWill(lastwilltopic.c_str(), 2, true, "0"); 
}

By the way - perfect job. Thank you.

Keep alive

I am publishing every 1 sec 3 messages to mosquitto, one of them is having around 500-600 bytes and other two around 200 bytes each.

Keep Alive on ESP is set with mqttClient.setKeepAlive(30) to be 30 sec ( default 15). On my mosquitto I have 120 seconds timeout for the connection so will be like 3-4 consecutive packets missed before the cleanup.

So every 120 sec I've got a disconnect from mosquitto because of not receiving the keepalive. If I don't transmit any packet I don't have problems with keepalive.

Do you have any suggestion ?

using lib to pulish data to io.adafruit.com

Adafruit made mqtt lib to sub &pub data on cloud io.adafruit.com, it used user key to authentication, I've tried to use key as client id setClientId(AIO_KEY); but it didn't connect to server, have any clue to how to add this feature ?
my sample sketch is here

#include <ESP8266WiFi.h>
#include <AsyncMqttClient.h>
#define AIO_USERNAME    "mkeyno"  
#define AIO_KEY         "bd8977eab79646c3b7779e8c47154a851"
 
AsyncMqttClient mqttClient;
uint32_t last_Temp_reading;
byte QOS=1;
bool Retain=true;
 

void onMqttConnect(bool sessionPresent) {
  Serial.print(F("** Connected to the broker **"));
  Serial.print(F("  Session present: "));  Serial.println(sessionPresent);
         uint16_t packetIdSub = mqttClient.subscribe("mkeyno/feeds/ESP8266", 2);  Serial.print(F("Subscribing at QoS 2, packetId: "));  Serial.println(packetIdSub);  
                                mqttClient.publish("mkeyno/feeds/ESP8266", 0, true, "test 1"); Serial.println(F("Publishing at QoS 0")); 
  uint16_t       packetIdPub1 = mqttClient.publish("mkeyno/feeds/ESP8266", 1, true, "test 2"); Serial.print(F("Publishing at QoS 1, packetId: "));  Serial.println(packetIdPub1);
  uint16_t       packetIdPub2 = mqttClient.publish("mkeyno/feeds/ESP8266", 2, true, "test 3");Serial.print(F("Publishing at QoS 2, packetId: "));   Serial.println(packetIdPub2);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.print(F("** Disconnected from the broker reason="));
   Serial.println(static_cast<uint8_t>(reason));
  Serial.println(F("Reconnecting to MQTT..."));
 /*
 TCP_DISCONNECTED = 0,
  MQTT_UNACCEPTABLE_PROTOCOL_VERSION = 1,
  MQTT_IDENTIFIER_REJECTED = 2,
  MQTT_SERVER_UNAVAILABLE = 3,
  MQTT_MALFORMED_CREDENTIALS = 4,
MQTT_NOT_AUTHORIZED = 5
 */
  mqttClient.connect();
}

void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.print(F("\t** Subscribe acknowledged **"));
  Serial.print(F("  packetId: "));Serial.print(packetId);Serial.print(F("  qos: ")); Serial.println(qos); 
}

void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println(F("** Unsubscribe acknowledged **"));
  Serial.print(F("  packetId: ")); Serial.println(packetId); 
}

void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  Serial.println(F("** Publish received onMqttMessage**"));
  Serial.print(F("  topic: "));  Serial.print(topic);
  Serial.print(F("  qos: "));  Serial.print(properties.qos);
  Serial.print(F("  dup: "));  Serial.print(properties.dup);
  Serial.print(F("  retain: "));  Serial.print(properties.retain);
  Serial.print(F("  len: "));  Serial.print(len);
  Serial.print(F("  index: "));  Serial.print(index);
  Serial.print(F("  total: "));  Serial.println(total);
}

void onMqttPublish(uint16_t packetId) {
  Serial.print(F("\t** Publish acknowledged **"));
  Serial.print(F("  packetId: "));  Serial.println(packetId);
}

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);
   String MyMAC=WiFi.macAddress();Serial.print("My MAC: ");Serial.println(MyMAC);
 
  Serial.print("Connecting to Wi-Fi");
  WiFi.begin("qqq", "aaaaaa");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
String MyIP=WiFi.localIP().toString();
   Serial.print("AP IP address: ");Serial.println(MyIP);
   
  

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  mqttClient.onSubscribe(onMqttSubscribe);
  mqttClient.onUnsubscribe(onMqttUnsubscribe);
  mqttClient.onMessage(onMqttMessage);
  mqttClient.onPublish(onMqttPublish);
  mqttClient.setServer("https://io.adafruit.com", 8883);
  mqttClient.setKeepAlive(5).setCleanSession(false).setWill("mkeyno/feeds/ESP8266", 2, true, "no").setClientId(AIO_KEY);//.setCredentials("username", "password")
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}

String val;
void loop() {
 if((millis()- last_Temp_reading)> 5000)
 {
  val=String(millis()/1000);
  Serial.println("MQTT..."+val); 
 mqttClient.publish("mkeyno/feeds/ESP8266", QOS, Retain,  val.c_str());
 last_Temp_reading=millis();
 }
}

Compilation error if this library is not used in .ino file

I found that this library must be used and included only in main .ino file.

I created a new sketch together with a cpp (mqtt.cpp) file. In cpp file I want to do all these mqtt tasks.
These are the only two lines of codes in cpp file:

#include <ESP8266WiFi.h>
#include <AsyncMqttClient.h>

And I always get warning at the second line:


Arduino: 1.6.9 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 921600, 4M (3M SPIFFS)"

In file included from C:\Users\eos1d3\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\ESP8266WiFi\src/WiFiClient.h:25:0,

                 from C:\Users\eos1d3\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\ESP8266WiFi\src/ESP8266WiFi.h:39,

                 from sketch\mqtt.cpp:2:

c:\users\eos1d3\appdata\local\arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2\xtensa-lx106-elf\include\c++\4.8.2\bits\stl_vector.h: In member function 'std::vector<_Tp, _Alloc>::size_type std::vector<_Tp, _Alloc>::_M_check_len(std::vector<_Tp, _Alloc>::size_type, const char*) const':

C:\Users\eos1d3\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/Arduino.h:253:18: error: expected unqualified-id before '(' token

 #define max(a,b) ((a)>(b)?(a):(b))

                  ^

c:\users\eos1d3\appdata\local\arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2\xtensa-lx106-elf\include\c++\4.8.2\bits\stl_bvector.h: In member function 'std::vector<bool, _Alloc>::size_type std::vector<bool, _Alloc>::_M_check_len(std::vector<bool, _Alloc>::size_type, const char*) const':

C:\Users\eos1d3\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/Arduino.h:253:18: error: expected unqualified-id before '(' token

 #define max(a,b) ((a)>(b)?(a):(b))

                  ^

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

If I move the codes in cpp to .ino file, it compiles fine.
And I also downgraded ESP8266 core to 2.2, the problem is still the same.

Non-clean sessions Support?

Hi,
I wanted to know if your MQTT supports non clean sessions.
In short, I am running my ESP8266 off of battery so I want it to periodically wake up and check for messages on the MQTT topic. Since I am doing this, there is a chance I could miss messages that are published to the topic. With support for non clean sessions, I could get the messages when my ESP8266 comes back online.

Connection and disconnection issues

Hi it is me again. :)

With the FullyFeatured example, using current version of the library, I find it needs very long time to get disconnection status after first batch of callback calls. onMqttDisconnect callbacks work, but It took around 8 to 12 minutes to get disconnect status when tested with Adafruit IO.

Then I used the above example to test with Mosquitto on my RPI3. And I never see onMqttDisconnect is called. This is the log in 45 minutes:

Connecting to Wi-Fi.............. OK
Connecting to MQTT...
== Connected
Subscribing, packetId: 1
Publishing at QoS 0
Publishing at QoS 1, packetId: 2
Publishing at QoS 2, packetId: 3
== Subscribe acknowledged
  packetId: 1
  qos: 0
== Publish received
  topic: eos1d3/feeds/lol
  qos: 0
  len: 6
  index: 0
  total: 6
payload: test 3
== Publish received
  topic: eos1d3/feeds/lol
  qos: 0
  len: 6
  index: 0
  total: 6
payload: test 1
== Publish acknowledged
  packetId: 2
== Publish received
  topic: eos1d3/feeds/lol
  qos: 0
  len: 6
  index: 0
  total: 6
payload: test 2
== Publish acknowledged
  packetId: 3
== Publish received
  topic: eos1d3/feeds/lol
  qos: 0
  len: 6
  index: 0
  total: 6
payload: test 3

But I remember the old library worked very well with these brokers.

And the fatal problem is after disconnection, there is no way to reconnect to broker (Adafruit or Mosquitto), even passing the credentials to mqttclient is also the same.

All tested are done with FullyFeatured example and my own Sketh example. And both Adafruit IO an Mosquitto on RPI3 are tested.

I also tested with ESP8266 core 2.2.0 and 2.3.0. Both versions are having the same problem.

For FullyFeatured example, I just changed the account name, password and topics. The rest of codes remained the same.

_clear() in _onTimeout() callback

What should calling _clear() in _onTimeout() do or what does actually this timeout mean? Because I think it makes my connection not work after internet connectivity recovery. _onPoll() actually fires quite happily, but there is one _onTimeout() call in between which ruins it... It flags the connection as not connected (due to _clear()) and it never recovers again*.
Maybe it's not a bug or a bug somewhere else, but commenting out _clear() seems to work for me.
(But _onTimeout() is still called once in a while, probably after sending ping, weird)

Edit:
*) it does recover (disconnects), but those repeated timeouts keep the connection dropping.
Edit2:
Seems like TCP ACK issue, need to investigate where does it come from.

big messages & order

Hello,

i have a scenario where i receive different topic message with a big json (> 1024)

i have created a global buffer like
char mqttBuffer[MQTT_TOPICS][MAX_TOPIC_LEN];

and i concat the chunk that i receive on the callback onMqttMessage
to the correct index.

it's that approach correct?
the data it's there :) i can parse, read it and everything (when total = num_char_readed)
but it's that efficient?

it consume a bit of memory, should i change it in some other way?

are the message chunk received in different order for different topic?
ie: it's possible to reiceive a chunk of topic1, then topic2, then the rest of topic1?
if it's not possible, then i can just use 1 single buff, but i need a confirmation on that

Feature request

Auto read a file and send response when got a "trigger message" from broker?

Retained flag missing from received messages

From http://www.hivemq.com/blog/mqtt-essentials-part-8-retained-messages

Also the subscribing client can identify if a received message was a retained message or not, because the broker sends out retained messages with the retained flag still set to true. A client can then decide on how to process the message.

The receive message should include the retain flag. But the callback from current implementation do not have it. So there is no way to check if the message is a normal message or retained one.

Including the library breaks mutli .ino build

As the title says, if I include the AsyncMqttClient.h library in any of the sketches, I can not call functions from other tabs(ino files).

Simple to reproduce:
Create new sketch and add a new tab whatever the name
main.ino

#include <AsyncMqttClient.h>
void setup() {
  test();
}
void loop() {}

test.ino

int test(){
  return 1
  }

It will compile if #include <AsyncMqttClient.h> is removed.

Constant disconnect/reconnect cycle

I was having some issues with exceptions occurring when I integrated this client into my own code, so I decided to try the example code provided in this repo. Unfortunately, using the provided example code, I am just seeing the following console output:

Connecting to Wi-Fi...... OK
Connecting to MQTT...
** Disconnected from the broker **
Reconnecting to MQTT...
** Disconnected from the broker **
Reconnecting to MQTT...
** Disconnected from the broker **
Reconnecting to MQTT...
** Disconnected from the broker **
Reconnecting to MQTT...

The connection never actually seems to be made to the broker even though I know it is running.

Any clues or tips?

QOS 1 and 2 publish - automatic retry

It is not made clear in the doc: Will this library automatically retry publishing any unconfirmed QOS 1 or 2 messages, or is it up the implementation to attempt to publish again if no confirmation was received?

Random disconnects cant figure out whats wrong.

Edzelf/Esp-radio#87

https://gist.github.com/NonaSuomy/e50cfdf079fe1bbbcac30a381e34fd93

D: Metadata block 48 bytes
D: Streamtitle found, 47 bytes
D: StreamTitle='Billy Talent - Afraid of Heights';
D: Publish to topic espradio/icy/streamtitle : Billy Talent - Afraid of Heights
D: MQTT Publish acknowledged, packetId = 34
D: 10 minutes over
D: Metadata block 64 bytes
D: Streamtitle found, 48 bytes
D: StreamTitle='The Killers - When You Were Young';
D: Publish to topic espradio/icy/streamtitle : The Killers - When You Were Young
D: MQTT Publish acknowledged, packetId = 35
D: MQTT Disconnected from the broker, reason 0, reconnecting...
D: MQTT reconnection attempt: 1
D: MQTT Disconnected from the broker, reason 0, reconnecting...
D: MQTT Disconnected from the broker, reason 0, reconnecting...

Any help would be appreciated.

For now, I just check if every loop if connected then reconnect but would like to find out what's causing the disconnect. MQTT broker is local and nothing else seems to have the disconnect happen I believe reason 0 is something to do with the client failing.

Reconnect does not work when WIfi is lost

If Wifi is lost, reconnect does not work, using the example provided (FullyFeatured)
The event "onMqttDisconnect" is fired but "onMqttConnect" is never trigered.

** Disconnected from the broker **
Reconnecting to MQTT...

Stays always like this.

Make it completely safe about TCP buffer

Currently, the CONNECT, DISCONNECT, PUBACK, PUBREC, PUBREL and PUBCOMP packets might not get sent (or worse, might corrupt the TCP flow if a partial packet is sent) if the TCP buffer is full.

Stuck in reconnect loop

First off, this library is awesome; thank you for creating it. It's rock solid except for when my ESP gets disconnected and gets stuck in the reconnect loop. Here is the log from the fully featured example:

Disconnected from MQTT.
Connecting to MQTT...
Disconnected from MQTT.
Connecting to MQTT...

I can't trigger the disconnection consistently so I'm not sure what's causing it but getting stuck in the reconnect loop is worse. The Mosca MQTT server manages other clients & messages just fine while the ESP is caught in this loop. I assume the ESP has WiFi connection since it's in the MQTT reconnect loop. I'm using Adafruit' ESP8266 Feather HUZZAH. Any thoughts as to why this might be happening?

Is there a danger of using `String("xox").c_str()`

I'd like to know if there is any problem of using temporary strings within a function to send a mqtt message. Does you lib copy them over to a buffer for sending later, or resending if the ack is not received?

example doesn't build.

Using the example, https://github.com/marvinroger/async-mqtt-client/blob/master/docs/1.-Getting-started.md

I get the following error

Arduino: 1.6.8 (Mac OS X), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

Build options changed, rebuilding all
/var/folders/0s/sftdlnmx35scwybt6gn15s640000gp/T/arduino_modified_sketch_466625/sketch_may19a.ino: In function 'void onMqttDisconnect(AsyncMqttClientDisconnectReason)':
sketch_may19a:23: error: no matching function for call to 'HardwareSerial::println(AsyncMqttClientDisconnectReason&)'
   Serial.println(reason);
                        ^
/var/folders/0s/sftdlnmx35scwybt6gn15s640000gp/T/arduino_modified_sketch_466625/sketch_may19a.ino:23:24: note: candidates are:
In file included from /Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Stream.h:26:0,
                 from /Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/HardwareSerial.h:31,
                 from /Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Arduino.h:246,
                 from sketch/sketch_may19a.ino.cpp:1:
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:79:16: note: size_t Print::println(const __FlashStringHelper*)
         size_t println(const __FlashStringHelper *);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:79:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'const __FlashStringHelper*'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:80:16: note: size_t Print::println(const String&)
         size_t println(const String &s);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:80:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'const String&'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:81:16: note: size_t Print::println(const char*)
         size_t println(const char[]);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:81:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'const char*'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:82:16: note: size_t Print::println(char)
         size_t println(char);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:82:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'char'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:83:16: note: size_t Print::println(unsigned char, int)
         size_t println(unsigned char, int = DEC);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:83:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'unsigned char'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:84:16: note: size_t Print::println(int, int)
         size_t println(int, int = DEC);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:84:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'int'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:85:16: note: size_t Print::println(unsigned int, int)
         size_t println(unsigned int, int = DEC);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:85:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'unsigned int'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:86:16: note: size_t Print::println(long int, int)
         size_t println(long, int = DEC);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:86:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'long int'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:87:16: note: size_t Print::println(long unsigned int, int)
         size_t println(unsigned long, int = DEC);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:87:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'long unsigned int'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:88:16: note: size_t Print::println(double, int)
         size_t println(double, int = 2);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:88:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'double'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:89:16: note: size_t Print::println(const Printable&)
         size_t println(const Printable&);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:89:16: note:   no known conversion for argument 1 from 'AsyncMqttClientDisconnectReason' to 'const Printable&'
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:90:16: note: size_t Print::println()
         size_t println(void);
                ^
/Users/matthewbordignon/Library/Arduino15/packages/esp8266/hardware/esp8266/2.2.0/cores/esp8266/Print.h:90:16: note:   candidate expects 0 arguments, 1 provided
exit status 1
no matching function for call to 'HardwareSerial::println(AsyncMqttClientDisconnectReason&)'

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

Doing this, temporarily lets it build

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.print("== Disconnected: ");
//  Serial.println(reason); // << --- NOT WORKING
  Serial.println("Reconnecting to MQTT...");
  mqttClient.connect();
}

Can I also suggest you add the example as a separate file as well when you get time. ie /examples/pubsub_example.ino

Matt.

Make a configurable limit on topic length

The only way to crash the device currently is by sending a message on a topic with a length larger than what the ESP8266 RAM can handle. A setMaxTopicLength() function could be added, so the topic buffer would be allocated once, and the message would be skipped if the topic length is larger than the limit. What would be a good default? Can you guys tell me what's the longest topic you use?

null terminated payloads

I was wondering if it would be possible to make the buffer for the payload null terminated. As in always have it len + 1, and have that be '\0'.

I'm asking as for some reason sometime when I use mqtt spy i get a non null terminated string and it overruns the buffer and I risk an exception. My way round it was to first copy into a new buyer that was null terminated. Now I just set buffer[len] = '\0', however I'm not sure how long you've made the receiving buffer so this might also not be the best practice.

In the end I want to make it safe you use String(buffer), and avoid another intermediate copy!

A

using Async connection for a Server - Clinets connection

hi @marvinroger sorry to make the issue for my question , actually I've planned to set a ESP module as AP and other ESP module as Station mode and like IOT home , the server received and send command to those , Iggre told me I should use asyinc lib instead of Esp8266WebServer lib , I really appreciated if you could guide me to what strategy should follow

Error httpupdate

Hi,
I tried using ESP8266httpUpdate OTA with my ESP8266 07 - arduino 1.8.2 - esp8266 2.3.0 core along with async-mqtt-client . It returned this error message:
HTTP_UPDATE_FAILD Error (-104): Wrong HTTP codeStart
I tried using httpupdate with other libs (not async), it worked well. The include list is below:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <EEPROM.h>
#include <Ticker.h>
#include <ArduinoOTA.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>
#include <string.h>
#include <PubSubClient.h>

Can some one help me please. Thanks.

Library won't reconnect.

I have the library set to reconnect on disconnection, but that doesn't work, and I find the clients frequently disconnected even though they are on WiFi. Is there a setting I can use, or another way I can make them keep trying to reconnect?

esp8266 crashed....

Hi!
Esp crashed when got retained message in subscribed topic (only after reboot) - how i can debug it?

`Exception (28):
epc1=0x402073d3 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

ctx: sys
sp: 3ffffc80 end: 3fffffb0 offset: 01a0

stack>>>
3ffffe20: 3ffebe3e 0000002d 3fff1620 40207165
3ffffe30: 3fff3714 00000000 402066a8 4020b5e8
3ffffe40: 3fff411c 3ffffed0 40206660 4020b64
...
fffff80: 4020de06 3ffeef78 00000000 3fff3b6c
3fffff90: 3fffdc80 00000000 3fff4274 40216dcb
3fffffa0: 40000f49 3fffdab0 3fffdab0 40000f49
<<<stack<<<

ets Jan 8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld`

FullyFeatured.ino example - subscribe to publish?

Are lines 10, 11, 12 really required? mqttClient.publish appears to work OK without subscribing to the topic first.
uint16_t packetIdSub = mqttClient.subscribe("test/lol", 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);

Reconnect only works on second/third try....

Reconnecting always takes two goes..

Using this sketch, which disconnects after 10 seconds, and immediately reconnects.. you can see it has to try twice!

here is the serial output, millis() in brackets... forced disconnect and reconnect...

Connecting to Wi-Fi........ OK
Connecting to MQTT...
 [    5080] Connected to the broker
 [    5081] Subscribe done

 [   14052] Manual Disconnect Started....
 [   14056] Disconnected from the broker reason = TCP_DISCONNECTED
 [   14056] Reconnecting to MQTT..
 [   14064] Connected to the broker
 [   14064] Subscribe done
 [   14093] Disconnected from the broker reason = TCP_DISCONNECTED
 [   14093] Reconnecting to MQTT..
 [   15102] Connected to the broker
 [   15102] Subscribe done

here is mosquito output. initial connections first then 2 lines, and the disconnect and reconnect attempts.

1495404891: New connection from 172.17.0.1 on port 1883.
1495404891: Client myDevice already connected, closing old connection.
1495404891: Client myDevice disconnected.
1495404891: New client connected from 172.17.0.1 as myDevice (c0, k5, u'username').


1495404900: Client myDevice disconnected.
1495404900: New connection from 172.17.0.1 on port 1883.
1495404900: Client myDevice disconnected.
1495404900: New client connected from 172.17.0.1 as myDevice (c0, k5, u'username').
1495404900: Socket error on client myDevice, disconnecting.
1495404901: New connection from 172.17.0.1 on port 1883.
1495404901: Client myDevice disconnected.
1495404901: New client connected from 172.17.0.1 as myDevice (c0, k5, u'username').

the sketch

#include <ESP8266WiFi.h>
#include <AsyncMqttClient.h>


const char * ssid = "ccc";
const char * pass = "ccc";

AsyncMqttClient mqttClient;

void onMqttConnect(bool sessionPresent) {
  Serial.printf(" [%8u] Connected to the broker\n", millis());  
//  mqttClient.subscribe("test/a", 2);
//  mqttClient.subscribe("test/b", 2);
//  mqttClient.subscribe("test/c", 2);
//  mqttClient.subscribe("test/d", 2);
//  mqttClient.subscribe("test/e", 2);
//  mqttClient.subscribe("test/f", 2);
//  mqttClient.subscribe("test/g", 2);
  Serial.printf(" [%8u] Subscribe done\n", millis());  

  
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
String text; 
  switch( reason) {
  case AsyncMqttClientDisconnectReason::TCP_DISCONNECTED:
     text = "TCP_DISCONNECTED"; 
     break; 
  case AsyncMqttClientDisconnectReason::MQTT_UNACCEPTABLE_PROTOCOL_VERSION:
     text = "MQTT_UNACCEPTABLE_PROTOCOL_VERSION"; 
     break; 
  case AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED:
     text = "MQTT_IDENTIFIER_REJECTED";  
     break;
  case AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE: 
     text = "MQTT_SERVER_UNAVAILABLE"; 
     break;
  case AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS:
     text = "MQTT_MALFORMED_CREDENTIALS"; 
     break;
  case AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED:
     text = "MQTT_NOT_AUTHORIZED"; 
     break;
  
  }
  Serial.printf(" [%8u] Disconnected from the broker reason = %s\n", millis(), text.c_str() );
  Serial.printf(" [%8u] Reconnecting to MQTT..\n", millis());
  mqttClient.connect();
}

void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.printf(" [%8u] Subscribe acknowledged id: %u, qos: %u\n", millis() ,packetId, qos);
}

void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("** Unsubscribe acknowledged **");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  Serial.println("** Publish received **");
  Serial.print("  topic: ");
  Serial.println(topic);
  Serial.print("  qos: ");
  Serial.println(properties.qos);
  Serial.print("  dup: ");
  Serial.println(properties.dup);
  Serial.print("  retain: ");
  Serial.println(properties.retain);
  Serial.print("  len: ");
  Serial.println(len);
  Serial.print("  index: ");
  Serial.println(index);
  Serial.print("  total: ");
  Serial.println(total);
}

void onMqttPublish(uint16_t packetId) {
  Serial.println("** Publish acknowledged **");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

uint32_t timer = 0;  

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);
  Serial.print("Connecting to Wi-Fi");
  WiFi.begin(ssid, pass);

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

  Serial.println(" OK");

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  mqttClient.onSubscribe(onMqttSubscribe);
//  mqttClient.onUnsubscribe(onMqttUnsubscribe);
//  mqttClient.onMessage(onMqttMessage);
//  mqttClient.onPublish(onMqttPublish);
  mqttClient.setServer(IPAddress(192, 168, 1, 234), 1883);
  mqttClient.setKeepAlive(5).setCleanSession(false).setWill("topic/online", 2, true, "no").setCredentials("username", "password").setClientId("myDevice");
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
  timer = millis(); 
}

bool havetried = false; 

void loop() {
  if (!havetried && mqttClient.connected() &&  millis() - timer > 10000) {
    Serial.printf("\n [%8u] Manual Disconnect Started....\n", millis() ); 
    mqttClient.disconnect(); 
    timer = millis(); 
    havetried = true; 
  }
}

String instead of char*

Is it possible to use String instead of char* on .publish, .subscribe, .setwill
Strings are easier to use than char*.

For example:
String topic=id+"/order"
mqttClient.publish(topic, 0, true, "1");

AsyncMqttClient::setSecure(bool) -- Need help

Ive tried very thing i can think off.

Currently using:
Arduino: 1.8.3
ESP Arduino: 2.4.0-rc1
AsyncTCP: Latest git pull (27th)
AsyncMQTT: Latest(27th)

Build: Generic ESP8266 Module, 1mb (64kb)

The Sketch im trying to build (test build script):
"
#define ASYNC_TCP_SSL_ENABLED 1

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <AsyncMqttClient.h>

AsyncMqttClient mqttClient;

void setup() {
// put your setup code here, to run once:

mqttClient.connect();
mqttClient.setSecure(true);
}

void loop() {
// put your main code here, to run repeatedly:

}
"

The Error:
(~ = my dir)
"
C:\Users~\AppData\Local\Temp\arduino_build_20908\sketch\sketch_jun28a.ino.cpp.o:(.text.setup+0x4): undefined reference to `AsyncMqttClient::setSecure(bool)'

C:\Users~\Local\Temp\arduino_build_20908\sketch\sketch_jun28a.ino.cpp.o: In function `setup':

C:\Users~\AppData\Local\Temp\arduino_modified_sketch_817953/sketch_jun28a.ino:14: undefined reference to `AsyncMqttClient::setSecure(bool)'

collect2.exe: error: ld returned 1 exit status
"

The build also tells me this:
Using library ESP8266WiFi at version 1.0 in folder: ...
Using library Ticker at version 1.0 in folder: ...
Using library async-mqtt-client at version 0.8.1 in folder: ...
Using library ESPAsyncTCP at version 1.0.0 in folder: ...

If any one has any idea?
Tim.

panic in onMessage handler

hi, I'm getting a panic in my onMessage handler:

MQTT: got msg on topic: advent/aaa/c

Panic /home/karlp/.platformio/packages/framework-arduinoespressif8266/cores/esp8266/core_esp8266_main.cpp:98 __yield
< stack dump omitted, but I can provide it if you're keen >

The fail there is from "cont_can_yield" failing, which has a few issues reported, apparently from non-arduino context code calling yield? I suppose this implies that the handlers are "non arduino" code? So code like the following in a handler:

void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total)
{
    Serial.printf("MQTT: got msg on topic: %s\n", topic);
    for (int i = 0; i < 5; i++) {
        strip.SetPixelColor(1, RgbColor(40, 40, 0));
        strip.Show();
        delay(40);
        strip.SetPixelColor(0, RgbColor(0, 40, 40));
        strip.Show();
        delay(40);
    }
    Serial.println("here!")

Is simply unacceptable? I had presumed that since "delay" == yield, I could do this quite happily, but I guess not? I suppose I can setup handlers here instead...

enhancement client id default

future enhancement,

"Set the client ID. Defaults to esp8266."

Can we have it set to instead, esp8266 + mac address?

_keepAlive

This might be nothing. I might have just missed it, but when I search for the variable _keepAlive it doesn't come up with any functions that use it. Just the function to set it, the declaration of _keepAlive, and where it is assigned. There is nothing that uses it?

What am i missing?

sorry if I'm being stupid! Just trying to work out why I'm getting these disconnects!

unable to access the "char* topic" and "char* payload" inside "void loop()" after saving values in global variables.

Hi,
First of all, thank you for this amazing library!

I am facing one issue. And I am not able to resolve it.

in the following function:

void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total)
{
    payload_new = payload;
    topic_new = topic;
    Serial.println("** new message received **");
    Serial.print("topic: ");
    Serial.println(topic_new);
    Serial.print("payload: ");
    Serial.println(payload_new);
}

here, payload_new and topic_new are char* declared as global (before setup() ).

I am able to get the values inside the above function. But when I try to print them inside loop(), it gives a blank space.

void loop()
{
    Serial.println("reveived value is: ");
    Serial.println(payload_new);
}

How can I access the values of those variables inside the loop() as well?

I apologise if this is a noob question. But I tried googling and was not successful.

Payload not being null-terminated

I am using an ESP8266-12F and the Arduino IDE 1.6.12. I installed the latest master on November 30th, but I have been having problems with the payload. Starting with FullyFeatured.ino and entering my wifi info, I also added the following lines to the end of onMqttMessage (after line 58):
` Serial.print(" payload: '");
Serial.print(payload);
Serial.println("'");

char new_payload[len+1];
new_payload[len] = '\0';
strncpy(new_payload, payload, len);
Serial.print("**new_payload: '");
Serial.print(new_payload);
Serial.println("'");`

Following is an example of the types of results I am seeing:
`** Publish received **
topic: test/lol
qos: 0
dup: 0
retain: 0
len: 6
index: 0
total: 6
payload: 'test 1@�'
**new_payload: 'test 1'

** Publish received **
topic: test/lol
qos: 1
dup: 0
retain: 0
len: 6
index: 0
total: 6
payload: 'test 2P�'
**new_payload: 'test 2'

** Publish received **
topic: test/lol
qos: 2
dup: 0
retain: 0
len: 6
index: 0
total: 6
payload: 'test 3 '
**new_payload: 'test 3'`

Note that payload always has extra characters at the end and is not properly null-terminated. When I create a new char and set the last byte to null, the payload is correctly displayed. Trying to work directly with payload is impossible, whether storing it as a string or trying to convert it with atoi(), however all operations with new_payload appear to be working.

Attempting to fix payload directly with this line causes immediate resets:
payload[len] = '\0';

This has been tested on two different ESP8266-12F boards to ensure it wasn't a hardware fault, and the value of len always matches the exact data I'm trying to send.

Stack Trace using SSL example

I'm getting the following stack-trace when connecting to an SSL enabled mosquitto broker. Could this be related to my mosquitto configuration? I didn't modify anything other than the necessary vaeriables at the top of the code.
Build was: platformio run --target upload

I am using Mosquitto as the broker if that is helpful. The only log messages from the broker are:

1499780241: New connection from 192.168.1.3 on port 8883.
1499780331: Client (null) has exceeded timeout, disconnecting.
1499780448: mosquitto version 1.3.4 terminating

Stacktrace:

Exception 3: LoadStoreError: Processor internal physical address or data error during load or store
Decoding 28 results
0x4020e647: __memcpy_aux at /Users/igrokhotkov/e/newlib-xtensa/xtensa-lx106-elf/newlib/libc/machine/xtensa/../../../../.././newlib/libc/machine/xtensa/memcpy.S line 92
0x40246114: chip_v6_unset_chanfreq at ?? line ?
0x402204fb: SHA512_Final at crypto/sha512.c line 207 (discriminator 3)
0x40219770: x509_new at ssl/x509.c line 201
0x4023d427: pp_attach at ?? line ?
0x4023d476: pp_attach at ?? line ?
0x402178f5: process_certificate at ssl/tls1.c line 2005
0x40218cd2: do_clnt_handshake at ssl/tls1_clnt.c line 107
0x4010020c: _umm_free at umm_malloc.c line ?
0x402069b6: ax_port_read at ?? line ?
0x4021871c: do_handshake at ssl/tls1.c line 2005
:  (inlined by) basic_read at ssl/tls1.c line 1481
0x40100688: free at ?? line ?
0x40218884: ssl_read at ssl/tls1.c line 2005
0x4020677d: tcp_ssl_read at ?? line ?
0x40205fa9: AsyncClient::_recv(tcp_pcb*, pbuf*, signed char) at ?? line ?
0x40212b1e: tcp_output at /Users/ivan/e/arduino-esp8266/tools/sdk/lwip/src/core/tcp_out.c line 925
0x40205fdb: AsyncClient::_s_recv(void*, tcp_pcb*, pbuf*, signed char) at ?? line ?
0x4021681c: tcp_input at /Users/ivan/e/arduino-esp8266/tools/sdk/lwip/src/core/tcp_in.c line 394 (discriminator 1)
0x401068f8: pvPortMalloc at ?? line ?
0x40214dd5: ip_input at /Users/ivan/e/arduino-esp8266/tools/sdk/lwip/src/core/ipv4/ip.c line 559
0x40214271: ethernet_input at /Users/ivan/e/arduino-esp8266/tools/sdk/lwip/src/netif/etharp.c line 1379
0x40103c12: lmacTxFrame at ?? line ?
0x4010402d: ppEnqueueRxq at ?? line ?
0x40103dc3: ppProcessTxQ at ?? line ?
0x40103dfe: ppProcessTxQ at ?? line ?
0x4022641b: ets_snprintf at ?? line ?

Provide information on memory management

Could you maybe add some documentation about the memory management.

How big is the buffer?
max send and receive size?
Is the buffer fixed, or dynamic? (i've had a peek at the code, but it is not so obvious), is the message even buffered by the lib, or is it held in memory by the async TCP code, until the ACK is received. if so are there imitations on msg size.
Can you send messages bigger than this buffer (i'm assuming it is 1460bytes)

How does this work on the receive side? Receiving large messages?

looking forward to switching :)

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.