ESP32进程开启http和webSocket服务
ESP32进程开启http和webSocket服务意义
在esp32上同时开启http(用来提供html页面),和webSocket(用来接受数据,控制芯片引脚)
代码环境
esp32+Micropython
实现代码
import usocket as socket
import network
import time
import ubinascii
import hashlib
import struct
import _thread
# 连接到Wi-Fi
ssid = 'your_SSID'
password = 'your_PASSWORD'
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while not station.isconnected():
time.sleep(1)
print('Connection successful')
print(station.ifconfig())
# WebSocket服务器
def websocket_server():
addr = socket.getaddrinfo('0.0.0.0', 8080)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('WebSocket Server Listening on', addr)
# WebSocket握手过程
def websocket_handshake(client):
request = client.recv(1024).decode()
headers = request.split('\r\n')
websocket_key = ""
for header in headers:
if 'Sec-WebSocket-Key' in header:
websocket_key = header.split(': ')[1]
break
websocket_accept = ubinascii.b2a_base64(hashlib.sha1(websocket_key.encode() + b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest()).decode().strip()
response = 'HTTP/1.1 101 Switching Protocols\r\n'
response += 'Upgrade: websocket\r\n'
response += 'Connection: Upgrade\r\n'
response += f'Sec-WebSocket-Accept: {websocket_accept}\r\n\r\n'
client.send(response.encode())
# 解码WebSocket掩码消息
def websocket_decode(message):
length = message[1] & 127
if length == 126:
mask = message[4:8]
data = message[8:]
elif length == 127:
mask = message[10:14]
data = message[14:]
else:
mask = message[2:6]
data = message[6:]
decoded = bytearray([data[i] ^ mask[i % 4] for i in range(len(data))])
return decoded
# 处理WebSocket消息
def websocket_handler(client):
while True:
try:
message = client.recv(1024)
if not message:
break
decoded_message = websocket_decode(message)
print('Received message:', decoded_message.decode('utf-8'))
# 在此处添加处理接收到的消息的逻辑
except Exception as e:
print('WebSocket Error:', e)
break
while True:
client, addr = s.accept()
print('WebSocket Client connected from', addr)
websocket_handshake(client)
websocket_handler(client)
client.close()
print('WebSocket Client disconnected')
# HTTP服务器
def http_server():
html = """<!DOCTYPE html>
<html>
<head>
<title>ESP32 HTTP Server</title>
</head>
<body>
<h1>Welcome to ESP32 HTTP Server</h1>
<button onclick="sendMessage()">Send Message</button>
<script>
let socket;
function connect() {
socket = new WebSocket('ws://10.102.2.205:8080');
socket.onopen = function() {
console.log('WebSocket is connected.');
};
socket.onmessage = function(event) {
console.log('Received message: ' + event.data);
};
socket.onclose = function() {
console.log('WebSocket is closed.');
};
socket.onerror = function(error) {
console.log('WebSocket error: ' + error);
};
}
function sendMessage() {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send('Hello ESP32!');
} else {
console.log('WebSocket is not open.');
}
}
window.onload = connect;
</script>
</body>
</html>
"""
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('HTTP Server Listening on', addr)
while True:
client, addr = s.accept()
print('HTTP Client connected from', addr)
request = client.recv(1024)
request = str(request)
print('Content = %s' % request)
response = html
client.send('HTTP/1.1 200 OK\n')
client.send('Content-Type: text/html\n')
client.send('Connection: close\n\n')
client.sendall(response)
client.close()
# 启动WebSocket服务器和HTTP服务器
_thread.start_new_thread(websocket_server, ())
_thread.start_new_thread(http_server, ())
使用方法
esp32与要访问网页的设备在连接同一个wifi下,在浏览器中输入ip(运行起来代码后Thonny会打印出来ip),点击网页的按钮esp32就会收到收到数据,然后就可以开发你想要的功能了。