Helft einem Anfänger ?String in Bedingung?

Hallo Leute

Ich bin so ein grosser Neuling das ich nichtmal mein Problem in einem Titel zusammenfassen kann. werde ihn gerne ändern wenn ich weis was genau das Proble ist.

const String clientId = "ESP8266Client";

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish ([color=red]clientId[/color]".outTopic", "i'm back bitches");
      // ... and resubscribe
      client.subscribe ([color=red]clientId[/color]".inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

Ich würde gerne den String "clientId" in meinen Topic einbinden. (um in meinem Broker eine Ordnerstruktur zu erreichen)
Jedoch bekomme ich die Fehlermeldung

exit status 1
expected ')' before string constant

Aber das ist ja genau das was ich will. Den globalen Namen in der Klammer verwenden. (rot markiert im obrigen Code)
schreibe ich einfach in " " den namen jedes mal selber klappt es ohne Probleme. Irgendetwas übersehe ich.

hier mein ganzer Code

/*
 Source Code: Basic ESP8266 MQTT example
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>


// Update these with values suitable for your network.

const char* ssid = "Gott";
const char* password = "xxmathysxx";
const char* mqtt_server = "192.168.0.21";
const int mqtt_server_port = 1887;
const char* mqtt_username = "MQTTBroker";
const char* mqtt_password = "Joshua0711";
const String clientId = "ESP8266Client";




WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}





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();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                      // but actually the LED is on; this is because
                                      // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}





void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish ("outTopic", "i'm back bitches");
      // ... and resubscribe
      client.subscribe ("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}








void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_server_port);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }

  if (WiFi.status() != WL_CONNECTED) {
     setup_wifi();
  }
  
  client.loop();
}

In Code-Tags:

/*
 Source Code: Basic ESP8266 MQTT example
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>


// Update these with values suitable for your network.

const char* ssid = "Gott";
const char* password = "xxmathysxx";
const char* mqtt_server = "192.168.0.21";
const int mqtt_server_port = 1887;
const char* mqtt_username = "MQTTBroker";
const char* mqtt_password = "Joshua0711";
const String clientId = "ESP8266Client";




WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}





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);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                      // but actually the LED is on; this is because
                                      // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}





void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish ("outTopic", "i'm back bitches");
      // ... and resubscribe
      client.subscribe ("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}








void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_server_port);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }

  if (WiFi.status() != WL_CONNECTED) {
     setup_wifi();
  }
  
  client.loop();
}

Meine dringende Empfehlung: Räume auf und formatiere lesbar.

Gruß

Gregor

PS: Weil ich ein freundlicher Mensch bin, behalte ich meine Meinung über Copy+Paste-Programmierer für mich :slight_smile:

So klappt es ohne Probleme:

const String clientId = "ESP8266Client";

void reconnect() {
  while (!client.connected()) {
     if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
        client.publish (".outTopic", "i'm back bitches");
        client.subscribe (".inTopic");
   } else {
        delay(5000);
   }
 }
}

Ich hätte gerne sowas: (klappt aber nicht):

const String clientId = "ESP8266Client";

void reconnect() {
  while (!client.connected()) {
     if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
        client.publish (clientId".outTopic", "i'm back bitches");
        client.subscribe (clientId".inTopic");
   } else {
        delay(5000);
   }
 }
}

ich hoffe so ist besser. Das ganze ist eine abgeändert Form des Example "Basic ESP8266 MQTT example" also ich hab bisher noch kaum was formatiert. xD und ich versuche auch möglichst wenig copy past (ich weis der fehler sieht stark danach aus) zuverwenden. Ich bin halt noch blutiger Anfänger.

Auf String sollte man nach Möglichkeit verzichten. Das führt oft zum zumüllen des Speichers und irgendwann zum Hängen des Microcontrollers.

Strings werden mit + aneinander angehängt.

Versuche mal clientId + ".outTopic"

Keine Ahnung ob das geht.

Gruß, Jürgen

Leider klappt das auch nicht.
Kriege den Fehler:

exit status 1
no matching function for call to 'PubSubClient::subscribe(StringSumHelper&)'

String + "irgendwas" ist eine extrem komplizierte Aktion, geht aber.
Danach musst du aber .c_str() verwenden um aus einem String etwas verwendbares zu machen.

Wenn ein String Objekt nur verwendet wird, um darauf .c_str() auszuführen, blamiert man sich hier.

const char clientId[] = "ESP8266Client";
const char outTopic[] = "ESP8266Client.outTopic";
const char inTopic[] = "ESP8266Client.inTopic"; 

...
     if (client.connect(clientId, mqtt_username, mqtt_password)) {
        client.publish (outTopic, "i'm back bitches");
...

... und fertig. Komplizierter geht's mit strcat()