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.");
}