├── .DS_Store ├── CombinedServer.ino ├── CombinedServerStressTest.ino ├── LICENSE ├── README.md ├── README_CN.md ├── WebSocketClient.ino ├── mycrypto ├── README.md ├── mycrypto.cpp └── mycrypto.h └── mywebsocket ├── mywebsocket.cpp └── mywebsocket.h /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vidalouiswang/Arduino_ESP32_Websocket/bb4122714d6dacdee6bb53717b70ac56f9d53842/.DS_Store -------------------------------------------------------------------------------- /CombinedServer.ino: -------------------------------------------------------------------------------- 1 | // Inlcude header files 2 | // 引入头文件 3 | #include // This line is optional if you are using Arduino IDE. 如果你使用Arduino IDE这行可以删掉。 4 | #include "mywebsocket/mywebsocket.h" 5 | #include 6 | 7 | // Declare and initialize instance 8 | // 声明和实例化 9 | myWebSocket::CombinedServer server; 10 | 11 | // Define IP and mask for AP mode 12 | // 定义AP模式IP和子网掩码 13 | IPAddress APIP = IPAddress(192, 168, 8, 1); 14 | IPAddress subnet = IPAddress(255, 255, 255, 0); 15 | 16 | void setup() 17 | { 18 | // Initialize serial port(for debug) 19 | // 初始化串口(测试使用) 20 | Serial.begin(115200); 21 | 22 | 23 | // Uncomment following part and input your SSID and password if you want to use in STA mode 24 | // 如果你在STA模式使用,取消下面这部分注释,填写你的SSID和密码 25 | 26 | // WiFi.begin("yourSSID", "Your password"); 27 | // while (WiFi.status() != WL_CONNECTED) 28 | // { 29 | // yield(); 30 | // delay(100); 31 | // yield(); 32 | // } 33 | 34 | 35 | // Call this to enable ESP32 hardware acceleration 36 | // 启用ESP32的硬件加速(SHA) 37 | mycrypto::SHA::initialize(); 38 | 39 | 40 | // For AP mode 41 | // Comment the following part if you'd like to use STA mode 42 | // AP模式 43 | // 注释掉下面这部分代码如果你使用STA模式 44 | WiFi.softAP("ESP32_WebSocketServer"); 45 | delay(300); 46 | WiFi.softAPConfig(APIP, APIP, subnet); 47 | 48 | 49 | // Set websocket connection callback(use Lambda function here, you could use normal function if you want to) 50 | // 设置websocket客户端的回调函数(此处使用Lambda函数,你也可以使用普通函数) 51 | server.setCallback( 52 | [](myWebSocket::WebSocketClient *client, myWebSocket::WebSocketEvents type, uint8_t *payload, uint64_t length) 53 | { 54 | if (length) 55 | { 56 | if (type == myWebSocket::TYPE_TEXT) 57 | { 58 | Serial.println("Got text data:"); 59 | Serial.println(String((char *)payload)); 60 | client->send(String("Hello from ESP32 WebSocket: ") + String(ESP.getFreeHeap())); 61 | } 62 | else if (type == myWebSocket::TYPE_BIN) 63 | { 64 | Serial.println("Got binary data, length: " + String((long)length)); 65 | Serial.println("First byte: " + String(payload[0])); 66 | Serial.println("Last byte: " + String(payload[length - 1])); 67 | } 68 | } 69 | }); 70 | 71 | // Set http callback(for debug) 72 | // 设置默认的HTTP回调函数(测试使用) 73 | server.on( 74 | "/", 75 | [](myWebSocket::ExtendedWiFiClient *client, myWebSocket::HttpMethod method, uint8_t *data, uint64_t len) 76 | { 77 | client->send(R"( 78 | 79 | 80 | ESP32 Combined Server 81 | 82 | 83 |

Hello World!

84 | 85 |
86 | 135 | 136 | )"); 137 | client->close(); 138 | }); 139 | 140 | // Start server 141 | // 启动服务器 142 | server.begin(80); 143 | } 144 | 145 | void loop() 146 | { 147 | // Loop server to accept websocket client and handle http resquest 148 | // 循环服务器来接受websocket客户端和处理http请求 149 | server.loop(); 150 | } 151 | -------------------------------------------------------------------------------- /CombinedServerStressTest.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mywebsocket/mywebsocket.h" 3 | #include 4 | 5 | myWebSocket::CombinedServer server; 6 | 7 | IPAddress APIP = IPAddress(192, 168, 8, 1); 8 | IPAddress subnet = IPAddress(255, 255, 255, 0); 9 | 10 | String globalHash = ""; 11 | 12 | #define MAX_DATA_LENGtH 8192 13 | 14 | void sendData(myWebSocket::WebSocketClient *client) 15 | { 16 | uint16_t length = random(1, MAX_DATA_LENGtH); 17 | uint8_t binaryOrText = random(10); 18 | uint8_t t = 0; 19 | uint8_t *data = new uint8_t[length]; 20 | if (binaryOrText > 5) 21 | { 22 | data[length - 1] = 0; 23 | length -= 1; 24 | // send text 25 | for (int i = 0; i < length; i++) 26 | { 27 | while (t < 32) 28 | { 29 | t = random(32, 127); 30 | } 31 | data[i] = t; 32 | t = 0; 33 | } 34 | String *a = new String((char *)data); 35 | delete data; 36 | globalHash = mycrypto::SHA::sha256(a); 37 | client->send(a); 38 | delete a; 39 | } 40 | else 41 | { 42 | // send binary 43 | for (int i = 0; i < length; i++) 44 | { 45 | data[i] = random(0, 255); 46 | } 47 | globalHash = mycrypto::SHA::sha256(data, length); 48 | client->send(data, length); 49 | delete data; 50 | } 51 | } 52 | 53 | void setup() 54 | { 55 | Serial.begin(115200); 56 | // WiFi.begin("yourSSID", "Your password"); 57 | // while (WiFi.status() != WL_CONNECTED) 58 | // { 59 | // yield(); 60 | // delay(100); 61 | // yield(); 62 | // } 63 | 64 | // call this to enable ESP32 hardware acceleration 65 | mycrypto::SHA::initialize(); 66 | 67 | WiFi.softAP("ESP32_WebSocketServer"); 68 | delay(300); 69 | WiFi.softAPConfig(APIP, APIP, subnet); 70 | server.setCallback( 71 | [](myWebSocket::WebSocketClient *client, myWebSocket::WebSocketEvents type, uint8_t *payload, uint64_t length) 72 | { 73 | if (length) 74 | { 75 | if (type == myWebSocket::TYPE_TEXT) 76 | { 77 | if (globalHash == "") 78 | { 79 | Serial.println("Got text"); 80 | String *a = new String((char *)payload); 81 | delete payload; 82 | client->setRecvBufferDeleted(); 83 | String hash = mycrypto::SHA::sha256(a); 84 | delete a; 85 | client->send(hash); 86 | sendData(client); 87 | } 88 | else 89 | { 90 | String remoteHash = String((char *)payload); 91 | if (remoteHash == globalHash) 92 | { 93 | Serial.println("OK"); 94 | } 95 | else 96 | { 97 | Serial.println("failed"); 98 | } 99 | globalHash = ""; 100 | } 101 | } 102 | else if (type == myWebSocket::TYPE_BIN) 103 | { 104 | Serial.println("Got binary"); 105 | String hash = mycrypto::SHA::sha256(payload, length); 106 | client->send(hash); 107 | sendData(client); 108 | } 109 | } 110 | }); 111 | 112 | server.on( 113 | "/", 114 | [](myWebSocket::ExtendedWiFiClient *client, myWebSocket::HttpMethod method, uint8_t *data, uint64_t len) 115 | { 116 | client->send(R"( 117 | 118 | 119 | 120 | ESP32 Combined Server 121 | 122 | 123 | 124 |

Hello World!

