Giter VIP home page Giter VIP logo

arduinomqttclient's People

Contributors

aentinger avatar chris-hatton avatar dependabot[bot] avatar kacp3r3 avatar mazgch avatar pennam avatar per1234 avatar rocketct avatar sandeepmistry avatar tbaust 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

arduinomqttclient's Issues

Wrong condition for stopping a connection on endMessage

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;
    }
  }

makes some attempts to minimize the delay for reconnection, just a hobby

#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

QoS2 PUBREC causes connection drop

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?

Can't send retained messages

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?

Clean Session

Hi, it would be nice to get a chance to set the flag for clean session to high or either low.

Best Regards

Fabian

onMessage

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());
}

Failure to connect to 127.0.0.1 (localhost) using Mosquitto Broker

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:
image

However, it fails when I try to connect to my local host.
image

I attempted to figure out if it was my localhost bugging out but it was working fine as I was able to publish.
image
image

I can't figure out why it can't connect to localhost.

Thank you,
Ryan

MKR 1500: failed connection error code 2 - mosquitto: socket error disconnecting

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.

Stuck on .poll()?

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()?

MQTT in combination with Servo not possible?

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.

MQTT not connecting to AWS IOT with MKR NB 15000

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.

Reconnect

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.

First feedback

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

Var type error

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():
image

Retained messages are not received

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.

last will

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.

Provide example of mutual TLS implementation

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 ?

Connection lost message size > 256

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");"

MKR1000 mqtt example failed, error code -2

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)

mqttClient.connected() is freezing on VIDOR when MQTT connection drops

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

can not set setKeepAliveInterval

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.

How to use username and paswword on the connect function

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

Document MQTT version support

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

Giga R1 WiFi works with a small change

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.

SSL/TLS with Aduino UNO Wifi REV2

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:

https://docs.arduino.cc/tutorials/mkr-wifi-1010/securely-connecting-an-arduino-mkr-wifi-1010-to-aws-iot-core

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.

Doesn't connect to ThingsBoard

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.

[Question] TLS PSK Authentication

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?

Client stops sending mqtt data after some hours

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:

  1. the loop() code is still running
  2. i'm still able to ping my arduino
  3. my broker is still running, other devices on the network can still publish on it

The code is hosted on arduino create

Close the client, received PUBACK (QoS1)

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.

Connection handling delays

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! ;)

Slow and then non responsive mqtt.read

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.

can't compile on ESP32 with mqttClient cannot be abstract type

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.

make TX_PAYLOAD_BUFFER_SIZE overridable

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

MqttClient works only as global scope variable

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.

demo_ino_files.zip

Best regards

Implementing QoS 1

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?

Changing the "body" to "heartbeat"

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.

MQTT won't connect to AWS IoT without serial connection.

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.

  1. Power the Arduino from computer USB and the serial port shows up (COM6). MQTT works fine, it can connect to the cellular network and AWS.
  2. Power the Arduino from computer USB with charging only USB cable, which means there is no serial port showing up in computer device manager. the cellular network connection is fine, but the MQTT won't connect.
  3. Power the Arduino from a power bank with a data-supported USB (the one used to download code to Arduino). The cellular network connection is fine, but the MQTT won't connect.
  4. I tried to power the Arduino from the VIN pin, got the same result, it can connect to the cellular network, but won't connect to AWS.

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.

124

This MQTT library needs IPv6 support

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

MQTT acknowledgement for QoS 1

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.

  1. Callback whether the message has been delivered / received to IOT HUB (MS AZURE) ? The main reason is to keep tracking and consistency whether all the messages from arduino has been received to MS azure. If there are, can you point me where it is so i will integrate to my routines.
  2. Device twin callback i.e. firmware update via MS AZURE ? Also, if so can you point me where to find this routines ?

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

For Esp8266 (nodemcu) examples don't connect to network (and don't compile)

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:

  • Arduino 1.8.13
  • ArduinoMqttClient 0.1.5
  • Esp8266 boards 2.7.4

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.