Codementor Events

NodeMCU + socket.io

Published Sep 26, 2022
NodeMCU + socket.io

Hello, my name is Alex. And I'm making different cool stuff.
This article is just kind of a note for myself, so it was easier to recall stuff later. But if you'll find code examples userfull - great!

So the idea is very simple. I want to build small car with remote control via internet. So I 3d printed what you can see on the picture, placed cheap photo and added nodeMCU.

Nodemcu will receive move commands via sockets. And phone will just be standalone thing with video-chat opened on it.

IMG_5965.JPG

Part 1 - socket.io server

It's very stupid, but it will help you to understand if nodeMCU is connected and it receives commands šŸ’Ŗ

index.js

const httpServer = require("http").createServer();
const io = require("socket.io")(httpServer, {

});
var i = 0;
io.on("connection", (socket) => {

        console.log('connected')
        setInterval(()=>{
                i++;
                io.emit("hello", "world " + i);
        }, 50)

});



httpServer.listen(3000);

package.json

{
  "name": "socket_server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "socket.io": "^4.5.2"
  }
}

Part 2 - nodeMCU

Be carefull, you'll need to install bunch of libraries in arduino IDE.
Sketch -> include library -> ...

Screenshot 2022-09-26 at 16.05.17.png

And maybe some other libraries as well :3


#include <ESP8266WiFi.h>        // Include the Wi-Fi library
#include <ESP8266WiFiMulti.h>
#include <Arduino.h>
#include <ArduinoJson.h>

const char* ssid     = "WIFINAME";         // The SSID (name) of the Wi-Fi network you want to connect 2.4ghz!
const char* password = "your password!";     // The password of the Wi-Fi network

#include <WebSocketsClient.h>
#include <SocketIOclient.h>
#include <Hash.h>
SocketIOclient socketIO;
#define USE_SERIAL Serial

void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
  switch (type) {
    case sIOtype_DISCONNECT:
      USE_SERIAL.printf("[IOc] Disconnected!\n");
      break;
    case sIOtype_CONNECT:
      USE_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:
      USE_SERIAL.printf("[IOc] get event: %s\n", payload);
      break;
    case sIOtype_ACK:
      USE_SERIAL.printf("[IOc] get ack: %u\n", length);
      hexdump(payload, length);
      break;
    case sIOtype_ERROR:
      USE_SERIAL.printf("[IOc] get error: %u\n", length);
      hexdump(payload, length);
      break;
    case sIOtype_BINARY_EVENT:
      USE_SERIAL.printf("[IOc] get binary: %u\n", length);
      hexdump(payload, length);
      break;
    case sIOtype_BINARY_ACK:
      USE_SERIAL.printf("[IOc] get binary ack: %u\n", length);
      hexdump(payload, length);
      break;
  }
}
void setup() {
  Serial.begin(115200);         // Start the Serial communication to send messages to the computer
  delay(10);
  Serial.println('\n');

  WiFi.begin(ssid, password);             // Connect to the network
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print(++i); Serial.print(' ');
  }

  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());         // Send the IP address of the ESP8266 to the computer


  //put your server ip address
   socketIO.begin("xx.xx.xx.xx", 3000, "/socket.io/?EIO=4");

    // event handler
    socketIO.onEvent(socketIOEvent);

}

void loop() { 
    socketIO.loop();
  //
  }

I'll post some videos when it will finally work.
I need to set up website with sockets to control car and video-chat to see what's happening.

Discover and read more posts from Alex Polymath
get started
post comments2Replies
Manan Varma
a year ago

Hi Alex, great work! Can you please share the git repo of the socket.io-client library that you used?
Cheers!

ronit
2 years ago

Hi Alex,
You saved my job. Iā€™m not able to communicate via socketIO in esp32. but then I saw your code and I found out that it was a compatibility issue (EIO=4). Just for testing I was running server code in my host system code from chatgpt and always getting a disconnected issue. But finally got a reference from here.
Thanks a lot for your this post.

Just a curiosity from where you got this reference that you can write EIO=4