Arduino MQTT   - Page 1
Forum section: electronics / general

author: King123
author_rank: Contributor
timestamp: September 15, 2022, 04:13:03 pm
content: I've following example code given in Arduino IDE that I am trying to understandCode:#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);}Serial.println();}EthernetClient ethClient;PubSubClient client(ethClient);void reconnect() {// Loop until we're reconnectedwhile (!client.connected()) {Serial.print("Attempting MQTT connection...");// Attempt to connectif (client.connect("arduinoClient")) {Serial.println("connected");// Once connected, publish an announcement...client.publish("outTopic","hello world");// ... and resubscribeclient.subscribe("inTopic");} else {Serial.print("failed, rc=");Serial.print(client.state());Serial.println(" try again in 5 seconds");// Wait 5 seconds before retryingdelay(5000);}}}void setup(){Serial.begin(57600);client.setServer(server, 1883);client.setCallback(callback);Ethernet.begin(mac, ip);// Allow the hardware to sort itself outdelay(1500);}void loop(){if (!client.connected()) {reconnect();}client.loop();}I don't understand this specific part in codeCode: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:digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)delay(1000); // wait for a seconddigitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOWdelay(1000); // wait for a second

author: pcprogrammer
author_rank: Super Contributor
timestamp: September 15, 2022, 04:26:12 pm
content: 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/#msg4383625And 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.

author: sokoloff
author_rank: Super Contributor
timestamp: September 15, 2022, 04:34:42 pm
content: 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.

author: King123
author_rank: Contributor
timestamp: September 15, 2022, 04:49:24 pm
content: Quote from: pcprogrammer on September 15, 2022, 04:26:12 pmDoes the client take's at least 5 seconds to reconnect with broker ?Code:#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 resubscribeclient.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 reconnectif (reconnect()) {lastReconnectAttempt = 0;}}} else {// Client connectedclient.loop();}}

author: pcprogrammer
author_rank: Super Contributor
timestamp: September 15, 2022, 05:04:44 pm
content: 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.

author: King123
author_rank: Contributor
timestamp: September 15, 2022, 05:22:52 pm
content: Quote from: pcprogrammer on September 15, 2022, 05:04:44 pmenc28j60 module is connected with Arduino mega boardQuote from: pcprogrammer on September 15, 2022, 05:04:44 pmcomputer is setup as server and MQTT broker. Arduino is setup as a client

author: pcprogrammer
author_rank: Super Contributor
timestamp: September 15, 2022, 06:36:37 pm
content: 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.

author: King123
author_rank: Contributor
timestamp: September 17, 2022, 05:52:31 pm
content: I am confused with following conceptsDoes the broker lose connection with the client and try to reconnect or does the client lose connection with the broker and try to reconnect?

author: pcprogrammer
author_rank: Super Contributor
timestamp: September 17, 2022, 06:47:52 pm
content: 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.

author: sokoloff
author_rank: Super Contributor
timestamp: September 18, 2022, 12:05:51 am
content: 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.