写在前面
此项目是构建一个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 = " " ; const char * password = " " ; const char * websockets_server_host = " " ; const uint16_t websockets_server_port = 8080 ; using namespace websockets; void onMessageCallback (WebsocketsMessage message) { Serial.print("Got Message: " ); Serial.println(message.data()); DynamicJsonDocument jsonDoc (256 ) ; DeserializationError error = deserializeJson(jsonDoc, message.data()); if (error) { Serial.print("JSON parsing failed: " ); Serial.println(error.c_str()); return ; } int messageType = jsonDoc["type" ]; String data = jsonDoc["data" ]; switch (messageType) { case 1000 : Serial.println("Received message type 1000" ); 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); } void setup () { Serial.begin(115200 ); WiFi.begin(ssid, password); for (int i = 0 ; i < 10 && WiFi.status() != WL_CONNECTED; i++) { Serial.print("." ); delay(1000 ); } Serial.println("WIFI has connected!" ); client.onMessage(onMessageCallback); client.onEvent(onEventsCallback); client.connect(websockets_server_host, websockets_server_port, "/" ); DynamicJsonDocument jsonDoc (256 ) ; jsonDoc["type" ] = 1000 ; jsonDoc["data" ] = "secretkey" ; SendJSON(jsonDoc); client.ping(); } void loop () { client.poll(); DynamicJsonDocument jsonDoc (256 ) ; jsonDoc["type" ] = 1001 ; jsonDoc["data" ] = "secretkey" ; SendJSON(jsonDoc); delay(10000 ); }