ESP32 HTTPS Server
WebsocketHandler.hpp
1 #ifndef SRC_WEBSOCKETHANDLER_HPP_
2 #define SRC_WEBSOCKETHANDLER_HPP_
3 
4 #include <Arduino.h>
5 #include <lwip/def.h>
6 
7 #include <string>
8 #undef min
9 #undef max
10 
11 #include <sstream>
12 
13 #include "HTTPSServerConstants.hpp"
14 #include "ConnectionContext.hpp"
15 #include "WebsocketInputStreambuf.hpp"
16 
17 namespace httpsserver {
18 
19 // Structure definition for the WebSocket frame.
21 {
22  // Byte 0
23  uint8_t opCode : 4; // [7:4]
24  uint8_t rsv3 : 1; // [3]
25  uint8_t rsv2 : 1; // [2]
26  uint8_t rsv1 : 1; // [1]
27  uint8_t fin : 1; // [0]
28 
29  // Byte 1
30  uint8_t len : 7; // [7:1]
31  uint8_t mask : 1; // [0]
32 };
33 
35 {
36 public:
37  // WebSocket op codes as found in a WebSocket frame.
38  static const int OPCODE_CONTINUE = 0x00;
39  static const int OPCODE_TEXT = 0x01;
40  static const int OPCODE_BINARY = 0x02;
41  static const int OPCODE_CLOSE = 0x08;
42  static const int OPCODE_PING = 0x09;
43  static const int OPCODE_PONG = 0x0a;
44 
45  static const uint16_t CLOSE_NORMAL_CLOSURE = 1000;
46  static const uint16_t CLOSE_GOING_AWAY = 1001;
47  static const uint16_t CLOSE_PROTOCOL_ERROR = 1002;
48  static const uint16_t CLOSE_CANNOT_ACCEPT = 1003;
49  static const uint16_t CLOSE_NO_STATUS_CODE = 1005;
50  static const uint16_t CLOSE_CLOSED_ABNORMALLY = 1006;
51  static const uint16_t CLOSE_NOT_CONSISTENT = 1007;
52  static const uint16_t CLOSE_VIOLATED_POLICY = 1008;
53  static const uint16_t CLOSE_TOO_BIG = 1009;
54  static const uint16_t CLOSE_NO_EXTENSION = 1010;
55  static const uint16_t CLOSE_UNEXPECTED_CONDITION = 1011;
56  static const uint16_t CLOSE_SERVICE_RESTART = 1012;
57  static const uint16_t CLOSE_TRY_AGAIN_LATER = 1013;
58  static const uint16_t CLOSE_TLS_HANDSHAKE_FAILURE = 1015;
59 
60  static const uint8_t SEND_TYPE_BINARY = 0x01;
61  static const uint8_t SEND_TYPE_TEXT = 0x02;
62 
64  virtual ~WebsocketHandler();
65  virtual void onClose();
66  virtual void onMessage(WebsocketInputStreambuf *pWebsocketInputStreambuf);
67  virtual void onError(std::string error);
68 
69  void close(uint16_t status = CLOSE_NORMAL_CLOSURE, std::string message = "");
70  void send(std::string data, uint8_t sendType = SEND_TYPE_BINARY);
71  void send(uint8_t *data, uint16_t length, uint8_t sendType = SEND_TYPE_BINARY);
72  bool closed();
73 
74  void loop();
75  void initialize(ConnectionContext * con);
76 
77 private:
78  int read();
79 
80  ConnectionContext * _con;
81  bool _receivedClose; // True when we have received a close request.
82  bool _sentClose; // True when we have sent a close request.
83 };
84 
85 }
86 
87 #endif
Definition: WebsocketHandler.hpp:20
Definition: WebsocketHandler.hpp:34
Definition: WebsocketInputStreambuf.hpp:21
Internal class to handle the state of a connection.
Definition: ConnectionContext.hpp:18
Definition: ConnectionContext.cpp:3