arduino-libraries / arduinomqttclient Goto Github PK
View Code? Open in Web Editor NEWArduinoMqttClient Library for Arduino
License: GNU Lesser General Public License v2.1
ArduinoMqttClient Library for Arduino
License: GNU Lesser General Public License v2.1
Am I correct SSL isn’t supported?
Thanks.
Hi Arduino Team
I am testing this library in ESP32, in https://test.mosquitto.org/ work fine, but in my server with IP and nodered i have the error code 2
I have testing with library pubsubclient and work without error
For secure connections where the Client
is served over SSL, the message size is slightly greater and the below assert fails.
I replaced the !=
condition with <
so that it fails only when message could not be send in full.
int MqttClient::endMessage()
{
if (!_txStreamPayload) {
if (!publishHeader(_txPayloadBufferIndex) ||
(clientWrite(_txPayloadBuffer, _txPayloadBufferIndex) != _txPayloadBufferIndex)) {
stop();
return 0;
}
}
#ifndef MyMqtt_h
#define MyMqtt_h
#include <Arduino.h>
#include <ArduinoMqttClient.h>
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
const char broker[] = "xxx.xxx.xxx.xxx";
int port = 1883;
char* topics(const char* topic) {
static char buffer[50];
snprintf(buffer, sizeof(buffer), "/%s/%s", mqttid, topic);
return buffer;
}
void topics_subscribe() {
mqttClient.subscribe(topics("info/command"));
// topics can be unsubscribed using:
// mqttClient.unsubscribe(topic);
}
void onMqttMessage(int messageSize) {
// we received a message, print out the topic and contents
Serial.print("Received a message with topic '");
Serial.print(mqttClient.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");
// use the Stream interface to print the contents
while (mqttClient.available()) {
Serial.print((char)mqttClient.read());
}
Serial.println();
Serial.println();
}
void setup_mqtt() {
//#if TX_PAYLOAD_BUFFER_SIZE < 512 // If the max message size is too small, throw an error at compile time. See MqttClient.cpp line 35
//#error "TX_PAYLOAD_BUFFER_SIZE is too small in libraries/ArduinoMqttClient/src/MqttClient.cpp at line 35, increase it to 512"
//#endif
// You can provide a unique client ID, if not set the library uses Arduino-millis()
// Each client must have a unique client ID
// mqttClient.setId("clientId");
mqttClient.setId(clientid);
// You can provide a username and password for authentication
mqttClient.setUsernamePassword("xxxxxxxxxx", "xxxxxxxxx");
if (WiFi.isConnected()) {
Serial.print("Attempting to connect to the MQTT broker: ");
Serial.println(broker);
if (!mqttClient.connect(broker, port)) {
Serial.print("MQTT connection failed! Error code = ");
Serial.println(mqttClient.connectError());
} else {
Serial.println("Client connected!");
topics_subscribe();
}
mqttClient.onMessage(onMqttMessage);
}
}
#include <ESP8266Ping.h>
const IPAddress remote_ip(xxx, xxx, xxx, xxx);
#include <ESP8266HTTPClient.h>
HTTPClient http;
int attemptReconnect() {
int connected;
if (Ping.ping(remote_ip, 1)) {
if (D)Serial.println("Success!!");
http.setReuse(true);
WiFiClient client;
http.begin(client, "xxx.xxx.xxx.xxx", 1883);
int httpCode = http.GET();
if (D)Serial.printf("[HTTP] GET... code: %s\n", http.errorToString(httpCode).c_str());
if (D)Serial.printf("[HTTP] GET... code: %d\n", httpCode);
if (httpCode == -5) {
connected = -5;
} else {
connected = 0;
}
http.end();
} else {
connected = 0;
if (D)Serial.println("Error :(");
}
if (connected == -5) {
if (!mqttClient.connect(broker, port)) {
if (D)Serial.print("MQTT connection failed! Error code = ");
if (D)Serial.println(mqttClient.connectError());
}
return mqttClient.connectError();
} else {
return -2;
}
}
int xxx = 1000;
void loop_mqtt() {
if (!mqttClient.connected()) { // if the client has been disconnected,
//Serial.println("Client disconnected, attempting reconnection");
BWoD(xxx) {
if (xxx < 600000) {
xxx = xxx * 1.5;
} else {
xxx = 1000;
}
Serial.printf("------------- %d -------------\n", xxx);
if (!attemptReconnect()) { // try reconnecting
mqttreconnect++;
xxx = 1000;
if (D)Serial.print("Client reconnected!");
if (D)Serial.println();
topics_subscribe();
}
}
} else {
mqttClient.poll();
}
BWoD(1000) {
if (mqttClient.connected()) {
if (D) {
Serial.print("Sending message to topic: ");
Serial.println(topics("info"));
Serial.println(info_topic());
}
// send message, the Print interface can be used to set the message contents
mqttClient.beginMessage(topics("info"));
mqttClient.print(info_topic());
mqttClient.endMessage();
if (D)Serial.println();
if (D) {
Serial.print("Sending message to topic: ");
Serial.println(topics("data"));
Serial.println(data_topic());
}
// send message, the Print interface can be used to set the message contents
mqttClient.beginMessage(topics("data"));
mqttClient.print(data_topic());
mqttClient.endMessage();
if (D)Serial.println();
}
}
}
#endif
I'm using ArduinoMqttClient together with a mosquitto broker, and sometimes when sending a QoS2 message, the connection will drop silently. (It seems this always happens on the second QoS2 message, but I'm not sure)
This is the output of mosquitto at the time of the connection drop:
1643105742: Received PUBLISH from mqtt:topic:01045ea9a2:a24a82972a (d0, q2, r0,
m2, 'mqtt:topic:01045ea9a2:a24a82972a/Notify', ... (29 bytes))
1643105742: Sending PUBREC to mqtt:topic:01045ea9a2:a24a82972a (m2, rc0)
1643105742: Received PINGREQ from mqtt:topic:01045ea9a2:a24a82972a
1643105742: Sending PINGRESP to mqtt:topic:01045ea9a2:a24a82972a
1643105742: Received DISCONNECT from mqtt:topic:01045ea9a2:a24a82972a
1643105742: Client mqtt:topic:01045ea9a2:a24a82972a disconnected.
It seems like ArduinoMqttClient responds to PUBREC with a PINGREQ instead of the correct message. How could this happen?
Hi! I'm trying to send a retained message, my code is as follows:
mqttClient.beginMessage(topicVRCommand, true);
mqttClient.print("WAKE_UP_KITCHEN");
mqttClient.endMessage();
The message is not going as retained even though i have the reained flag as true. Anyone had the same problem?
Hi, it would be nice to get a chance to set the flag for clean session to high or either low.
Best Regards
Fabian
First Comment…It works great to Publish Topics.
I fought PubSubClient for a week and could not get it to work.
I used ArduinoMQTT for 10 minutes and it worked perfect to Publish Topics.
First my setup…
Sparkfun Redboard (I live in Colorado so shipping is cheap)
Sparkfun ESP8266 WiFi shield.
No problem connecting to my WiFi and Publishing a topic. I use MQTT Explorer to Subscribe to the Topic I'm publishing (myHome/heartbeat) and there are no issues.
When I publish a topic from MQTT Explorer (myHome/FrontDoor/open) and subscribe from the Redboard, the onMessage routine is not triggered when I publish the topic from MQTT Explorer.
Here is my current code...
#include <SoftwareSerial.h>
#include <SparkFunESP8266WiFi.h>
#include <ArduinoMqttClient.h>
//*************************************************************************
#define WLAN_SSID "MAGA2020"
#define WLAN_PASS "Fido2020"
#define myMQTTID "MAGA-2a20a1b2"
//*************************************************************************
unsigned long previousMillis = 0;
unsigned int count = 0;
IPAddress MQTT_BROKER(192,168,33,201);
ESP8266Client myWiFiClient;
MqttClient myMQTTClient(myWiFiClient);
// Forward declaration
void OnMQTTMessage(int messageSize);
//*************************************************************************
void setup() {
Serial.begin(115200);
while(!Serial);
Serial.print("Initializing ESP8266 WiFi Shield");
while (!esp8266.begin())
Serial.print(".");
Serial.print("\nSuccessfully Connected to ESP8266 WiFi Shield");
Serial.print(" WiFi Mode = ");
Serial.println(esp8266.getMode());
Serial.print("\nConnecting to WiFi SSID: ");
Serial.println(WLAN_SSID);;
while (esp8266.connect(WLAN_SSID, WLAN_PASS) < 0) {
delay(500);
Serial.print(".");
} // END WHILE
delay(2000);
Serial.print("Connecting to MQTT Broker at IP: ");
Serial.println(MQTT_BROKER);
myMQTTClient.setId(myMQTTID);
if (!myMQTTClient.connect(MQTT_BROKER)) {
Serial.print("MQTT Connection Failed. Error Code = ");
Serial.println(myMQTTClient.connectError());
while(1);
}
Serial.println("\Sucessfully Connected to MQTT Broker.");
myMQTTClient.onMessage(OnMQTTMessage);
myMQTTClient.subscribe("myHome/FrontDoor/open", 0);
Serial.println("Setup Complete");
delay(2000);
} // END SETUP
//*************************************************************************
void loop() {
myMQTTClient.poll();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= 15000) {
String payload = "";
payload+= count;
previousMillis = currentMillis;
if (count < 5)
Serial.println("Publishing Topic");
myMQTTClient.beginMessage("myHome/heartbeat",payload.length(),false,1,false);
myMQTTClient.print(payload);
myMQTTClient.endMessage();
count++;
}
} // END MAIN LOOP
//*************************************************************************
//*********************************************************************
void OnMQTTMessage(int messageSize) {
Serial.print("Got Message from Broker ");
Serial.println(myMQTTClient.messageTopic());
}
Hi,
I am following this guide for my school project: [https://docs.arduino.cc/tutorials/uno-wifi-rev2/uno-wifi-r2-mqtt-device-to-device]
The receiver code is basically the same as the one given in the example folder of this library.
When code works perfectly fine when using the broker "test.mosquitto.org" as shown below:
However, it fails when I try to connect to my local host.
I attempted to figure out if it was my localhost bugging out but it was working fine as I was able to publish.
I can't figure out why it can't connect to localhost.
Thank you,
Ryan
Running an MKR-15000 board that pushes data over MQTTS to 8883 mosquitto server. Half the time the board and server broker the initial connection just fine and everything runs perfectly. However, the other half of the time the connection gets hung up and is unable to connect to the server. The board will eventually return a code -2 and mosquitto will identify the new connection and then say there was a socket error - disconnecting.
Has anyone seen this issue before? i cant for the life of be understand why it only happens half the time. Is it an SSL issue? Msoquitto issue? Library issue?? -- why cant the function fail and retry? If i restart the arduino I typically get a connection but it would be better if it could retry on its own.
When running it on Arduino MKR NB1500, it frequently stucked on .poll() and cause Arduino to freeze. I can't get any logs on what's happening. But I suspect maybe the data connection was briefly bad and the process stuck on .poll() based on my LED status. Is there a way to set timeout on poll()?
Hi,
I don't know if this is the right place to open an issue but I will give it a try, forgive me if I am in the wrong place. I have posted an issue on forum.arduino.cc but it seems that there are no responders at all after a few days. And I don't know if this is related to the MQTT or something else. Lots of ifs and buts, sorry for that.
Anyhow, this mqtt library works very fine as long as I am not adding something else in the sketch like a servo. I have described the issue quite thoroughly here (link below) so I will not write the same thing again. Would be great if someone has any idea of how to solve the problem because I am surely stuck.
This is the description: https://forum.arduino.cc/index.php?topic=596987.msg4054335#msg4054335
UPDATE: After so many hours of trial and error I tried one more thing just after writing this issue since I found another post with a totally different problem but he changed the pin to 8 instead of 9. Aaaand.. problem solved. So no issue with the mqtt. Sorry for not being able to find this out myself. Thank you.
can i use it for prototyping an IOT project?
I am using the Cloud Example from Arduino IDE and could establish a NB-IOT connection but now I am stuck on the mqtt connection. I read many thread but nobody seems to have the exact same issue. The sole response of "ERROR" does not lead me to anything.
I am connected to PC via USB and antenna attached.
Here is my debug log:
OK
AT+CEREG?
+CEREG: 0,1
OK
You're connected to the cellular network
Attempting to MQTT broker: xxxxxx.1.amazonaws.com
AT+USOCR=6
+USOCR: 0
OK
AT+USOCO=0,"xxxxxx.1.amazonaws.com",8883
ERROR
+UUSOCL: 0
AT+USOCL=0
ERROR
.AT+USOER
+USOER: 9
OK
AT+USOCR=6
+USOCR: 0
OK
AT+USOCO=0,"xxxxxx.1.amazonaws.com",8883
ERROR
This repeats infinite times.
Hi
I am using the Google Cloud IoT core example. This requires the broker to reconnect on expiry of the JWT token.
Is there a reconnect option? It seems disconnect() is a private function? I have not dug to far into the code as yet.
Dear Sandeep
I'm glad I found a promising solution. Since this point it is far better than the other solutions.
Already did some tests on different devices (Arduino Nano + W5100 & NodeMCU Esp32S) and recognized some bugs and defect.
My MQTT broker is ActiveMQ and when my device subscribed and received a message somehow ACK didn't reached the broker, amount of dequeued messages wasn't change on GUI but on Serial out I saw the messages.
By the way, is it possible to use this library as "Request/Reply" solution? Bombarded my devices with ~1000messages ,- ack back to broker also missed. And I could not send an answer in onMessage function (after the 3rd message Arduino crashed, maybe because of memory limitations.) But when I moved beginMessage; print;endMessage into the main loop then only the last message
was answered because poll function didn't turned back after a received message.
So basically is it possible to pre-configure the amount of handled message via ::poll ? Receive one message, return to main loop, answer it if want, etc...
Is it on plan?
Br, Ed
Hello! I want to create smart IoT lamp. But, if I try to use if() function, I do not understand results. My loop function:
void loop() {
int messageSize = mqttClient.parseMessage();
if (messageSize) {
// we received a message, print out the topic and contents
Serial.print("Received a message with topic '");
Serial.print(mqttClient.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");
// use the Stream interface to print the contents
while (mqttClient.available()) {
Serial.print(String(mqttClient.read()));
}
if (String(mqttClient.read()) == String(48)){
digitalWrite(ledPin, HIGH);
Serial.println(" tru");
} else {
digitalWrite(ledPin, LOW);
Serial.println(" fals");
}
Serial.println();
Serial.println();
}
}
In serial, I do receive values, but cant compare them in if():
Hello,
Is there a known issue with retained messages not being received?
I am using ArduinoMqttClient on a ESP32 type board. I am able to successfully subscribe to 2 topics and i can successfully receive any message that comes on those topic AFTER my application is running. However, retained messages on that topic are never being received.
I try to add a last will for more than one topic. I can't get it to work and there is no helping article on the internet.
Would it be possible to add functionality to enable the use of tokens?
Sorry but how I can send more than 263 character in one message.
Now Message is truncate at 263.
Thank
Hi, the broker I use (EMQx) is using mutual TLS, so I have to provide client certificates.
I didn't find a way in doing so so far with this lib.
I saw in the doc how to use SSL/TLS (extract below) but no indication on how I could pass certificate to the connection client.
// To connect with SSL/TLS:
// 1) Change WiFiClient to WiFiSSLClient.
// 2) Change port value from 1883 to 8883.
// 3) Change broker value to a server with a known SSL/TLS root certificate
// flashed in the WiFi module.
I tried using the SSLClient lib but with no success so far
Is mutual TLS possible ?
Hi i have tried to mod the Arduino example "AWS_IoT_GSM" to be able to get longer message size on MQTT with following code below:
void publishMessage(String input) {
Serial.println("Publishing message");
bool retained = false;
int qos = 0; // Have tested with both 0 and 1
bool dup = false;
mqttClient.beginMessage("arduino/outgoing",input.length(),retained,qos,dup);
mqttClient.print(input);
mqttClient.endMessage();
}
I can send one or two message then i lose connection. But it works fine if i just use
"mqttClient.beginMessage("arduino/outgoing");"
Hi, I've tried the example provided in this library, it connects well to my wifi but I cant seem to connect to the broker (I've tried google iot core and aws iot core, but none also works and return the same error). It always returns error code -2.
Board version: Arduino SAMD Boards 1.8.6
Firmware: WINC1501 Model B (19.6.1)
Hey there,
I'm facing an issue with the mqttClient.connected()
command on MKR VIDOR 4000: it seems to freeze when the MQTT connection is broken.
I've been successfully using this command before on MKR1000, MKR GSM 1400, MKR NB 1500.
I've set up the code below so that you can reproduce. I've simulated a broken MQTT connection by turning my Wi-Fi access point off and on again.
#include <ArduinoMqttClient.h>
#include <WiFiNINA.h>
#include "arduino_secrets.h"
/////// Enter your sensitive data in arduino_secrets.h
const char wifi_ssid[] = SECRET_WIFI_SSID;
const char wifi_pass[] = SECRET_WIFI_PASS;
const char mqtt_broker[] = "test.mosquitto.org";
const int mqtt_port = 1883;
WiFiClient networkClient;
MqttClient mqttClient(networkClient);
void setup() {
Serial.begin(9600);
while (!Serial);
Serial.println();
mqttClient.setId("TestVIDOR");
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
if (!mqttClient.connected()) {
connectMQTT();
}
mqttClient.poll();
}
void connectWiFi() {
Serial.print("Attempting to connect to SSID: ");
Serial.print(wifi_ssid);
while (WiFi.begin(wifi_ssid, wifi_pass) != WL_CONNECTED) {
// failed, retry
Serial.print(".");
delay(5000);
}
Serial.println();
Serial.println("You're connected to the network");
}
void connectMQTT() {
Serial.print("Attempting to connect to MQTT broker: ");
Serial.print(mqtt_broker);
while (!mqttClient.connected()) {
if (!mqttClient.connect(mqtt_broker, mqtt_port)) {
// failed, retry
Serial.print(".");
delay(5000);
}
}
Serial.println();
Serial.println("You're connected to the MQTT broker");
}
The VIDOR board reconnects to Wi-Fi and then freezes when it comes to MQTT:
22:29:20.066 -> Attempting to connect to SSID: Logan
22:29:25.711 -> You're connected to the network
22:29:25.711 -> Attempting to connect to MQTT broker: test.mosquitto.org
22:29:27.911 -> You're connected to the MQTT broker
// Wi-Fi interruption //
22:29:48.061 -> Attempting to connect to SSID: Logan.
22:29:59.894 -> You're connected to the network
// nothing else after //
On the other boards, the code reconnects instantly to the Wi-Fi and to the broker. This is the output for MKR1000 (just changed the Wi-Fi library to WiFi101.h
):
22:35:11.458 -> Attempting to connect to SSID: Logan
22:35:13.013 -> You're connected to the network
22:35:13.013 -> Attempting to connect to MQTT broker: test.mosquitto.org
22:35:17.924 -> You're connected to the MQTT broker
// Wi-Fi interruption //
22:35:29.854 -> Attempting to connect to SSID: Logan..
22:35:42.733 -> You're connected to the network
22:35:42.733 -> Attempting to connect to MQTT broker: test.mosquitto.org
22:35:45.101 -> You're connected to the MQTT broker
i use setKeepAliveInterval to set keepalive time ,and use my phone as AP,and in loop cycle to check status of connected() , but no matter which value i set, it allways alert me the mqtt is disconnected after 10 seconds when i turn off the AP of my phone.
how can i adjust the keepaliveinterval.
When I call mqttClient.connect()
my sensors stop collecting data. I looked briefly at the code but nothing looks like it would be blocking I2C (which is used for sensor data collection).
Hello,
I am not getting an incoming message for a subscribed topic
Hi
I try to use the WiFiSimpleSender Example for a device that should send MQTT messages to my Network.
The problem I have is that I can't connect to my broker without using credentials.
I modified the original statement from this:
mqttClient.connect(broker, port)
to this:
mqttClient.connect(broker, port, user, pass)
but unfortunately, it didn't work.
Would you give me any suggestions?
Thanks, Chris
Hi,
Which MQTT version does the library currently support? We are struggling our heads to know why our arduino nano 33 iot always get a connection refused when connecting to EMQX 4.x broker but not when connecting to mosquito.
const char broker[] = "test.mosquitto.org";
int port = 1883;
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
void setup() {
Serial.begin(1000000);
while (!Serial);
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
// failed, retry
Serial.print(".");
delay(5000);
}
Serial.println("Device connected to the network");
if (!mqttClient.connect(broker, port)) {
Serial.print("MQTT connection failed! Error code = ");
Serial.println(mqttClient.connectError());
while (1);
}
Serial.println("You're connected to the MQTT broker");
}
that ends up with a succesfully connection to "test.mosquitto.org".
But if we use for example:
IPAddress broker(192, 168, 1, 33);
then we always ends up with an unsuccessfully connection. We have no idea why... port 1883 is open and accessible from local network but EMQX 4.x broker supports MQTT 3.1.1 and 5.0
Could be that the problem? Any other idea?
Thank you so much in advance
I tested ver 0.1.6 using Giga R1 WiFi. Only a small change is required to make the examples work. I removed the check for ESP32 because Giga also uses WiFi.h.
Old
#elif defined(ESP32)
#include <WiFi.h>
#endif
New
#else
#include <WiFi.h>
#endif
Is it too much to hope new boards will implement the standard Arduino WiFi API? For example, Uno R4 will have a WiFi option. Would be nice to avoid releasing a new version of the library whenever a new board with WiFi appears.
How can i connect Arduino Uno Wifi REV2 with AWS (Amazon Web Server) for an IoT application. I tried following this tutorial to connect to AWS Iot and kept getting errors:
I'm having a problem with the key is too large for my Arduino. What should I do?
The bug is:
Sketch uses 207536 bytes (426%) of program storage space. Maximum is 48640 bytes.
text section exceeds available space in board
Global variables use 16050 bytes (261%) of dynamic memory, leaving -9906 bytes for local variables. Maximum is 6144 bytes.
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it.
Error compiling for board Arduino Uno WiFi Rev2.
As per subject, release V0.1.6 doesn't connect to ThingsBoard v3.4.4. Actually it does, Thingsboard debug logs show success, "alive" goes true, but the MqttClient eventually times out and thinks it didn't get connected. I guess it requires a different ACK from the broker, not sure.
Is this library compatible with PSK Authentication? The MQTT server that my company has is set up for PSK based authentication and encryption and as such, I believe it doesn't use a root certificate, but rather a psk identity and key to be passed in when connecting as a client. As an example, when connecting from the terminal I'd put in this command to subscribe:
mosquitto_sub -h 160.36.60.20 -t 'test' -u username -P password -p 8883 --psk-identity user --psk 123456789
It works fine, but with the Arduino I can't input the psk information. Is there a way to do it with this library, or does psk need to be on the Arduino's crypto chip itself?
Hi,
I'm using this library on a mkr 1010 to send some data every 5 seconds. I based my sketch on the WiFi Simple Sender example. After 1-2 hours the library stops sending mqtt messages to my broker.
For now i did the following observations:
The code is hosted on arduino create
Trying to shutdown the client at some point however do not know the right time when the messaging is done, i.e. looking for the time when message has been published and PUBACK (QoS1) or PUBREC/PUBCOM (QoS2) were received.
Does anybody knows how to get status and what is the status for the finished message ? I want to put condition in my sketch to close the client.
Hello,
I've been playing with the lib with MKR NB 1500 and I encounter delays that seem to be linked to the use of MQTT.
I'm trying to close MQTT and cellular connections before putting the device to sleep.
I'm using the following sketch:
#include <MKRNB.h>
#include <ArduinoMqttClient.h>
NB nbAccess;
//GPRS gprs;
NBClient nbClient;
MqttClient mqttClient(nbClient);
const char mqtt_user[] = "none";
const char mqtt_pass[] = "none";
const char mqtt_id[] = "MKRNB1500";
const char mqtt_broker[] = "broker.hivemq.com";
void connectionManager(bool _way);
void setup() {
Serial.begin(9600);
while (!Serial);
mqttClient.setId(mqtt_id);
mqttClient.setUsernamePassword(mqtt_user, mqtt_pass);
connectionManager(1);
connectionManager(0);
}
void loop() {
}
void connectionManager(bool _way = 1) {
switch (_way) {
case 1:
Serial.print("Connecting to cellular network");
// Discarding the GPRS client, seems working without it
//while ((nbAccess.begin() != NB_READY) || (gprs.attachGPRS() != GPRS_READY))
while (nbAccess.begin() != NB_READY)
Serial.print(".");
Serial.println("\nYou're connected to the network");
//-- Comment this part to avoid establishing the MQTT connection
Serial.print("Connecting to MQTT broker '");
Serial.print(mqtt_broker);
Serial.print("'");
while (!mqttClient.connect(mqtt_broker))
Serial.print(".");
Serial.println("\nYou're connected to the MQTT broker");
//--
break;
case 0:
//-- Comment this part when the MQTT connection is not established
Serial.println("\nClosing MQTT connection...");
mqttClient.stop();
//--
Serial.println("Disconnecting from cellular network...");
nbAccess.shutdown();
Serial.println("Offline.\n");
break;
}
}
When I establish the MQTT connection with the broker, it takes ~10 seconds to execute the mqttClient.stop() call. Then it takes another ~40sec to execute the nbAccess.shutdown() call:
18:35:25.250 -> Connecting to cellular network
18:35:28.893 -> You're connected to the network
18:35:28.928 -> Connecting to MQTT broker 'broker.hivemq.com'
18:35:29.605 -> You're connected to the MQTT broker
18:35:29.605 ->
18:35:29.605 -> Closing MQTT connection...
18:35:39.667 -> Disconnecting from cellular network...
18:36:19.672 -> Offline.
18:36:19.672 ->
When I don't establish the MQTT connection, the nbAccess.shutdown() call is executed instantaneously:
18:37:22.351 -> Connecting to cellular network
18:37:29.172 -> You're connected to the network
18:37:29.172 -> Disconnecting from cellular network...
18:37:29.206 -> Offline.
18:37:29.206 ->
So it seems I'm getting some delays here depending if the MQTT connections was open or not.
Any thoughts about it?
Thanks! ;)
Hi
I am using an ESP 32 with the the example. I am experiencing strange behavor.
A published message its taking a long time to arrive. Then I can send a message and it does not arrive. Operation is not consitant.
Is there any debug to see why. The message then might arrive a later.
Tried different QOS / Retain true / flase and the issues alwasy occour.
Help. Its just not usable.
trying to get this library working on an ESP32. but each time I compile it. it fails with the following error.
Arduino: 1.8.5 (Linux), Board: "ESP32 Dev Module, Disabled, Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS), 240MHz (WiFi/BT), QIO, 80MHz, 4MB (32Mb), 921600, None"
temp:13: error: cannot declare variable 'mqttClient' to be of abstract type 'MqttClient'
MqttClient mqttClient(wifiClient);
^
In file included from /home/laywah/Arduino/libraries/ArduinoMqttClient/src/ArduinoMqttClient.h:23:0,
from /home/laywah/git/arduino/temp/temp/temp.ino:3:
/home/laywah/Arduino/libraries/ArduinoMqttClient/src/MqttClient.h:35:7: note: because the following virtual functions are pure within 'MqttClient':
class MqttClient : public Client {
^
In file included from /home/laywah/.arduino15/packages/esp32/hardware/esp32/1.0.2/cores/esp32/Arduino.h:157:0,
from sketch/temp.ino.cpp:1:
/home/laywah/.arduino15/packages/esp32/hardware/esp32/1.0.2/cores/esp32/Client.h:31:17: note: virtual int Client::connect(IPAddress, uint16_t, int)
virtual int connect(IPAddress ip, uint16_t port, int timeout) =0;
^
/home/laywah/.arduino15/packages/esp32/hardware/esp32/1.0.2/cores/esp32/Client.h:32:17: note: virtual int Client::connect(const char*, uint16_t, int)
virtual int connect(const char *host, uint16_t port, int timeout) =0;
^
Multiple libraries were found for "WiFi.h"
Used: /home/laywah/.arduino15/packages/esp32/hardware/esp32/1.0.2/libraries/WiFi
Not used: /opt/arduino-1.8.5/libraries/WiFi
exit status 1
cannot declare variable 'mqttClient' to be of abstract type 'MqttClient'
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
Hi, is it possible to make TX_PAYLOAD_BUFFER_SIZE overridable, as an instance variable, or compile build option? I was surprised to find that it is only 256 bytes. Thanks
Hello everyone,
I noticed that MqttClient works only if it is declared as global: if I try to create a local instance in "setup()" that connects, publishes and disconnects, the flow hangs on the "print" method right after the "beginMessage". The same program works if MqttClient is declared in global scope instead of local.
Any particular reason for this?
Attached you have a zip with two ino files: one should reproduce the bug, and one should work, demonstrating the behaviour explained above.
Best regards
I try to use QoS 1 which fortunately is already part of the library, but I am not really sure how to implement some things. because the way I approach the things at the moment seems to lead to issues.
For example, if I send a message like this:
mqttClient.beginMessage("/devices/" + deviceID + "/events", false, 1, false);
mqttClient.print("Hello world!");
mqttClient.end();
I see that the end() function is polling until a PUBACK is received or until the defined connectionTimeout is elapsed. Is it true that the library does not send automatically a new PUBLISH message after a while if there is no PUBACK received?
If so, how can I implement this in a good way? Is for example the approach below good enough? Since the end() function seems to return 0 if no PUBACK is received after the defined connectionTimeout.
int messageArrived = false;
while (!messageArived) {
mqttClient.beginMessage("/devices/" + deviceID + "/events", false, 1, false);
mqttClient.print("Hello world!");
mqttClient.end();
}
Of course, I have to close the connection after a while if I don't get any response, but that is another subject.
I am wondering because I am not sure if all variables are set to the right ones if we call the function again without having end() returning 0.
The same problem occurs with receiving messages. If the callback function is called it is receiving data until _rxLength is zero. But, let's say that we have received a message of 1000 bytes and after 600 bytes we are not receiving the last 400 bytes anymore. It seems that clientTimedRead() returns -1. Therefore the client does not send back a PUBACK message. My idea was to create a loop that is looping until a PUBACK is sent (so that we don't get data from the broker again). I did this by creating a global variable:
volatile bool messageNotReceived= true;
The loop that is looping is:
MQTTClient.onMessage(receivedMessage);
while (messageNotReceived) {
mqttClient.poll();
}
Where the callback function is defined as:
static void receivedMessage(void)
{
int rd = 0;
while (mqttClient.available()) {
rd = mqttClient.read();
}
messageNotReceived = false;
}
But when I did this I saw that the while loop is running forever, because available() keeps returning 400. So I had to think about a way to leave the while loop and wait till a new Message was received from the broker. Therefore all the values should be the same as before to make sure that the new incoming data is handled fine.
static void receivedMessage(void)
{
int rd = 0;
while (mqttClient.available()) {
rd = mqttClient.read();
if (rd == -1) {
while(mqttClient.parseMessage());
return;
}
}
messageNotReceived = false;
}
I saw that the parseMessage() function sets _rxLength to zero when I implemented it as above. The code above runs fine for a while. I get new data as long as I do not send a PUBACK. But after some time it seems to go wrong. Although the connection with the broker and my provider is still alive (I keep sending messages in the mean time), I got an error reading the data (I use the NB library, so after a while if the library calls AT+USORD to read messages, I got an error).
Something says me that calling just parseMessage() is not enough to set the values to the right values before reading a new incoming message. Does someone know the right routine for this?
From what I can understand, we send the actual message to our cloud by calling the print
function. When looking at the cloud telemetry, it first says "body" then the message itself followed by the "enqueuedTime". Is there a way to change the word "body" to "heartbeat"? Or how can I send a heartbeat to the cloud?
I'm using Arduino MKR WiFi 1010 for this development, with Azure IoT Hub as my broker.
Hi,
I am using the Arduino MKR NB1500 to connect to the AWS IoT.
My current issue is the MQTT won't connect to AWS if the USB serial port is not recognized by my computer.
Scenarios as below.
My final goal is to power the Arduino from the power bank or VIN pin, but none of them work.
Please help, thank you! here is the log.
IPv6 is now reaching over 40% according to Google statistics; https://www.google.com/intl/en/ipv6/statistics.html
Within a few years, IPv4 will be in the minority.
Some network providers have already switched to IPv6-only, e.g. Telstra mobile users in Australia, as well as many providers in India, China, and other regions. https://www.sidn.nl/en/news-and-blogs/australias-telstra-switches-mobile-users-to-ipv6-only
e.g.
PS /home/sly/Code/iot-lab> host mqtt001-purpleiot-dev.australiaeast.cloudapp.azure.com
mqtt001-purpleiot-dev.australiaeast.cloudapp.azure.com has IPv6 address 2603:1010:2:3::73
It is duplication to https://github.com/arduino/ArduinoCloudProviderExamples/issues/10
but I am not sure where is the right point to ask / point the issue to...
Hello,
I have been using https://github.com/VSChina/ESP32_AzureIoT_Arduino
for connection for some time and it has one very important feature. Recently I switched over to MKR GSM and started using examples https://github.com/arduino/ArduinoCloudProviderExamples
and would like to understand if there are routines for following features part of libraries that are used.
Attaching example from callback from ESP32 routine (acknowledge)
static void SendConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result)
{
if (result == IOTHUB_CLIENT_CONFIRMATION_OK)
{
Serial.println("Send Confirmation Callback finished.");
}
}
This was an output to serial monitor:
10:18:23.212 -> Info: >>>IoTHubClient_LL_SendEventAsync accepted message for transmission to IoT Hub.
10:18:23.521 -> Info: >>>Confirmation[2] received for message tracking id = 2 with result = IOTHUB_CLIENT_CONFIRMATION_OK
10:18:23.521 -> Send Confirmation Callback finished.
Attaching example from callback from ESP32 routine (devicetwin)
static void DeviceTwinCallback(DEVICE_TWIN_UPDATE_STATE updateState, const unsigned char *payLoad, int size)
{
char *temp = (char *)malloc(size + 1);
if (temp == NULL)
{
return;
}
memcpy(temp, payLoad, size);
temp[size] = '\0';
// Display Twin message.
Serial.println(temp);
free(temp);
}
Thank you
I am testing the library on an ESP8266 based board and samples don't work without codes modifications.
First, I must replace this code bloc with just #include <ESP8266WiFi.h>
because otherwise I have a compile error on line where the WiFiClient client
is declared.
#include <ArduinoMqttClient.h>
#if defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_AVR_UNO_WIFI_REV2)
#include <WiFiNINA.h>
#elif defined(ARDUINO_SAMD_MKR1000)
#include <WiFi101.h>
#elif defined(ARDUINO_ESP8266_ESP12)
#include <ESP8266WiFi.h>
#endif
Second, the code is locked in setup, in while loop that check the wifi status and forbid sketch start without wifi connexion.
To get the example working I replaced this :
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
// failed, retry
Serial.print(".");
delay(5000);
}
with this:
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
while (WiFi.status() != WL_CONNECTED) {
// failed, retry
delay(5000);
}
Infos:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.