Search code examples
arduino-esp8266arduino-esp32embeddedwebserver

Can't conncect ESP32 to ESP8266 or vice versa. socket error on fd 48, errno: 104, "Connection reset by peer"


im trying to communicate wia WiFi usin esp8266 and esp32 devices (cuz have 2 esp8266 and 1 esp32). Im using ESPAsyncWebServer library (https://github.com/me-no-dev/ESPAsyncWebServer works via HTTPClient). When i try to connect two esp8266 it works, one of them as a web server and other one connects to this WiFi server. But it doesnt works between ESP32 and ESP8266.

İ've tried to make ESP32 server didnt work, then i tried to make it client but still didnt work. İ couldn't figure it out. Here is codes, For ESP32 WebServer,

#include <Arduino.h>
#include <WiFi.h>
#include <cstring>

#include "ESPAsyncWebServer.h"
// Set your access point network credentials
const char* ssid = "ESP32-Access-Point-1";
const char* password = "3423046avz";


AsyncWebServer server(80);

// Ekranda gösterilecek default değerler
char sensor0[50]  = "15.22.2023/PL52/12.22.2021";
char sensor1[50]  = "15.22.2023/PL53/12.22.2021";
char sensor2[50]  = "BUGUN/PL54/YARIN";
char sensor3[50]  = "15.22.2023/PL55/SALI";
char sensor4[50]  = "15.22.2023/PL56/12.22.2021";
char sensor5[50]  = "15.22.2023/PL57/12.22.2021";
char sensor6[50]  = "15.22.2023/PL58/12.22.2021";
char sensor7[50]  = "15.22.2023/PL59/CUMA";
char sensor8[50]  = "15.22.2023/PL60/12.22.2021";
char sensor9[50]  = "15.22.2023/PL61/12.22.2021";
char sensor10[50] = "15.22.2023/PL62/12.22.2021";
char sensor11[50] = "15.22.2023/GOZDE/12.22.2021";
char sensor12[50] = "15.22.2023/HELP/12.22.2021";
char sensor13[50] = "15.22.2023/SAL/12.22.2021";
char sensor14[50] = "15.22.2023/BAHA/12.22.2021";
char sensor15[50] = "EGEMEN/BEY/KOMBO";

// Kod yazmayı kolaylaştırmak için diziye atıyorum
char* senser_ptr[] ={sensor0,sensor1,sensor2,sensor3,sensor4,sensor5,sensor6,sensor7,sensor8,sensor9,sensor10,sensor11,sensor12,sensor13,sensor14,sensor15}; 

// Seri porttan gelen veriyi saklamak için buffer
char buffer[50];

// Gelen char değerleri verilen başlangıç ve bitiş aralığı için sayıya çeviren (sadece tam sayılar) fonksyon
// Hangi sütün ve hangi satır geldiğini anlamayı kolaylaştırma açısından
int charsToInt(char *buffer,int start,int end);

// Nextion fonksyonunda yazdırmak için gelne char değerleri String e çevirip atıyorum
String charsToString(char *buffer,int start,int end);

void setup() {
  Serial.begin(115200);
  delay(50);
  Serial.print("Setting AP (Access Point)…");
  WiFi.softAPConfig(
        IPAddress(192, 168, 4, 1),
        IPAddress(192, 168, 4, 1),
        IPAddress(255, 255, 255, 0));
  WiFi.softAP(ssid,password);

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

   // Aşağıdaki adres ler sorgulandığında gönderilecek verileri yaz
  server.on("/sensor0", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor0);
  });
  server.on("/sensor1", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor1);
  });
  server.on("/sensor2", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor2);
  });
  server.on("/sensor3", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor3);
  });
  server.on("/sensor4", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor4);
  });
  server.on("/sensor5", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor5);
  });
  server.on("/sensor6", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor6);
  });
  server.on("/sensor7", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor7);
  });
  server.on("/sensor8", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor8);
  });
  server.on("/sensor9", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor9);
  });
  server.on("/sensor10", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor10);
  });
  server.on("/sensor11", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor11);
  });
  server.on("/sensor12", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor12);
  });
  server.on("/sensor13", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor13);
  });
  server.on("/sensor14", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor14);
  });
  server.on("/sensor15", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor15);
  });

  server.begin();
}

