NodeMCU + socket.io |
Привет меня зовут Алекс. И я делаю разные классные вещи.
Эта статья — своего рода заметка для себя, чтобы потом было легче вспоминать. Но если вы найдете полные примеры кода — отлично!
Итак, идея очень проста. Я хочу построить небольшую машину с дистанционным управлением через интернет. Итак, я напечатал на 3D-принтере то, что вы видите на картинке, поместил дешевое фото и добавил узел MCU.
Nodemcu будет получать команды перемещения через сокеты. А телефон будет просто автономной вещью с открытым на нем видео-чатом.
Часть 1 — сервер socket.io
Это очень глупо, но поможет вам понять, подключен ли nodeMCU и получает ли он команды 💪
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);
пакет.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"
}
}
Часть 2 — nodeMCU
Будьте осторожны, вам нужно будет установить кучу библиотек в Arduino IDE.
Эскиз -> включить библиотеку -> …
И, возможно, какие-то другие библиотеки: 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();
//
}
Я опубликую несколько видео, когда это, наконец, заработает.
Мне нужно настроить веб-сайт с розетками для управления автомобилем и видеочатом, чтобы видеть, что происходит.