1

Refer to

I executed the code in the given link. However i am not able to receive the subscribe message that are send from MQTT test broker(MQTT Lens) on the serial console.

Please help. I am receiving successful call to both publish methods

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "honored";
const char* ss_pswd = "12345678";
const char* mqtt_server = "iot.eclipse.org";


void callback(char* topic, byte* payload, unsigned int length);
WiFiClient EspClient;

PubSubClient client(EspClient);

void wifi_setup() {
  Serial.print("Connecting to: ");
  Serial.println(ssid);
  WiFi.begin(ssid, ss_pswd);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String ClientId = "ESP8266";
    ClientId += String(random(0xffff), HEX);
    if (client.connect(ClientId.c_str())) {
      Serial.println("connected");
      client.publish("outtopic", "hello world, finally");
      client.subscribe("/room/test");
    } else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      Serial.println("Try again...");
      delay(5000);
    }
  }
}
void sendMQTTMessage() {
  Serial.println("sending your message");
  if (!client.connected()) {
    reconnect();
  }
  client.publish("/sensor/pir", "on");
}
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived: ");
  Serial.println(topic);
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
}

void setup() {
  Serial.begin(115200);
  wifi_setup();
  client.setServer(mqtt_server, 1883);
  sendMQTTMessage();
  client.setCallback(callback);
  delay(2000);
  Serial.println("going into deep sleep");
  ESP.deepSleep(10 * 1000000);
}

void loop() {

}
Rohit
  • 49
  • 2

1 Answers1

1

My solution: update_mqtt() is called before deepSleep

PubSubClient mqtt_client(client);
boolean cb = false;

void callback_mqtt_switch(char* topic, byte* payload, unsigned int length) { String lowerstr = ""; for (uint8_t i = 0; i < length; i++) { lowerstr += (char)payload[i]; } lowerstr.toLowerCase(); DebugOut("Sleep payload: " + lowerstr); if (!back_to_sleep) { sleep_on = lowerstr == "ein"; } cb = true; }

void update_mqtt() { int i = 0; while (!cb && i++ < 30) { mqtt_client.loop(); delay(10); } #ifdef TEST Serial.print("Warte "); Serial.println(i * 10); // max. 300ms gewartet #endif cb = false; }

sempaiscuba
  • 1,042
  • 9
  • 21
  • 32
geb
  • 11
  • 2