// T-Energy-S3 MQTT Battery Monitor (Deep Sleep Edition) // Wakes on button press, publishes voltage, then sleeps #include #include #include #include "config.h" #define BATTERY_PIN 3 #define BUTTON_PIN GPIO_NUM_0 #define PUBLISH_COUNT 3 #define PUBLISH_DELAY_MS 1000 WiFiClientSecure secureClient; PubSubClient mqtt(secureClient); void printMac() { Serial.printf("MAC Address: %s\n", WiFi.macAddress().c_str()); } bool connectWifi() { Serial.printf("Connecting to %s...\n", WIFI_SSID); WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID); int attempts = 0; while (WiFi.status() != WL_CONNECTED && attempts < 20) { delay(500); Serial.print("."); attempts++; } if (WiFi.status() == WL_CONNECTED) { Serial.printf("\nConnected! IP: %s\n", WiFi.localIP().toString().c_str()); return true; } else { Serial.println("\nWiFi connection failed"); return false; } } bool connectMqtt() { Serial.printf("Connecting to MQTT %s:%d...\n", MQTT_HOST, MQTT_PORT); String clientId = "t-energy-" + WiFi.macAddress(); if (mqtt.connect(clientId.c_str(), MQTT_USER, MQTT_PASS)) { Serial.println("MQTT connected!"); return true; } else { Serial.printf("MQTT failed, rc=%d\n", mqtt.state()); return false; } } void publishVoltage() { int mv = analogReadMilliVolts(BATTERY_PIN) * 2; Serial.printf("Battery: %d mV\n", mv); char payload[16]; snprintf(payload, sizeof(payload), "%d", mv); if (mqtt.publish(MQTT_TOPIC, payload)) { Serial.printf("Published to %s: %s\n", MQTT_TOPIC, payload); } else { Serial.println("Publish failed"); } mqtt.loop(); } void enterDeepSleep() { Serial.println("Entering deep sleep... press button to wake"); Serial.flush(); esp_sleep_enable_ext0_wakeup(BUTTON_PIN, LOW); esp_deep_sleep_start(); } void setup() { Serial.begin(115200); delay(1000); Serial.println("\n=== T-Energy-S3 MQTT Monitor ===\n"); // Check wake reason esp_sleep_wakeup_cause_t wakeup_reason = esp_sleep_get_wakeup_cause(); if (wakeup_reason == ESP_SLEEP_WAKEUP_EXT0) { Serial.println("Woke up from button press!"); } else { Serial.println("Initial boot"); } printMac(); pinMode(BATTERY_PIN, INPUT); analogReadResolution(12); analogSetPinAttenuation(BATTERY_PIN, ADC_11db); // TLS setup secureClient.setInsecure(); mqtt.setServer(MQTT_HOST, MQTT_PORT); if (connectWifi() && connectMqtt()) { for (int i = 0; i < PUBLISH_COUNT; i++) { publishVoltage(); if (i < PUBLISH_COUNT - 1) { delay(PUBLISH_DELAY_MS); } } } // Disconnect cleanly mqtt.disconnect(); WiFi.disconnect(true); enterDeepSleep(); } void loop() { // Never reached - we sleep in setup() }