HiveMQ using ESP32 and NODERED

Hi here a small tutorial of how to connect the ESP32 with HIVEMQ and use NODE-RED as a dashboard / visualiser.

First here a template code (that work flawlessly for me):Just replace the XXXX with your input/value
make sure you install the needed library.

#include <WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>

//---- WiFi settings
const char* ssid = “XXXX”;
const char* password = “XXXX”;
//---- MQTT Broker settings
const char* mqtt_server = “XXXX”; // replace with your broker url
const char* mqtt_username = “XXXX”;
const char* mqtt_password = “XXXX”;
const int mqtt_port =8883;

WiFiClientSecure espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;

#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];

const char* sensor1_topic= “sensor1”;
const char* sensor2_topic=“sensor2”;

static const char *root_ca PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
T8KOEUt+zwvo/7V3LvSye0rgTBIlD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P4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";

void setup() {

Serial.begin(9600);
Serial.print("\nConnecting to ");
Serial.println(ssid);

WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
randomSeed(micros());
Serial.println("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());

while (!Serial) delay(1);

espClient.setCACert(root_ca);
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}

void loop() {

  if (!client.connected()) reconnect();
  client.loop();

publishMessage(sensor1_topic,String(XXXX),true);    
publishMessage(sensor2_topic,String(XXXX),true);
}

//=======================================================================Function=================================================================================

void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);
String clientId = “ESP8266Client-”; // Create a random client ID
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
Serial.println(“connected”);

  client.subscribe(command1_topic);   // subscribe the topics here
  //client.subscribe(command2_topic);   // subscribe the topics here
} else {
  Serial.print("failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 5 seconds");   // Wait 5 seconds before retrying
  delay(5000);
}
}
}

//=======================================
// This void is called every time we have a message from the broker

void callback(char* topic, byte* payload, unsigned int length) {
String incommingMessage = “”;
for (int i = 0; i < length; i++) incommingMessage+=(char)payload[i];
Serial.println(“Message arrived [”+String(topic)+“]”+incommingMessage);
// check for other commands
/* else if( strcmp(topic,command2_topic) == 0){
if (incommingMessage.equals(“1”)) { } // do something else
}
*/
}

//======================================= publising as string
void publishMessage(const char* topic, String payload , boolean retained){
if (client.publish(topic, payload.c_str(), true))
Serial.println(“Message publised [”+String(topic)+"]: "+payload);
}
3 Likes

Hi @Mike,

Thank you so much for being an active member of our community!
We certainly appreciate this a lot.

Cheers,
Florian from the HiveMQ Team.

1 Like

Once the ESP32 is connected to the BROKER you should see 1/100 in your cluster.

afterward you will have to setup credential in your HIVEMQ to do so go to ‘‘Your cluster → manage Cluster → acces management’’ in this section you can add your MQTT Credentials.

after the connection of the client confirmed head over NodeRed and add a MQTT IN flow

double clic on said flow and enter the name of your Topic

after that clic on the pencil on the right to the server

in the SERVER field paste your HIVEMQ URL
Check the USE TLS box
goto SECURITY section and enter your credential previously configured

Once this is done you should see a blue dot underneath the MQTT IN FLOW that confirm you are connected to the broker.

Only thing left is to creat your own dashboard

Hope this help, if you have any question il try to answer them as clearly as i can.

1 Like

Here a picture with a volume trend using Node-Red with HiveMQ

1 Like


Here is a picture of the local display showing the local IP aswell as the Broker used by the ESP32 (at the bottom of the screen)

1 Like

https://drive.google.com/drive/folders/1oTTaHoQWhAlI77lzhTBZC9XNSXaR1LBC?usp=sharing

here a link to the .INO file

The template as been updated.

I have tried compiling this code in Arduino IDE and get the following error.

Compilation error: ‘command1_topic’ was not declared in this scope

Any pointers please?

If you are not using command just comment it. It should run without any more issue

it has been fixed thanks for pointing it out

Thank you, all working now.

1 Like

I can successfully connect the ESP to HIVEMQT and see the messages being sent and received on the serial monitor but I can’t connect my NODERED flow.

I suspect it is the configuration of my MQTT in node. In URL I paste the URL address from the arduino sketch. Does it need http:// at the beginning?
Are the security credentials the username and password used in the sketch?

Sorry to ask all these questions but I would really like to get this working

Don’t worry, I have now got it sorted out.

no worries my friend please add what you did to fix your issues in case someone else experiance the same issue :slight_smile:

i realised i did forget to mention that you might have to open the port 8883 on your routeur if you are unable to connect to the broker with NodeRed

As I said, all sorted. Configured my MQTT nodes with the correct URL (no HTTP://)
Port 8883, clicked on use TLS but entered nothing in the TLS config.

1 Like

Hi all. This is my first post here.
I have a question about the root_ca certificate string in this example.

Is this just an example certificate or will it work for anyone? I ask because in the “Getting started with Arduino ESP8266” tutorial it says I have to create a certificate with certs-from-mozilla.py and then load it into LittleFS. That sound like more of a hassle.

Yes its an example certificate

So it will or not work for me as-is?

Yes it should work just fine

It works fine using Wifi but when we try connecting it using Grps via SIM, it doesn’t work. Anyone who is successful connecting hive mq using SIM?