ESP32 wifi AP_STA problem

I need to have an ESP32 in AP_STA mode, and just can't make it work.

It should connect to the wifi router for IOT, and to an internal network mesh using PainlessMesh.

With this simple code it creates the mesh, than connects to the wifi router a couple of seconds and than the STA connection drops and never returns.
Been searching and trying different approaches, and code snippets but in the end is always the same. I also tried to setup a fixed channel on the wifi router, tried the same channel on the AP and different channel and no change at all.

If anyone can spot if I'm missing something here, will be much appreciated.

#include <WiFi.h>
#include <WiFiClient.h>
#include <painlessMesh.h>

// Configurações do Wi-Fi (Router)
const char* ssid = "ssid";           
const char* password = "pass";  

// Configurações da Mesh
#define MESH_PREFIX "MyMeshNetwork"
#define MESH_PASSWORD "SuperSecret"
#define MESH_PORT 5555
int meshChannel = 6;  // Canal fixo para a mesh (deve ser o mesmo do router)

Scheduler userScheduler;
painlessMesh mesh;

// Funções de callback da mesh
void receivedCallback(uint32_t from, String& msg) {
  Serial.printf("Mensagem recebida do nó %u: %s\n", from, msg.c_str());
}

void newConnectionCallback(uint32_t nodeId) {
  Serial.printf("Novo nó conectado: %u\n", nodeId);
}

void setup() {
  Serial.begin(115200);

  // Configurar Wi-Fi (modo STA)
  WiFi.mode(WIFI_AP_STA);

  WiFi.softAP("MeshAP", "MeshPass", 1);
  mesh.init(MESH_PREFIX, MESH_PASSWORD, &userScheduler, MESH_PORT);
  mesh.onReceive(&receivedCallback);
  mesh.onNewConnection(&newConnectionCallback);
  Serial.println("Mesh inicializada.");

  WiFi.begin(ssid, password, 6);
  Serial.println("A conectar ao Wi-Fi...");
  WiFi.setSleep(false);

  unsigned long startWiFiTime = millis();
  while (WiFi.status() != WL_CONNECTED) {
    if (millis() - startWiFiTime > 10000) {  // Timeout de 10 segundos
      Serial.println("Falha ao conectar ao Wi-Fi.");
      break;
    }
    delay(500);
    Serial.print(".");
  }

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("\nWi-Fi conectado.");
    Serial.println(WiFi.localIP());
  }

}

void loop() {
  mesh.update();  // Atualizar a mesh
  if (checkwifi_chrono.hasPassed(1000))
  {
    checkwifi_chrono.restart();
    checkWiFiConnection();  // Verificar estado do Wi-Fi e reconectar se necessário
  }
}

void checkWiFiConnection() {
    unsigned long startReconnectTime = millis();
    while (WiFi.status() != WL_CONNECTED) {
      if (millis() - startReconnectTime > 10000) {  // Timeout de 10 segundos
        Serial.println("Falha ao reconectar ao Wi-Fi.");
        return;
      }
      delay(500);
      Serial.print(".");
    }
    Serial.println("\nWi-Fi reconectado com sucesso.");
  
}

The following sequence works for me:

	...

        // set up STA
        if (*staSSID) { 
            // set up STA IPv4
            if (*staIPv4) { // static IPv4 address
                WiFi.config (IPAddress (staIPv4), IPAddress (staGateway), IPAddress (staSubnetMask), *staDns1 ? IPAddress (staDns1) : IPAddress (255, 255, 255, 255), *staDns2 ? IPAddress (staDns2) : IPAddress (255, 255, 255, 255)); // INADDR_NONE == 255.255.255.255
            } else { // DHCP IPv4
		        ;
            }  
            WiFi.begin (staSSID, staPassword);
        }

        // set up AP for IPv4
        if (*apSSID) {
            if (WiFi.softAP (apSSID, apPassword)) { 
                WiFi.softAPConfig (IPAddress (apIP), IPAddress (apGateway), IPAddress (apSubnetMask));
                WiFi.begin ();
            } else {
                // failed to initialize AP
            }
        } 

        // set WiFi mode
        if (*staSSID) {
            if (*apSSID) {
                WiFi.mode (WIFI_AP_STA); // both, AP and STA modes
            } else {
                WiFi.mode (WIFI_STA); // only STA mode
            }
        } else {
            if (*apSSID)
                WiFi.mode (WIFI_AP); // only AP mode
        }

Thanks so much for taking the time to post this approach, AP and STA works perfectly together.
The problem is when I add PainlessMesh library and set the mesh network, the Wifi connects in the beginning but drops after a couple seconds.

EDIT: I was over thinking this, in fact PainlessMesh had it figured, just need to use mesh.stationManual(STATION_SSID, STATION_PASSWORD);

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.