void connectToWifi() { Serial.println("Connecting to Wi-Fi..."); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected to Wi-Fi with IP: "); Serial.println(WiFi.localIP()); }void connectToMqtt() { while (!mqttClient.connected()) { Serial.println("Connecting to MQTT..."); if (mqttClient.connect(ID)) { Serial.println("Connected to MQTT"); } else { Serial.print("Failed to connect to MQTT, state: "); Serial.println(mqttClient.state()); delay(2000); } } }
```
```
void setup() { Serial.begin(115200);// Setup MQTT server mqttClient.setServer(MQTT_HOST, MQTT_PORT);// Connect to WiFi connectToWifi();// Connect to MQTT connectToMqtt(); }
```
```
void loop() {
// Ensure the client is connected
if (!mqttClient.connected()) {
connectToMqtt();
}
// Handle MQTT client loop
mqttClient.loop();
// Publish message every 1 second
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
publishMsgBasket();
}
}
```
```
void publishMsgBasket() {
String msg = set_fruitbasketMsg();
String topic = "MYfancyTopic/Dummy/Data/Basket";
mqttClient.publish(topic.c_str(), msg.c_str());
}
```
Now the ESP32 should send the data packet every 1000ms (1 second) to the MQTT broker via your router. To verify this, you can use sniffer tools to subscribe to the topic or even monitor the entire broker (i.e., all topics). Here, we will show you our favorite tool, which allows you to do many additional things.
Now the ESP32 should send the data packet every 1000ms (1 second) to the MQTT broker via your router. To verify this, you can use sniffer tools to subscribe to the topic or even monitor the entire broker (i.e., all topics). Here, we will show you our favorite tool, which allows you to do many additional things.