void loop() {  
  if(Serial.available()){
    if(Serial.read() == '*'){
      Serial.readBytesUntil('#',buffer,50); 

      int index = charsToInt(buffer,0,1);

      String str = charsToString(buffer,2,50);


      strcpy(senser_ptr[index], str.c_str());

      Serial.print("String: ");
      Serial.println(str);
      Serial.print("senser_ptr: ");
      Serial.println(senser_ptr[index]);

      memset(buffer,NULL,sizeof(buffer));
      Serial.print(buffer);
    }
  }
}

// Gelen char değerleri verilen başlangıç ve bitiş aralığı için sayıya çeviren (sadece tam sayılar) fonksyon
// Hangi sütün ve hangi satır geldiğini anlamayı kolaylaştırma açısından
int charsToInt(char *buffer,int start,int end){
  
  uint8_t counter = 0; // 10^(counter) verisi tutarak hangi basamakta olduğumuzu tutuyorum
  int value = 0;       // Geri döndüreceğim veriyi tutuyorum
  while(end >= start){ // Sağdan sola 1 ler basamağı olduğu için o şekilde ilerletiyorum
    value += (buffer[end]-'0')* pow(10,counter); // 0 karakterinin başlangıç değeri 48 olduğunda bu değeri çıkarark int e çeviyorum
    counter++;
    end--;
  }
  return value;
}

// Nextion fonksyonunda yazdırmak için gelne char değerleri String e çevirip atıyorum
String charsToString(char *buffer,int start,int end){
  String str;
  while(start < end){
    if(buffer[start] == NULL) break; 
    str += buffer[start];

    start++;
  }
  return str;
}

ESP32 WiFi CLient,

#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>


//Changables
const long timeInterval = 5000; 
#define DEBUG_MODE true

// Set your network credentials
const char* ssid = "ESP32-Access-Point-1";
const char* password = "3423046avz";

const IPAddress staticIP(192, 168, 4, 1);  // Set your desired static IP address
const IPAddress gateway(192, 168, 4, 1);     // Set your gateway IP address
const IPAddress subnet(255, 255, 255, 0);   
String ipAddressString;

String serverNames[] = {"sensor0","sensor1","sensor2","sensor3","sensor4","sensor5","sensor6","sensor7","sensor8","sensor9","sensor10","sensor11","sensor12","sensor13","sensor14","sensor15"};
String calibrationData;
unsigned long previousMillis = 0;

// Priviate Func Definatiosn
String httpGETRequest(const char* serverName);
int sendCalibrationData();

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  
  WiFi.mode(WIFI_STA);
  WiFi.config(staticIP, gateway, subnet);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");

  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }

  Serial.println("");

  Serial.print("Connected to WiFi network"+ String(ssid) + "with IP Address: ");
  Serial.println(WiFi.localIP());
  IPAddress ipAddress = WiFi.localIP();
  String ipAddressString = ipAddress.toString();
  ipAddressString = "http://"+ipAddressString +"/calibration_data";                                         
  Serial.println(ipAddressString);
}

void loop() {
  unsigned long currentMillis = millis();

  // put your main code here, to run repeatedly:
  if(currentMillis - previousMillis >= timeInterval) {
     // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED ){ 

      sendCalibrationData();

      // save the last HTTP GET Request
      previousMillis = currentMillis;
    }
    else {
      Serial.println("WiFi Disconnected");
    }
  }
}

