WebSerial.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. #include "WebSerial.h"
  2. #include "wslp.h"
  3. #include <assert.h>
  4. // DO NOT change magic bytes
  5. #define WSL_MAGIC_BYTE_1 0xAB
  6. #define WSL_MAGIC_BYTE_2 0xCD
  7. #define WSL_LOG_PACKET_HEADER_SIZE 14
  8. #define WSL_CALC_LOG_PACKET_SIZE(len) (WSL_LOG_PACKET_HEADER_SIZE + len)
  9. typedef enum {
  10. WSL_WRITE_ROW = 0x01,
  11. WSL_MESSAGE = 0x02,
  12. WSL_PING = 0x03,
  13. WSL_PONG = 0x04,
  14. } WSLPacketType;
  15. static const uint8_t WSL_PONG_MSG[] = {WSL_MAGIC_BYTE_1, WSL_MAGIC_BYTE_2, WSLPacketType::WSL_PONG};
  16. static const size_t WSL_PONG_MSG_LEN = sizeof(WSL_PONG_MSG) / sizeof(WSL_PONG_MSG[0]);
  17. static const uint8_t WSL_HEAD[] = {
  18. WSL_MAGIC_BYTE_1, // Magic Bytes
  19. WSL_MAGIC_BYTE_2, // Magic Bytes
  20. WSLPacketType::WSL_WRITE_ROW, // Packet Type (1 byte)
  21. 0x00, // Reserved
  22. 0x00, // Reserved
  23. 0x00, // Reserved
  24. 0x00, // Reserved
  25. 0x00, // Padding
  26. 0x00, // Padding
  27. 0x00, // Padding
  28. 0x00, // Padding
  29. 0x00 // Reserved
  30. };
  31. static const size_t WSL_HEAD_LEN = sizeof(WSL_HEAD) / sizeof(WSL_HEAD[0]);
  32. static const size_t WSL_MSG_SIZE_LEN = sizeof(uint16_t);
  33. void WebSerialClass::setAuthentication(const String& username, const String& password){
  34. _username = username;
  35. _password = password;
  36. _authenticate = !_username.isEmpty() && !_password.isEmpty();
  37. if (_ws != nullptr) {
  38. _ws->setAuthentication(_username.c_str(), _password.c_str());
  39. }
  40. }
  41. void WebSerialClass::begin(AsyncWebServer *server, const char* url) {
  42. _server = server;
  43. _ws = new AsyncWebSocket("/wserial");
  44. if (_authenticate) {
  45. _ws->setAuthentication(_username.c_str(), _password.c_str());
  46. }
  47. // Webpage Handler
  48. _server->on(url, HTTP_GET, [&](AsyncWebServerRequest *request){
  49. if(_authenticate){
  50. if(!request->authenticate(_username.c_str(), _password.c_str()))
  51. return request->requestAuthentication();
  52. }
  53. AsyncWebServerResponse *response = request->beginResponse(200, "text/html", WEBSERIAL_HTML, sizeof(WEBSERIAL_HTML));
  54. response->addHeader("Content-Encoding", "gzip");
  55. request->send(response);
  56. });
  57. // WS Handler
  58. _ws->onEvent([&](__unused AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, __unused void * arg, uint8_t *data, __unused size_t len) -> void {
  59. // if(type == WS_EVT_CONNECT){
  60. // } else if(type == WS_EVT_DISCONNECT){
  61. // } else if(type == WS_EVT_DATA){
  62. if (type == WS_EVT_CONNECT) {
  63. client->setCloseClientOnQueueFull(false);
  64. return;
  65. }
  66. if(type == WS_EVT_DATA){
  67. // Detect magic bytes
  68. if (data[0] == WSL_MAGIC_BYTE_1 && data[1] == WSL_MAGIC_BYTE_2) {
  69. if (data[2] == WSLPacketType::WSL_MESSAGE) {
  70. // Parse message size (uint16_t)
  71. size_t message_size = (data[4] << 8) | data[3];
  72. // Issue callback
  73. if(_recv != nullptr){
  74. _recv(data + 5, message_size);
  75. }
  76. } else if (data[2] == WSLPacketType::WSL_PING) {
  77. // Send pong
  78. client->binary(WSL_PONG_MSG, WSL_PONG_MSG_LEN);
  79. }
  80. }
  81. }
  82. });
  83. // Attach AsyncWebServer with Websockets
  84. _server->addHandler(_ws);
  85. }
  86. // onMessage Callback Handler
  87. void WebSerialClass::onMessage(WSLMessageHandler recv) {
  88. _recv = recv;
  89. }
  90. void WebSerialClass::onMessage(WSLStringMessageHandler callback) {
  91. _recvString = callback;
  92. _recv = [&](uint8_t *data, size_t len) {
  93. if(data && len) {
  94. String msg;
  95. msg.reserve(len);
  96. msg.concat((char*)data, len);
  97. _recvString(msg);
  98. }
  99. };
  100. }
  101. // Print func
  102. size_t WebSerialClass::write(uint8_t m) {
  103. if (!_ws)
  104. return 0;
  105. #ifdef WSL_HIGH_PERF
  106. // We do not support non-buffered write on webserial for the HIGH_PERF version
  107. // we fail with a stack trace allowing the user to change the code to use write(const uint8_t* buffer, size_t size) instead
  108. if(!_initialBufferCapacity) {
  109. #ifdef ESP8266
  110. ets_printf("Non-buffered write is not supported. Please use write(const uint8_t* buffer, size_t size) instead.");
  111. #else
  112. log_e("Non-buffered write is not supported. Please use write(const uint8_t* buffer, size_t size) instead.");
  113. #endif
  114. assert(false);
  115. return 0;
  116. }
  117. #endif // WSL_HIGH_PERF
  118. write(&m, 1);
  119. return(1);
  120. }
  121. // Println / Printf / Write func
  122. size_t WebSerialClass::write(const uint8_t* buffer, size_t size) {
  123. if (!_ws || size == 0)
  124. return 0;
  125. #ifdef WSL_HIGH_PERF
  126. // No buffer, send directly (i.e. use case for log streaming)
  127. if (!_initialBufferCapacity) {
  128. size = buffer[size - 1] == '\n' ? size - 1 : size;
  129. _send(buffer, size);
  130. return size;
  131. }
  132. // fill the buffer while sending data for each EOL
  133. size_t start = 0, end = 0;
  134. while (end < size) {
  135. if (buffer[end] == '\n') {
  136. if (end > start) {
  137. _buffer.concat(reinterpret_cast<const char*>(buffer + start), end - start);
  138. }
  139. _send(reinterpret_cast<const uint8_t*>(_buffer.c_str()), _buffer.length());
  140. start = end + 1;
  141. }
  142. end++;
  143. }
  144. if (end > start) {
  145. _buffer.concat(reinterpret_cast<const char*>(buffer + start), end - start);
  146. }
  147. return size;
  148. #else
  149. loop();
  150. if (_print_buffer_offset + size > WSL_PRINT_BUFFER_SIZE) {
  151. // Flush print buffer if full
  152. _flush_print_buffer();
  153. }
  154. memcpy(_print_buffer + _print_buffer_offset, buffer, size);
  155. _print_buffer_offset += size;
  156. _last_print_buffer_write_time = micros();
  157. return(size);
  158. #endif
  159. }
  160. #ifdef WSL_HIGH_PERF
  161. void WebSerialClass::_send(const uint8_t* buffer, size_t size) {
  162. if (_ws && size > 0) {
  163. _ws->cleanupClients(WSL_MAX_WS_CLIENTS);
  164. if (_ws->count()) {
  165. if (size > UINT16_MAX)
  166. size = UINT16_MAX;
  167. AsyncWebSocketMessageBuffer* wsbuffer = _ws->makeBuffer(WSL_HEAD_LEN + WSL_MSG_SIZE_LEN + size);
  168. _write_row_packet(wsbuffer->get(), buffer, size);
  169. _ws->binaryAll(wsbuffer);
  170. }
  171. }
  172. // if buffer grew too much, free it, otherwise clear it
  173. if (_initialBufferCapacity) {
  174. if (_buffer.length() > _initialBufferCapacity) {
  175. setBuffer(_initialBufferCapacity);
  176. } else {
  177. _buffer.clear();
  178. }
  179. }
  180. }
  181. #else // WSL_HIGH_PERF
  182. bool WebSerialClass::_has_enough_space(size_t size) {
  183. // Check if total packet size exceeds buffer limit
  184. return (_buffer_offset + WSL_CALC_LOG_PACKET_SIZE(size) > WSL_BUFFER_SIZE);
  185. }
  186. size_t WebSerialClass::_write_row(uint8_t *data, size_t len) {
  187. // Split the logData into multiple packets
  188. size_t remaining_size = len;
  189. uint8_t* current_ptr = data;
  190. while (remaining_size > 0) {
  191. size_t packet_size = (remaining_size > WSL_MAX_ROW_PACKET_PAYLOAD_SIZE) ? WSL_MAX_ROW_PACKET_PAYLOAD_SIZE : remaining_size;
  192. // Clear if buffer is full
  193. if (!_has_enough_space(packet_size)) {
  194. _flush_global_buffer();
  195. }
  196. // Write Packet to Buffer
  197. _buffer_offset += _write_row_packet(_buffer, current_ptr, packet_size);
  198. // Set remaining size
  199. remaining_size -= packet_size;
  200. current_ptr += packet_size;
  201. }
  202. return len;
  203. }
  204. void WebSerialClass::_flush_print_buffer() {
  205. if (_print_buffer_offset > 0) {
  206. if (_buffer_offset + _print_buffer_offset > WSL_BUFFER_SIZE) {
  207. // Flush global buffer to websocket
  208. _flush_global_buffer();
  209. }
  210. // Flush print to global buffer and create a packet
  211. _write_row(_print_buffer, _print_buffer_offset);
  212. _print_buffer_offset = 0;
  213. _last_print_buffer_flush_time = millis();
  214. }
  215. }
  216. void WebSerialClass::_flush_global_buffer() {
  217. if (_buffer_offset > 0) {
  218. // Flush buffer to websocket
  219. _ws->binaryAll(_buffer, _buffer_offset);
  220. // Reset buffer offset
  221. _buffer_offset = 0;
  222. }
  223. }
  224. #endif // WSL_HIGH_PERF
  225. void WebSerialClass::loop() {
  226. #ifndef WSL_HIGH_PERF
  227. if ((unsigned long)(millis() - _last_cleanup_time) > WSL_CLEANUP_TIME_MS) {
  228. _last_cleanup_time = millis();
  229. _ws->cleanupClients(WSL_MAX_WS_CLIENTS);
  230. }
  231. // If FLUSH_TIME ms has been passed since last packet time, flush logs
  232. if (_last_print_buffer_write_time != 0) {
  233. if ((unsigned long)(micros() - _last_print_buffer_write_time) > WSL_PRINT_FLUSH_TIME_US) {
  234. _flush_print_buffer();
  235. }
  236. }
  237. // If FLUSH_TIME ms has been passed since last flush time, flush logs
  238. if (_last_print_buffer_flush_time != 0) {
  239. if ((unsigned long)(millis() - _last_print_buffer_flush_time) > WSL_GLOBAL_FLUSH_TIME_MS) {
  240. _flush_global_buffer();
  241. }
  242. }
  243. #endif // WSL_HIGH_PERF
  244. }
  245. void WebSerialClass::setBuffer(size_t initialCapacity) {
  246. #ifdef WSL_HIGH_PERF
  247. assert(initialCapacity <= UINT16_MAX);
  248. _initialBufferCapacity = initialCapacity;
  249. _buffer = String();
  250. _buffer.reserve(initialCapacity);
  251. #endif
  252. }
  253. size_t WebSerialClass::_write_row_packet(uint8_t* dest, const uint8_t *payload, size_t payload_size) {
  254. // sanity check to ensure the payload size is within the hard limit
  255. if(payload_size > UINT16_MAX)
  256. payload_size = UINT16_MAX;
  257. // Write header
  258. memmove(dest, WSL_HEAD, WSL_HEAD_LEN);
  259. // Message Length (2 bytes)
  260. memset(dest + WSL_HEAD_LEN, static_cast<uint16_t>(payload_size), WSL_MSG_SIZE_LEN);
  261. // Set Message
  262. memmove(dest + WSL_HEAD_LEN + WSL_MSG_SIZE_LEN, payload, payload_size);
  263. // Return total packet size
  264. return WSL_HEAD_LEN + WSL_MSG_SIZE_LEN + payload_size;
  265. }
  266. WebSerialClass WebSerial;