Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Problemas ao conectar o esp32 ao servidor socket do node #703

Discussion options

Alguém poderia me ajudar. Não sei o motivo de estar dando errado, já faz mais de semanas que ando pesquisando. Se alguém puder me ajudar, agradeço de coração. Esse é um requisito para produzir meu TCC. Obrigado

////////////////// Server node /////////////////////////////

const express = require('express');
const http = require('http');
const app = express();
const path = require('path');

const server = http.createServer(app); //cria o servidor socket
const io = require('socket.io')(server);

io.on('connection', socket => {
    console.log('Usuário conectado:[ID]', socket.id); //mostra no servidor quando um usuário se conecta e informa o id dele

    socket.on('sendMessage', data => {
        console.log('Message received: ' + data)
        // socket.broadcast.emit('receivedMessage', data) //Envia a mensagem para todos conectados na aplicação
    });
});

server.listen(5000, () => {         //configuração da porta 
    console.log('Servidor online! porta 5000');
});

////////////// Esp32 code /////////////////////////////////qq

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

#include <ArduinoJson.h>

#include <WebSocketsClient.h>
#include <SocketIOclient.h>

//#include <Hash.h>

const char* ssid     = "Acerte o nome do Ratico";
const char* password = "HichiKko S2";

SocketIOclient socketIO;

void hexdump(const void *mem, uint32_t len, uint8_t cols = 16) {
  const uint8_t* src = (const uint8_t*) mem;
  Serial.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);
  for (uint32_t i = 0; i < len; i++) {
    if (i % cols == 0) {
      Serial.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);
    }
    Serial.printf("%02X ", *src);
    src++;
  }
  Serial.printf("\n");
}

void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
  switch (type) {
    case sIOtype_DISCONNECT:
      Serial.printf("[IOc] Disconnected!\n");
      break;
    case sIOtype_CONNECT:
      Serial.printf("[IOc] Connected to url: %s\n", payload);

      // join default namespace (no auto join in Socket.IO V3)
      socketIO.send(sIOtype_CONNECT, "/");
      break;
    case sIOtype_EVENT:
      Serial.printf("[IOc] get event: %s\n", payload);
      break;
    case sIOtype_ACK:
      Serial.printf("[IOc] get ack: %u\n", length);
      hexdump(payload, length);
      break;
    case sIOtype_ERROR:
      Serial.printf("[IOc] get error: %u\n", length);
      hexdump(payload, length);
      break;
    case sIOtype_BINARY_EVENT:
      Serial.printf("[IOc] get binary: %u\n", length);
      hexdump(payload, length);
      break;
    case sIOtype_BINARY_ACK:
      Serial.printf("[IOc] get binary ack: %u\n", length);
      hexdump(payload, length);
      break;
  }
}

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

  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  delay(5000);

  Serial.setDebugOutput(true);

  Serial.println();
  Serial.println();
  Serial.println();

  // server address, port and URL
  socketIO.begin("192.168.0.101", 5000, "/");

  // event handler
  socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;
void loop() {
  socketIO.loop();
}
You must be logged in to vote

based on google translate, you have some problem but I am not sure what exactly.
can you post logs of the debug output on the ESP?

only think I can see in the code is that your socketIO.begin does not set the protocol version,
which may results in problems.

    socketIO.begin("192.168.0.101", 5000, "/socket.io/?EIO=4");

Replies: 2 comments · 1 reply

Comment options

based on google translate, you have some problem but I am not sure what exactly.
can you post logs of the debug output on the ESP?

only think I can see in the code is that your socketIO.begin does not set the protocol version,
which may results in problems.

    socketIO.begin("192.168.0.101", 5000, "/socket.io/?EIO=4");
You must be logged in to vote
1 reply
@WellingtonSouzaAbreu
Comment options

Ele compila perfeitamente, só não conecta ao servidor.

////// Serial

WiFi connected
IP address: xxx.xxx.x.xxx

[IOc] Disconnected!
[IOc] Disconnected!

Essa biblioteca requer alguma versão específica do node?

Meu arquivo json do servidor:

"scripts": {
"start": "nodemon server.js"
},
"dependencies": {
"ejs": "^3.1.3",
"express": "^4.17.1",
"node-sass-middleware": "^0.11.0",
"nodemon": "^2.0.12",
"socket.io": "^2.3.0",
"socket.io-client": "^2.3.0"
}
}

Answer selected by WellingtonSouzaAbreu
Comment options

Funcionou!

Estava dando desconectado sempre quanto estava usando a versão 4 do socket.io do node, fui testando as versões e quando atualizei a versão do socket.io do node para a 2.3.0 funcionou perfeitamente.

Cara, parabéns pelo trabalho e obrigado pela contribuição, abraços

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
🙏
Q&A
Labels
None yet
2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.