I have a esp8266 in Access Point mode that waits until receive data, once it get the data it switch to client mode, connect to another esp8266 and send some data. The AP mode is working, it is getting the data correctly. However, when it changes to Client mode and try to connect the another ESP, I always get a http code -1 and the data never reaches the destination.
Here is what I'm doing:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
// SSID and Password for AP mode
const char *ssid = "node_middle1";
const char *password = "a12345678";
// SSID and Password for other ESP network
const char *nextSSID = "main_node";
const char *nextPassword = "a12345678";
// Check if already get data from last node
int connectionMadeWithLastNode = 0;
// Check if configClientMode() was already called
int clientModeConfigured = 0;
// Fixed IP in network on AP mode
IPAddress apIP(192, 168, 4, 1);
ESP8266WebServer server(80);
void response();
void configAPMode();
void configClientMode();
void sendMessage();
void setup() {
Serial.begin(115200);
configAPMode();
}
void loop() {
if(connectionMadeWithLastNode == 0){
server.handleClient();
} else {
if(clientModeConfigured == 0) {
configClientMode();
} else{
sendMessage();
}
}
}
void response() {
Serial.print("MENSAGEM DO ULTIMO NÓ: ");
Serial.println(server.arg("plain"));
server.send(200);
connectionMadeWithLastNode = 1;
}
void configAPMode() {
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(ssid, password);
server.on("/", response);
server.begin();
}
void configClientMode() {
WiFi.softAPdisconnect();
WiFi.begin(nextSSID, nextPassword);
clientModeConfigured = 1;
Serial.println("CLIENT MODE");
}
void sendMessage(){
if (WiFi.status() == WL_CONNECTED){
HTTPClient http;
http.begin("http://192.168.4.1");
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST("{\"Value\": 200}");
Serial.print("HTTP Code: ");
Serial.println(httpCode);
http.end();
}
}
I think the problem is the configClientMode(). I already tried to call WiFi.mode(WIFI_STA) but that did not work.
PS: I already tested the another ESP separately and it's woking.