写在前面

此项目是构建一个esp8266客户端,连接远程服务器以ws通信,数据格式是json。

所需arduino库

我使用的是ArduinoWebsockets库,亲测在nodemcu上可以使用。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <ArduinoJson.h>
#include <ArduinoWebsockets.h>
#include <ESP8266WiFi.h>

const char* ssid = " "; //Enter SSID
const char* password = " "; //Enter Password
const char* websockets_server_host = " "; //Enter server adress
const uint16_t websockets_server_port = 8080; // Enter server port

using namespace websockets;

void onMessageCallback(WebsocketsMessage message) {
Serial.print("Got Message: ");
Serial.println(message.data());
// 解析JSON消息
DynamicJsonDocument jsonDoc(256);
DeserializationError error = deserializeJson(jsonDoc, message.data());

if (error) {
Serial.print("JSON parsing failed: ");
Serial.println(error.c_str());
return;
}

// 提取JSON字段值
int messageType = jsonDoc["type"];
String data = jsonDoc["data"];

// 在这里根据消息类型执行相应的操作
switch (messageType) {
case 1000:
Serial.println("Received message type 1000");
// 在这里执行处理消息类型1000的代码
// data 变量包含了密钥信息
break;
case 1001:
Serial.println("Received message type 1001");
break;
default:
Serial.println("Unknown message type");
break;
}

}

void onEventsCallback(WebsocketsEvent event, String data) {
if(event == WebsocketsEvent::ConnectionOpened) {
Serial.println("Connnection Opened");
} else if(event == WebsocketsEvent::ConnectionClosed) {
Serial.println("Connnection Closed");
} else if(event == WebsocketsEvent::GotPing) {
Serial.println("Got a Ping!");
} else if(event == WebsocketsEvent::GotPong) {
Serial.println("Got a Pong!");
}
}

WebsocketsClient client;
void SendJSON(DynamicJsonDocument jsonDoc)
{
String jsonStr;
bool ifsuccess=false;
serializeJson(jsonDoc, jsonStr);
ifsuccess = client.send(jsonStr);
Serial.println(jsonStr);
//Serial.println(ifsuccess);
}
void setup() {
Serial.begin(115200);
// Connect to wifi
WiFi.begin(ssid, password);

// Wait some time to connect to wifi
for(int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) {
Serial.print(".");
delay(1000);
}
Serial.println("WIFI has connected!");
// run callback when messages are received
client.onMessage(onMessageCallback);

// run callback when events are occuring
client.onEvent(onEventsCallback);

// Connect to server
client.connect(websockets_server_host, websockets_server_port, "/");

DynamicJsonDocument jsonDoc(256);
jsonDoc["type"] = 1000;
jsonDoc["data"] = "secretkey";
SendJSON(jsonDoc);

// Send a ping
client.ping();
}

void loop() {
client.poll();
DynamicJsonDocument jsonDoc(256);
jsonDoc["type"] = 1001;
jsonDoc["data"] = "secretkey";
SendJSON(jsonDoc);
delay(10000);
}