String httpGETRequest(const char* serverName) {
  WiFiClient client;
  HTTPClient http;
    
  // Your Domain name with URL path or IP address with path
  http.begin(client, serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "--"; 
  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

int sendCalibrationData(){
  for(int j = 0;j<=15;j++){
    String lastDate;
    String deviceID;
    String nextDate;
    int ind1,ind2;
    String serverName = "http://192.168.4.1/" + serverNames[j];
    Serial.println(serverName);
    calibrationData = httpGETRequest(serverName.c_str());

    // Gelen veriyi '/' karakterlerine göre böl
    ind1 = calibrationData.indexOf('/');
    lastDate = calibrationData.substring(0,ind1);

    ind2 = calibrationData.indexOf('/',ind1+1);
    deviceID = calibrationData.substring(ind1+1,ind2);

    nextDate = calibrationData.substring(ind2+1);


    Serial1.println('*'+ ((j<=9 ) ? '0'+ String(j) : String(j)) + '1' + lastDate+'#'); // Megaya göndermek üzere sensör verisini düzenleyip gönder
    delay(500);
    Serial1.println('*'+ ((j<=9 ) ? '0'+ String(j) : String(j)) + '2' + deviceID+'#');
    delay(500);
    Serial1.println('*'+ ((j<=9 ) ? '0'+ String(j) : String(j)) + '3' + nextDate+'#');

#ifdef DEBUG_MODE   
    Serial.printf("lastDate: %s deviceID: %s  nextDate: %s",lastDate,deviceID,nextDate);
#endif
  }
  return 1;
}

ESP8266 WiFi Server,

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <cstring>

#include <ESPAsyncTCP.h>
#include "ESPAsyncWebServer.h"

// Wifi ağının adı ve şifresini belirle
const char* ssid = "ESP32-Access-Point-1";
const char* password = "3423046avz";


AsyncWebServer server(80);

// Ekranda gösterilecek default değerler
char sensor0[50]  = "15.22.2023/PL52/12.22.2021";
char sensor1[50]  = "15.22.2023/PL53/12.22.2021";
char sensor2[50]  = "BUGUN/PL54/YARIN";
char sensor3[50]  = "15.22.2023/PL55/SALI";
char sensor4[50]  = "15.22.2023/PL56/12.22.2021";
char sensor5[50]  = "15.22.2023/PL57/12.22.2021";
char sensor6[50]  = "15.22.2023/PL58/12.22.2021";
char sensor7[50]  = "15.22.2023/PL59/CUMA";
char sensor8[50]  = "15.22.2023/PL60/12.22.2021";
char sensor9[50]  = "15.22.2023/PL61/12.22.2021";
char sensor10[50] = "15.22.2023/PL62/12.22.2021";
char sensor11[50] = "15.22.2023/GOZDE/12.22.2021";
char sensor12[50] = "15.22.2023/HELP/12.22.2021";
char sensor13[50] = "15.22.2023/SAL/12.22.2021";
char sensor14[50] = "15.22.2023/BAHA/12.22.2021";
char sensor15[50] = "EGEMEN/BEY/KOMBO";

// Kod yazmayı kolaylaştırmak için diziye atıyorum
char* senser_ptr[] ={sensor0,sensor1,sensor2,sensor3,sensor4,sensor5,sensor6,sensor7,sensor8,sensor9,sensor10,sensor11,sensor12,sensor13,sensor14,sensor15}; 

// Seri porttan gelen veriyi saklamak için buffer
char buffer[50];

// Gelen char değerleri verilen başlangıç ve bitiş aralığı için sayıya çeviren (sadece tam sayılar) fonksyon
// Hangi sütün ve hangi satır geldiğini anlamayı kolaylaştırma açısından
int charsToInt(char *buffer,int start,int end){
  
  uint8_t counter = 0; // 10^(counter) verisi tutarak hangi basamakta olduğumuzu tutuyorum
  int value = 0;       // Geri döndüreceğim veriyi tutuyorum
  while(end >= start){ // Sağdan sola 1 ler basamağı olduğu için o şekilde ilerletiyorum
    value += (buffer[end]-'0')* pow(10,counter); // 0 karakterinin başlangıç değeri 48 olduğunda bu değeri çıkarark int e çeviyorum
    counter++;
    end--;
  }
  return value;
}

// Nextion fonksyonunda yazdırmak için gelne char değerleri String e çevirip atıyorum
String charsToString(char *buffer,int start,int end){
  String str;
  while(start < end){
    if(buffer[start] == NULL) break; 
    str += buffer[start];

    start++;
  }
  return str;
}

// Bunun yerine memset te kullanılabilir sadece char diziyi boşaltıyor.
void emptyBuffer(char *buffer, int len){
  for(int i = 0;i<len;i++){
    buffer[i] = NULL;
  }
}

void setup() {
  Serial.begin(115200);
  delay(50);
  Serial.print("Setting AP (Access Point)…");
  WiFi.softAPConfig(
        IPAddress(192, 168, 4, 1),
        IPAddress(192, 168, 4, 1),
        IPAddress(255, 255, 255, 0));
  WiFi.softAP(ssid,password); // Sabit ip de wifi accses pointi aç

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP); // Ip adresini yazdır

  // Aşağıdaki adres ler sorgulandığında gönderilecek verileri yaz
  server.on("/sensor0", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor0);
  });
  server.on("/sensor1", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor1);
  });
  server.on("/sensor2", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor2);
  });
  server.on("/sensor3", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor3);
  });
  server.on("/sensor4", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor4);
  });
  server.on("/sensor5", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor5);
  });
  server.on("/sensor6", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor6);
  });
  server.on("/sensor7", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor7);
  });
  server.on("/sensor8", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor8);
  });
  server.on("/sensor9", HTTP_GET, [](AsyncWebServerRequest *request){
    sensor9[6]++;
    request->send_P(200, "text/plain", sensor9);
  });
  server.on("/sensor10", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor10);
  });
  server.on("/sensor11", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor11);
  });
  server.on("/sensor12", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor12);
  });
  server.on("/sensor13", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor13);
  });
  server.on("/sensor14", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor14);
  });
  server.on("/sensor15", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", sensor15);
  });
  server.begin();
}

