nodemcu32s 和 mini D1 组局域网并用 webSocket 通信

实现思路

使用 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);
}

效果

相关推荐
jipinxiaofeihua7 分钟前
(文章8) 05章-C++泛型编程(下)
linux·运维·网络
回眸&啤酒鸭1 小时前
【回眸】AI 大模型驱动 Tessy 单元测试集成效果全景展示
网络·人工智能·单元测试
Milky.Way2 小时前
单片机——基础介绍(CPU内部)
单片机·嵌入式硬件
用户84913717547162 小时前
抄来的 SNMP4J 代码能跑,却把"没回执"记成了"值为 0"——一次 GET 到底该怎么采对?
网络协议
..Dauntless..2 小时前
【stm32】中断(四)——保护与恢复
stm32·单片机·嵌入式硬件
进击的荆棘3 小时前
Linux网络——传输层协议UDP
linux·运维·服务器·网络·udp
知识汲取者4 小时前
HTTP、SSE、WebSocket:三个老技术的区别、场景与选型
websocket·http·ai
创界工坊工作室5 小时前
133-基于Arduino六足爬虫机器人设计
stm32·单片机·嵌入式硬件·机器人·51单片机·proteus
LabVIEW开发5 小时前
SIM928 电压源 + LabVIEW 低温偏置怎么加?
单片机·嵌入式硬件·labview
ShineWinsu6 小时前
对于Qt:TCP的解析
linux·c++·qt·网络协议·面试·tcp·客户端