Hallo
ich versuche gerade eine MQTT Nachricht mit einem ESP8266 an meinen
Node-red Server/Brocker abzusetzen. Leider schaffe ich es einfach nicht
mich zu verbinden.
Als Beispielcodes verwende ich die DHT Geschichten, die man über all
findet, z.B.:
Hier
https://www.arduino.cc/en/Tutorial/MKRConnectorDHTOLED
oder hier:
https://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/
Nur ohne DHT-Sensor. Entsprechend abgespeckt ist mein Code. Mit dem WLAN
verbindet er sich noch Problemlos, das klappt, aber die Verbindung zum
MQTT Server scheitert mit dem Fehler -2 (rc=-2).
Den Node-Red Flow hab ich mal in Bildern Angehangen (1-4). Ich hab auch
gecheckt, ob der Server an sich läuft (Bild 5).
Findet jemand den Fehler, was ich falsch mache, oder hat eine Idee?
1 | #include <ESP8266WiFi.h>
|
2 | #include <PubSubClient.h>
|
3 |
|
4 | const char* ssid = "NAME";
|
5 | const char* password = "PASSWORT";
|
6 | const char* mqtt_server = "123.456.789.0";
|
7 |
|
8 | WiFiClient espClient;
|
9 | PubSubClient client(espClient);
|
10 |
|
11 | void setup_wifi() {
|
12 | delay(100);
|
13 | Serial.print("Connecting to ");
|
14 | Serial.println(ssid);
|
15 | WiFi.begin(ssid, password);
|
16 | while (WiFi.status() != WL_CONNECTED)
|
17 | {
|
18 | delay(500);
|
19 | Serial.print(".");
|
20 | }
|
21 | randomSeed(micros());
|
22 | Serial.println("");
|
23 | Serial.println("WiFi connected");
|
24 | Serial.println("IP address: ");
|
25 | Serial.println(WiFi.localIP());
|
26 | }
|
27 |
|
28 | void reconnect()
|
29 | {
|
30 | // Loop until we're reconnected
|
31 | while (!client.connected()) {
|
32 | Serial.print("Attempting MQTT connection...");
|
33 | if (client.connect("ESP8266Client")) {
|
34 | Serial.println("connected");
|
35 | client.subscribe("room/value");
|
36 | }
|
37 | else {
|
38 | Serial.print("failed, rc=");
|
39 | Serial.print(client.state());
|
40 | Serial.println(" try again in 5 seconds");
|
41 | delay(5000);
|
42 | }
|
43 | }
|
44 | }
|
45 |
|
46 | void setup()
|
47 | {
|
48 | Serial.begin(115200);
|
49 | setup_wifi();
|
50 | client.setServer(mqtt_server, 1883);
|
51 | }
|
52 |
|
53 | void loop()
|
54 | {
|
55 | if (!client.connected()) {
|
56 | reconnect();
|
57 | }
|
58 | if(!client.loop())
|
59 | client.connect("ESP8266Client");
|
60 | client.publish("room/value", "77");
|
61 | delay(1000);
|
62 | }
|