Author Topic: Arduino MQTT  (Read 1341 times)

0 Members and 1 Guest are viewing this topic.

Offline King123Topic starter

  • Contributor
  • Posts: 18
  • Country: in
Arduino MQTT
« on: September 15, 2022, 04:13:03 pm »
I've following example code given in Arduino IDE that I am trying to understand

Code: [Select]

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(172, 16, 0, 100);
IPAddress server(172, 16, 0, 2);

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i=0;i<length;i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

EthernetClient ethClient;
PubSubClient client(ethClient);

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduinoClient")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic","hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

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

  client.setServer(server, 1883);
  client.setCallback(callback);

  Ethernet.begin(mac, ip);
  // Allow the hardware to sort itself out
  delay(1500);
}

void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}


I don't understand this specific part in code
Code: [Select]
void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

I don't understand where to add led blink code in main loop below client.loop function or above if condition  ?

Code: [Select]
digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
 

Online pcprogrammer

  • Super Contributor
  • ***
  • Posts: 3704
  • Country: nl
Re: Arduino MQTT
« Reply #1 on: September 15, 2022, 04:26:12 pm »
For starters don't use the blocking delay even if the example code uses it to do the waits. See your own question here:  https://www.eevblog.com/forum/microcontrollers/arduino-how-to-control-relay-without-blocking-delay/msg4383625/#msg4383625

And it depends on what the client.loop function does. When it is blocking while there is a connection your led will not blink, and then you might want to look into the interrupt option mentioned in the link above.
If not blocking, then use what was given in the above link to make the led blink without blocking the loop.

And then you can put your code at the beginning of the loop function, or before the client.loop call, or after it. It does not make a difference.

« Last Edit: September 15, 2022, 04:28:01 pm by pcprogrammer »
 
The following users thanked this post: King123

Offline sokoloff

  • Super Contributor
  • ***
  • Posts: 1799
  • Country: us
Re: Arduino MQTT
« Reply #2 on: September 15, 2022, 04:34:42 pm »
If you want the LED to blink only when connected, then you want to add a "turn it off" before the reconnect(); call and to place the blinking code after that call (assuming that reconnect() is blocking).

If reconnect() is blocking, you won't have a blinking LED while not connected no matter where in the loop you put the code to blink the LED.

Otherwise, think of the last thing you do in loop() N and the first thing you do in loop() N+1 as being immediately adjacent, so it doesn't matter.
 
The following users thanked this post: King123

Offline King123Topic starter

  • Contributor
  • Posts: 18
  • Country: in
Re: Arduino MQTT
« Reply #3 on: September 15, 2022, 04:49:24 pm »
And then you can put your code at the beginning of the loop function, or before the client.loop call, or after it. It does not make a difference.

Does the client take's at least  5 seconds to reconnect with broker ?

Code: [Select]
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

// Update these with values suitable for your hardware/network.
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(172, 16, 0, 100);
IPAddress server(172, 16, 0, 2);

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
}

EthernetClient ethClient;
PubSubClient client(ethClient);

long lastReconnectAttempt = 0;

boolean reconnect() {
  if (client.connect("arduinoClient")) {
    // Once connected, publish an announcement...
    client.publish("outTopic","hello world");
    // ... and resubscribe
    client.subscribe("inTopic");
  }
  return client.connected();
}

void setup()
{
  client.setServer(server, 1883);
  client.setCallback(callback);

  Ethernet.begin(mac, ip);
  delay(1500);
  lastReconnectAttempt = 0;
}


void loop()
{
  if (!client.connected()) {
    long now = millis();
    if (now - lastReconnectAttempt > 5000) {
      lastReconnectAttempt = now;
      // Attempt to reconnect
      if (reconnect()) {
        lastReconnectAttempt = 0;
      }
    }
  } else {
    // Client connected

    client.loop();
  }

}
 

Online pcprogrammer

  • Super Contributor
  • ***
  • Posts: 3704
  • Country: nl
Re: Arduino MQTT
« Reply #4 on: September 15, 2022, 05:04:44 pm »
That depends on the whole setup.

What is connected to your arduino board? Is it a W5500 module?

The client is most likely a web browser on your computer, so it depends on when that refreshes the page how long it takes. If there is no client it will never connect.

Your arduino is setup as a server, and only when some external client tries to connects, a connection will be made.

The question you asked here is basically not answerable.

Offline King123Topic starter

  • Contributor
  • Posts: 18
  • Country: in
Re: Arduino MQTT
« Reply #5 on: September 15, 2022, 05:22:52 pm »
That depends on the whole setup.

What is connected to your arduino board? Is it a W5500 module?

enc28j60 module is connected with Arduino mega board

The client is most likely a web browser on your computer, so it depends on when that refreshes the page how long it takes. If there is no client it will never connect.

computer is  setup as server and MQTT broker.  Arduino is setup as a client 
 

Online pcprogrammer

  • Super Contributor
  • ***
  • Posts: 3704
  • Country: nl
Re: Arduino MQTT
« Reply #6 on: September 15, 2022, 06:36:37 pm »
Then the time to get a connection depends on the server. And you probably need a timeout between connection attempts. So try to connect a couple of times, and when it fails, wait a bit longer and try it again, until a connection is established.

You could then base the on off of the LED on the connection status. Maybe use the callback function to blink the led when a message is received.

Offline King123Topic starter

  • Contributor
  • Posts: 18
  • Country: in
Re: Arduino MQTT
« Reply #7 on: September 17, 2022, 05:52:31 pm »
I am confused with following concepts

Does the broker lose connection with the client and try to reconnect or does the client lose connection with the broker and try to reconnect?
 

Online pcprogrammer

  • Super Contributor
  • ***
  • Posts: 3704
  • Country: nl
Re: Arduino MQTT
« Reply #8 on: September 17, 2022, 06:47:52 pm »
The client detects a loss of connection, and tries to reconnect. The server only facilitates connections when a client asks for it. At least that is normal client server behavior. I'm not familiar with MQTT protocols, but guess it works the same.

Offline sokoloff

  • Super Contributor
  • ***
  • Posts: 1799
  • Country: us
Re: Arduino MQTT
« Reply #9 on: September 18, 2022, 12:05:51 am »
MQTT most commonly runs over TCP, which means the client initiates the connection to the server, after which time the connection stays open and both sides can use it. When the connection breaks, that is usually detected on the next attempt to send something. It can be re-established by the client trying again to connect.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf