// Reads an MPP Solar / PIP inverter over RS232 and publishes the values via MQTT. // Board: ESP32 DevKitC. Library: PubSubClient (Nick O'Leary). #include #include #include "mpp_protocol.h" // ---- your settings ---- const char *WIFI_SSID = "your-wifi"; const char *WIFI_PASSWORD = "your-password"; const char *MQTT_HOST = "192.168.1.10"; const int MQTT_PORT = 1883; const char *MQTT_TOPIC = "inverter/status"; // ----------------------- const int RX_PIN = 16, TX_PIN = 17; const unsigned long POLL_MS = 10000, REPLY_TIMEOUT_MS = 2000; WiFiClient network; PubSubClient mqtt(network); // Sends a command and returns the checked payload of the reply bool query(const char *command, std::string &result) { while (Serial2.available()) Serial2.read(); // drop leftovers std::string request = mpp::frame(command); Serial2.write(reinterpret_cast(request.data()), request.size()); std::string reply; unsigned long start = millis(); while (millis() - start < REPLY_TIMEOUT_MS) { if (!Serial2.available()) { delay(5); continue; } char c = Serial2.read(); if (c == '\r') return mpp::payload(reply, result); reply += c; } return false; } // Non-blocking: values stay visible on USB even without WiFi or broker void keepConnected() { if (WiFi.status() == WL_CONNECTED && !mqtt.connected()) mqtt.connect("mpp-reader"); mqtt.loop(); } void setup() { Serial.begin(115200); Serial2.begin(2400, SERIAL_8N1, RX_PIN, TX_PIN); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); mqtt.setServer(MQTT_HOST, MQTT_PORT); mqtt.setBufferSize(512); } void loop() { keepConnected(); std::string data; std::string json = query("QPIGS", data) ? mpp::qpigsToJson(data) : ""; if (json.empty()) { Serial.println("No valid reply - check wiring (swap RX/TX) and baud rate"); } else { Serial.println(json.c_str()); mqtt.publish(MQTT_TOPIC, json.c_str()); } unsigned long start = millis(); while (millis() - start < POLL_MS) { mqtt.loop(); delay(10); } }