WebSerial.cpp 10 KB

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