Search code examples
mqttesp8266arduino-idearduino-esp8266

ESP8266 crashes when PubSubClient set mqttserver


I'm using NodeMCU (ESP12E) controlled using pubsubclient library. NodeMCU is crashed when i call
client.setServer(mqtt_server, 1883);
Message:

Exception (28):
    epc1=0x4000bf80 epc2=0x00000000 epc3=0x00000000 excvaddr=0x0000096c depc=0x00000000

It seems setServer action conflicting with ESP8266WebServer.
I tried: this but the problem is not resolved.
This is my code:

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

// Khởi tạo biến toàn cục
const char* mqtt_server = "iot.eclipse.org";

WiFiClient espClient;
PubSubClient client;
ESP8266WebServer *server;
void setup() {
  EEPROM.begin(512);
  Serial.begin(9600);
  //I tried this
  server = new (ESP8266WebServer);
  //Check wifi, if failed -> run as web server
  if (!setup_wifi()) {
    wifiStartServerMode();
  }

  //.....Some function to get username and password from EEPROM

  // Call back-end using new local WiFiClient
  //  String serverResponse = registerDevice(mac, username, userpassword, 3);
  //If ok, serser response this:
  String serverResponse = "null;null;root/phan/abc";
  if (serverResponse.indexOf(';') > 0) {
    Serial.println("start mqtt client");
    client.setClient(espClient);

    ////////////////
    //CRASHED HERE//
    ///////////////
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);
    String tempTopic = getValue(serverResponse, ';', 2);
    for (int i = 0; i < tempTopic.length(); i++) {
      topic += tempTopic[i];
    }
    //Đăng ký nhận tín hiệu
    client.subscribe(topic);
    errConnect2BackEnd = false;
    stConnectBroker = true;
  } else if (serverResponse.equals("failed")) {//Không thể kết nối server
    Serial.println("Can't connect to server");
    //TODO: Báo lỗi, không kết nối server
  } else {
    Serial.print("Error: ");
    Serial.println(serverResponse);
    //TODO: Nhập sai thông tin đăng nhập -> reset để nhập lại (nhấn nút, xóa EEPROM)
  }
  Serial.println("End of setup");

}

Function start run server in loop and stop when it's done

  //-> run as web server

  void wifiStartServerMode() {
  //Active AP_ST_MODE
  setupAP_STA_Mode();
  //Run server->handleClient(); in loop
  viewRunConfig();
  server->stop();
  server->close();
  delay(100);
  delete(server);
  setup_Station_Mode();
}

When function "wifiStartServerMode" not run, it still crash.

What could be the problem?


Solution

  • If your algorithm is right. Please check pointer.....and move others files.
    It seems bug of Arduino IDE, when i copy this functions, code to other files.
    It works.