You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript向ESP32接入点发送消息?

实现ESP32 AP与Orange Pi网站的JS消息交互

核心思路

ESP32在AP模式下运行WebSocket服务器,Orange Pi上的网页通过JavaScript的WebSocket API与ESP32建立连接,实现双向消息交互。如果需要用户设备不直接连接ESP32 AP,可通过Orange Pi做消息转发。


第一步:ESP32端配置WebSocket服务器

用Arduino框架的WebSocketsServer库实现AP模式下的WebSocket服务:

#include <WiFi.h>
#include <WebSocketsServer.h>

// 你的ESP32 AP配置
const char* AP_SSID = "ESP32-AP";
const char* AP_PASS = "your-ap-password";
WebSocketsServer webSocket = WebSocketsServer(81);

void handleWebSocketEvent(uint8_t clientNum, WStype_t type, uint8_t* payload, size_t length) {
  switch(type) {
    case WStype_CONNECTED:
      Serial.printf("Client [%u] connected from %s\n", clientNum, webSocket.remoteIP(clientNum).toString().c_str());
      webSocket.sendTXT(clientNum, "Connected to ESP32");
      break;
    case WStype_TEXT:
      Serial.printf("Received from client [%u]: %s\n", clientNum, payload);
      // 回复消息
      webSocket.sendTXT(clientNum, String("ESP32 echo: ") + (char*)payload);
      break;
    case WStype_DISCONNECTED:
      Serial.printf("Client [%u] disconnected\n", clientNum);
      break;
    default:
      break;
  }
}

void setup() {
  Serial.begin(115200);
  // 启动AP模式
  WiFi.softAP(AP_SSID, AP_PASS);
  Serial.print("ESP32 AP IP: ");
  Serial.println(WiFi.softAPIP());
  // 初始化WebSocket服务器
  webSocket.begin();
  webSocket.onEvent(handleWebSocketEvent);
}

void loop() {
  webSocket.loop();
}

第二步:Orange Pi上的网页实现

场景1:用户设备直接连接ESP32 AP

网页运行在Orange Pi上,用户访问网页后手动连接ESP32的AP,再通过JS连接ESP32的WebSocket:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>ESP32 Message Hub</title>
</head>
<body>
    <div>
        <label>ESP32 AP SSID: </label>
        <input type="text" id="ssid" value="ESP32-AP">
    </div>
    <div>
        <label>AP密码: </label>
        <input type="password" id="pass" value="your-ap-password">
    </div>
    <button onclick="initConnection()">连接ESP32</button>

    <div style="margin-top: 20px;">
        <input type="text" id="msgInput" placeholder="输入消息...">
        <button onclick="sendMsg()">发送</button>
    </div>

    <div id="log" style="margin-top:20px; border:1px solid #ddd; padding:10px; height:300px; overflow-y:auto;"></div>

    <script>
        let wsConn;

        function initConnection() {
            // ESP32 AP默认IP是192.168.4.1,若修改过请对应调整
            const esp32IP = "192.168.4.1";
            wsConn = new WebSocket(`ws://${esp32IP}:81`);

            wsConn.onopen = () => addLog("已连接到ESP32");
            wsConn.onmessage = (e) => addLog(`ESP32: ${e.data}`);
            wsConn.onerror = (err) => addLog(`连接错误: ${err.message}`);
            wsConn.onclose = () => addLog("与ESP32断开连接");
        }

        function sendMsg() {
            const msg = document.getElementById("msgInput").value.trim();
            if (!msg || !wsConn || wsConn.readyState !== WebSocket.OPEN) return;
            
            wsConn.send(msg);
            addLog(`你: ${msg}`);
            document.getElementById("msgInput").value = "";
        }

        function addLog(text) {
            const logDiv = document.getElementById("log");
            logDiv.innerHTML += `<div>${text}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }
    </script>
</body>
</html>

场景2:Orange Pi作为消息转发节点(用户设备连Orange Pi所在网络)

如果不想让用户设备直接连ESP32 AP,可在Orange Pi上用Node.js搭建WebSocket转发服务:

  1. 安装依赖:
sudo apt install nodejs npm
npm install ws
  1. 转发服务代码(命名为ws-relay.js):
const WebSocket = require('ws');

// 连接ESP32的WebSocket
const esp32Client = new WebSocket('ws://192.168.4.1:81');
// 启动Orange Pi上的WebSocket服务,监听8080端口
const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (client) => {
    console.log('新客户端连接');
    // 转发客户端消息到ESP32
    client.on('message', (data) => {
        if (esp32Client.readyState === WebSocket.OPEN) esp32Client.send(data);
    });
    // 转发ESP32消息到客户端
    esp32Client.on('message', (data) => client.send(data));
    client.on('close', () => console.log('客户端断开'));
});

esp32Client.on('open', () => console.log('已连接ESP32'));
esp32Client.on('error', (err) => console.error('ESP32连接失败:', err));
  1. 启动服务:
node ws-relay.js
  1. 修改前端JS的连接地址为Orange Pi的IP:
wsConn = new WebSocket(`ws://<你的Orange Pi IP>:8080`);

关键注意事项

  • ESP32 AP默认IP为192.168.4.1,若修改过AP配置需同步调整代码中的IP。
  • 浏览器JS无法直接控制设备连接WiFi,场景1需要用户手动连接ESP32的AP后再操作网页。
  • 确保Orange Pi和ESP32之间的网络连通,端口81(ESP32)和8080(Orange Pi转发服务)未被防火墙拦截。

内容的提问来源于stack exchange,提问作者Toni Ivanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:01:14