125 | 126 |
127 | 250 | 358 | 359 | 360 | )"); 361 | client->close(); 362 | }); 363 | server.begin(80); 364 | 365 | Serial.println("Connect to AP, and open \"192.168.8.1\""); 366 | } 367 | 368 | void loop() 369 | { 370 | server.loop(); 371 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Arduino ESP32 Websocket 2 | 3 | Lastest code refer to https://github.com/vidalouiswang/Abc/ 4 | 5 | [中文(有中英双语注释)](https://github.com/vidalouiswang/Arduino_ESP32_Websocket/blob/main/README_CN.md) 6 | 7 | This lib work with Espressif offical framework esp32-arduino. 8 | Only had tested on esp32 dev module. I'm not sure it support ESP8266 or not. 9 | In my opinion, ESP32-WROOM-32(module) and ESP8266-12F(module) have almost same price but ESP32 is much powerful. 10 | 11 | Before I made this lib, I had used another two libs you could find on github(most stars) for days, they both did very good job. 12 | 13 | But connecting speed of the first one it will take 1700 ~ 1900 ms(handshake), it should be 90 ~ 110 ms(test at same time to same server). 14 | 15 | Another one has memory leak when act a server(I try to fix it but couldn't find reason). 16 | 17 | This lib doesn't support wss://. Because I think use AES(or other encryption) to encrypt data before send it is much better(of course you need both user have same key), that depends on your design. 18 | 19 | 2022/05/23 Add more comments to default example. 20 | 21 | 2022/07/05 Bug fixed. 22 | 23 | 2022/07/11 Latest push add AES 256 CBC code, but this isn't necessary for websocket, you could remove it if you want to. 24 | 25 | 2022/07/31 Add standard full comments(English version and Chinese version) to header file["mywebsocket.h"](https://github.com/vidalouiswang/Arduino_ESP32_Websocket/blob/main/mywebsocket/mywebsocket.h); The class "WebSocketClients" had been removed. 26 | 27 | # Characteristic of this this project 28 | 29 | ### High speed 30 | Connecting and data transfering. 31 | 32 | Same connect speed as a browser "new Websocket()" client in Chrome(to my remote server, it is 98ms). 33 | 34 | ### Easy to use 35 | You could start from the examples. 36 | 37 | ### No memory leak 38 | Client and server had been fully tested for days, send and receive large data(16 KB text and binary, random data and length every time, use sha256 to verify data), echo to each other. 39 | 40 | ### Easily handle http request and websocket request when act a server 41 | One line code to start a server to handle http and websocket requests. 42 | 43 | ### Stable 44 | Easily transfer 64KB binary data in AP and STA mode with very low time time consumption and zero error(complex code environment, test more than 10000 times, use sha256 to verify data). 45 | 46 | ### Note 47 | When you test the client, every time after connection lost and reconnected again, you will find heap memory will reduce a little bit, that's not a memory leak, for deeper reason, you should search "lwip memory leak" in google. 48 | 49 | For more configs, look into ["mywebsocket.h"](https://github.com/vidalouiswang/Arduino_ESP32_Websocket/blob/main/mywebsocket/mywebsocket.h). 50 | 51 | The default cache size is large, because heap of ESP32 is huge, you could reduce a little bit if you want. 52 | 53 | # License 54 | (GNU General Public License v3.0 License) 55 | 56 | Copyright 2022, Vida Wang 57 | 58 | 59 | Children are the future of mankind, but there are still many children who are enduring hunger all over the world at this moment. If you are a good person and you like this lib, please donate to UNICEF. 60 | https://unicef.org 61 | -------------------------------------------------------------------------------- /README_CN.md: -------------------------------------------------------------------------------- 1 | # Arduino ESP32 Websocket 2 | 3 | 最新代码请转到 https://github.com/vidalouiswang/Abc/ 4 | 5 | 这个库是基于Espressif arduino-esp32 构建的. 6 | 只在ESP32完成了测试,我不确定是否支持ESP8266。 7 | 因为我觉得ESP32-WROOM-32模组和ESP8266-12F模组价格差不多,没有理由再使用ESP8266。 8 | 9 | 我写这个库之前也用过两个Github上star最多的两个库,那两个也不错。 10 | 11 | 但是第一个库连接速度太慢,握手过程需要大概 1700 ~ 1900毫秒,而正常情况下只需要90 ~ 110毫秒,在大约同样的时间连接同样的服务器。 12 | 13 | 第二个库使用websocket服务器的时候有内存泄漏,我尝试修复他那个bug但是没有找到怎么修复。 14 | 15 | 这个库不支持wss服务器和客户端,因为我觉得发数据之前先用AES加密数据安全性更高,https也不是绝对安全的,但是AES-CBC-256目前是绝对安全的,当然,你得有同样的解密密匙,这个就取决于你的设计了。 16 | 17 | ### 头文件中有全部的标准的中英双语注释(cpp文件的注释后面会补充) 18 | 19 | 2022/05/23 默认例子里补了点中文注释。 20 | 21 | 2022/07/05 修复了bug。 22 | 23 | 2022/07/11 最新的提交更新了直接使用AES的代码,但是这个对于websocket不是必须的,你不想要可以删除这部分代码。 24 | 25 | 2022/07/31 为头文件["mywebsocket.h"](https://github.com/vidalouiswang/Arduino_ESP32_Websocket/blob/main/mywebsocket/mywebsocket.h) 补充了全部的标准的中英双语注释;类"WebSocketClients"已被移除。 26 | 27 | # 这个项目的特点 28 | 29 | ### 快速 30 | 连接和数据传输速度都很快。 31 | 32 | 连接(握手)速度和Chrome websocket客户端一样,到我的服务器需要98ms。 33 | 34 | ### 使用简单 35 | 看一眼例子10秒钟就会用了。 36 | 37 | ### 没有内存泄漏 38 | 客户端和服务器都经过了数天的高强度测试,数据规模是单次16KB,二进制和文本都分别进行了测试,每次测试使用随机函数生成随机长度的字节数组或字符串,使用sha256对传输的数据完整性进行校验,服务器和客户端互相发送数据互相校验。 39 | 40 | ### 非常简单就可以创建一个服务器同时处理HTTP请求和Websocket请求 41 | 一行代码就可以创建一个同时处理两种请求的服务器,非常简单,非常适合新手。 42 | 43 | ### 稳定 44 | AP模式和STA模式都可以轻松的传输64KB的二进制数据,处理速度很快,测试过程放在了一个比较复杂的项目中,测试了一万多次,数据都使用sha256校验,没有任何错误。一般情况下堆内存会剩余大概280KB,所以我觉得一次性传输128KB都没问题,当然这个取决于你的堆内存剩余。 45 | 46 | ### 注意事项 47 | 使用客户端的时候,你可以尝试制造断开连接,比如让服务器下线,重复多次后你会发现每次堆内存都会少一点,大概100字节,超过10次以上这个数据就不会减少了,这个不是内存泄漏,有关这个问题你可以取google搜索"lwip memory leak",有个帖子里面讲了这个问题的原因。 48 | 49 | 其他的配置你可以在头文件["mywebsocket.h"](https://github.com/vidalouiswang/Arduino_ESP32_Websocket/blob/main/mywebsocket/mywebsocket.h)中找到。 50 | 缓存定义的都比较大,因为ESP32堆内存实在是很大,如果你觉得太大你可以自己调小一点。 51 | 52 | # 协议 53 | (GNU General Public License v3.0 License) 54 | 55 | Copyright 2022, Vida Wang 56 | 57 | 58 | 孩子是人类的未来,但是现在全世界仍然有许多孩子饱受饥饿,如果你是个善良的人、认可我的代码,请捐助联合国儿童基金会,谢谢。 59 | https://unicef.cn 60 | -------------------------------------------------------------------------------- /WebSocketClient.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mywebsocket/mywebsocket.h" 3 | #include 4 | 5 | myWebSocket::WebSocketClient client; 6 | 7 | u32_t t = 0; 8 | 9 | void setup() 10 | { 11 | //call this to enable ESP32 hardware acceleration 12 | mycrypto::SHA::initialize(); 13 | 14 | Serial.begin(115200); 15 | WiFi.begin("SSID", "password"); 16 | while (WiFi.status() != WL_CONNECTED) 17 | { 18 | yield(); 19 | delay(100); 20 | yield(); 21 | } 22 | 23 | Serial.println("WiFi connected."); 24 | 25 | client.setCallBack( 26 | [](myWebSocket::WebSocketEvents type, uint8_t *payload, uint64_t length) 27 | { 28 | if (type == myWebSocket::WS_CONNECTED) 29 | { 30 | 31 | Serial.println("Websocket connected. Time: " + String(millis() - t)); 32 | Serial.println("long msg will be send to server in 1000 ms."); 33 | yield(); 34 | delay(1000); 35 | yield(); 36 | String *b = new String(""); 37 | for (int i = 0; i < 8192; i++) 38 | { 39 | yield(); 40 | b->concat((char)random(96, 127)); 41 | yield(); 42 | } 43 | client.send(b); 44 | Serial.println(*b); 45 | delete b; 46 | } 47 | else if (type == myWebSocket::WS_DISCONNECTED) 48 | { 49 | Serial.println("Websocket disconnected."); 50 | } 51 | else if (type == myWebSocket::TYPE_TEXT) 52 | { 53 | Serial.println("Got text: " + String((char *)payload)); 54 | } 55 | else if (type == myWebSocket::TYPE_BIN) 56 | { 57 | Serial.println("Got binary, length:" + String((long)length)); 58 | /* 59 | if you'd like to malloc or new a heap space to send data 60 | but current heap isn't big enough for that 61 | you could do this: 62 | 63 | delete payload; 64 | client.setRecvBufferDeleted(); 65 | 66 | that will clear received buffer immediately 67 | 68 | actually, this process could use transfer **payload to instead 69 | but that may confused new hand 70 | so class use a bool and a function to did this 71 | 72 | note: 73 | no recommended to use this method, unless it's necessary 74 | otherwise you may forget to delete buffer but 75 | client.setRecvBufferDeleted() was called 76 | that will cause memory leak 77 | */ 78 | } 79 | else 80 | { 81 | //... 82 | } 83 | }); 84 | 85 | Serial.println("Connecting to websocket server..."); 86 | 87 | //record connect timestamp 88 | t = millis(); 89 | 90 | //connect 91 | client.connect("abc.com", 80, "/"); 92 | 93 | //you could set interval after connection lost 94 | //auto connect is true by default 95 | //timeout is 5000ms 96 | client.setAutoReconnect(true, 5000); 97 | 98 | // you have different ways to connect to server 99 | // client.connect("abc.com", 8080, "/"); 100 | // client.connect("ws://abc.com"); == port = 80, path = "/" 101 | // client.connect("ws://abc.com:8080"); == port = 8080, path = "/" 102 | // client.connect("ws://abc.com:8080/yourpath"); == port = 8080, path = "/yourpath" 103 | // client.connect("ws://abc.com/yourpath"); == port = 80, path = "/yourpath" 104 | } 105 | 106 | void loop() 107 | { 108 | client.loop(); 109 | } 110 | -------------------------------------------------------------------------------- /mycrypto/README.md: -------------------------------------------------------------------------------- 1 | At first this component only have SHA1 and Base64 for websocket use 2 | (because I don't know how to use offical part, and don't know it will use hardware accleration or not, so I made this). 3 | Then I add SHA256 and AES-256-CBC to it, so it could be use at other places. 4 | Except for Base64, the other parts of this component implemented by referring to the ESP32 offical technical reference manual, SHA and AES accleration parts. 5 | 6 | 最初这个组件只有SHA1和Base64供websocket使用(因为我不会用官方库,也不知道是软件实现还是使用了硬件加速器 7 | (因为一开始是使用1.0.6,底层是esp-idf 3,后来的版本迁移esp-idf 4导致官方组件很乱,我也懒得找了,所以自己写了一个),所以自己调用硬件加速才有了这个组件)。 8 | 后来我又添加了SHA256和AES-256-CBC,所以它也可以在其他地方使用。 9 | 这个组件除了Base64其他都是参照ESP32官方技术参考手册,SHA加速器和AES加速器部分直接使用硬件加速实现的。 10 | -------------------------------------------------------------------------------- /mycrypto/mycrypto.cpp: -------------------------------------------------------------------------------- 1 | #include "mycrypto.h" 2 | 3 | namespace mycrypto 4 | { 5 | // universal sha digest function 6 | // use esp32 built-in hardware acceleration module 7 | // all procedures is from Espressif offical technical document 8 | // befor using this function, you need call "periph_module_enable(PERIPH_SHA_MODULE);" at first 9 | // this is included in this class 10 | // call SHA::initialize(); 11 | // or you will got all zero result 12 | void SHA::sha(uint8_t *data, uint64_t length, uint32_t *output, SHAType type) 13 | { 14 | // type 1 for sha1 15 | // 0 for sha256 16 | if (length <= 0) 17 | { 18 | bzero(output, (type & 1 ? 5 : 8)); 19 | return; 20 | } 21 | 22 | // original length 23 | uint64_t ori = length; 24 | 25 | // calc padding length 26 | length = ((length * 8) % 512); 27 | uint64_t zeroLength = ((length < 448) ? (448 - length) : (448 + 512 - length)) / 8; 28 | 29 | // add length 30 | length = ori + zeroLength + 8; 31 | 32 | // allocate buffer 33 | uint8_t *buf = new (std::nothrow) uint8_t[length]; 34 | 35 | if (!buf) 36 | { 37 | output[0] = 0; 38 | return; 39 | } 40 | 41 | // padding zero 42 | bzero(buf, length); 43 | 44 | // copy original data 45 | memcpy(buf, data, ori); 46 | 47 | // padding the "1" after data 48 | buf[ori] = (uint8_t)0x80; 49 | 50 | // add data length(bits) into the tail 51 | uint64_t bits = ori * 8; 52 | for (int i = 0; i < 8; i++) 53 | { 54 | buf[ori + zeroLength + i] = (bits >> ((7 - i) * 8)) & 0xff; 55 | } 56 | 57 | uint64_t i = 0; 58 | 59 | // fill 512 bits(1 block) to start 60 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 0, (uint32_t)((buf[i + 0] << 24) + (buf[i + 1] << 16) + (buf[i + 2] << 8) + (buf[i + 3]))); 61 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 4, (uint32_t)((buf[i + 4] << 24) + (buf[i + 5] << 16) + (buf[i + 6] << 8) + (buf[i + 7]))); 62 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 8, (uint32_t)((buf[i + 8] << 24) + (buf[i + 9] << 16) + (buf[i + 10] << 8) + (buf[i + 11]))); 63 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 12, (uint32_t)((buf[i + 12] << 24) + (buf[i + 13] << 16) + (buf[i + 14] << 8) + (buf[i + 15]))); 64 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 16, (uint32_t)((buf[i + 16] << 24) + (buf[i + 17] << 16) + (buf[i + 18] << 8) + (buf[i + 19]))); 65 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 20, (uint32_t)((buf[i + 20] << 24) + (buf[i + 21] << 16) + (buf[i + 22] << 8) + (buf[i + 23]))); 66 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 24, (uint32_t)((buf[i + 24] << 24) + (buf[i + 25] << 16) + (buf[i + 26] << 8) + (buf[i + 27]))); 67 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 28, (uint32_t)((buf[i + 28] << 24) + (buf[i + 29] << 16) + (buf[i + 30] << 8) + (buf[i + 31]))); 68 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 32, (uint32_t)((buf[i + 32] << 24) + (buf[i + 33] << 16) + (buf[i + 34] << 8) + (buf[i + 35]))); 69 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 36, (uint32_t)((buf[i + 36] << 24) + (buf[i + 37] << 16) + (buf[i + 38] << 8) + (buf[i + 39]))); 70 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 40, (uint32_t)((buf[i + 40] << 24) + (buf[i + 41] << 16) + (buf[i + 42] << 8) + (buf[i + 43]))); 71 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 44, (uint32_t)((buf[i + 44] << 24) + (buf[i + 45] << 16) + (buf[i + 46] << 8) + (buf[i + 47]))); 72 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 48, (uint32_t)((buf[i + 48] << 24) + (buf[i + 49] << 16) + (buf[i + 50] << 8) + (buf[i + 51]))); 73 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 52, (uint32_t)((buf[i + 52] << 24) + (buf[i + 53] << 16) + (buf[i + 54] << 8) + (buf[i + 55]))); 74 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 56, (uint32_t)((buf[i + 56] << 24) + (buf[i + 57] << 16) + (buf[i + 58] << 8) + (buf[i + 59]))); 75 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 60, (uint32_t)((buf[i + 60] << 24) + (buf[i + 61] << 16) + (buf[i + 62] << 8) + (buf[i + 63]))); 76 | i += 64; 77 | 78 | // start 79 | if (type & 1) 80 | { 81 | DPORT_REG_WRITE(SHA_1_START_REG, (uint32_t)(1)); 82 | while (DPORT_REG_READ(SHA_1_BUSY_REG)) 83 | { 84 | // yield(); 85 | // because of the hardware acceleration is very fast 86 | // for 8KB data only needs less than 300us(ESPRESSIF YYDS) 87 | // so yield() is no need to call 88 | } 89 | } 90 | else 91 | { 92 | DPORT_REG_WRITE(SHA_256_START_REG, (uint32_t)(1)); 93 | while (DPORT_REG_READ(SHA_256_BUSY_REG)) 94 | { 95 | } 96 | } 97 | 98 | // to process other blocks 99 | // always fill 512bits(a block) at one time 100 | for (; i < length; i += 64) 101 | { 102 | // fill 512 bits into registers to continue 103 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 0, (uint32_t)((buf[i + 0] << 24) + (buf[i + 1] << 16) + (buf[i + 2] << 8) + (buf[i + 3]))); 104 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 4, (uint32_t)((buf[i + 4] << 24) + (buf[i + 5] << 16) + (buf[i + 6] << 8) + (buf[i + 7]))); 105 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 8, (uint32_t)((buf[i + 8] << 24) + (buf[i + 9] << 16) + (buf[i + 10] << 8) + (buf[i + 11]))); 106 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 12, (uint32_t)((buf[i + 12] << 24) + (buf[i + 13] << 16) + (buf[i + 14] << 8) + (buf[i + 15]))); 107 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 16, (uint32_t)((buf[i + 16] << 24) + (buf[i + 17] << 16) + (buf[i + 18] << 8) + (buf[i + 19]))); 108 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 20, (uint32_t)((buf[i + 20] << 24) + (buf[i + 21] << 16) + (buf[i + 22] << 8) + (buf[i + 23]))); 109 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 24, (uint32_t)((buf[i + 24] << 24) + (buf[i + 25] << 16) + (buf[i + 26] << 8) + (buf[i + 27]))); 110 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 28, (uint32_t)((buf[i + 28] << 24) + (buf[i + 29] << 16) + (buf[i + 30] << 8) + (buf[i + 31]))); 111 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 32, (uint32_t)((buf[i + 32] << 24) + (buf[i + 33] << 16) + (buf[i + 34] << 8) + (buf[i + 35]))); 112 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 36, (uint32_t)((buf[i + 36] << 24) + (buf[i + 37] << 16) + (buf[i + 38] << 8) + (buf[i + 39]))); 113 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 40, (uint32_t)((buf[i + 40] << 24) + (buf[i + 41] << 16) + (buf[i + 42] << 8) + (buf[i + 43]))); 114 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 44, (uint32_t)((buf[i + 44] << 24) + (buf[i + 45] << 16) + (buf[i + 46] << 8) + (buf[i + 47]))); 115 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 48, (uint32_t)((buf[i + 48] << 24) + (buf[i + 49] << 16) + (buf[i + 50] << 8) + (buf[i + 51]))); 116 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 52, (uint32_t)((buf[i + 52] << 24) + (buf[i + 53] << 16) + (buf[i + 54] << 8) + (buf[i + 55]))); 117 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 56, (uint32_t)((buf[i + 56] << 24) + (buf[i + 57] << 16) + (buf[i + 58] << 8) + (buf[i + 59]))); 118 | DPORT_REG_WRITE(DR_REG_SHA_BASE + 60, (uint32_t)((buf[i + 60] << 24) + (buf[i + 61] << 16) + (buf[i + 62] << 8) + (buf[i + 63]))); 119 | 120 | // continue 121 | if (type & 1) 122 | { 123 | DPORT_REG_WRITE(SHA_1_CONTINUE_REG, (uint32_t)(1)); 124 | 125 | while (DPORT_REG_READ(SHA_1_BUSY_REG)) 126 | { 127 | } 128 | } 129 | else 130 | { 131 | DPORT_REG_WRITE(SHA_256_CONTINUE_REG, (uint32_t)(1)); 132 | 133 | while (DPORT_REG_READ(SHA_256_BUSY_REG)) 134 | { 135 | } 136 | } 137 | } 138 | delete buf; 139 | 140 | // get sha result 141 | if (type & 1) 142 | { 143 | DPORT_REG_WRITE(SHA_1_LOAD_REG, (uint32_t)(1)); 144 | while (DPORT_REG_READ(SHA_1_BUSY_REG)) 145 | { 146 | } 147 | } 148 | else 149 | { 150 | DPORT_REG_WRITE(SHA_256_LOAD_REG, (uint32_t)(1)); 151 | while (DPORT_REG_READ(SHA_256_BUSY_REG)) 152 | { 153 | } 154 | } 155 | 156 | uint8_t shaLen = type & 1 ? 5 : 8; 157 | 158 | // read result 159 | for (int i = 0; i < shaLen; i++) 160 | { 161 | output[i] = (uint32_t)DPORT_REG_READ(DR_REG_SHA_BASE + (i * 4)); 162 | } 163 | } 164 | 165 | // this is for arduino framework 166 | String SHA::aSHA(uint8_t *data, uint64_t length, SHAType type, SHAOutputCase hexCase) 167 | { 168 | // for sha1 is 160 bits which is 5x32 bits 169 | // for sha256 is 256 bits which is 8x32 bits 170 | uint8_t shaLen = type & 1 ? 5 : 8; 171 | uint32_t output[shaLen]; 172 | 173 | // call sha 174 | sha(data, length, output, type); 175 | 176 | // to store formated hex string 177 | char hex[9]; 178 | bzero(hex, 9); 179 | 180 | // return value 181 | String res = ""; 182 | 183 | // format 184 | char format[] = "%08x"; 185 | 186 | // case 187 | if (hexCase == UPPER_CASE) 188 | { 189 | format[3] = 'X'; 190 | } 191 | 192 | // convert result into hex string 193 | for (int i = 0; i < shaLen; i++) 194 | { 195 | sprintf(hex, format, output[i]); 196 | res += hex; 197 | bzero(hex, 9); 198 | } 199 | return res; 200 | } 201 | 202 | void SHA::convertU32ToU8(uint8_t *data, uint64_t length, uint8_t *output, SHAType type) 203 | { 204 | int len = type & 1 ? 5 : 8; 205 | uint32_t o[len]; 206 | sha(data, length, o, type); 207 | int k = 0; 208 | for (int i = 0; i < len; i++) 209 | { 210 | output[k++] = (uint8_t)((o[i] & (uint32_t)(0xff000000)) >> 24); 211 | output[k++] = (uint8_t)((o[i] & (uint32_t)(0x00ff0000)) >> 16); 212 | output[k++] = (uint8_t)((o[i] & (uint32_t)(0x0000ff00)) >> 8); 213 | output[k++] = (uint8_t)(o[i] & (uint32_t)(0x000000ff)); 214 | } 215 | } 216 | 217 | // a very simple base64 encode method 218 | char *Base64::base64Encode(uint8_t *data, uint64_t length) 219 | { 220 | const char *base64Table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 221 | 222 | uint32_t group = 0; 223 | 224 | uint8_t extra = length % 3; 225 | 226 | uint64_t len = length - extra; 227 | 228 | char *res = new (std::nothrow) char[extra == 0 ? (len / 3 * 4 + 1) : (len / 3 * 4 + 5)]{0}; 229 | 230 | uint64_t location = 0; 231 | for (uint64_t i = 0; i < len; i += 3, location += 4) 232 | { 233 | group = (data[i + 0] << 24) + (data[i + 1] << 16) + (data[i + 2] << 8); 234 | 235 | res[location] = base64Table[((uint8_t)(((uint32_t)(4227858432U) & group) >> 26))]; 236 | res[location + 1] = base64Table[((uint8_t)(((uint32_t)(66060288U) & group) >> 20))]; 237 | res[location + 2] = base64Table[((uint8_t)(((uint32_t)(1032192U) & group) >> 14))]; 238 | res[location + 3] = base64Table[((uint8_t)(((uint32_t)(16128U) & group) >> 8))]; 239 | group = 0; 240 | } 241 | 242 | if (extra == 1) 243 | { 244 | res[location] = base64Table[((uint8_t)(data[len] >> 2))]; 245 | res[location + 1] = base64Table[((uint8_t)((data[len] & 3U) << 4))]; 246 | res[location + 2] = '='; 247 | res[location + 3] = '='; 248 | } 249 | else if (extra == 2) 250 | { 251 | uint16_t t = (data[len] << 8) + (data[len + 1]); 252 | res[location] = base64Table[((uint8_t)((uint32_t)(t & 64512U) >> 10))]; 253 | res[location + 1] = base64Table[((uint8_t)((uint32_t)(t & 1008U) >> 4))]; 254 | res[location + 2] = base64Table[((uint8_t)((uint32_t)(t & 15U) << 2))]; 255 | res[location + 3] = '='; 256 | } 257 | 258 | return res; 259 | } 260 | 261 | uint8_t Base64::getCharIndex(uint8_t c) 262 | { 263 | if (c > 96 && c < 123) 264 | { 265 | return c - 97 + 26; 266 | } 267 | else if (c > 64 && c < 91) 268 | { 269 | return c - 65; 270 | } 271 | else if (c > 47 && c < 58) 272 | { 273 | return c - 48 + 52; 274 | } 275 | else if (c == 43) 276 | { 277 | return 62; 278 | } 279 | else if (c == 47) 280 | { 281 | return 63; 282 | } 283 | else 284 | { 285 | return 0; 286 | } 287 | } 288 | 289 | uint8_t *Base64::base64Decode(uint8_t *data, uint64_t iLen, uint64_t *oLen) 290 | { 291 | *oLen = 0; 292 | 293 | if (iLen % 4) 294 | { 295 | return nullptr; 296 | } 297 | 298 | uint64_t eIndex = 0; 299 | 300 | for (int i = 1; i < 3; i++) 301 | { 302 | if (data[iLen - i] == '=') 303 | { 304 | eIndex = i; 305 | } 306 | } 307 | 308 | iLen -= eIndex; 309 | 310 | uint8_t *output = new uint8_t[iLen / 4 * 3 + 3]; 311 | // bzero(output, iLen / 4 * 3 + 2); 312 | 313 | uint8_t tLen = 0; 314 | uint8_t arr[4] = {0}; 315 | 316 | for (uint64_t i = 0; i < iLen; i++) 317 | { 318 | arr[tLen++] = data[i]; 319 | if (tLen >= 4) 320 | { 321 | output[(*oLen)++] = getCharIndex(arr[0]) << 2 | (getCharIndex(arr[1]) & 48U) >> 4; 322 | output[(*oLen)++] = getCharIndex(arr[1]) << 4 | (getCharIndex(arr[2]) & 60U) >> 2; 323 | output[(*oLen)++] = getCharIndex(arr[2]) << 6 | (getCharIndex(arr[3]) & 63U); 324 | tLen = 0; 325 | } 326 | } 327 | if (tLen == 2) 328 | { 329 | output[(*oLen)++] = (getCharIndex(arr[0])) << 2 | (getCharIndex(arr[1])) >> 4; 330 | } 331 | else if (tLen == 3) 332 | { 333 | output[(*oLen)++] = (getCharIndex(arr[0])) << 2 | (getCharIndex(arr[1])) >> 4; 334 | output[(*oLen)++] = (getCharIndex(arr[1])) << 4 | (getCharIndex(arr[2])) >> 2; 335 | } 336 | 337 | output[(*oLen)] = 0; 338 | 339 | return output; 340 | } 341 | 342 | // AES encryption and decryption according to ESPRESSIF ESP32 technical reference manual, 343 | // chapter 22, page 523(Chinese version) 344 | uint8_t *AES::aes256CBCEncrypt(uint8_t *key, // 32 bytes 345 | uint8_t *iv, // 16 bytes 346 | uint8_t *plain, // plain 347 | uint32_t length, // length of plain 348 | uint32_t *outLen // length of output 349 | ) 350 | { 351 | // declare 32bit key and iv 352 | uint32_t key32[8] = {0}; 353 | 354 | // data block is 128 bits, so iv as same as data block length 355 | uint32_t iv32[4] = {0}; 356 | 357 | // convert key and iv to uint32 array 358 | for (uint8_t i = 0, j = 0; i < 8; ++i, j += 4) 359 | { 360 | key32[i] = 361 | (key[j] << 24) + (key[j + 1] << 16) + (key[j + 2] << 8) + (key[j + 3]); 362 | if (i < 4) 363 | { 364 | iv32[i] = 365 | (iv[j] << 24) + (iv[j + 1] << 16) + (iv[j + 2] << 8) + (iv[j + 3]); 366 | } 367 | } 368 | 369 | // padding plain with pkcs7 padding 370 | uint8_t paddingData = 16 - (length % 16); 371 | uint32_t bufferLength = length + paddingData; 372 | 373 | // allocate buffer to hold original data after padding 374 | uint8_t *bufferPadding = new (std::nothrow) uint8_t[bufferLength]; 375 | 376 | if (!bufferPadding) 377 | { 378 | ESP_LOGD(MY_CRYPTO_DEBUG_HEADER, "memory allocate failed"); 379 | (*outLen) = 0; 380 | return nullptr; 381 | } 382 | 383 | // copy original data 384 | memcpy(bufferPadding, plain, length); 385 | 386 | // padding 387 | memset(bufferPadding + length, paddingData, paddingData); 388 | 389 | // allocate buffer for uint32 array 390 | uint32_t *buffer = new (std::nothrow) uint32_t[bufferLength / 4]; 391 | if (!buffer) 392 | { 393 | ESP_LOGD(MY_CRYPTO_DEBUG_HEADER, "memory allocate failed"); 394 | delete bufferPadding; 395 | (*outLen) = 0; 396 | return nullptr; 397 | } 398 | 399 | // convert uint8 array to uint32 array 400 | for (uint32_t i = 0, k = 0; i < bufferLength; i += 4) 401 | { 402 | buffer[k++] = 403 | (bufferPadding[i] << 24) + (bufferPadding[i + 1] << 16) + (bufferPadding[i + 2] << 8) + (bufferPadding[i + 3]); 404 | } 405 | 406 | // length for uint32 array after padding and convertion 407 | bufferLength /= 4; 408 | 409 | // remove padding buffer 410 | delete bufferPadding; 411 | 412 | // xor first block with iv 413 | for (uint8_t i = 0; i < 4; ++i) 414 | { 415 | buffer[i] ^= iv32[i]; 416 | } 417 | 418 | // config aes mode and endian 419 | DPORT_REG_WRITE(AES_MODE_REG, (uint32_t)2); 420 | DPORT_REG_WRITE(AES_ENDIAN, (uint32_t)42); 421 | 422 | // fill key into register 423 | for (uint8_t i = 0; i < 8; ++i) 424 | { 425 | DPORT_REG_WRITE(AES_KEY_BASE + (i * 4), key32[i]); 426 | } 427 | 428 | // start encrypting 429 | for (uint32_t i = 0; i < bufferLength; i += 4) 430 | { 431 | // fill plain data(after padding) into register 432 | DPORT_REG_WRITE(AES_TEXT_BASE, buffer[i]); 433 | DPORT_REG_WRITE(AES_TEXT_BASE + 4, buffer[i + 1]); 434 | DPORT_REG_WRITE(AES_TEXT_BASE + 8, buffer[i + 2]); 435 | DPORT_REG_WRITE(AES_TEXT_BASE + 12, buffer[i + 3]); 436 | 437 | // start encrypting 438 | DPORT_REG_WRITE(AES_START_REG, (uint32_t)1); 439 | 440 | // wait idle register 441 | while (!(DPORT_REG_READ(AES_IDLE_REG))) 442 | { 443 | } 444 | 445 | // read cipher data from register 446 | buffer[i] = DPORT_REG_READ(AES_TEXT_BASE); 447 | buffer[i + 1] = DPORT_REG_READ(AES_TEXT_BASE + 4); 448 | buffer[i + 2] = DPORT_REG_READ(AES_TEXT_BASE + 8); 449 | buffer[i + 3] = DPORT_REG_READ(AES_TEXT_BASE + 12); 450 | 451 | // encryption finished 452 | if (i + 4 >= bufferLength) 453 | { 454 | break; 455 | } 456 | 457 | // xor next block with former cipher text(cbc) 458 | buffer[i + 4] ^= buffer[i]; 459 | buffer[i + 5] ^= buffer[i + 1]; 460 | buffer[i + 6] ^= buffer[i + 2]; 461 | buffer[i + 7] ^= buffer[i + 3]; 462 | } 463 | 464 | // convert uint32 array into uint8 array 465 | // this is optional, here only for uniform output and input 466 | uint8_t *u8Buffer = new uint8_t[bufferLength * 4]; 467 | for (uint32_t i = 0, j = 0; i < bufferLength; ++i, j += 4) 468 | { 469 | u8Buffer[j] = (buffer[i] & (uint32_t)(0xff000000U)) >> 24; 470 | u8Buffer[j + 1] = (buffer[i] & (uint32_t)(0x00ff0000U)) >> 16; 471 | u8Buffer[j + 2] = (buffer[i] & (uint32_t)(0x0000ff00U)) >> 8; 472 | u8Buffer[j + 3] = (buffer[i] & (uint32_t)(0x000000ffU)); 473 | } 474 | 475 | // remove uint32 array 476 | delete buffer; 477 | 478 | // return result 479 | (*outLen) = bufferLength * 4; 480 | return u8Buffer; 481 | } 482 | 483 | uint8_t *AES::aes256CBCDecrypt( 484 | uint8_t *key, // key 485 | uint8_t *iv, // iv 486 | uint8_t *cipher, // cipher data 487 | uint32_t length, // length of cipher data 488 | uint32_t *outLen // length of output 489 | ) 490 | { 491 | 492 | // length of input must be an integer of multiple of 16 493 | if (length % 16) 494 | { 495 | ESP_LOGD(MY_CRYPTO_DEBUG_HEADER, "data is invalid"); 496 | (*outLen) = 0; 497 | return nullptr; 498 | } 499 | 500 | // declare 32bit key and iv for convertion 501 | uint32_t key32[8] = {0}; 502 | uint32_t iv32[4] = {0}; 503 | 504 | // convert key and iv to uint32 array 505 | for (uint8_t i = 0, j = 0; i < 8; ++i, j += 4) 506 | { 507 | key32[i] = 508 | (key[j] << 24) + (key[j + 1] << 16) + (key[j + 2] << 8) + (key[j + 3]); 509 | if (i < 4) 510 | { 511 | iv32[i] = 512 | (iv[j] << 24) + (iv[j + 1] << 16) + (iv[j + 2] << 8) + (iv[j + 3]); 513 | } 514 | } 515 | 516 | // calcuate length of uint32 array 517 | uint32_t bufferLength = length / 4; 518 | 519 | // allocate buffer 520 | uint32_t *buffer = new (std::nothrow) uint32_t[bufferLength]; 521 | 522 | if (!buffer) 523 | { 524 | ESP_LOGD(MY_CRYPTO_DEBUG_HEADER, "buffer allocate failed when aes decrypting"); 525 | (*outLen) = 0; 526 | return nullptr; 527 | } 528 | 529 | // convert uint8 array to uint32 array 530 | for (uint32_t i = 0, j = 0; i < bufferLength; ++i, j += 4) 531 | { 532 | buffer[i] = 533 | (cipher[j] << 24) + (cipher[j + 1] << 16) + (cipher[j + 2] << 8) + (cipher[j + 3]); 534 | } 535 | 536 | // fill key into register 537 | for (uint8_t i = 0; i < 8; ++i) 538 | { 539 | DPORT_REG_WRITE(AES_KEY_BASE + (i * 4), key32[i]); 540 | } 541 | 542 | // config aes mode and endian 543 | DPORT_REG_WRITE(AES_MODE_REG, (uint32_t)6); 544 | DPORT_REG_WRITE(AES_ENDIAN, (uint32_t)42); 545 | 546 | // start decrypting 547 | // from last block to previous block 548 | for (uint32_t i = bufferLength - 4;;) 549 | { 550 | // fill cipher data to registers 551 | DPORT_REG_WRITE(AES_TEXT_BASE, buffer[i]); 552 | DPORT_REG_WRITE(AES_TEXT_BASE + 4, buffer[i + 1]); 553 | DPORT_REG_WRITE(AES_TEXT_BASE + 8, buffer[i + 2]); 554 | DPORT_REG_WRITE(AES_TEXT_BASE + 12, buffer[i + 3]); 555 | 556 | // start decrypting current block 557 | DPORT_REG_WRITE(AES_START_REG, (uint32_t)1); 558 | 559 | // wait idle register 560 | while (!(DPORT_REG_READ(AES_IDLE_REG))) 561 | { 562 | } 563 | 564 | // read plain data 565 | buffer[i] = DPORT_REG_READ(AES_TEXT_BASE); 566 | buffer[i + 1] = DPORT_REG_READ(AES_TEXT_BASE + 4); 567 | buffer[i + 2] = DPORT_REG_READ(AES_TEXT_BASE + 8); 568 | buffer[i + 3] = DPORT_REG_READ(AES_TEXT_BASE + 12); 569 | // got plain data of current block 570 | 571 | // the first block has been decrypted 572 | // ready to break; 573 | if (!i) 574 | { 575 | break; 576 | } 577 | 578 | // xor plain data(after decryption) of current block with former block cipher data 579 | if (i >= 4) 580 | { 581 | buffer[i] ^= buffer[i - 4]; 582 | buffer[i + 1] ^= buffer[i - 3]; 583 | buffer[i + 2] ^= buffer[i - 2]; 584 | buffer[i + 3] ^= buffer[i - 1]; 585 | // got original data of current block 586 | } 587 | i -= 4; 588 | } 589 | 590 | // xor first block with iv 591 | for (uint8_t i = 0; i < 4; ++i) 592 | { 593 | buffer[i] ^= iv32[i]; 594 | } 595 | 596 | // read padding length 597 | uint8_t paddingLength = (buffer[bufferLength - 1] & (uint32_t)(0xffU)); 598 | if (!paddingLength || paddingLength > 0x10) 599 | { 600 | ESP_LOGD(MY_CRYPTO_DEBUG_HEADER, "length of padding is invalid"); 601 | (*outLen) = 0; 602 | delete buffer; 603 | return nullptr; 604 | } 605 | 606 | // get length of real data 607 | uint32_t realLength = (bufferLength * 4) - paddingLength; 608 | 609 | // allocate buffer for real data 610 | uint8_t *outputBuffer = new (std::nothrow) uint8_t[realLength]; 611 | 612 | if (!outputBuffer) 613 | { 614 | ESP_LOGD(MY_CRYPTO_DEBUG_HEADER, "allocate memory failed"); 615 | (*outLen) = 0; 616 | delete buffer; 617 | return nullptr; 618 | } 619 | 620 | // copy real data from uint32 array to uint8 array 621 | for (uint32_t i = 0, j = 0, k = 0, t = 0xff000000U; i < realLength; ++i) 622 | { 623 | outputBuffer[i] = (uint8_t)((buffer[j] & t) >> (24 - (k << 3))); 624 | ++k; 625 | t >>= 8; 626 | if (!(k % 4)) 627 | { 628 | ++j; 629 | k = 0; 630 | t = 0xff000000U; 631 | } 632 | } 633 | 634 | // remove uint32 array 635 | delete buffer; 636 | 637 | // return data 638 | (*outLen) = realLength; 639 | return outputBuffer; 640 | } 641 | 642 | // get hex string of aes 256 cbc 643 | String AES::aes256CBCEncrypt(String key, // key 644 | String iv, // iv 645 | String plain // data 646 | ) 647 | { 648 | if (!key.length() || !iv.length() || !plain.length()) 649 | { 650 | return "invalid input data"; 651 | } 652 | 653 | if (key.length() != 32) 654 | { 655 | return "invalid length of key"; 656 | } 657 | 658 | if (iv.length() != 16) 659 | { 660 | return "invalid length of iv"; 661 | } 662 | 663 | uint32_t outLen = 0; 664 | uint8_t *buffer = aes256CBCEncrypt((uint8_t *)key.c_str(), 665 | (uint8_t *)iv.c_str(), 666 | (uint8_t *)plain.c_str(), 667 | plain.length(), 668 | &outLen); 669 | if (!outLen || !buffer) 670 | { 671 | if (buffer) 672 | { 673 | delete buffer; 674 | } 675 | return "invalid input data"; 676 | } 677 | 678 | String output = ""; 679 | char t[3]; 680 | t[2] = 0; 681 | 682 | for (uint32_t i = 0; i < outLen; ++i) 683 | { 684 | sprintf(t, "%02x", buffer[i]); 685 | output += t; 686 | } 687 | 688 | delete buffer; 689 | 690 | return output; 691 | } 692 | 693 | // get original data of aes 256 cbc hex string 694 | String AES::aes256CBCDecrypt( 695 | String key, // key 696 | String iv, // iv 697 | String cipher // data, hex format 698 | ) 699 | { 700 | if (!key.length() || !iv.length() || !cipher.length()) 701 | { 702 | return "invalid input data"; 703 | } 704 | 705 | if (cipher.length() % 16) 706 | { 707 | return "invalid length of data"; 708 | } 709 | 710 | if (key.length() != 32) 711 | { 712 | return "invalid length of key"; 713 | } 714 | 715 | if (iv.length() != 16) 716 | { 717 | return "invalid length of iv"; 718 | } 719 | 720 | uint32_t bufferLength = cipher.length() / 2; 721 | 722 | uint8_t encryptedBuffer[bufferLength] = {0}; 723 | 724 | if (!encryptedBuffer) 725 | { 726 | return "allocate memory failed"; 727 | } 728 | 729 | for (uint32_t i = 0, j = 0; j < bufferLength; i += 2) 730 | { 731 | sscanf(cipher.substring(i, i + 2).c_str(), "%02x", (encryptedBuffer + j)); 732 | ++j; 733 | } 734 | 735 | uint32_t outLen = 0; 736 | uint8_t *decryptedBuffer = aes256CBCDecrypt( 737 | (uint8_t *)key.c_str(), 738 | (uint8_t *)iv.c_str(), 739 | encryptedBuffer, 740 | bufferLength, 741 | &outLen); 742 | 743 | if (!outLen || !decryptedBuffer) 744 | { 745 | return "error when decrypting data"; 746 | } 747 | 748 | String output = String((const char *)decryptedBuffer, outLen); 749 | delete decryptedBuffer; 750 | 751 | return output; 752 | } 753 | } 754 | -------------------------------------------------------------------------------- /mycrypto/mycrypto.h: -------------------------------------------------------------------------------- 1 | /* 2 | This library able to get sha1/256 and base64 encode/decode using in the 3 | "esp32-arduino" framework. 4 | SHA part is according to offical document of ESP32-WROOM-32(D/E/UE), 5 | using ESP32 hardware acceleration to get sha digest. 6 | If you are using ESP32-C3 or other modules of ESP32, you 7 | should replace those "registers address" to fit in the core, 8 | because of these chip may have different address. 9 | */ 10 | 11 | #ifndef MY_CRYPTO_H_ 12 | #define MY_CRYPTO_H_ 13 | 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include "soc/dport_access.h" 20 | #include "soc/hwcrypto_reg.h" 21 | 22 | #ifndef _DRIVER_PERIPH_CTRL_H_ 23 | #if ESP_IDF_VERSION_MAJOR < 4 24 | #include "esp_private/periph_ctrl.h" 25 | #else 26 | #include "driver/periph_ctrl.h" 27 | #endif 28 | #endif 29 | 30 | #define MY_CRYPTO_DEBUG_HEADER "mycrypto" 31 | 32 | namespace mycrypto 33 | { 34 | typedef enum 35 | { 36 | SHA1 = 1, 37 | SHA256 = 0 38 | } SHAType; 39 | 40 | typedef enum 41 | { 42 | LOWER_CASE, 43 | UPPER_CASE 44 | } SHAOutputCase; 45 | 46 | class SHA 47 | { 48 | private: 49 | static void sha(uint8_t *data, uint64_t length, uint32_t *output, SHAType type = SHA256); 50 | static String aSHA(uint8_t *data, uint64_t length, SHAType type, SHAOutputCase hexCase = LOWER_CASE); 51 | static void convertU32ToU8(uint8_t *data, uint64_t length, uint8_t *output, SHAType type); 52 | 53 | public: 54 | static inline void initialize() 55 | { 56 | periph_module_enable(PERIPH_SHA_MODULE); 57 | } 58 | 59 | static inline void sha1(uint8_t *data, uint64_t length, uint32_t *output) 60 | { 61 | sha(data, length, output, SHA1); 62 | } 63 | 64 | static inline void sha1(uint8_t *data, uint64_t length, uint8_t *output) 65 | { 66 | convertU32ToU8(data, length, output, SHA1); 67 | } 68 | 69 | static inline void sha256(uint8_t *data, uint64_t length, uint8_t *output) 70 | { 71 | convertU32ToU8(data, length, output, SHA256); 72 | } 73 | 74 | static inline void sha256(uint8_t *data, uint64_t length, uint32_t *output) 75 | { 76 | sha(data, length, output, SHA256); 77 | } 78 | 79 | static inline void sha1(uint32_t data, uint8_t *output) 80 | { 81 | uint8_t t[4] = {((uint8_t)(data >> 24)), ((uint8_t)(data >> 16)), ((uint8_t)(data >> 8)), ((uint8_t)(data))}; 82 | convertU32ToU8(t, 4, output, SHA1); 83 | } 84 | 85 | static inline void sha256(uint32_t data, uint8_t *output) 86 | { 87 | uint8_t t[4] = {((uint8_t)(data >> 24)), ((uint8_t)(data >> 16)), ((uint8_t)(data >> 8)), ((uint8_t)(data))}; 88 | convertU32ToU8(t, 4, output, SHA256); 89 | } 90 | 91 | static inline String sha1(uint8_t *data, uint64_t length, SHAOutputCase hexCase = LOWER_CASE) 92 | { 93 | return aSHA(data, length, SHA1, hexCase); 94 | } 95 | 96 | static inline String sha256(uint8_t *data, uint64_t length, SHAOutputCase hexCase = LOWER_CASE) 97 | { 98 | return aSHA(data, length, SHA256, hexCase); 99 | } 100 | 101 | static inline String sha1(String data, SHAOutputCase hexCase = LOWER_CASE) 102 | { 103 | return aSHA((uint8_t *)data.c_str(), data.length(), SHA1, hexCase); 104 | } 105 | 106 | static inline String sha256(String data, SHAOutputCase hexCase = LOWER_CASE) 107 | { 108 | return aSHA((uint8_t *)data.c_str(), data.length(), SHA256, hexCase); 109 | } 110 | 111 | static inline String sha1(String *data, SHAOutputCase hexCase = LOWER_CASE) 112 | { 113 | return aSHA((uint8_t *)data->c_str(), data->length(), SHA1, hexCase); 114 | } 115 | 116 | static inline String sha256(String *data, SHAOutputCase hexCase = LOWER_CASE) 117 | { 118 | return aSHA((uint8_t *)data->c_str(), data->length(), SHA256, hexCase); 119 | } 120 | 121 | static inline String sha1(const char *data, uint64_t length, SHAOutputCase hexCase = LOWER_CASE) 122 | { 123 | return aSHA((uint8_t *)data, length, SHA1, hexCase); 124 | } 125 | 126 | static inline String sha256(const char *data, uint64_t length, SHAOutputCase hexCase = LOWER_CASE) 127 | { 128 | return aSHA((uint8_t *)data, length, SHA256, hexCase); 129 | } 130 | }; 131 | 132 | class Base64 133 | { 134 | private: 135 | static uint8_t getCharIndex(uint8_t c); 136 | static uint8_t *base64Decode(uint8_t *data, uint64_t iLen, uint64_t *oLen); 137 | 138 | public: 139 | static char *base64Encode(uint8_t *data, uint64_t length); 140 | 141 | static inline String base64Encode(const char *data, uint64_t length) 142 | { 143 | char *a = base64Encode((uint8_t *)data, length); 144 | String b = String(a); // this will make a copy in RAM 145 | delete a; 146 | return b; 147 | } 148 | 149 | static inline String base64Encode(String data) 150 | { 151 | return base64Encode((const char *)data.c_str(), data.length()); 152 | } 153 | 154 | static inline uint8_t *base64Decode(std::string data, uint64_t *oLen) 155 | { 156 | return base64Decode((uint8_t *)data.c_str(), data.length() - 1, oLen); 157 | } 158 | 159 | static inline uint8_t *base64Decode(String data, uint64_t *oLen) 160 | { 161 | return base64Decode((uint8_t *)data.c_str(), data.length(), oLen); 162 | } 163 | 164 | static inline String base64Decode(String data) 165 | { 166 | uint64_t oLen = 0; 167 | uint8_t *output = base64Decode((uint8_t *)data.c_str(), data.length(), &oLen); 168 | String a = String((char *)output); // this will make a copy 169 | delete output; 170 | return a; 171 | } 172 | 173 | static inline uint8_t *base64Decode(const char *data, uint64_t iLen, uint64_t *oLen) 174 | { 175 | return base64Decode((uint8_t *)data, iLen, oLen); 176 | } 177 | }; 178 | 179 | class AES 180 | { 181 | public: 182 | static inline void initialize() { periph_module_enable(PERIPH_AES_MODULE); } 183 | 184 | // AES encryption and decryption according to ESPRESSIF ESP32 technical reference manual, 185 | // chapter 22, page 523(Chinese version) 186 | static uint8_t *aes256CBCEncrypt(uint8_t *key, // 32 bytes 187 | uint8_t *iv, // 16 bytes 188 | uint8_t *plain, // plain data 189 | uint32_t length, // length of plain 190 | uint32_t *outLen // length of output 191 | ); 192 | 193 | static uint8_t *aes256CBCDecrypt( 194 | uint8_t *key, // 32 bytes key 195 | uint8_t *iv, // 16 bytes iv 196 | uint8_t *cipher, // cipher data 197 | uint32_t length, // length of cipher data 198 | uint32_t *outLen // length of output 199 | ); 200 | 201 | // get hex string of aes 256 cbc 202 | static String aes256CBCEncrypt(String key, // key 203 | String iv, // iv 204 | String plain // data 205 | ); 206 | 207 | // get original data form aes 256 cbc hex string 208 | static String AES::aes256CBCDecrypt( 209 | String key, // key 210 | String iv, // iv 211 | String cipher // data, hex format 212 | ); 213 | }; 214 | } 215 | 216 | #endif -------------------------------------------------------------------------------- /mywebsocket/mywebsocket.cpp: -------------------------------------------------------------------------------- 1 | #include "mywebsocket.h" 2 | 3 | namespace myWebSocket 4 | { 5 | 6 | // generate server key by client key 7 | String generateServerKey(String clientKey) 8 | { 9 | int shaLen = 20; 10 | uint8_t output[shaLen] = {0}; 11 | 12 | // this part use ESP32 SHA hardware acceleration module directly 13 | // you could change it if you don't use ESP32 14 | mycrypto::SHA::sha1((uint8_t *)clientKey.c_str(), clientKey.length(), output); 15 | 16 | uint8_t tmp = 0; 17 | 18 | for (uint32_t i = 0; i < shaLen; ++i) 19 | tmp |= output[i]; 20 | 21 | if (!tmp) 22 | return String(""); 23 | 24 | return mycrypto::Base64::base64Encode((const char *)output, shaLen); 25 | } 26 | 27 | // make websocket client request headers 28 | String WebSocketClient::generateHanshake() 29 | { 30 | // copy header 31 | String wsHeader = String(myWebSocketHeader); 32 | 33 | // make host 34 | this->domain = String(this->host + ":" + String(this->port)); 35 | 36 | // replace host and path 37 | wsHeader.replace("@HOST@", this->domain); 38 | wsHeader.replace("@PATH@", this->path); 39 | 40 | // generate 16 bytes random key 41 | uint8_t key[16]; 42 | for (uint8_t i = 0; i < 16; i++) 43 | { 44 | key[i] = random(0xFF); 45 | } 46 | 47 | // hash 48 | uint8_t output[20]; 49 | 50 | mycrypto::SHA::sha1(key, 16, output); 51 | 52 | #ifdef DEBUG_MYCRYPTO 53 | bool isSHAValid = false; 54 | for (int i = 0; i < 16; i++) 55 | { 56 | if (output[i]) 57 | { 58 | isSHAValid = true; 59 | break; 60 | } 61 | } 62 | 63 | if (!isSHAValid) 64 | { 65 | ESP_LOGW(MY_WEBSOCKET_DEBUG_HEADER, "SHA failed, SHA module may not enabled first"); 66 | return String(""); 67 | } 68 | #endif 69 | 70 | char *a = mycrypto::Base64::base64Encode(output, 16); 71 | 72 | // store client key 73 | this->clientKey = String(a); // arduino String will make a copy 74 | delete a; 75 | 76 | wsHeader.replace("@KEY@", this->clientKey); 77 | return wsHeader; 78 | } 79 | 80 | bool WebSocketClient::connect(String url) 81 | { 82 | if (url.startsWith("wss://")) 83 | { 84 | return false; 85 | } 86 | if (url.startsWith("ws://")) 87 | { 88 | url = url.substring(url.indexOf("ws://") + 5); 89 | } 90 | 91 | int a = url.indexOf(":"); 92 | int b = url.indexOf("/", (a < 0 ? 0 : a)); 93 | 94 | String domain = ""; 95 | uint16_t port = 80; 96 | String path = "/"; 97 | 98 | if (a < 0) 99 | { 100 | if (b < 0) 101 | { // abc.com 102 | domain = url; 103 | } 104 | else 105 | { // abc.com/path 106 | domain = url.substring(0, b); 107 | path = url.substring(b); 108 | } 109 | } 110 | else 111 | { 112 | if (b < 0) 113 | { // abc.com:8080 114 | port = url.substring(a + 1).toInt(); 115 | } 116 | else 117 | { // abc.com:8080/path 118 | port = url.substring(a + 1, b).toInt(); 119 | path = url.substring(b); 120 | } 121 | domain = url.substring(0, a); 122 | } 123 | return this->connect(domain, port, path); 124 | } 125 | 126 | bool WebSocketClient::handShake() 127 | { 128 | String header = generateHanshake(); 129 | if (header.isEmpty()) 130 | { 131 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "request header is empty"); 132 | return false; 133 | } 134 | // generate server key to verify after server responsed 135 | String serverKey = this->clientKey + String("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); 136 | serverKey = generateServerKey(serverKey); 137 | 138 | if (!serverKey.length()) 139 | { 140 | if (this->fn) 141 | { 142 | this->fn(ERROR_GENERATE_KEY, nullptr, 0); 143 | return false; 144 | } 145 | } 146 | 147 | this->client->setTimeout(3); 148 | 149 | // connect to remote server 150 | if (!this->client->connect(this->host.c_str(), this->port)) 151 | { 152 | // connect failed 153 | this->status = TCP_FAILED; 154 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "connect failed"); 155 | if (this->fn) 156 | this->fn(TCP_FAILED, nullptr, 0); 157 | return false; 158 | } 159 | else 160 | { 161 | // connected to remote server 162 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "connected"); 163 | this->client->setNoDelay(1); 164 | this->status = TCP_CONNECTED; 165 | 166 | // write handshake header 167 | uint64_t wroteLen = this->client->print(header); 168 | this->client->flush(); 169 | 170 | if (wroteLen != header.length()) 171 | { 172 | this->status = TCP_ERROR; 173 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "error when send handshake header to server"); 174 | if (this->fn) 175 | this->fn(WS_DISCONNECTED, nullptr, 0); 176 | return false; 177 | } 178 | 179 | while (!this->client->available()) 180 | { 181 | yield(); 182 | } 183 | 184 | // read server response 185 | uint64_t len = this->client->read(this->buffer, MY_WEBSOCKET_BUFFER_LENGTH); 186 | if (len > 0) 187 | { 188 | // add string end 189 | this->buffer[len] = 0; 190 | 191 | // convert to arduino String is more convenient 192 | String handShakeStr = String((char *)this->buffer); 193 | 194 | // check if there has and tail 195 | if (handShakeStr.indexOf("\r\n\r\n") >= 0) 196 | { 197 | // get the server key 198 | int keyStart = handShakeStr.indexOf("Sec-WebSocket-Accept: ") + 22; 199 | int keyEnd = handShakeStr.indexOf("\r\n", keyStart); 200 | String key = handShakeStr.substring(keyStart, keyEnd); 201 | if (key == serverKey && 202 | handShakeStr.indexOf("Upgrade: websocket") >= 0 && 203 | handShakeStr.indexOf("Connection: Upgrade") >= 0 && 204 | handShakeStr.indexOf("HTTP/1.1 101") >= 0) 205 | { 206 | bzero(this->buffer, MY_WEBSOCKET_BUFFER_LENGTH); 207 | this->status = WS_CONNECTED; 208 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "websocket client connected"); 209 | if (this->fn) 210 | this->fn(WS_CONNECTED, nullptr, 0); 211 | return true; 212 | } 213 | else 214 | { 215 | // according to standard should disconnect socket 216 | this->client->stop(); 217 | this->status = HANDSHAKE_UNKNOWN_ERROR; 218 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "handshake failed, response header:(%s)", this->buffer); 219 | if (this->fn) 220 | this->fn(HANDSHAKE_UNKNOWN_ERROR, nullptr, 0); 221 | return false; 222 | } 223 | } 224 | else 225 | { 226 | this->client->stop(); 227 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "handshake failed, response header:(%s)", this->buffer); 228 | this->status = HANDSHAKE_UNKNOWN_ERROR; 229 | if (this->fn) 230 | this->fn(HANDSHAKE_UNKNOWN_ERROR, nullptr, 0); 231 | return false; 232 | } 233 | } 234 | else 235 | { 236 | this->status = TCP_ERROR; 237 | if (this->fn) 238 | this->fn(TCP_ERROR, nullptr, 0); 239 | return false; 240 | } 241 | } 242 | } 243 | 244 | uint64_t WebSocketClient::send(const char *data) 245 | { 246 | uint64_t len = strlen(data); 247 | uint8_t *d = (uint8_t *)malloc(len); 248 | if (!d) 249 | { 250 | return 0; 251 | } 252 | memcpy(d, data, len); 253 | uint64_t r = this->_send(TYPE_TEXT, d, strlen(data)); 254 | free(d); 255 | return r; 256 | } 257 | 258 | uint64_t WebSocketClient::_send(WebSocketEvents type, uint8_t *data, uint64_t len) 259 | { 260 | if (!data || !len) 261 | { 262 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "empty content to send"); 263 | return 0; 264 | } 265 | 266 | uint8_t mask[4]; 267 | for (int i = 0; i < 4; i++) 268 | { 269 | mask[i] = random(0xff); 270 | } 271 | 272 | // frame header 273 | uint8_t header[10]; 274 | bzero(header, 10); 275 | 276 | // fin 277 | header[0] = header[0] | (uint8_t)128; 278 | 279 | // mask 280 | header[1] = this->isFromServer ? 0 : ((uint8_t)128); 281 | 282 | // fill frame type 283 | switch (type) 284 | { 285 | case TYPE_TEXT: 286 | header[0] |= (uint8_t)1; 287 | break; 288 | case TYPE_BIN: 289 | header[0] |= (uint8_t)2; 290 | break; 291 | case TYPE_CLOSE: 292 | header[0] |= (uint8_t)8; 293 | break; 294 | case TYPE_PING: 295 | header[0] |= (uint8_t)9; 296 | break; 297 | case TYPE_PONG: 298 | header[0] |= (uint8_t)10; 299 | break; 300 | default: 301 | return 0; 302 | } 303 | 304 | // convert length and send it to server 305 | if (len < 126) 306 | { 307 | header[1] = header[1] | (uint8_t)len; 308 | this->client->write((const char *)header, 2); 309 | } 310 | else if (len > 125 && len < 65536) 311 | { 312 | header[1] = header[1] | (uint8_t)126; 313 | uint16_t msgLen = (uint16_t)len; 314 | header[2] = (uint8_t)(msgLen >> 8); 315 | header[3] = (uint8_t)((msgLen << 8) >> 8); 316 | this->client->write((const char *)header, 4); 317 | } 318 | else 319 | { 320 | header[1] = header[1] | (uint8_t)127; 321 | uint64_t msgLen = len; 322 | for (int i = 0, j = 2; i < 8; i++, j++) 323 | { 324 | header[j] = (uint8_t)(((msgLen) << (i * 8)) >> 56); 325 | } 326 | this->client->write((const char *)header, 10); 327 | } 328 | 329 | // masking 330 | if (!this->isFromServer) 331 | { 332 | for (uint64_t i = 0; i < len; i++) 333 | { 334 | yield(); 335 | data[i] = data[i] ^ mask[i & 3]; 336 | yield(); 337 | } 338 | } 339 | 340 | // send mask byte 341 | if (!this->isFromServer) 342 | { 343 | this->client->write((const char *)mask, 4); 344 | } 345 | 346 | // send data 347 | return this->client->write((const char *)data, len); 348 | } 349 | 350 | void WebSocketClient::loop() 351 | { 352 | 353 | if (this->status == WS_CONNECTED) 354 | { 355 | if (!this->client->connected()) 356 | { 357 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "connection lost"); 358 | 359 | // maual disconnect 360 | this->client->stop(); 361 | 362 | // set statue 363 | this->status = WS_DISCONNECTED; 364 | 365 | // call callback 366 | if (this->fn) 367 | this->fn(WS_DISCONNECTED, nullptr, 0); 368 | 369 | return; 370 | } 371 | 372 | // read frame header 373 | uint64_t len = this->client->read(this->buffer, 2); 374 | 375 | if (!len) // no msg 376 | { 377 | return; 378 | } 379 | 380 | if (len < 0) // socket error 381 | { 382 | this->client->stop(); 383 | 384 | // set statue and call callback 385 | this->status = TCP_ERROR; 386 | if (this->fn) 387 | this->fn(TCP_ERROR, nullptr, 0); 388 | 389 | return; 390 | } 391 | 392 | // msg arived 393 | bool isThisFrameisFin = this->buffer[0] & (uint8_t)128; 394 | 395 | // last frame 396 | WebSocketEvents type; 397 | uint8_t opcode = this->buffer[0] & (uint8_t)15; 398 | switch (opcode) 399 | { 400 | case 0: 401 | type = TYPE_CON; 402 | break; 403 | case 1: 404 | type = TYPE_TEXT; 405 | break; 406 | case 2: 407 | type = TYPE_BIN; 408 | break; 409 | case 9: 410 | type = TYPE_PING; 411 | break; 412 | case 10: 413 | type = TYPE_PONG; 414 | break; 415 | case 8: 416 | type = TYPE_CLOSE; 417 | default: 418 | type = TYPE_UNKNOWN; 419 | this->client->stop(); 420 | this->status = WS_DISCONNECTED; 421 | if (this->fn) 422 | this->fn(WS_DISCONNECTED, nullptr, 0); 423 | return; 424 | } 425 | 426 | // get real length type 427 | uint64_t length = (uint64_t)(this->buffer[1] & (uint8_t)(127)); 428 | 429 | // marked if recv buffer has been deleted by user 430 | this->isRecvBufferHasBeenDeleted = false; 431 | 432 | // declare buffer pointer 433 | uint8_t *buf = nullptr; 434 | uint8_t maskBytes[4]; 435 | 436 | // read real length 437 | if (length > 125) 438 | { 439 | // read real length 440 | bzero(this->buffer, MY_WEBSOCKET_BUFFER_LENGTH); 441 | 442 | // 126: payload length > 125 && payload length < 65536 443 | // 127: > 65535 444 | uint8_t extraPayloadBytes = length == 126 ? 2 : 8; 445 | length = 0; 446 | 447 | // read real length bytes 448 | this->client->read(this->buffer, extraPayloadBytes); 449 | 450 | extraPayloadBytes -= 1; 451 | 452 | // convert to uint64_t 453 | // for front byte 454 | for (uint8_t i = 0; i < extraPayloadBytes; i++) 455 | { 456 | length += this->buffer[i]; 457 | length = length << 8; 458 | } 459 | // for last byte 460 | length += this->buffer[extraPayloadBytes]; 461 | 462 | // see if beyond max length 463 | if (extraPayloadBytes > MY_WEBSOCKET_CLIENT_MAX_PAYLOAD_LENGTH) 464 | { 465 | this->status = MAX_PAYLOAD_EXCEED; 466 | if (this->fn) 467 | this->fn(MAX_PAYLOAD_EXCEED, nullptr, 0); 468 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "MAX_PAYLOAD_EXCEED"); 469 | return; 470 | } 471 | } 472 | 473 | // define another length for optimze unmask process 474 | uint64_t bufferLength = length; 475 | 476 | // length +1 for text type end of string 477 | if (type == TYPE_TEXT && isThisFrameisFin) 478 | { 479 | // for '\0' if there isn't '\0' at tail 480 | bufferLength += 1; 481 | } 482 | 483 | // for optimize unmask process 484 | bufferLength += 4 - (bufferLength % 4); 485 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "optimized length:%d", bufferLength); 486 | 487 | // if length overflow it will be 0(though it won't happen forever on esp32 because of limited RAM size) 488 | if (!bufferLength || this->accBufferOffset + length > MY_WEBSOCKET_CLIENT_MAX_PAYLOAD_LENGTH) 489 | { 490 | this->status = MAX_PAYLOAD_EXCEED; 491 | if (this->fn) 492 | this->fn(MAX_PAYLOAD_EXCEED, nullptr, 0); 493 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "MAX_PAYLOAD_EXCEED"); 494 | return; 495 | } 496 | 497 | // allocate buffer 498 | buf = new (std::nothrow) uint8_t[bufferLength]; 499 | 500 | // check buffer allocate success or not 501 | if (buf == nullptr) 502 | { 503 | this->status = BUFFER_ALLOC_FAILED; 504 | if (this->fn) 505 | this->fn(BUFFER_ALLOC_FAILED, nullptr, 0); 506 | return; 507 | } 508 | 509 | // if this client is transfer from server 510 | // that means 4 bytes mask key should read at first 511 | if (this->isFromServer) 512 | { 513 | this->client->read(maskBytes, 4); 514 | } 515 | 516 | // otherwise this client is directly connected to remote 517 | // no mask key should read 518 | uint64_t readLength = this->client->read(buf, length); 519 | 520 | // read times 521 | int times = 0; 522 | 523 | // single read times 524 | int segmentLength = 0; 525 | 526 | // read data 527 | while (readLength < length && ++times < READ_MAX_TIMES) 528 | { 529 | while (!this->client->available()) 530 | { 531 | yield(); 532 | delay(1); 533 | } 534 | 535 | // read more data 536 | segmentLength = this->client->read(buf + readLength, length - readLength); 537 | 538 | // no more data to read 539 | if (!segmentLength) 540 | { 541 | break; 542 | } 543 | 544 | // accumulate read length 545 | readLength += segmentLength; 546 | 547 | // reset single time read length 548 | segmentLength = 0; 549 | 550 | if (times > READ_MAX_TIMES) 551 | { 552 | if (buf) 553 | delete buf; 554 | 555 | this->client->stop(); 556 | this->status = REACH_MAX_READ_TIMES; 557 | 558 | if (this->fn) 559 | this->fn(REACH_MAX_READ_TIMES, nullptr, 0); 560 | 561 | return; 562 | } 563 | } 564 | 565 | if (readLength == length) 566 | { 567 | // correct data length 568 | if (this->isFromServer) 569 | { 570 | // unmask 571 | // this will consume 2200us if length type is uint64_t with 240MHz cpu config 572 | // data size 64KB, AP mode 573 | for (uint64_t i = 0; i ^ bufferLength; i += 4) 574 | { 575 | buf[i] = buf[i] ^ maskBytes[i & 3]; 576 | buf[(i + 1)] = buf[(i + 1)] ^ maskBytes[(i + 1) & 3]; 577 | buf[(i + 2)] = buf[(i + 2)] ^ maskBytes[(i + 2) & 3]; 578 | buf[(i + 3)] = buf[(i + 3)] ^ maskBytes[(i + 3) & 3]; 579 | } 580 | 581 | // set extra tail zero 582 | memset(buf + length, 0, bufferLength - length); 583 | } 584 | 585 | // copy data to extra buffer if this frame isn't last frame 586 | // otherwise call callback 587 | if (isThisFrameisFin) 588 | { 589 | // call handler 590 | if (this->accBufferOffset) 591 | { 592 | // copy last chunk 593 | memcpy(this->accBuffer + this->accBufferOffset, buf, length); 594 | this->accBufferOffset += length; 595 | 596 | if (this->fn) 597 | this->fn(type, this->accBuffer, this->accBufferOffset); 598 | 599 | if (!this->isRecvBufferHasBeenDeleted) 600 | { 601 | delete this->accBuffer; 602 | } 603 | this->accBufferOffset = 0; 604 | } 605 | else 606 | { 607 | if (this->fn) 608 | this->fn(type, buf, length); 609 | } 610 | } 611 | else 612 | { 613 | // define extra buffer 614 | if (!this->accBufferOffset) 615 | { 616 | this->accBuffer = new (std::nothrow) uint8_t[MY_WEBSOCKET_CLIENT_MAX_PAYLOAD_LENGTH]; 617 | 618 | // check extra buffer allocate state 619 | if (!(this->accBuffer)) 620 | { 621 | if (buf != nullptr) 622 | { 623 | delete buf; 624 | } 625 | 626 | this->status = BUFFER_ALLOC_FAILED; 627 | if (this->fn) 628 | this->fn(BUFFER_ALLOC_FAILED, nullptr, 0); 629 | 630 | return; 631 | } 632 | } 633 | 634 | // copy original buffer 635 | memcpy(this->accBuffer + this->accBufferOffset, buf, length); 636 | 637 | // accumulate extra buffer offset 638 | this->accBufferOffset += length; 639 | } 640 | } 641 | else 642 | { 643 | this->client->stop(); 644 | this->status = TCP_ERROR; 645 | if (this->fn) 646 | this->fn(TCP_ERROR, nullptr, 0); 647 | } 648 | 649 | if (!(this->isRecvBufferHasBeenDeleted)) 650 | { 651 | if (buf) 652 | { 653 | delete buf; 654 | } 655 | } 656 | } 657 | else 658 | { 659 | // disconnected 660 | if (this->autoReconnect && !this->isFromServer) 661 | { 662 | if (millis() - this->lastConnectTime > this->connectTimeout) 663 | { 664 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "reconnecting..."); 665 | this->lastConnectTime = millis(); 666 | this->handShake(); 667 | } 668 | } 669 | } 670 | } 671 | 672 | bool CombinedServer::begin(uint16_t port) 673 | { 674 | this->server = new WiFiServer(port, 100); 675 | this->server->setNoDelay(true); 676 | this->server->begin(); 677 | return true; 678 | } 679 | 680 | int CombinedServer::isWebSocketClientArrayHasFreeSapce() 681 | { 682 | for (int i = 0; i < MAX_CLIENTS; i++) 683 | { 684 | if (nullptr == this->webSocketClients[i]) 685 | { 686 | return i; 687 | break; 688 | } 689 | } 690 | return -1; 691 | } 692 | 693 | int CombinedServer::isHttpClientArrayHasFreeSpace() 694 | { 695 | for (int i = 0; i < MAX_CLIENTS; i++) 696 | { 697 | if (nullptr == this->clients[i]) 698 | { 699 | return i; 700 | break; 701 | } 702 | } 703 | return -1; 704 | } 705 | 706 | void CombinedServer::newWebSocketClientHandShanke(ExtendedWiFiClient *client, String request, int index) 707 | { 708 | // websocket 709 | int keyStart = request.indexOf("Sec-WebSocket-Key: "); // + 19; 710 | if (keyStart < 0) 711 | { 712 | // client->print("HTTP/1.1 403\r\n\r\n"); 713 | // client->flush(); 714 | client->stop(); 715 | delete client; 716 | return; 717 | } 718 | 719 | // length of "Sec-WebSocket-Key: " 720 | keyStart += 19; 721 | 722 | // to generate server key 723 | String clientKey = request.substring(keyStart, request.indexOf("\r\n", keyStart)); 724 | 725 | String serverKey = clientKey + String("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); 726 | serverKey = generateServerKey(serverKey); 727 | 728 | if (!serverKey.length()) 729 | { 730 | if (this->fn) 731 | { 732 | this->fn(nullptr, ERROR_GENERATE_KEY, nullptr, 0); 733 | client->stop(); 734 | delete client; 735 | return; 736 | } 737 | } 738 | 739 | String response = "HTTP/1.1 101 Switching Protocols\r\n"; 740 | response += "Connection: upgrade\r\n"; 741 | response += "Upgrade: websocket\r\n"; 742 | response += "Content-Length: 0\r\n"; 743 | response += "Sec-WebSocket-Accept: " + serverKey + "\r\n\r\n"; 744 | 745 | // give response to client 746 | client->print(response); 747 | client->flush(); 748 | 749 | // transfer to a object of WebSocketClient 750 | WebSocketClient *webSocketClient = new WebSocketClient(client); 751 | 752 | // set callback 753 | webSocketClient->setCallBack( 754 | [this, webSocketClient](WebSocketEvents type, uint8_t *payload, uint64_t length) 755 | { 756 | // here don't process any events 757 | // all events will push to callback 758 | if (this->fn) 759 | this->fn(webSocketClient, type, payload, length); 760 | }); 761 | 762 | // push websocket client into queue 763 | this->webSocketClients[index] = webSocketClient; 764 | } 765 | 766 | int CombinedServer::findHttpCallback(String path) 767 | { 768 | if (this->nonWebSocketRequests.size() <= 0) 769 | { 770 | return -1; 771 | } 772 | 773 | for (int i = 0; i < this->nonWebSocketRequests.size(); i++) 774 | { 775 | if (path == this->nonWebSocketRequests.at(i)->path) 776 | { 777 | return i; 778 | } 779 | } 780 | return -1; 781 | } 782 | 783 | void CombinedServer::httpHandler(ExtendedWiFiClient *client, String *request) 784 | { 785 | // from http handshake 786 | if (request != nullptr) 787 | { 788 | if (request->length() > 0) 789 | { 790 | HttpMethod method; 791 | int pathStart = request->indexOf("GET ", 0); // + 4; 792 | 793 | if (pathStart < 0) 794 | { 795 | pathStart = request->indexOf("POST ", 0); // + 5; 796 | if (pathStart < 0) 797 | { 798 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "can not find path of http request"); 799 | return; 800 | } 801 | pathStart += 5; 802 | method = POST; 803 | } 804 | else 805 | { 806 | pathStart += 4; 807 | method = GET; 808 | } 809 | 810 | int pathEnd = request->indexOf(" HTTP", pathStart); 811 | 812 | if (pathStart >= pathEnd) 813 | { 814 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "can not find path of http request"); 815 | return; 816 | } 817 | 818 | // get path 819 | String path = request->substring(pathStart, pathEnd); 820 | 821 | if (path.length()) 822 | { 823 | // find GET process callback 824 | int index = this->findHttpCallback(path); 825 | 826 | if (index >= 0) 827 | { 828 | if (this->autoFillHttpResponseHeader) 829 | { 830 | // fill header 831 | String res = "HTTP/1.1 " + String(this->nonWebSocketRequests.at(index)->code ? this->nonWebSocketRequests.at(index)->code : 200) + " OK\r\n"; 832 | res += "Content-Type: " + this->nonWebSocketRequests.at(index)->mimeType + "\r\n"; 833 | res += "Connection: keep-alive\r\n"; 834 | res += "Transfer-Encoding: chunked\r\n\r\n"; 835 | client->print(res); 836 | } 837 | 838 | if (this->nonWebSocketRequests.at(index)->fn) 839 | this->nonWebSocketRequests.at(index)->fn(client, method, (uint8_t *)request, request->length()); 840 | } 841 | else 842 | { 843 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "no http handler mathced: %s", path.c_str()); 844 | client->print("HTTP/1.1 404\r\n"); 845 | client->print("Connection: close\r\n"); 846 | client->print("Content-Type: text/plain\r\n"); 847 | client->print("Content-Length: 3\r\n\r\n404"); 848 | client->flush(); 849 | client->stop(); 850 | } 851 | } 852 | else 853 | { 854 | client->stop(); 855 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "empty http request path"); 856 | } 857 | return; 858 | } 859 | else 860 | { 861 | client->stop(); 862 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "request is empty"); 863 | } 864 | } 865 | 866 | // from loop 867 | if (this->publicPostHandler == nullptr) 868 | { 869 | return; 870 | } 871 | 872 | uint8_t *data = new (std::nothrow) uint8_t[MY_WEBSOCKET_HTTP_POST_LENGTH]; 873 | 874 | if (!data) 875 | { 876 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "memory full"); 877 | 878 | if (this->fn) 879 | this->fn(nullptr, BUFFER_ALLOC_FAILED, nullptr, 0); 880 | } 881 | 882 | long len = client->read(data, MY_WEBSOCKET_HTTP_POST_LENGTH); 883 | 884 | if (len < 0) 885 | { 886 | // socket error 887 | client->stop(); 888 | if (this->fn) 889 | this->fn(nullptr, TCP_ERROR, nullptr, 0); 890 | } 891 | else 892 | { 893 | // empty content 894 | return; 895 | } 896 | 897 | try 898 | { 899 | this->publicPostHandler->fn(client, NO_METHOD, data, len); 900 | } 901 | catch (std::exception &e) 902 | { 903 | delete data; 904 | data = nullptr; 905 | } 906 | 907 | if (data != nullptr) 908 | { 909 | delete data; 910 | } 911 | } 912 | 913 | void CombinedServer::loop() 914 | { 915 | if (this->server->hasClient()) 916 | { 917 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "A new client connected"); 918 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "Free Heap: %d", ESP.getFreeHeap()); 919 | 920 | // get client 921 | WiFiClient newClient = this->server->available(); 922 | 923 | // store fd 924 | ExtendedWiFiClient *client = new ExtendedWiFiClient(newClient); 925 | client->setNoDelay(true); 926 | 927 | // for process request data 928 | String request = ""; 929 | 930 | if (client->available()) 931 | { 932 | // read to uint8_t buffer is faster than arduino String 933 | bzero(this->headerBuffer, MY_WEBSOCKET_MAX_HEADER_LENGTH); 934 | int len = client->read(this->headerBuffer, MY_WEBSOCKET_MAX_HEADER_LENGTH); 935 | if (len < 0) 936 | { 937 | client->stop(); 938 | delete client; 939 | 940 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "error when read request header"); 941 | if (this->fn) 942 | this->fn(nullptr, TCP_ERROR, nullptr, 0); 943 | 944 | return; 945 | } 946 | 947 | if (len >= MY_WEBSOCKET_MAX_HEADER_LENGTH) 948 | { 949 | client->stop(); 950 | delete client; 951 | 952 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "request header length beyond max length"); 953 | 954 | if (this->fn) 955 | this->fn(nullptr, MAX_HEADER_LENGTH_EXCEED, nullptr, 0); 956 | 957 | return; 958 | } 959 | 960 | this->headerBuffer[len++] = 0; 961 | 962 | // convert to arduino String 963 | request = String((char *)this->headerBuffer); 964 | 965 | memset(this->headerBuffer + len, 0xff, MY_WEBSOCKET_MAX_HEADER_LENGTH - len); 966 | } 967 | else 968 | { 969 | return; 970 | } 971 | 972 | if (request.length() > 0) 973 | { 974 | if (request.indexOf("\r\n\r\n") >= 0) 975 | { 976 | if ( 977 | request.indexOf("Connection: Upgrade") >= 0 && 978 | request.indexOf("Upgrade: websocket") >= 0 && 979 | request.indexOf("Sec-WebSocket-Key") >= 0) 980 | { 981 | // websocket request 982 | int index = this->isWebSocketClientArrayHasFreeSapce(); 983 | if (index < 0) 984 | { 985 | // queue full 986 | client->print("HTTP/1.1 404\r\nError: queue-full\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"); 987 | client->flush(); 988 | client->stop(); 989 | delete client; 990 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "websocket queue full"); 991 | } 992 | else 993 | { 994 | // process websocket request 995 | this->newWebSocketClientHandShanke(client, request, index); 996 | } 997 | } 998 | else 999 | { 1000 | // http request 1001 | int index = this->isHttpClientArrayHasFreeSpace(); 1002 | if (index >= 0) 1003 | { 1004 | this->clients[index] = client; 1005 | this->httpHandler(client, &request); 1006 | } 1007 | else 1008 | { 1009 | client->print("HTTP/1.1 404\r\nError: queue-full\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"); 1010 | client->flush(); 1011 | client->stop(); 1012 | delete client; 1013 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "http queue full"); 1014 | } 1015 | } 1016 | } 1017 | } 1018 | } 1019 | 1020 | // loop websocket clients 1021 | WebSocketClient *loopClient = nullptr; 1022 | 1023 | // loop http clients 1024 | ExtendedWiFiClient *extendedclient = nullptr; 1025 | for (int i = 0; i < MAX_CLIENTS; i++) 1026 | { 1027 | // websocket 1028 | loopClient = this->webSocketClients[i]; 1029 | if (nullptr != loopClient) 1030 | { 1031 | if (loopClient->connected()) 1032 | { 1033 | if (loopClient->available()) 1034 | { 1035 | loopClient->loop(); 1036 | } 1037 | } 1038 | else 1039 | { 1040 | delete loopClient; 1041 | this->webSocketClients[i] = nullptr; 1042 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "A websocket client disconnected"); 1043 | } 1044 | } 1045 | 1046 | // others 1047 | extendedclient = this->clients[i]; 1048 | if (nullptr != extendedclient) 1049 | { 1050 | if (extendedclient->connected()) 1051 | { 1052 | if (extendedclient->available()) 1053 | { 1054 | this->httpHandler(extendedclient, nullptr); 1055 | } 1056 | } 1057 | else 1058 | { 1059 | delete extendedclient; 1060 | this->clients[i] = nullptr; 1061 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "A client disconnected"); 1062 | } 1063 | } 1064 | } 1065 | } 1066 | 1067 | void CombinedServer::on(const char *path, NonWebScoketCallback fn, const char *mimeType, int statusCode, bool cover) 1068 | { 1069 | HttpCallback *cb = new HttpCallback(); 1070 | cb->path = String(path); 1071 | cb->code = statusCode; 1072 | cb->mimeType = String(mimeType); 1073 | cb->fn = fn; 1074 | 1075 | if (cb->path.isEmpty() || !fn) 1076 | { 1077 | delete cb; 1078 | ESP_LOGD(MY_WEBSOCKET_DEBUG_HEADER, "invalid path or callback for request"); 1079 | return; 1080 | } 1081 | 1082 | bool stored = false; 1083 | for ( 1084 | std::vector::iterator it = this->nonWebSocketRequests.begin(); 1085 | it != this->nonWebSocketRequests.end(); 1086 | it++) 1087 | { 1088 | if ((*it)->path == cb->path) 1089 | { 1090 | if (cover) 1091 | { 1092 | (*it)->fn = fn; 1093 | delete cb; 1094 | break; 1095 | } 1096 | else 1097 | { 1098 | delete (*it); 1099 | this->nonWebSocketRequests.push_back(cb); 1100 | break; 1101 | } 1102 | stored = true; 1103 | } 1104 | } 1105 | 1106 | if (!stored) 1107 | { 1108 | this->nonWebSocketRequests.push_back(cb); 1109 | } 1110 | } 1111 | 1112 | CombinedServer::~CombinedServer() 1113 | { 1114 | // do some clean process 1115 | 1116 | // delete header buffer 1117 | if (this->headerBuffer != nullptr) 1118 | { 1119 | delete this->headerBuffer; 1120 | } 1121 | 1122 | // delete post handler 1123 | if (this->publicPostHandler != nullptr) 1124 | { 1125 | delete this->publicPostHandler; 1126 | } 1127 | 1128 | // delete http callbacks 1129 | if (this->nonWebSocketRequests.size() > 0) 1130 | { 1131 | for (int i = 0; i < this->nonWebSocketRequests.size(); i++) 1132 | { 1133 | delete this->nonWebSocketRequests.at(i); 1134 | } 1135 | } 1136 | 1137 | // stop all clients and delete them 1138 | for (int i = 0; i < MAX_CLIENTS; i++) 1139 | { 1140 | if (nullptr != this->clients[i]) 1141 | { 1142 | this->clients[i]->stop(); 1143 | delete this->clients[i]; 1144 | } 1145 | if (nullptr != this->webSocketClients[i]) 1146 | { 1147 | this->webSocketClients[i]->stop(); 1148 | delete this->webSocketClients[i]; 1149 | } 1150 | } 1151 | 1152 | // release vector memory 1153 | std::vector().swap(this->nonWebSocketRequests); 1154 | } 1155 | }; 1156 | -------------------------------------------------------------------------------- /mywebsocket/mywebsocket.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file mywebsocket.h 3 | * @author Vida Wang (support@vida.wang) 4 | * @brief 5 | * 6 | * This is a small websocket server/client and http server component. 7 | * Fast speed, no memory leak. 8 | * Designed for ESP32 work with offical framework arduino-esp32 version 2.0.3. 9 | * Websocket client/server don't support wss. 10 | * 11 | * I'm not a native English speaker, so there may have many errors of words or grammar in comments, my apologies. 12 | * 13 | * 这是一个小型websocket客户端/服务器和http服务器组件。 14 | * 快速无内存泄漏。 15 | * 为ESP32设计,可与乐鑫官方arduino-esp32库2.0.3版本一同使用。 16 | * 不支持wss。 17 | * 18 | * @version 1.0.5 19 | * @date 2022-07-30 20 | * 21 | * @copyright Copyright (c) 2022 22 | * 23 | */ 24 | 25 | #ifndef MY_WEBSOCKET_H_ 26 | #define MY_WEBSOCKET_H_ 27 | 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include "../mycrypto/mycrypto.h" 33 | #include 34 | 35 | #define myWebSocketHeader "GET @PATH@ HTTP/1.1\r\nHost: @HOST@\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nCache-Control: no-cache\r\nUpgrade: websocket\r\nSec-WebSocket-Key: @KEY@\r\n\r\n" 36 | 37 | #define DEBUG_MYCRYPTO 1 38 | 39 | #define READ_MAX_TIMES 100 40 | 41 | // maximum payload length of websocket 42 | // websocket消息最大长度 43 | #define MY_WEBSOCKET_CLIENT_MAX_PAYLOAD_LENGTH 102400 44 | 45 | // buffer length for websocket handshake 46 | // 握手缓冲区长度 47 | #define MY_WEBSOCKET_BUFFER_LENGTH 1024 48 | 49 | // http post body length 50 | // http post body长度 51 | #define MY_WEBSOCKET_HTTP_POST_LENGTH 1024 52 | 53 | // http header length 54 | // http头最大长度 55 | #define MY_WEBSOCKET_MAX_HEADER_LENGTH 1024 56 | 57 | // client length 58 | // 最大客户端数量 59 | #define MAX_CLIENTS 10 60 | 61 | #define MY_WEBSOCKET_DEBUG_HEADER "myWebsocket" 62 | 63 | namespace myWebSocket 64 | { 65 | /** 66 | * @brief generate keys for hankshake 67 | * 为握手生成密匙 68 | * 69 | * @param clientKey client key 客户端密匙 70 | * @return server key 服务器密匙 71 | */ 72 | String generateServerKey(String clientKey); 73 | 74 | /** 75 | * @brief put all types together for one callback handle all events 76 | * 把所有的类型放在一起,这样可以用一个回调函数解决一切 77 | */ 78 | typedef enum 79 | { 80 | TCP_CONNECTED = 0xfe, // tcp connection established tcp连接已建立 81 | TCP_TIMEOUT = 0xfd, // tcp connect timeout tcp连接超时 82 | TCP_FAILED = 0xfc, // tcp connect failed tcp连接失败 83 | WS_CONNECTED = 0xfb, // websocket connected websocket连接已建立 84 | WS_DISCONNECTED = 0xa8, // websocket disconnected websocket连接已断开 85 | TCP_ERROR = 0xf8, // tcp connection error tcp连接错误 86 | HANDSHAKE_UNKNOWN_ERROR = 0xf7, // unknown error when handshake 握手时出现未知错误 87 | MAX_PAYLOAD_EXCEED = 0xf6, // data length exceeded 数据超出最大长度 88 | BUFFER_ALLOC_FAILED = 0xf5, // buffer allocate failed 缓冲区分配失败 89 | MAX_HEADER_LENGTH_EXCEED = 0xf4, // length of http header exceeded http头长度超出最大长度 90 | REACH_MAX_READ_TIMES = 0xae, // reach maximum retry count 超过最大重试次数 91 | ERROR_GENERATE_KEY = 0xac, // error when generate key 生成密匙时发生错误 92 | 93 | // the following types for websocket data frame 94 | // 下面的类型是websocket数据帧类型 95 | 96 | TYPE_CON = 0x00, // extra data frame 附加数据帧 97 | TYPE_TEXT = 0x01, // text frame 文本数据帧 98 | TYPE_BIN = 0x02, // binary frame 二进制数据帧 99 | TYPE_CLOSE = 0x08, // close frame 关闭连接数据帧 100 | TYPE_PING = 0x09, // ping frame ping数据帧 101 | TYPE_PONG = 0x0a, // pong frame pong数据帧 102 | TYPE_UNKNOWN = 0xff // reserved 保留位 103 | } WebSocketEvents; 104 | 105 | /** 106 | * @brief add some functions to WiFiClient 107 | * 给WiFiClient添加几个函数 108 | */ 109 | class ExtendedWiFiClient : public WiFiClient 110 | { 111 | public: 112 | inline ExtendedWiFiClient() {} 113 | inline ExtendedWiFiClient(const WiFiClient &externalClient) : WiFiClient(externalClient) {} 114 | inline ~ExtendedWiFiClient() {} 115 | 116 | // 117 | 118 | /** 119 | * @brief this is for default method with "Transfer-Encoding: chunked" 120 | * 默认的分段发送数据函数 121 | * 122 | * @param content data to send, pointer of class String object 123 | * 需要发送的数据,一个String类的对象的指针 124 | * @return bytes had been sent 已发送的数据的字节数 125 | */ 126 | inline uint64_t send(String *content) 127 | { 128 | if (!content) 129 | return 0; 130 | if (!content->length()) 131 | return 0; 132 | String *res = new String(content->c_str()); 133 | *res = String(res->length(), HEX) + "\r\n" + *res + "\r\n"; 134 | size_t len = 0; 135 | try 136 | { 137 | len = this->print(*res); 138 | } 139 | catch (std::exception &e) 140 | { 141 | } 142 | 143 | delete res; 144 | return len; 145 | } 146 | 147 | /** 148 | * @brief this is for default method with "Transfer-Encoding: chunked" 149 | * 默认的分段发送数据函数 150 | * 151 | * @param content data to send, c string, c字符串 152 | * 需要发送的数据,c字符串 153 | * @return bytes had been sent 已发送的数据的字节数 154 | */ 155 | inline uint64_t send(const char *content) 156 | { 157 | if (!content) 158 | return 0; 159 | String *res = new String(content); 160 | auto len = this->send(res); 161 | delete res; 162 | return len; 163 | } 164 | 165 | /** 166 | * @brief send zero block and close socket 167 | * 发送结束数据块然后断开socket 168 | */ 169 | inline void close() 170 | { 171 | this->print("0\r\n\r\n"); 172 | this->flush(); 173 | this->stop(); 174 | } 175 | }; 176 | 177 | /** 178 | * @brief websocket client message callback 179 | * websocket 客户端消息回调函数 180 | */ 181 | typedef std::function WebSocketMessageCallback; 182 | 183 | class WebSocketClient 184 | { 185 | private: 186 | /** 187 | * @brief websocket server host name 188 | * websocket服务器主机 189 | */ 190 | String host = ""; 191 | 192 | /** 193 | * @brief id set by user for other purpose 194 | * 用户设置的用于其他用途的id 195 | */ 196 | int id = -1; 197 | 198 | /** 199 | * @brief websocket server port 200 | * websocket服务器端口 201 | */ 202 | uint16_t port = 80; 203 | 204 | /** 205 | * @brief websocket request path 206 | * websocket请求路径 207 | */ 208 | String path = "/"; 209 | 210 | /** 211 | * @brief for handshake websocket握手 212 | * 213 | * @return true 握手成功 214 | * @return false 握手失败 215 | */ 216 | bool handShake(); 217 | 218 | /** 219 | * @brief host, port, and path for handshake 220 | * 主机名、端口、路径用于握手 221 | */ 222 | String domain = ""; 223 | 224 | /** 225 | * @brief websocket message callback 226 | * websocket消息回调函数 227 | */ 228 | WebSocketMessageCallback fn = nullptr; 229 | 230 | /** 231 | * @brief for basic tcp connection 232 | * 建立底层tcp连接 233 | */ 234 | ExtendedWiFiClient *client = new ExtendedWiFiClient(); 235 | 236 | /** 237 | * @brief consecutive frame buffer 238 | * 连续帧缓冲区 239 | */ 240 | uint8_t *accBuffer = nullptr; 241 | 242 | /** 243 | * @brief offset of consecutive frame buffer 244 | * 连续帧缓冲区偏移量 245 | */ 246 | uint64_t accBufferOffset = 0; 247 | 248 | /** 249 | * @brief reconnect after connection lost or not 250 | * 是否在断开连接后自动重连 251 | */ 252 | bool autoReconnect = true; 253 | 254 | /** 255 | * @brief recv buffer has been deleted by user or not 256 | * 接收缓冲区是否被用户主动释放 257 | */ 258 | bool isRecvBufferHasBeenDeleted = false; 259 | 260 | /** 261 | * @brief to record last connect time 262 | * 记录上次尝试连接的时间 263 | */ 264 | uint64_t lastConnectTime = 0; 265 | 266 | /** 267 | * @brief a timeout when websocket disconnected from server and reconnect 268 | * 当websocket与服务器丢失连接之后多久再次重新尝试连接 269 | */ 270 | uint64_t connectTimeout = 5000; 271 | 272 | /** 273 | * @brief buffer for handshake 274 | * websocket 握手缓冲区 275 | */ 276 | uint8_t *buffer = new uint8_t[MY_WEBSOCKET_BUFFER_LENGTH]; 277 | 278 | /** 279 | * @brief a key generated as client key 280 | * 客户端密匙 281 | */ 282 | String clientKey; 283 | 284 | /** 285 | * @brief to generate information for handshake 286 | * 为websocket握手生成需要的数据 287 | * 288 | * @return websocket header for handshake 用于websocket握手的头数据 289 | */ 290 | String generateHanshake(); 291 | 292 | /** 293 | * @brief internal universal send function, send data to server or client, attention attached 294 | * 通用的内部发送数据函数,用于把数据发送到客户端或者服务器,请阅读注意事项 295 | * 296 | * @param type type of websocket frame, websocket数据帧类型 297 | * @param data payload 数据 298 | * @param len length of payload 数据长度 299 | * @return how many data have been sent in bytes 发送了多少字节数据 300 | * 301 | * @attention the data stored in pointer "data" will be changed because of the masking process 302 | * (when act as a client), you should make a copy before send if you didn't want this function 303 | * mofidy original data 304 | * 305 | * 客户端在发送数据时,存储于指针"data"中的数据会被masking过程修改,如果你还需要使用这些原始数据,你可以在发送数据 306 | * 之前对原始数据创建一份拷贝 307 | */ 308 | uint64_t _send(WebSocketEvents type, uint8_t *data, uint64_t len); 309 | 310 | public: 311 | /** 312 | * @brief to indicate current status of client 313 | * 用于指示当前client的状态 314 | */ 315 | WebSocketEvents status; 316 | 317 | /** 318 | * @brief default constructor 319 | * 默认构造函数 320 | */ 321 | inline WebSocketClient() {} 322 | 323 | // this will be true if this client is transfer from local websocket server 324 | // the client will not reconnect automaticlly if this is true 325 | 326 | /** 327 | * @brief to indicate current object is transfer from local server or not, attention attached 328 | * 用于指示当前对象是否是由本地websocket服务器转换而来,请阅读注意事项 329 | * 330 | * @attention the client won't reconnect automatically if this varible set to true 331 | * 客户端不会自动重新连接如果这个变量被设置为true 332 | */ 333 | bool isFromServer = false; 334 | 335 | // only CombinedServer will call this function 336 | // to transfer the client in 337 | 338 | /** 339 | * @brief a special constructor only for CombinedServer, to transfer client in 340 | * 一个特殊的构造函数仅被CombinedServer类的对象使用,用于传输socket连接 341 | * 342 | * @param client an object of ExtendedWiFiClient(socket) 一个ExtendedWiFiClient的对象(套接字) 343 | */ 344 | inline WebSocketClient(ExtendedWiFiClient *client) 345 | { 346 | if (this->client) 347 | { 348 | try 349 | { 350 | this->client->stop(); 351 | delete this->client; 352 | } 353 | catch (std::exception &e) 354 | { 355 | } 356 | } 357 | this->client = client; 358 | this->isFromServer = true; 359 | this->status = WS_CONNECTED; 360 | this->autoReconnect = false; 361 | } 362 | 363 | /** 364 | * @brief Destroy the Web Socket Client object 365 | * 析构函数 366 | */ 367 | inline ~WebSocketClient() 368 | { 369 | // do clean process 370 | // 执行清理 371 | delete this->buffer; 372 | if (this->client != nullptr) 373 | { 374 | delete this->client; 375 | } 376 | } 377 | 378 | /** 379 | * @brief to check socket if available 380 | * 查看套接字是否连接正常 381 | * 382 | * @return true connected 正常 383 | * @return false disconnected or others 断开或其他 384 | */ 385 | inline bool available() 386 | { 387 | return this->client->available(); 388 | } 389 | 390 | /** 391 | * @brief to check socket if available(only a name different from available) 392 | * 查看套接字是否连接正常(只是名字和available不一样) 393 | * 394 | * @return true connected 正常 395 | * @return false disconnected or others 断开或其他 396 | */ 397 | inline uint8_t connected() 398 | { 399 | return this->client->connected(); 400 | } 401 | 402 | /** 403 | * @brief connect to remote server, error code will transfered in if callback has been set 404 | * or if error occurred when connecting, you could check status manually 405 | * 连接到远程服务器,如果设置了回调函数,如果在连接中发生了错误,回调函数会被执行,错误代码会被传送到回调函数的 406 | * "type" 407 | * 408 | * @param host host name 主机名 409 | * @param port port of server 主机端口号 410 | * @param path path of websocket, websocket路径 411 | * @return true connected 已连接 412 | * @return false error when connecting 连接时发生错误 413 | */ 414 | inline bool connect(String host, uint16_t port, String path = "/") 415 | { 416 | this->host = host; 417 | this->port = port; 418 | this->path = path; 419 | this->status = WS_DISCONNECTED; 420 | return this->handShake(); 421 | } 422 | 423 | /** 424 | * @brief connect to remote server, error code will transfered in if callback has been set 425 | * or if error occurred when connecting, you could check status manually 426 | * 连接到远程服务器,如果设置了回调函数,如果在连接中发生了错误,回调函数会被执行,错误代码会被传送到回调函数的 427 | * "type" 428 | * 429 | * @param url full address, examples: 完整的地址,例如: 430 | * ws://abc.com or 431 | * ws://abc.com:8080 or 432 | * ws://abc.com:8080/abc or 433 | * abc.com or 434 | * abc.com:8080 435 | * ... 436 | * 437 | * @return true connected 已连接 438 | * @return false error when connecting 连接时发生错误 439 | */ 440 | bool connect(String url); 441 | 442 | /** 443 | * @brief connect to remote server, error code will transfered in if callback has been set 444 | * or if error occurred when connecting, you could check status manually 445 | * 连接到远程服务器,如果设置了回调函数,如果在连接中发生了错误,回调函数会被执行,错误代码会被传送到回调函数的 446 | * "type" 447 | * 448 | * @param url full address, examples: 完整的地址,例如: 449 | * ws://abc.com or 450 | * ws://abc.com:8080 or 451 | * ws://abc.com:8080/abc or 452 | * abc.com or 453 | * abc.com:8080 454 | * ... 455 | * 456 | * @return true connected 已连接 457 | * @return false error when connecting 连接时发生错误 458 | */ 459 | inline bool connect(const char *url) 460 | { 461 | return this->connect(String(url)); 462 | } 463 | 464 | /** 465 | * @brief connect to remote server, error code will transfered in if callback has been set 466 | * or if error occurred when connecting, you could check status manually 467 | * 连接到远程服务器,如果设置了回调函数,如果在连接中发生了错误,回调函数会被执行,错误代码会被传送到回调函数的 468 | * "type" 469 | * 470 | * @param host host name 主机名 471 | * @param port port of server 主机端口号 472 | * @param path path of websocket, websocket路径 473 | * @return true connected 已连接 474 | * @return false error when connecting 连接时发生错误 475 | */ 476 | inline bool connect(const char *host, uint16_t port, const char *path) 477 | { 478 | return this->connect(String(host), port, String(path)); 479 | } 480 | 481 | /** 482 | * @brief set websocket event callback, include all types of events 483 | * buffer will be set to nullptr and length will be set to 0 if callback 484 | * called because of not a websocket data frame event 485 | * 486 | * 设置websocket的回调函数,包含所有事件的类型,如果回调函数不是因为数据被执行, 487 | * 则buffer会被设置成空指针,长度会被设置成0 488 | * 489 | * @param fn callback 回调函数 490 | */ 491 | inline void setCallBack(WebSocketMessageCallback fn) 492 | { 493 | this->fn = fn; 494 | } 495 | 496 | /** 497 | * @brief main loop of websocket client, websocket客户端的主循环 498 | * 499 | */ 500 | void loop(); 501 | 502 | /** 503 | * @brief mark the buffer that use for contain data from socket has been removed 504 | * by user, attention attached 505 | * 506 | * 标记用于存放从socket接收到数据的缓冲区已经被用于释放,请阅读注意事项 507 | * 508 | * @attention be careful use this function, if you forget delete buffer but this function 509 | * had been called, you will got memory leak 510 | * 511 | * 小心使用这个函数,因为如果你忘记了释放缓冲区而又调用了这个函数,会发生内存泄漏 512 | */ 513 | inline void setRecvBufferDeleted() { this->isRecvBufferHasBeenDeleted = true; } 514 | 515 | /** 516 | * @brief set a special id by user for other purpose 517 | * 由用户设置一个特殊的ID用于其他用途 518 | * 519 | * @param id 520 | */ 521 | inline void setID(int id) { this->id = id; } 522 | 523 | /** 524 | * @brief get id set by user 获取由用户自行设置的id 525 | * 526 | * @return id set by user 用户设置的id 527 | */ 528 | inline int getID() { return this->id; } 529 | 530 | /** 531 | * @brief send a string 发送一个字符串 532 | * 533 | * @param data a pointer to String object 一个指向String类对象的指针 534 | * @return bytes had been sent 已被发送的数据字节数 535 | */ 536 | inline uint64_t send(String *data) 537 | { 538 | return this->send(data->c_str()); 539 | } 540 | 541 | /** 542 | * @brief send a string 发送一个字符串 543 | * 544 | * @param data an object of class String 一个指向String类的对象 545 | * @return bytes had been sent 已被发送的数据字节数 546 | */ 547 | inline uint64_t send(String data) 548 | { 549 | return this->send(data.c_str()); 550 | } 551 | 552 | /** 553 | * @brief send a string 发送一个字符串 554 | * 555 | * @param data c string, c字符串 556 | * @return bytes had been sent 已被发送的数据字节数 557 | */ 558 | uint64_t send(const char *data); 559 | 560 | /** 561 | * @brief send binary data 发送二进制数据 562 | * 563 | * @param data pointer of binary array 二进制数组的指针 564 | * @param length length of binary array 数组长度 565 | * @return bytes had been sent 已被发送的数据字节数 566 | */ 567 | inline uint64_t send(uint8_t *data, uint64_t length) 568 | { 569 | if (!data || !length) 570 | return 0; 571 | return this->_send(TYPE_BIN, data, length); 572 | } 573 | 574 | /** 575 | * @brief send c string as binary type 以二进制数据格式发送c字符串 576 | * 577 | * @param data pointer of c string, c字符串 578 | * @return bytes had been sent 已被发送的数据字节数 579 | */ 580 | inline uint64_t send(char *data) 581 | { 582 | if (!data) 583 | return 0; 584 | 585 | uint32_t length = strlen(data); 586 | 587 | if (!length) 588 | return 0; 589 | return this->_send(TYPE_BIN, (uint8_t *)data, length); 590 | } 591 | 592 | /** 593 | * @brief manual hard disconnect from websocket, attention attached 594 | * 手动强制断开websocket连接,请阅读注意事项 595 | * 596 | * @attention client will NOT reconnect after this function called 597 | * 当此函数被执行后,客户端 [不再] 自动连接 598 | * 599 | */ 600 | inline void stop() 601 | { 602 | this->autoReconnect = false; 603 | this->client->stop(); 604 | } 605 | 606 | /** 607 | * @brief alias of "stop". manual hard disconnect from websocket, attention attached 608 | * "stop"的别名。手动强制断开websocket连接,请阅读注意事项 609 | * 610 | * @attention client will NOT reconnect after this function called 611 | * 当此函数被执行后,客户端 [不再] 自动连接 612 | * 613 | */ 614 | inline void disconnect() 615 | { 616 | this->stop(); 617 | } 618 | 619 | /** 620 | * @brief set client reconnect after connection lost 621 | * 设置客户端是否自动重连 622 | * 623 | * @param autoReconnect true: auto reconnect 自动重连, false: will NOT auto reconnect [不]自动重连 624 | * @param timeout timeout for auto reconnect after connection lost, in milliseconds 625 | * 断开后多久自动重连的超时时间,以毫秒计 626 | */ 627 | inline void setAutoReconnect(bool autoReconnect = true, uint64_t timeout = 5000) 628 | { 629 | this->autoReconnect = autoReconnect; 630 | this->connectTimeout = timeout; 631 | } 632 | }; 633 | 634 | /** 635 | * @brief currently support get and post 636 | * 目前支持get和post 637 | */ 638 | typedef enum 639 | { 640 | GET, 641 | POST, 642 | NO_METHOD, 643 | OTHERS 644 | } HttpMethod; 645 | 646 | // for universal websocket server message callback 647 | // 通用的websocket服务器消息回调函数 648 | typedef std::function WebSocketServerCallback; 649 | 650 | // for http handler 651 | // http请求回调函数 652 | typedef std::function NonWebScoketCallback; 653 | 654 | /** 655 | * @brief http callback arguments 656 | * http回调函数参数 657 | */ 658 | typedef struct 659 | { 660 | String path; 661 | int code = 0; 662 | String mimeType; 663 | NonWebScoketCallback fn = nullptr; 664 | } HttpCallback; 665 | 666 | /** 667 | * @brief this class handles http and websocket requests 668 | * 这个类处理http和websocket请求 669 | */ 670 | class CombinedServer 671 | { 672 | private: 673 | /** 674 | * @brief http clients 675 | * http客户端 676 | */ 677 | ExtendedWiFiClient *clients[MAX_CLIENTS] = {nullptr}; 678 | 679 | /** 680 | * @brief websocket clients 681 | * websocket客户端 682 | */ 683 | WebSocketClient *webSocketClients[MAX_CLIENTS] = {nullptr}; 684 | 685 | /** 686 | * @brief server request callback 687 | * 服务器请求回调函数 688 | */ 689 | WebSocketServerCallback fn = nullptr; 690 | 691 | /** 692 | * @brief router table 693 | * 路由表 694 | */ 695 | std::vector nonWebSocketRequests; 696 | 697 | /** 698 | * @brief base server object 699 | * 底层服务器 700 | */ 701 | WiFiServer *server = nullptr; 702 | 703 | /** 704 | * @brief public post handler 705 | * 公用的post请求处理器 706 | */ 707 | HttpCallback *publicPostHandler = nullptr; 708 | 709 | /** 710 | * @brief mark if should fill http header or not 711 | * if this set to true you should only provide main content of html/js/css... 712 | * otherwise you could process raw data in callback edit your own response header 713 | * 714 | * 如果这个变量设置为true,那么你只需要提供响应的主要内容 715 | * 否则你需要自己构造http头 716 | */ 717 | bool autoFillHttpResponseHeader = true; 718 | 719 | // buffer for http request header 720 | // http请求头缓冲区 721 | uint8_t *headerBuffer = new uint8_t[MY_WEBSOCKET_MAX_HEADER_LENGTH]; 722 | 723 | /** 724 | * @brief check if there have free space in websocket clients queue 725 | * 查找websocket客户端队列是否有空余位置 726 | * 727 | * @return index of free space 空余的位置, -1 == full 返回 -1 则队列已满 728 | */ 729 | int isWebSocketClientArrayHasFreeSapce(); 730 | 731 | /** 732 | * @brief check if there have free space in http clients queue 733 | * 查找http客户端队列是否有空余位置 734 | * 735 | * @return index of free space 空余的位置, -1 == full 返回 -1 则队列已满 736 | */ 737 | int isHttpClientArrayHasFreeSpace(); 738 | 739 | /** 740 | * @brief find http callback for http request path 741 | * 查找对应请求路径的http处理函数 742 | * 743 | * @param path path of http request http请求的路径 744 | * @return index of callback 处理函数的position, -1 == nothing 返回 -1 代表没有对应路径的处理函数 745 | */ 746 | int findHttpCallback(String path); 747 | 748 | /** 749 | * @brief http handler http请求处理函数 750 | * 751 | * @param client socket 套接字 752 | * @param request http request header, http请求头 753 | */ 754 | void httpHandler(ExtendedWiFiClient *client, String *request); 755 | 756 | /** 757 | * @brief a client require upgrade to websocket protocols 758 | * 客户端请求升级到websocket连接 759 | * 760 | * @param client socket 套接字 761 | * @param request request header 请求头 762 | * @param index position of queue in websocket queue, websocket队列空余的位置 763 | */ 764 | void newWebSocketClientHandShanke(ExtendedWiFiClient *client, String request, int index); 765 | 766 | public: 767 | inline CombinedServer() {} 768 | ~CombinedServer(); 769 | 770 | /** 771 | * @brief set universal server callback 772 | * 设置通用服务器回调函数 773 | * 774 | * @param fn callback 回调函数 775 | */ 776 | inline void setCallback(WebSocketServerCallback fn) 777 | { 778 | this->fn = fn; 779 | } 780 | 781 | // 782 | // 783 | 784 | /** 785 | * @brief set whether to automatically fill header 786 | * if you'd like process raw data then you should call 787 | * this function at first and provide false in argument 788 | * 789 | * 设置是否自动填充http头 790 | * 如果你想自己处理http头你应该先调用此函数且提供false为参数 791 | * 792 | * @param autoFill true: fill http header automatically 793 | * 自动填充http头, 794 | * false: will not fill http header 795 | * 不会自动填充http头 796 | */ 797 | inline void setAutoFillHttpResponseHeader(bool autoFill) 798 | { 799 | this->autoFillHttpResponseHeader = autoFill; 800 | } 801 | 802 | /** 803 | * @brief set process handler for http request 804 | * 设置http请求处理函数 805 | * 806 | * @param path path of http request, http请求路径 807 | * @param fn callback 回调函数 808 | * @param mimeType mime type 源类型 809 | * @param statusCode http status code, http响应状态码 810 | * @param cover cover former callback or not 是否覆盖之前的回调函数 811 | */ 812 | void on(const char *path, 813 | NonWebScoketCallback fn, 814 | const char *mimeType = "text/html;charset=utf-8", 815 | int statusCode = 200, 816 | bool cover = true); 817 | 818 | /** 819 | * @brief set process handler for http request 820 | * 设置http请求处理函数 821 | * 822 | * @param path path of http request, http请求路径 823 | * @param fn callback 回调函数 824 | * @param mimeType mime type 源类型 825 | * @param statusCode http status code, http响应状态码 826 | * @param cover cover former callback or not 是否覆盖之前的回调函数 827 | */ 828 | inline void on(String path, 829 | NonWebScoketCallback fn, 830 | String mimeType = "text/html;charset=utf-8", 831 | int statusCode = 200, 832 | bool cover = true) 833 | { 834 | this->on(path.c_str(), fn, mimeType.c_str(), cover); 835 | } 836 | 837 | /** 838 | * @brief set public http post request handler 839 | * 设置公用的http post请求处理回调函数,这个功能我没用过 840 | * 841 | * @param fn callback 回调函数 842 | */ 843 | inline void setPublicPostHandler(NonWebScoketCallback fn) 844 | { 845 | if (!fn) 846 | return; 847 | 848 | if (this->publicPostHandler != nullptr) 849 | { 850 | delete this->publicPostHandler; 851 | } 852 | this->publicPostHandler = new HttpCallback(); 853 | this->publicPostHandler->path = ""; 854 | this->publicPostHandler->fn = fn; 855 | } 856 | 857 | /** 858 | * @brief start server 开启服务器 859 | * 860 | * @param port port of server 服务器端口 861 | * @return true 862 | */ 863 | bool begin(uint16_t port = 80); 864 | 865 | /** 866 | * @brief main loop of server 服务器主循环 867 | * 868 | */ 869 | void loop(); 870 | }; 871 | } // namespace myWebSocket 872 | 873 | #endif 874 | --------------------------------------------------------------------------------