knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.78k stars 1.46k forks source link

Custom Topic from SPIFF #977

Closed Heeyen closed 1 year ago

Heeyen commented 1 year ago

hello i have tried relatively many things and i just don't know what to do i am trying to subscribe to a topic after it has been read from spiffs it is composed of "server/shutter/" and the clientID that is read from the spiffs. If I insert the topic written out as a string in client.subscribe e.g.: client.subscribe("server/shutter/terrace") everything works fine. But as soon as I insert the read string, it no longer works.

`#include

include

include

include "SPIFFS.h"

include

include

// Create AsyncWebServer object on port 80 AsyncWebServer server(80); WiFiClient espClient; PubSubClient client(espClient);

// Search for parameter in HTTP POST request const char PARAM_INPUT_1 = "ssid"; const char PARAM_INPUT_2 = "pass"; const char PARAM_INPUT_3 = "serverIP"; const char PARAM_INPUT_4 = "clientID";

char topicBuf[100]; char clientBuf[50];

//Variables to save values from HTML form String ssid; String pass; String serverIP; String clientID; String topicName;

// File paths to save input values permanently const char ssidPath = "/ssid.txt"; const char passPath = "/pass.txt"; const char serverIPPath = "/serverIP.txt"; const char clientIDPath = "/clientID.txt";

// Timer variables unsigned long previousMillis = 0; const long interval = 10000; // interval to wait for Wi-Fi connection (milliseconds)

// Initialize SPIFFS void initSPIFFS() { if (!SPIFFS.begin(true)) { Serial.println("An error has occurred while mounting SPIFFS"); } Serial.println("SPIFFS mounted successfully"); }

// Read File from SPIFFS String readFile(fs::FS &fs, const char * path){ Serial.printf("Reading file: %s\r\n", path);

File file = fs.open(path); if(!file || file.isDirectory()){ Serial.println("- failed to open file for reading"); return String(); }

String fileContent; while(file.available()){ fileContent = file.readStringUntil('\n'); break;
} return fileContent; }

// Write file to SPIFFS void writeFile(fs::FS &fs, const char path, const char message){ Serial.printf("Writing file: %s\r\n", path);

File file = fs.open(path, FILE_WRITE); if(!file){ Serial.println("- failed to open file for writing"); return; } if(file.print(message)){ Serial.println("- file written"); } else { Serial.println("- frite failed"); } }

void callback(char topic, byte payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println();

/// Hier wird die angekommene Nachricht verarbeitet }

void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Create a random client ID String clientId = "ESP8266Client-"; clientId += String(random(0xffff), HEX); // Attempt to connect if (client.connect(clientId.c_str())) {

  client.subscribe(topicName.c_str());
}

} }

// Initialize WiFi bool initWiFi() { if(ssid=="" || serverIP=="" ){ Serial.println("Undefined SSID or IP address."); return false; }

WiFi.mode(WIFI_STA); WiFi.begin(ssid.c_str(),pass.c_str()); Serial.println("Connecting to WiFi...");

unsigned long currentMillis = millis(); previousMillis = currentMillis;

while(WiFi.status() != WL_CONNECTED) { currentMillis = millis(); if (currentMillis - previousMillis >= interval) { Serial.println("Failed to connect."); return false; }

}

Serial.println(WiFi.localIP()); return true; }

void setup() { // Serial port for debugging purposes Serial.begin(115200);

initSPIFFS();

// Load values saved in SPIFFS ssid = readFile(SPIFFS, ssidPath); pass = readFile(SPIFFS, passPath); serverIP = readFile(SPIFFS, serverIPPath); clientID = readFile (SPIFFS, clientIDPath); Serial.println(ssid); Serial.println(pass); Serial.println(serverIP); Serial.println(clientID);

strcpy(topicBuf, "server/shutter/"); strcpy(clientBuf, clientID.c_str());

strcat(topicBuf,clientBuf);

if(initWiFi()) { client.setServer(serverIP.c_str(), 1883);

while (!client.connected()) {
Serial.println("Connecting to MQTT...");

if (client.connect(clientID.c_str() )) {
  Serial.println("connected");  
  client.setCallback(callback);
  client.subscribe(topicBuf);

} else {

  Serial.print("failed with state ");
  Serial.print(client.state());
  delay(2000);

}

}

} else { // Connect to Wi-Fi network with SSID and password Serial.println("Setting AP (Access Point)"); // NULL sets an open Access Point WiFi.softAP("Sensor Setup", NULL);

IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP); 

// Web Server Root URL
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  request->send(SPIFFS, "/wifimanager.html", "text/html");
});

server.serveStatic("/", SPIFFS, "/");

server.on("/", HTTP_POST, [](AsyncWebServerRequest *request) {
  int params = request->params();
  for(int i=0;i<params;i++){
    AsyncWebParameter* p = request->getParam(i);
    if(p->isPost()){
      // HTTP POST ssid value
      if (p->name() == PARAM_INPUT_1) {
        ssid = p->value().c_str();
        Serial.print("SSID set to: ");
        Serial.println(ssid);
        // Write file to save value
        writeFile(SPIFFS, ssidPath, ssid.c_str());
      }
      // HTTP POST pass value
      if (p->name() == PARAM_INPUT_2) {
        pass = p->value().c_str();
        Serial.print("Password set to: ");
        Serial.println(pass);
        // Write file to save value
        writeFile(SPIFFS, passPath, pass.c_str());
      }
      // HTTP POST serverIP value
      if (p->name() == PARAM_INPUT_3) {
        serverIP = p->value().c_str();
        Serial.print("IP Address set to: ");
        Serial.println(serverIP);
        // Write file to save value
        writeFile(SPIFFS, serverIPPath, serverIP.c_str());
      }
      // HTTP POST clientID value
      if (p->name() == PARAM_INPUT_4) {
        clientID = p->value().c_str();
        Serial.print("Gateway set to: ");
        Serial.println(clientID);
        // Write file to save value
        writeFile(SPIFFS, clientIDPath, clientID.c_str());
      }
      //Serial.printf("POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
    }
  }
  request->send(200, "text/plain", "Done. ESP will restart, and connect to your Network: " + serverIP);
  delay(3000);
  ESP.restart();
});

server.begin();

} }

void loop() { if (!client.connected()) { reconnect(); }; client.loop(); } `