#include <Arduino.h> #include <WiFi.h> #include <PubSubClient.h> #ifndef WIFI_SSID #define WIFI_SSID "UPB-Guest" #endif #ifndef WIFI_PASSWORD #define WIFI_PASSWORD "" #endif #ifndef MQTT_HOST #define MQTT_HOST "test.mosquitto.org" #endif #ifndef MQTT_PORT #define MQTT_PORT 1883 #endif #ifndef BASE_TOPIC #define BASE_TOPIC "devices/esp32" #endif WiFiClient net; PubSubClient mqtt(net); // PubSubClient uses a separate setServer(...) unsigned long lastPub = 0; // ---------- Wi-Fi ---------- void connectWiFi() { if (WiFi.status() == WL_CONNECTED) return; WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("WiFi connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.printf("\nWiFi OK, IP: %s\n", WiFi.localIP().toString().c_str()); } // ---------- MQTT callback (PubSubClient signature) ---------- void mqttCallback(char* topic, byte* payload, unsigned int length) { // payload is NOT null-terminated; build a String safely String msg; msg.reserve(length); for (unsigned int i = 0; i < length; i++) msg += (char)payload[i]; Serial.printf("Message on %s: %s\n", topic, msg.c_str()); } // ---------- MQTT connect & subscribe ---------- void connectMQTT() { // Build clientId like before String clientId = "esp32-client-" + String((uint32_t)ESP.getEfuseMac(), HEX); // Last Will String willTopic = String(BASE_TOPIC) + "/status"; const char* willMsg = "offline"; const bool willRetain = true; const uint8_t willQos = 0; // PubSubClient is QoS 0 only Serial.println("MQTT connecting..."); while (!mqtt.connect(clientId.c_str(), willTopic.c_str(), willQos, willRetain, willMsg)) { Serial.print("."); delay(1000); } Serial.println("\nMQTT connected!"); // Optional subscription String subTopic = String(BASE_TOPIC) + "/#"; mqtt.subscribe(subTopic.c_str()); // QoS 0 Serial.printf("Subscribed to %s\n", subTopic.c_str()); // Publish "online" once connected (retain) mqtt.publish(willTopic.c_str(), "online", true); } void setup() { Serial.begin(115200); delay(500); connectWiFi(); mqtt.setServer(MQTT_HOST, MQTT_PORT); mqtt.setCallback(mqttCallback); // Match your 1KB buffer from 256dpi/client mqtt.setBufferSize(1024); connectMQTT(); } void loop() { connectWiFi(); // ensure WiFi if (!mqtt.connected()) { connectMQTT(); } mqtt.loop(); // must be called often; non-blocking delay(10); // Publish every 5 seconds if (millis() - lastPub > 5000) { lastPub = millis(); String topic = String(BASE_TOPIC) + "/heartbeat"; String payload = String("{\"uptime_ms\":") + millis() + "}"; bool ok = mqtt.publish(topic.c_str(), payload.c_str()); // QoS 0 Serial.printf("Publish %s => %s (%s)\n", topic.c_str(), payload.c_str(), ok ? "OK" : "FAIL"); } }