void loop() { 
  // Seri ekranden gelen verileri ilgili sensör yerine kaydey
  if(Serial.available()){
    if(Serial.read() == '*'){
      Serial.readBytesUntil('#',buffer,50); 

      int index = charsToInt(buffer,0,1);

      String str = charsToString(buffer,2,50);


      strcpy(senser_ptr[index], str.c_str());

      Serial.print("String: ");
      Serial.println(str);
      Serial.print("senser_ptr: ");
      Serial.println(senser_ptr[index]);

      emptyBuffer(buffer,50);
      Serial.print(buffer);
    }
  }
}

ESP8266 WiFi client,

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#include <WiFiClient.h>

#define DEBUG_MODE true

//Changables
const long timeInterval = 5000;

// Set your network credentials
const char* ssid = "ESP32-Access-Point-1";
const char* password = "3423046avz";

const IPAddress staticIP(192, 168, 4, 1);  // Set your desired static IP address
const IPAddress gateway(192, 168, 4, 1);     // Set your gateway IP address
const IPAddress subnet(255, 255, 255, 0);   
String ipAddressString;

String serverNames[] = {"sensor0","sensor1","sensor2","sensor3","sensor4","sensor5","sensor6","sensor7","sensor8","sensor9","sensor10","sensor11","sensor12","sensor13","sensor14","sensor15"};
String calibrationData;
unsigned long previousMillis = 0;

// Priviate Func Definatiosn
String httpGETRequest(const char* serverName);
int sendCalibrationData();
//int sendCalibrationData(String data);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial1.begin(115200);
  
  WiFi.mode(WIFI_STA);
  WiFi.config(staticIP, gateway, subnet);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");

  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }

  Serial.println("");

  Serial.print("Connected to WiFi network"+ String(ssid) + "with IP Address: ");
  Serial.println(WiFi.localIP());
  IPAddress ipAddress = WiFi.localIP();
  ipAddressString = "http://"+ ipAddress.toString();                                      
  Serial.println(ipAddressString);
}

void loop() {
  unsigned long currentMillis = millis();

  // put your main code here, to run repeatedly:
  if(currentMillis - previousMillis >= timeInterval) {
     // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED ){ 

      sendCalibrationData();

      // save the last HTTP GET Request
      previousMillis = currentMillis;
    }
    else {
      Serial.println("WiFi Disconnected");
    }
  }
}
int sendCalibrationData(){
  for(int j = 0;j<=15;j++){
    String lastDate;
    String deviceID;
    String nextDate;
    int ind1,ind2;
    calibrationData = httpGETRequest((ipAddressString + '/' + serverNames[j]).c_str());

    // Gelen veriyi '/' karakterlerine göre böl
    ind1 = calibrationData.indexOf('/');
    lastDate = calibrationData.substring(0,ind1);

    ind2 = calibrationData.indexOf('/',ind1+1);
    deviceID = calibrationData.substring(ind1+1,ind2);

    nextDate = calibrationData.substring(ind2+1);


    Serial1.println('*'+ ((j<=9 ) ? '0'+ String(j) : String(j)) + '1' + lastDate+'#'); // Megaya göndermek üzere sensör verisini düzenleyip gönder
    delay(500);
    Serial1.println('*'+ ((j<=9 ) ? '0'+ String(j) : String(j)) + '2' + deviceID+'#');
    delay(500);
    Serial1.println('*'+ ((j<=9 ) ? '0'+ String(j) : String(j)) + '3' + nextDate+'#');

#ifdef DEBUG_MODE   
    Serial.printf("lastDate: %s deviceID: %s  nextDate: %s",lastDate,deviceID,nextDate);
#endif
  }
  return 1;
}

String httpGETRequest(const char* serverName) {
  WiFiClient client;
  HTTPClient http;
    
  // Your Domain name with URL path or IP address with path
  http.begin(client, serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "--"; 
  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

Solution

  • OKi ıve found the error. I made both the client and server IP same. This causes error in ESP32 devices but somehow this doesnt give any error in ESP8266. My bad.