sparkfun / SparkFun_MLX90614_Arduino_Library

Arduino library for the MLX90614 Infrared Thermometer.
MIT License
34 stars 35 forks source link

Esp32 Wifi Remote Control With Sockets #Locking #8

Closed alobogiron closed 4 years ago

alobogiron commented 5 years ago

Hey guys, I'm here trying to fix a bug that is already happening to me several times, I'm trying to make a connection between two esp's32 for a project, but the only connection that worked is crashing after a few minutes of use ... Could someone help and, if possible, provide links to other types of connections and documentation for them.

Let's go to the error, so I'm using this code: Server:

//Neste arquivo vão os 'includes' e as configurações pincipais
//que são compartilhadas entre os outros arquivos .ino
#include <WiFi.h>

#define SSID "ESP32Server"
#define PASSWORD "87654321"
#define SERVER_PORT 5000
#define PIN_LED 23

//Protocolo que o Server e o Client utilizarão para se comunicar
enum Protocol{
    PIN, //Pino que se deseja alterar o estado
    VALUE, //Estado para qual o pino deve ir (HIGH = 1 ou LOW = 0)
    BUFFER_SIZE //O tamanho do nosso protocolo. IMPORTANTE: deixar sempre como último do enum
};

//Diretiva de compilação que informará qual arquivo que queremos que seja compilado
//Caso queira que o arquivo Client.ino seja compilado, remova ou comente a linha do '#define' abaixo
//Caso queira que o arquivo Server.ino seja compilado, deixe o '#define IS_SERVER' abaixo descomentado
#define IS_SERVER

//Apenas vai compilar o código contido neste arquivo
//caso IS_SERVER esteja definido
#ifdef IS_SERVER

//Cria o server na porta definida por 'SERVER_PORT'
WiFiServer server(SERVER_PORT);

void setup()
{
    Serial.begin(115200);//Inicializa Serial
    pinMode(PIN_LED, OUTPUT);
    //Coloca este ESP como Access Point
    WiFi.mode(WIFI_AP);
    //SSID e Senha para se conectarem a este ESP
    WiFi.softAP(SSID, PASSWORD);
    //Inicia o server
    server.begin();
}
void loop()
{
    //Verifica se tem algum cliente se conectando
    WiFiClient client = server.available();
    if (client) 
    { 
        //Acende led sinalizando a entrada de um cliente
        digitalWrite(PIN_LED, 1);    
        //Se o cliente tem dados que deseja nos enviar
        if (client.available())
        {
            //Criamos um buffer para colocar os dados 
            uint8_t buffer[Protocol::BUFFER_SIZE];
            //Colocamos os dados enviados pelo cliente no buffer
            int len = client.read(buffer, Protocol::BUFFER_SIZE);
            //Printa o valor
            Serial.print("Size Buffer");
            Serial.println(len);
            //Verificamos qual o pino que o cliente enviou
            int pinNumber = buffer[Protocol::PIN];
            Serial.print("PIN ");
            Serial.println(buffer[Protocol::PIN]);
            //Verificamos qual o valor deste pino
            int value = buffer[Protocol::VALUE];
            Serial.print("VALUE ");
            Serial.println(buffer[Protocol::VALUE]);
            //Colocamos o pino em modo de saída
            pinMode(pinNumber, OUTPUT);
            //Alteramos o estado do pino para o valor passado
            digitalWrite(pinNumber, value);
        }

        //Fecha a conexão com o cliente
        client.stop();
    }
}
//Encerra o #ifdef do começo do arquivo
#endif

Client:

//Neste arquivo vão os 'includes' e as configurações pincipais
//que são compartilhadas entre os outros arquivos .ino
#include <WiFi.h>

#define SSID "ESP32Server"
#define PASSWORD "87654321"
#define SERVER_PORT 5000

//Protocolo que o Server e o Client utilizarão para se comunicar
enum Protocol{
    PIN, //Pino que se deseja alterar o estado
    VALUE, //Estado para qual o pino deve ir (HIGH = 1 ou LOW = 0)
    BUFFER_SIZE //O tamanho do nosso protocolo. IMPORTANTE: deixar sempre como último do enum
};

//Diretiva de compilação que informará qual arquivo que queremos que seja compilado
//Caso queira que o arquivo Client.ino seja compilado, remova ou comente a linha do '#define' abaixo
//Caso queira que o arquivo Server.ino seja compilado, deixe o '#define IS_SERVER' abaixo descomentado
//Apenas vai compilar o código contido neste arquivo
//caso IS_SERVER NÃO esteja definido 
//(if n def, atenção para o 'n')
#ifndef IS_SERVER
//Pino que vamos fazer a leitura
#define IN_PIN 23
#define ChangedPIN 2

void setup(){
    Serial.begin(115200);//Inicializa Serial
    //Colocamos o pino em modo de leitura
    pinMode(IN_PIN, INPUT);
    pinMode(ChangedPIN, OUTPUT);
    //Defino como modo estação ()Client
    WiFi.mode(WIFI_STA);
    //Conectamos Access Point criado
    //pelo outro ESP
    WiFi.begin(SSID, PASSWORD);

    //Esperamos conectar
    while (WiFi.status() != WL_CONNECTED){
        delay(500);
    }
}

void loop(){
    //Variável que utlizaremos para conectar ao servidor
    WiFiClient client;
    //Se não conseguiu se conectar então retornamos
    if (!client.connect(WiFi.gatewayIP(), SERVER_PORT)){
        return;
    }
    //Acende Led
    digitalWrite(ChangedPIN, 1);
    //Criamos um buffer para colocar os dados 
    uint8_t buffer[Protocol::BUFFER_SIZE];
    //Fazemos a leitura do pino
    int value = digitalRead(IN_PIN);
    Serial.println(digitalRead(IN_PIN));
    //Colocamos no buffer o número do pino
    //cujo estado queremos enviar
    buffer[Protocol::PIN] = ChangedPIN;
    //Colocamos no buffer o estado atual do pino
    buffer[Protocol::VALUE] = value;
    //Enviamos e finalizamos a conexão
    client.write(buffer, Protocol::BUFFER_SIZE);
    client.flush();
    client.stop();

}
//Encerra o #ifndef do começo do arquivo
#endif

What I got from this site:

The problem is that after a few minutes the connection is stuck, I realized that being a socket connection rather than HTTP, it closes and opens the connection to the Server several times; Is this what is causing the failures? I used a delay at the end, but it was no use. I really need help.

Blink leds to show the connection start, sorry if you are wrong.

SFEMark commented 4 years ago

Hi anonytario,

Sorry for the late response here but as this issue is not specifically related to the MLX90614 Arduino Library this is not the correct place to post issues with your ESP32 Project. If you are using SparkFun products, you may want to post on the SparkFun Forums. Otherwise, for help with ESP32-specific things, the ESP32 Forum would be the best place for that.

I'm going to go ahead and close this issue.