Hi .
I am using esp8266 01 and NodeMCU 1.0. I saw that if I restart my Arduino device,with my mqtt server running,arduinos cant subscribe to topics in order to receive command. If I restart my mqtt server although they do it.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>const char* ssid = "David";
const char* password = "hh6945441201";
const char* mqtt_server = "192.168.1.3";
WiFiClient espClient;
PubSubClient client(espClient);byte willQoS = 0;
const char* willTopic = "tele/esp/LWT/3";
const char* willMessage = "Offline";
boolean willRetain = true;
int mess = 9;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.println("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload*);*
- if (length - i == 1) {*
_ mess = payload - 48;_
* }*
* }*
* Serial.println();*
}
void reconnect() {
* // Loop until we're reconnected*
* while (!client.connected()) {*
* Serial.println("Attempting MQTT connection...");*
* // Create a random client ID*
* String clientId = "David_ESP_3";
if (client.connect(clientId.c_str())) {
_ Serial.println("connected");_
_ client.publish("tele/esp/LWT/3", "Online");_
_ client.subscribe("cmnd/esp/power/3");_
_ } else {_
_ delay(1000);_
_ Serial.print("failed, rc=");_
_ Serial.print(client.state());_
_ Serial.println(" try again in 5 seconds");_
_ // Wait 5 seconds before retrying*_
* delay(6000);*
* }*
* }*
}
void setup() {
* Serial.begin(115200);*
* setup_wifi();
client.setServer(mqtt_server, 1883);
_ client.setCallback(callback);_
client.connect("David_ESP_3", willTopic, willQoS, willRetain, willMessage);
_ client.publish("tele/esp/LWT/3", "Online");_
Serial.println("System_ESP_3");
_ //pinMode(2,OUTPUT); relay*_
}
void loop() {
* if (!client.connected()) {*
* reconnect();*
* }*
* client.loop();*
* if (mess == 1) {*
* //digitalWrite(2,HIGH);*
* client.publish ("stat/esp/power/3", "ON");*
* mess = 9;*
* }*
* else if (mess == 2) {*
* //digitalWrite(2, LOW);*
* client.publish ("stat/esp/power/3", "OFF");*
* mess = 9;*
* }*
* delay(500);*
* Serial.println("OK loop");*
}
[/quote]
this is my code for esp8266 01 and I plan to put a relay.
I don't know if I writing wrong my code or if is mqtt configuration problem.
