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

实现思路

使用 mini D1 来搭建一个 webSocket 服务,然后使用 nodemcu32 连接,然后就可以进行通信了。

服务端代码(mini D1)

在代码中主要是需要控制好 loop 函数中的延时,也就是最后一行代码 delay,如果太快了板子处理不过来反而会导致实时性很差。设置到 50100 就差不多。

#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);
}

效果

相关推荐
qq_51583806 彩雷王36 分钟前
1004-05,使用workflow对象创建http任务,redis任务
redis·网络协议·http
车载诊断技术1 小时前
什么是汽车中的SDK?
网络·架构·汽车·soa·电子电器架构
一颗星星辰1 小时前
Python | 第九章 | 排序和查找
服务器·网络·python
ZachOn1y1 小时前
计算机网络:计算机网络概述:网络、互联网与因特网的区别
网络·计算机网络·知识点汇总·考研必备
jmlinux1 小时前
环形缓冲区(Ring Buffer)在STM32 HAL库中的应用:防止按键丢失
c语言·stm32·单片机·嵌入式硬件
GOTXX2 小时前
应用层协议HTTP
linux·网络·网络协议·计算机网络·http·fiddler
江山如画,佳人北望2 小时前
智能平衡移动机器人-平台硬件电路
单片机·嵌入式硬件
江将好...3 小时前
定时器实验(Proteus 与Keil uVision联合仿真)
单片机·嵌入式硬件
地球空间-技术小鱼3 小时前
嵌入式系统学习
嵌入式硬件·学习
物随心转3 小时前
中断系统的原理
单片机·嵌入式硬件