实现思路
使用 mini D1
来搭建一个 webSocket
服务,然后使用 nodemcu32
连接,然后就可以进行通信了。
服务端代码(mini D1)
在代码中主要是需要控制好 loop 函数中的延时,也就是最后一行代码 delay
,如果太快了板子处理不过来反而会导致实时性很差。设置到 50
到 100
就差不多。
#include <WiFiClient.h>
#include <WebSocketsServer.h>
#include <Arduino_JSON.h>
// socket 服务
WebSocketsServer webSocket = WebSocketsServer(81);
#define USE_SERIAL Serial
// 收到消息后的处理函数
void msg_cb(uint8_t* payload) {
// 解析字符串 json
JSONVar infosObj = JSON.parse((char*)payload); // 将 payload 转换为 char*
if (JSON.typeof(infosObj) == "undefined") {
return;
}
if (infosObj.hasOwnProperty("dj_deg")) {
Serial.println((int)infosObj["dj_deg"]);
}
}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) {
switch (type) {
case WStype_DISCONNECTED:
USE_SERIAL.printf("[%u] Disconnected!\n", num);
break;
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
// send message to client
webSocket.sendTXT(num, "Connected");
}
break;
case WStype_TEXT:
msg_cb(payload);
// send message to client
// webSocket.sendTXT(num, "message here");
// send data to all connected clients
// webSocket.broadcastTXT("message here");
break;
case WStype_BIN:
USE_SERIAL.printf("[%u] get binary length: %u\n", num, length);
hexdump(payload, length);
// send message to client
// webSocket.sendBIN(num, payload, length);
break;
}
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_AP); // 将WiFi模式设为AP
WiFi.softAP("xmio", "12345678"); // 开启热点
Serial.println("");
IPAddress ip = WiFi.softAPIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
String httpUrl = "http://" + ipStr;
Serial.println("AP IP:");
Serial.println(ipStr);
// 开启 scoket 服务
webSocket.begin();
webSocket.onEvent(webSocketEvent);
}
void loop() {
webSocket.loop();
delay(50);
}
客户端代码(nodemcu32s )
和服务端一样,这里的 loop
中也能太快, 50ms
就差不多。要想服务端处理得更快的话其实不使用 json
插件最好。
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#include <WebSocketsClient.h>
#include <Wire.h>
#include <Arduino_JSON.h>
WiFiMulti wifiMulti;
WebSocketsClient webSocket;
#define USE_SERIAL Serial
const String wifi_name = "xmio";
const String wifi_pwd = "12345678";
String wifi_ip = ""; // wifi ip
String ws_connected = "0"; // 已连接 "1"
void hexdump(const void* mem, uint32_t len, uint8_t cols = 16) {
const uint8_t* src = (const uint8_t*)mem;
USE_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) {
USE_SERIAL.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);
}
USE_SERIAL.printf("%02X ", *src);
src++;
}
USE_SERIAL.printf("\n");
}
// socket 监听服务
void webSocketEvent(WStype_t type, uint8_t* payload, size_t length) {
switch (type) {
case WStype_DISCONNECTED:
USE_SERIAL.printf("[WSc] Disconnected!\n");
ws_connected = "0";
break;
case WStype_CONNECTED:
USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
ws_connected = "1";
// send message to server when Connected
// webSocket.sendTXT("hello");
break;
case WStype_TEXT:
USE_SERIAL.printf("[WSc] get text: %s\n", payload);
// send message to server
// webSocket.sendTXT("message here");
break;
case WStype_BIN:
USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
hexdump(payload, length);
// send data to server
// webSocket.sendBIN(payload, length);
break;
case WStype_ERROR:
case WStype_FRAGMENT_TEXT_START:
case WStype_FRAGMENT_BIN_START:
case WStype_FRAGMENT:
case WStype_FRAGMENT_FIN:
break;
}
}
void setup() {
wifiMulti.addAP(wifi_name.c_str(), wifi_pwd.c_str());
while (wifiMulti.run() != WL_CONNECTED) {
// 小车连接中...
Serial.println("wifi connect ing...");
delay(1000);
}
String ipAddress = WiFi.gatewayIP().toString();
wifi_ip = ipAddress;
Serial.println("wifi connected:");
Serial.println(wifi_ip);
webSocket.begin(wifi_ip, 81, "/");
webSocket.onEvent(webSocketEvent);
webSocket.setReconnectInterval(5000);
}
void loop(){
if (ws_connected == "1") {
// 发送一个字符串json
JSONVar infos;
infos["dj_deg"] = dj_deg;
String jsonString = JSON.stringify(infos);
webSocket.sendTXT(jsonString);
}
delay(50);
}