// Hive_MQTT_TLS_2.ino
// https://wokwi.com/projects/398851875260510209
// Connecting ESP32 to cloud HiveMQ using root certificate
// https://community.hivemq.com/t/connecting-esp32-to-cloud-hivemq-using-root-certificate/1770
#include <WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
//---- WiFi settings
const char* ssid = "Wokwi-GUEST";
const char* password = "";
//---- MQTT Broker settings
const char* mqtt_server = "0582ebf33e8341739b71952b55cf94dc.s1.eu.hivemq.cloud"; // replace with your broker url
const char* mqtt_username = "kelvinw_ps";
const char* mqtt_password = "Pass0kelvinwps";
const int mqtt_port = 8883;
const int retry_interval = 5000;
const int publish_interval = 2000;
WiFiClientSecure espClient;
PubSubClient mqttClient(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
const char* sensor1_topic = "user/kelvinw/temp";
const char* sensor2_topic = "user/kelvinw/humd";
const char* command1_topic = "user/kelvinw/led1";
const char* command2_topic = "user/kelvinw/led2";
#define LED1 12
#define LED2 13
static const char *root_ca PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13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l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";
void setup() {
Serial.begin(9600);
Serial.print("\nConnecting to ");
Serial.print(ssid);
Serial.print(" ");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());
Serial.println("");
// while (!Serial) delay(1);
// randomSeed(micros());
espClient.setCACert(root_ca);
mqttClient.setServer(mqtt_server, mqtt_port);
mqttClient.setCallback(callback);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
}
void loop() {
if (!mqttClient.connected()) reconnect();
mqttClient.loop();
unsigned long now = millis();
if (now - lastMsg >= publish_interval) {
lastMsg = now;
++value;
// snprintf(msg, MSG_BUFFER_SIZE, "Hello World! #%ld", value);
// Serial.print("Publish message: ");
// Serial.println(msg);
// mqttClient.publish(mqtt_topic, msg);
// publishMessage(sensor1_topic, msg, false);
// publishMessage(sensor2_topic, msg, false);
publishMessage(sensor1_topic, String(value) + String("°C"), false);
publishMessage(sensor2_topic, String(value) + String("%"), false);
// publishMessage(command1_topic, String("13579"), true); // Send a retained message
// publishMessage(command1_topic, String(""), true); // Delete a retained message
}
}
//=======================================================================Function=================================================================================
void reconnect() {
// Loop until we're reconnected
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection ... ");
String clientId = "ESP32Client-"; // Create a random client ID
char Id[5];
// clientId += String(random(0xffff), HEX);
sprintf(Id, "%04x", random(0xffff));
clientId += Id;
Serial.print(clientId);
Serial.print(" ... ");
// Attempt to connect
if (mqttClient.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
Serial.println("MQTT connected!");
mqttClient.subscribe(sensor1_topic); // subscribe the topics here
mqttClient.subscribe(sensor2_topic); // subscribe the topics here
mqttClient.subscribe(command1_topic); // subscribe the topics here
mqttClient.subscribe(command2_topic); // subscribe the topics here
} else {
// Arduino Client for MQTT
// https://pubsubclient.knolleary.net/api#state
Serial.print("failed, rc = ");
Serial.print(mqttClient.state());
Serial.print("; try again in ");
Serial.print(retry_interval);
Serial.println(" ms");
// Wait 5 seconds before retrying
delay(retry_interval);
}
}
}
//=======================================
// This void is called every time we have a message from the broker
void callback(char* topic, byte* payload, unsigned int length) {
String incomingMessage = "";
for (int i = 0; i < length; i++) incomingMessage += (char)payload[i];
Serial.println("Message arrived [" + String(topic) + "]: " + incomingMessage);
if (strcmp(topic, command1_topic) == 0) {
// digitalWrite(LED1, !digitalRead(LED1));
if (incomingMessage.equals("on")) {
digitalWrite(LED1, HIGH);
} else if (incomingMessage.equals("off")) {
digitalWrite(LED1, LOW);
}
} else if (strcmp(topic, command2_topic) == 0) {
// digitalWrite(LED2, !digitalRead(LED2));
if (incomingMessage.equals("on")) {
digitalWrite(LED2, HIGH);
} else if (incomingMessage.equals("off")) {
digitalWrite(LED2, LOW);
}
}
// check for other commands
/* else if (strcmp(topic, command2_topic) == 0) {
if (incomingMessage.equals("1")) { } // do something else
}
*/
}
//======================================= publishing as string
void publishMessage(const char* topic, String payload , boolean retained) {
// if (mqttClient.publish(topic, payload.c_str(), true))
if (mqttClient.publish(topic, payload.c_str(), retained))
Serial.println("Message published [" + String(topic) + "]: " + payload);
}