esp_websocket_client.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdio.h>
  7. #include "esp_websocket_client.h"
  8. #include "esp_transport.h"
  9. #include "esp_transport_tcp.h"
  10. #include "esp_transport_ssl.h"
  11. #include "esp_transport_ws.h"
  12. /* using uri parser */
  13. #include "http_parser.h"
  14. #include "freertos/task.h"
  15. #include "freertos/semphr.h"
  16. #include "freertos/queue.h"
  17. #include "freertos/event_groups.h"
  18. #include "esp_log.h"
  19. #include "esp_timer.h"
  20. static const char *TAG = "WEBSOCKET_CLIENT";
  21. #define WEBSOCKET_TCP_DEFAULT_PORT (80)
  22. #define WEBSOCKET_SSL_DEFAULT_PORT (443)
  23. #define WEBSOCKET_BUFFER_SIZE_BYTE (1024)
  24. #define WEBSOCKET_RECONNECT_TIMEOUT_MS (10*1000)
  25. #define WEBSOCKET_TASK_PRIORITY (5)
  26. #define WEBSOCKET_TASK_STACK (4*1024)
  27. #define WEBSOCKET_NETWORK_TIMEOUT_MS (10*1000)
  28. #define WEBSOCKET_PING_INTERVAL_SEC (10)
  29. #define WEBSOCKET_EVENT_QUEUE_SIZE (1)
  30. #define WEBSOCKET_PINGPONG_TIMEOUT_SEC (120)
  31. #define WEBSOCKET_KEEP_ALIVE_IDLE (5)
  32. #define WEBSOCKET_KEEP_ALIVE_INTERVAL (5)
  33. #define WEBSOCKET_KEEP_ALIVE_COUNT (3)
  34. #define ESP_WS_CLIENT_MEM_CHECK(TAG, a, action) if (!(a)) { \
  35. ESP_LOGE(TAG,"%s(%d): %s", __FUNCTION__, __LINE__, "Memory exhausted"); \
  36. action; \
  37. }
  38. #define ESP_WS_CLIENT_ERR_OK_CHECK(TAG, err, action) { \
  39. esp_err_t _esp_ws_err_to_check = err; \
  40. if (_esp_ws_err_to_check != ESP_OK) { \
  41. ESP_LOGE(TAG,"%s(%d): Expected ESP_OK; reported: %d", __FUNCTION__, __LINE__, _esp_ws_err_to_check); \
  42. action; \
  43. } \
  44. }
  45. #define ESP_WS_CLIENT_STATE_CHECK(TAG, a, action) if ((a->state) < WEBSOCKET_STATE_INIT) { \
  46. ESP_LOGE(TAG,"%s(%d): %s", __FUNCTION__, __LINE__, "Websocket already stop"); \
  47. action; \
  48. }
  49. const static int STOPPED_BIT = BIT0;
  50. const static int CLOSE_FRAME_SENT_BIT = BIT1; // Indicates that a close frame was sent by the client
  51. // and we are waiting for the server to continue with clean close
  52. ESP_EVENT_DEFINE_BASE(WEBSOCKET_EVENTS);
  53. typedef struct {
  54. int task_stack;
  55. int task_prio;
  56. char *uri;
  57. char *host;
  58. char *path;
  59. char *scheme;
  60. char *username;
  61. char *password;
  62. int port;
  63. bool auto_reconnect;
  64. void *user_context;
  65. int network_timeout_ms;
  66. char *subprotocol;
  67. char *user_agent;
  68. char *headers;
  69. int pingpong_timeout_sec;
  70. size_t ping_interval_sec;
  71. } websocket_config_storage_t;
  72. typedef enum {
  73. WEBSOCKET_STATE_ERROR = -1,
  74. WEBSOCKET_STATE_UNKNOW = 0,
  75. WEBSOCKET_STATE_INIT,
  76. WEBSOCKET_STATE_CONNECTED,
  77. WEBSOCKET_STATE_WAIT_TIMEOUT,
  78. WEBSOCKET_STATE_CLOSING,
  79. } websocket_client_state_t;
  80. struct esp_websocket_client {
  81. esp_event_loop_handle_t event_handle;
  82. TaskHandle_t task_handle;
  83. esp_transport_list_handle_t transport_list;
  84. esp_transport_handle_t transport;
  85. websocket_config_storage_t *config;
  86. websocket_client_state_t state;
  87. uint64_t keepalive_tick_ms;
  88. uint64_t reconnect_tick_ms;
  89. uint64_t ping_tick_ms;
  90. uint64_t pingpong_tick_ms;
  91. int wait_timeout_ms;
  92. int auto_reconnect;
  93. bool run;
  94. bool wait_for_pong_resp;
  95. EventGroupHandle_t status_bits;
  96. SemaphoreHandle_t lock;
  97. char *rx_buffer;
  98. char *tx_buffer;
  99. int buffer_size;
  100. ws_transport_opcodes_t last_opcode;
  101. int payload_len;
  102. int payload_offset;
  103. esp_transport_keep_alive_t keep_alive_cfg;
  104. struct ifreq *if_name;
  105. };
  106. static uint64_t _tick_get_ms(void)
  107. {
  108. return esp_timer_get_time()/1000;
  109. }
  110. static esp_err_t esp_websocket_client_dispatch_event(esp_websocket_client_handle_t client,
  111. esp_websocket_event_id_t event,
  112. const char *data,
  113. int data_len)
  114. {
  115. esp_err_t err;
  116. esp_websocket_event_data_t event_data;
  117. event_data.client = client;
  118. event_data.user_context = client->config->user_context;
  119. event_data.data_ptr = data;
  120. event_data.data_len = data_len;
  121. event_data.op_code = client->last_opcode;
  122. event_data.payload_len = client->payload_len;
  123. event_data.payload_offset = client->payload_offset;
  124. if ((err = esp_event_post_to(client->event_handle,
  125. WEBSOCKET_EVENTS, event,
  126. &event_data,
  127. sizeof(esp_websocket_event_data_t),
  128. portMAX_DELAY)) != ESP_OK) {
  129. return err;
  130. }
  131. return esp_event_loop_run(client->event_handle, 0);
  132. }
  133. static esp_err_t esp_websocket_client_abort_connection(esp_websocket_client_handle_t client)
  134. {
  135. ESP_WS_CLIENT_STATE_CHECK(TAG, client, return ESP_FAIL);
  136. esp_transport_close(client->transport);
  137. if (client->config->auto_reconnect) {
  138. client->reconnect_tick_ms = _tick_get_ms();
  139. ESP_LOGI(TAG, "Reconnect after %d ms", client->wait_timeout_ms);
  140. }
  141. client->state = WEBSOCKET_STATE_WAIT_TIMEOUT;
  142. esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_DISCONNECTED, NULL, 0);
  143. return ESP_OK;
  144. }
  145. static esp_err_t esp_websocket_client_set_config(esp_websocket_client_handle_t client, const esp_websocket_client_config_t *config)
  146. {
  147. websocket_config_storage_t *cfg = client->config;
  148. cfg->task_prio = config->task_prio;
  149. if (cfg->task_prio <= 0) {
  150. cfg->task_prio = WEBSOCKET_TASK_PRIORITY;
  151. }
  152. cfg->task_stack = config->task_stack;
  153. if (cfg->task_stack == 0) {
  154. cfg->task_stack = WEBSOCKET_TASK_STACK;
  155. }
  156. if (config->host) {
  157. cfg->host = strdup(config->host);
  158. ESP_WS_CLIENT_MEM_CHECK(TAG, cfg->host, return ESP_ERR_NO_MEM);
  159. }
  160. if (config->port) {
  161. cfg->port = config->port;
  162. }
  163. if (config->username) {
  164. free(cfg->username);
  165. cfg->username = strdup(config->username);
  166. ESP_WS_CLIENT_MEM_CHECK(TAG, cfg->username, return ESP_ERR_NO_MEM);
  167. }
  168. if (config->password) {
  169. free(cfg->password);
  170. cfg->password = strdup(config->password);
  171. ESP_WS_CLIENT_MEM_CHECK(TAG, cfg->password, return ESP_ERR_NO_MEM);
  172. }
  173. if (config->uri) {
  174. free(cfg->uri);
  175. cfg->uri = strdup(config->uri);
  176. ESP_WS_CLIENT_MEM_CHECK(TAG, cfg->uri, return ESP_ERR_NO_MEM);
  177. }
  178. if (config->path) {
  179. free(cfg->path);
  180. cfg->path = strdup(config->path);
  181. ESP_WS_CLIENT_MEM_CHECK(TAG, cfg->path, return ESP_ERR_NO_MEM);
  182. }
  183. if (config->subprotocol) {
  184. free(cfg->subprotocol);
  185. cfg->subprotocol = strdup(config->subprotocol);
  186. ESP_WS_CLIENT_MEM_CHECK(TAG, cfg->subprotocol, return ESP_ERR_NO_MEM);
  187. }
  188. if (config->user_agent) {
  189. free(cfg->user_agent);
  190. cfg->user_agent = strdup(config->user_agent);
  191. ESP_WS_CLIENT_MEM_CHECK(TAG, cfg->user_agent, return ESP_ERR_NO_MEM);
  192. }
  193. if (config->headers) {
  194. free(cfg->headers);
  195. cfg->headers = strdup(config->headers);
  196. ESP_WS_CLIENT_MEM_CHECK(TAG, cfg->headers, return ESP_ERR_NO_MEM);
  197. }
  198. cfg->user_context = config->user_context;
  199. cfg->auto_reconnect = true;
  200. if (config->disable_auto_reconnect) {
  201. cfg->auto_reconnect = false;
  202. }
  203. if (config->disable_pingpong_discon){
  204. cfg->pingpong_timeout_sec = 0;
  205. } else if (config->pingpong_timeout_sec) {
  206. cfg->pingpong_timeout_sec = config->pingpong_timeout_sec;
  207. } else {
  208. cfg->pingpong_timeout_sec = WEBSOCKET_PINGPONG_TIMEOUT_SEC;
  209. }
  210. if (config->network_timeout_ms <= 0) {
  211. cfg->network_timeout_ms = WEBSOCKET_NETWORK_TIMEOUT_MS;
  212. ESP_LOGW(TAG, "`network_timeout_ms` is not set, or it is less than or equal to zero, using default time out %d (milliseconds)", WEBSOCKET_NETWORK_TIMEOUT_MS);
  213. } else {
  214. cfg->network_timeout_ms = config->network_timeout_ms;
  215. }
  216. if (config->ping_interval_sec == 0) {
  217. cfg->ping_interval_sec = WEBSOCKET_PING_INTERVAL_SEC;
  218. } else {
  219. cfg->ping_interval_sec = config->ping_interval_sec;
  220. }
  221. return ESP_OK;
  222. }
  223. static esp_err_t esp_websocket_client_destroy_config(esp_websocket_client_handle_t client)
  224. {
  225. if (client == NULL) {
  226. return ESP_ERR_INVALID_ARG;
  227. }
  228. websocket_config_storage_t *cfg = client->config;
  229. if (client->config == NULL) {
  230. return ESP_ERR_INVALID_ARG;
  231. }
  232. free(cfg->host);
  233. free(cfg->uri);
  234. free(cfg->path);
  235. free(cfg->scheme);
  236. free(cfg->username);
  237. free(cfg->password);
  238. free(cfg->subprotocol);
  239. free(cfg->user_agent);
  240. free(cfg->headers);
  241. memset(cfg, 0, sizeof(websocket_config_storage_t));
  242. free(client->config);
  243. client->config = NULL;
  244. return ESP_OK;
  245. }
  246. static esp_err_t set_websocket_transport_optional_settings(esp_websocket_client_handle_t client, const char *scheme)
  247. {
  248. esp_transport_handle_t trans = esp_transport_list_get_transport(client->transport_list, scheme);
  249. if (trans) {
  250. const esp_transport_ws_config_t config = {
  251. .ws_path = client->config->path,
  252. .sub_protocol = client->config->subprotocol,
  253. .user_agent = client->config->user_agent,
  254. .headers = client->config->headers,
  255. .propagate_control_frames = true
  256. };
  257. return esp_transport_ws_set_config(trans, &config);
  258. }
  259. return ESP_ERR_INVALID_ARG;
  260. }
  261. esp_websocket_client_handle_t esp_websocket_client_init(const esp_websocket_client_config_t *config)
  262. {
  263. esp_websocket_client_handle_t client = calloc(1, sizeof(struct esp_websocket_client));
  264. ESP_WS_CLIENT_MEM_CHECK(TAG, client, return NULL);
  265. esp_event_loop_args_t event_args = {
  266. .queue_size = WEBSOCKET_EVENT_QUEUE_SIZE,
  267. .task_name = NULL // no task will be created
  268. };
  269. if (esp_event_loop_create(&event_args, &client->event_handle) != ESP_OK) {
  270. ESP_LOGE(TAG, "Error create event handler for websocket client");
  271. free(client);
  272. return NULL;
  273. }
  274. if (config->keep_alive_enable == true) {
  275. client->keep_alive_cfg.keep_alive_enable = true;
  276. client->keep_alive_cfg.keep_alive_idle = (config->keep_alive_idle == 0) ? WEBSOCKET_KEEP_ALIVE_IDLE : config->keep_alive_idle;
  277. client->keep_alive_cfg.keep_alive_interval = (config->keep_alive_interval == 0) ? WEBSOCKET_KEEP_ALIVE_INTERVAL : config->keep_alive_interval;
  278. client->keep_alive_cfg.keep_alive_count = (config->keep_alive_count == 0) ? WEBSOCKET_KEEP_ALIVE_COUNT : config->keep_alive_count;
  279. }
  280. if (config->if_name) {
  281. client->if_name = calloc(1, sizeof(struct ifreq) + 1);
  282. ESP_WS_CLIENT_MEM_CHECK(TAG, client->if_name, goto _websocket_init_fail);
  283. memcpy(client->if_name, config->if_name, sizeof(struct ifreq));
  284. }
  285. client->lock = xSemaphoreCreateRecursiveMutex();
  286. ESP_WS_CLIENT_MEM_CHECK(TAG, client->lock, goto _websocket_init_fail);
  287. client->config = calloc(1, sizeof(websocket_config_storage_t));
  288. ESP_WS_CLIENT_MEM_CHECK(TAG, client->config, goto _websocket_init_fail);
  289. client->transport_list = esp_transport_list_init();
  290. ESP_WS_CLIENT_MEM_CHECK(TAG, client->transport_list, goto _websocket_init_fail);
  291. esp_transport_handle_t tcp = esp_transport_tcp_init();
  292. ESP_WS_CLIENT_MEM_CHECK(TAG, tcp, goto _websocket_init_fail);
  293. esp_transport_set_default_port(tcp, WEBSOCKET_TCP_DEFAULT_PORT);
  294. esp_transport_list_add(client->transport_list, tcp, "_tcp"); // need to save to transport list, for cleanup
  295. esp_transport_tcp_set_keep_alive(tcp, &client->keep_alive_cfg);
  296. esp_transport_tcp_set_interface_name(tcp, client->if_name);
  297. esp_transport_handle_t ws = esp_transport_ws_init(tcp);
  298. ESP_WS_CLIENT_MEM_CHECK(TAG, ws, goto _websocket_init_fail);
  299. esp_transport_set_default_port(ws, WEBSOCKET_TCP_DEFAULT_PORT);
  300. esp_transport_list_add(client->transport_list, ws, "ws");
  301. if (config->transport == WEBSOCKET_TRANSPORT_OVER_TCP) {
  302. asprintf(&client->config->scheme, "ws");
  303. ESP_WS_CLIENT_MEM_CHECK(TAG, client->config->scheme, goto _websocket_init_fail);
  304. }
  305. esp_transport_handle_t ssl = esp_transport_ssl_init();
  306. ESP_WS_CLIENT_MEM_CHECK(TAG, ssl, goto _websocket_init_fail);
  307. esp_transport_set_default_port(ssl, WEBSOCKET_SSL_DEFAULT_PORT);
  308. esp_transport_list_add(client->transport_list, ssl, "_ssl"); // need to save to transport list, for cleanup
  309. if (config->use_global_ca_store == true) {
  310. esp_transport_ssl_enable_global_ca_store(ssl);
  311. } else if (config->cert_pem) {
  312. if (!config->cert_len) {
  313. esp_transport_ssl_set_cert_data(ssl, config->cert_pem, strlen(config->cert_pem));
  314. } else {
  315. esp_transport_ssl_set_cert_data_der(ssl, config->cert_pem, config->cert_len);
  316. }
  317. }
  318. if (config->client_cert) {
  319. if (!config->client_cert_len) {
  320. esp_transport_ssl_set_client_cert_data(ssl, config->client_cert, strlen(config->client_cert));
  321. } else {
  322. esp_transport_ssl_set_client_cert_data_der(ssl, config->client_cert, config->client_cert_len);
  323. }
  324. }
  325. if (config->client_key) {
  326. if (!config->client_key_len) {
  327. esp_transport_ssl_set_client_key_data(ssl, config->client_key, strlen(config->client_key));
  328. } else {
  329. esp_transport_ssl_set_client_key_data_der(ssl, config->client_key, config->client_key_len);
  330. }
  331. }
  332. if (config->skip_cert_common_name_check) {
  333. esp_transport_ssl_skip_common_name_check(ssl);
  334. }
  335. if (config->reconnect_timeout_ms <= 0) {
  336. client->wait_timeout_ms = WEBSOCKET_RECONNECT_TIMEOUT_MS;
  337. ESP_LOGW(TAG, "`reconnect_timeout_ms` is not set, or it is less than or equal to zero, using default time out %d (milliseconds)", WEBSOCKET_RECONNECT_TIMEOUT_MS);
  338. } else {
  339. client->wait_timeout_ms = config->reconnect_timeout_ms;
  340. }
  341. esp_transport_handle_t wss = esp_transport_ws_init(ssl);
  342. ESP_WS_CLIENT_MEM_CHECK(TAG, wss, goto _websocket_init_fail);
  343. esp_transport_set_default_port(wss, WEBSOCKET_SSL_DEFAULT_PORT);
  344. esp_transport_list_add(client->transport_list, wss, "wss");
  345. if (config->transport == WEBSOCKET_TRANSPORT_OVER_SSL) {
  346. asprintf(&client->config->scheme, "wss");
  347. ESP_WS_CLIENT_MEM_CHECK(TAG, client->config->scheme, goto _websocket_init_fail);
  348. }
  349. if (config->uri) {
  350. if (esp_websocket_client_set_uri(client, config->uri) != ESP_OK) {
  351. ESP_LOGE(TAG, "Invalid uri");
  352. goto _websocket_init_fail;
  353. }
  354. }
  355. if (esp_websocket_client_set_config(client, config) != ESP_OK) {
  356. ESP_LOGE(TAG, "Failed to set the configuration");
  357. goto _websocket_init_fail;
  358. }
  359. if (client->config->scheme == NULL) {
  360. asprintf(&client->config->scheme, "ws");
  361. ESP_WS_CLIENT_MEM_CHECK(TAG, client->config->scheme, goto _websocket_init_fail);
  362. }
  363. ESP_WS_CLIENT_ERR_OK_CHECK(TAG, set_websocket_transport_optional_settings(client, "ws"), goto _websocket_init_fail;)
  364. ESP_WS_CLIENT_ERR_OK_CHECK(TAG, set_websocket_transport_optional_settings(client, "wss"), goto _websocket_init_fail;)
  365. client->keepalive_tick_ms = _tick_get_ms();
  366. client->reconnect_tick_ms = _tick_get_ms();
  367. client->ping_tick_ms = _tick_get_ms();
  368. client->wait_for_pong_resp = false;
  369. int buffer_size = config->buffer_size;
  370. if (buffer_size <= 0) {
  371. buffer_size = WEBSOCKET_BUFFER_SIZE_BYTE;
  372. }
  373. client->rx_buffer = malloc(buffer_size);
  374. ESP_WS_CLIENT_MEM_CHECK(TAG, client->rx_buffer, {
  375. goto _websocket_init_fail;
  376. });
  377. client->tx_buffer = malloc(buffer_size);
  378. ESP_WS_CLIENT_MEM_CHECK(TAG, client->tx_buffer, {
  379. goto _websocket_init_fail;
  380. });
  381. client->status_bits = xEventGroupCreate();
  382. ESP_WS_CLIENT_MEM_CHECK(TAG, client->status_bits, {
  383. goto _websocket_init_fail;
  384. });
  385. client->buffer_size = buffer_size;
  386. return client;
  387. _websocket_init_fail:
  388. esp_websocket_client_destroy(client);
  389. return NULL;
  390. }
  391. esp_err_t esp_websocket_client_destroy(esp_websocket_client_handle_t client)
  392. {
  393. if (client == NULL) {
  394. return ESP_ERR_INVALID_ARG;
  395. }
  396. if (client->run) {
  397. esp_websocket_client_stop(client);
  398. }
  399. if (client->event_handle) {
  400. esp_event_loop_delete(client->event_handle);
  401. }
  402. if (client->if_name) {
  403. free(client->if_name);
  404. }
  405. esp_websocket_client_destroy_config(client);
  406. esp_transport_list_destroy(client->transport_list);
  407. vQueueDelete(client->lock);
  408. free(client->tx_buffer);
  409. free(client->rx_buffer);
  410. if (client->status_bits) {
  411. vEventGroupDelete(client->status_bits);
  412. }
  413. free(client);
  414. client = NULL;
  415. return ESP_OK;
  416. }
  417. esp_err_t esp_websocket_client_set_uri(esp_websocket_client_handle_t client, const char *uri)
  418. {
  419. if (client == NULL || uri == NULL) {
  420. return ESP_ERR_INVALID_ARG;
  421. }
  422. struct http_parser_url puri;
  423. http_parser_url_init(&puri);
  424. int parser_status = http_parser_parse_url(uri, strlen(uri), 0, &puri);
  425. if (parser_status != 0) {
  426. ESP_LOGE(TAG, "Error parse uri = %s", uri);
  427. return ESP_FAIL;
  428. }
  429. if (puri.field_data[UF_SCHEMA].len) {
  430. free(client->config->scheme);
  431. asprintf(&client->config->scheme, "%.*s", puri.field_data[UF_SCHEMA].len, uri + puri.field_data[UF_SCHEMA].off);
  432. ESP_WS_CLIENT_MEM_CHECK(TAG, client->config->scheme, return ESP_ERR_NO_MEM);
  433. }
  434. if (puri.field_data[UF_HOST].len) {
  435. free(client->config->host);
  436. asprintf(&client->config->host, "%.*s", puri.field_data[UF_HOST].len, uri + puri.field_data[UF_HOST].off);
  437. ESP_WS_CLIENT_MEM_CHECK(TAG, client->config->host, return ESP_ERR_NO_MEM);
  438. }
  439. if (puri.field_data[UF_PATH].len || puri.field_data[UF_QUERY].len) {
  440. free(client->config->path);
  441. if (puri.field_data[UF_QUERY].len == 0) {
  442. asprintf(&client->config->path, "%.*s", puri.field_data[UF_PATH].len, uri + puri.field_data[UF_PATH].off);
  443. } else if (puri.field_data[UF_PATH].len == 0) {
  444. asprintf(&client->config->path, "/?%.*s", puri.field_data[UF_QUERY].len, uri + puri.field_data[UF_QUERY].off);
  445. } else {
  446. asprintf(&client->config->path, "%.*s?%.*s", puri.field_data[UF_PATH].len, uri + puri.field_data[UF_PATH].off,
  447. puri.field_data[UF_QUERY].len, uri + puri.field_data[UF_QUERY].off);
  448. }
  449. ESP_WS_CLIENT_MEM_CHECK(TAG, client->config->path, return ESP_ERR_NO_MEM);
  450. }
  451. if (puri.field_data[UF_PORT].off) {
  452. client->config->port = strtol((const char*)(uri + puri.field_data[UF_PORT].off), NULL, 10);
  453. }
  454. if (puri.field_data[UF_USERINFO].len) {
  455. char *user_info = NULL;
  456. asprintf(&user_info, "%.*s", puri.field_data[UF_USERINFO].len, uri + puri.field_data[UF_USERINFO].off);
  457. if (user_info) {
  458. char *pass = strchr(user_info, ':');
  459. if (pass) {
  460. pass[0] = 0; //terminal username
  461. pass ++;
  462. free(client->config->password);
  463. client->config->password = strdup(pass);
  464. ESP_WS_CLIENT_MEM_CHECK(TAG, client->config->password, return ESP_ERR_NO_MEM);
  465. }
  466. free(client->config->username);
  467. client->config->username = strdup(user_info);
  468. ESP_WS_CLIENT_MEM_CHECK(TAG, client->config->username, return ESP_ERR_NO_MEM);
  469. free(user_info);
  470. } else {
  471. return ESP_ERR_NO_MEM;
  472. }
  473. }
  474. return ESP_OK;
  475. }
  476. static esp_err_t esp_websocket_client_recv(esp_websocket_client_handle_t client)
  477. {
  478. int rlen;
  479. client->payload_offset = 0;
  480. do {
  481. rlen = esp_transport_read(client->transport, client->rx_buffer, client->buffer_size, client->config->network_timeout_ms);
  482. if (rlen < 0) {
  483. ESP_LOGE(TAG, "Error read data");
  484. return ESP_FAIL;
  485. }
  486. client->payload_len = esp_transport_ws_get_read_payload_len(client->transport);
  487. client->last_opcode = esp_transport_ws_get_read_opcode(client->transport);
  488. if (rlen == 0 && client->last_opcode == WS_TRANSPORT_OPCODES_NONE ) {
  489. ESP_LOGV(TAG, "esp_transport_read timeouts");
  490. return ESP_OK;
  491. }
  492. esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_DATA, client->rx_buffer, rlen);
  493. client->payload_offset += rlen;
  494. } while (client->payload_offset < client->payload_len);
  495. // if a PING message received -> send out the PONG, this will not work for PING messages with payload longer than buffer len
  496. if (client->last_opcode == WS_TRANSPORT_OPCODES_PING) {
  497. const char *data = (client->payload_len == 0) ? NULL : client->rx_buffer;
  498. ESP_LOGD(TAG, "Sending PONG with payload len=%d", client->payload_len);
  499. esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_PONG | WS_TRANSPORT_OPCODES_FIN, data, client->payload_len,
  500. client->config->network_timeout_ms);
  501. } else if (client->last_opcode == WS_TRANSPORT_OPCODES_PONG) {
  502. client->wait_for_pong_resp = false;
  503. } else if (client->last_opcode == WS_TRANSPORT_OPCODES_CLOSE) {
  504. ESP_LOGD(TAG, "Received close frame");
  505. client->state = WEBSOCKET_STATE_CLOSING;
  506. }
  507. return ESP_OK;
  508. }
  509. static int esp_websocket_client_send_with_opcode(esp_websocket_client_handle_t client, ws_transport_opcodes_t opcode, const uint8_t *data, int len, TickType_t timeout);
  510. static int esp_websocket_client_send_close(esp_websocket_client_handle_t client, int code, const char *additional_data, int total_len, TickType_t timeout);
  511. static void esp_websocket_client_task(void *pv)
  512. {
  513. const int lock_timeout = portMAX_DELAY;
  514. esp_websocket_client_handle_t client = (esp_websocket_client_handle_t) pv;
  515. client->run = true;
  516. //get transport by scheme
  517. client->transport = esp_transport_list_get_transport(client->transport_list, client->config->scheme);
  518. if (client->transport == NULL) {
  519. ESP_LOGE(TAG, "There are no transports valid, stop websocket client");
  520. client->run = false;
  521. }
  522. //default port
  523. if (client->config->port == 0) {
  524. client->config->port = esp_transport_get_default_port(client->transport);
  525. }
  526. client->state = WEBSOCKET_STATE_INIT;
  527. xEventGroupClearBits(client->status_bits, STOPPED_BIT | CLOSE_FRAME_SENT_BIT);
  528. int read_select = 0;
  529. while (client->run) {
  530. if (xSemaphoreTakeRecursive(client->lock, lock_timeout) != pdPASS) {
  531. ESP_LOGE(TAG, "Failed to lock ws-client tasks, exiting the task...");
  532. break;
  533. }
  534. switch ((int)client->state) {
  535. case WEBSOCKET_STATE_INIT:
  536. if (client->transport == NULL) {
  537. ESP_LOGE(TAG, "There are no transport");
  538. client->run = false;
  539. break;
  540. }
  541. if (esp_transport_connect(client->transport,
  542. client->config->host,
  543. client->config->port,
  544. client->config->network_timeout_ms) < 0) {
  545. ESP_LOGE(TAG, "Error transport connect");
  546. esp_websocket_client_abort_connection(client);
  547. break;
  548. }
  549. ESP_LOGD(TAG, "Transport connected to %s://%s:%d", client->config->scheme, client->config->host, client->config->port);
  550. client->state = WEBSOCKET_STATE_CONNECTED;
  551. client->wait_for_pong_resp = false;
  552. esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_CONNECTED, NULL, 0);
  553. break;
  554. case WEBSOCKET_STATE_CONNECTED:
  555. if ((CLOSE_FRAME_SENT_BIT & xEventGroupGetBits(client->status_bits)) == 0) { // only send and check for PING
  556. // if closing hasn't been initiated
  557. if (_tick_get_ms() - client->ping_tick_ms > client->config->ping_interval_sec*1000) {
  558. client->ping_tick_ms = _tick_get_ms();
  559. ESP_LOGD(TAG, "Sending PING...");
  560. esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_PING | WS_TRANSPORT_OPCODES_FIN, NULL, 0, client->config->network_timeout_ms);
  561. if (!client->wait_for_pong_resp && client->config->pingpong_timeout_sec) {
  562. client->pingpong_tick_ms = _tick_get_ms();
  563. client->wait_for_pong_resp = true;
  564. }
  565. }
  566. if ( _tick_get_ms() - client->pingpong_tick_ms > client->config->pingpong_timeout_sec*1000 ) {
  567. if (client->wait_for_pong_resp) {
  568. ESP_LOGE(TAG, "Error, no PONG received for more than %d seconds after PING", client->config->pingpong_timeout_sec);
  569. esp_websocket_client_abort_connection(client);
  570. break;
  571. }
  572. }
  573. }
  574. if (read_select == 0) {
  575. ESP_LOGV(TAG, "Read poll timeout: skipping esp_transport_read()...");
  576. break;
  577. }
  578. client->ping_tick_ms = _tick_get_ms();
  579. if (esp_websocket_client_recv(client) == ESP_FAIL) {
  580. ESP_LOGE(TAG, "Error receive data");
  581. esp_websocket_client_abort_connection(client);
  582. break;
  583. }
  584. break;
  585. case WEBSOCKET_STATE_WAIT_TIMEOUT:
  586. if (!client->config->auto_reconnect) {
  587. client->run = false;
  588. break;
  589. }
  590. if (_tick_get_ms() - client->reconnect_tick_ms > client->wait_timeout_ms) {
  591. client->state = WEBSOCKET_STATE_INIT;
  592. client->reconnect_tick_ms = _tick_get_ms();
  593. ESP_LOGD(TAG, "Reconnecting...");
  594. }
  595. break;
  596. case WEBSOCKET_STATE_CLOSING:
  597. // if closing not initiated by the client echo the close message back
  598. if ((CLOSE_FRAME_SENT_BIT & xEventGroupGetBits(client->status_bits)) == 0) {
  599. ESP_LOGD(TAG, "Closing initiated by the server, sending close frame");
  600. esp_transport_ws_send_raw(client->transport, WS_TRANSPORT_OPCODES_CLOSE | WS_TRANSPORT_OPCODES_FIN, NULL, 0, client->config->network_timeout_ms);
  601. xEventGroupSetBits(client->status_bits, CLOSE_FRAME_SENT_BIT);
  602. }
  603. break;
  604. default:
  605. ESP_LOGD(TAG, "Client run iteration in a default state: %d", client->state);
  606. break;
  607. }
  608. xSemaphoreGiveRecursive(client->lock);
  609. if (WEBSOCKET_STATE_CONNECTED == client->state) {
  610. read_select = esp_transport_poll_read(client->transport, 1000); //Poll every 1000ms
  611. if (read_select < 0) {
  612. ESP_LOGE(TAG, "Network error: esp_transport_poll_read() returned %d, errno=%d", read_select, errno);
  613. esp_websocket_client_abort_connection(client);
  614. }
  615. } else if (WEBSOCKET_STATE_WAIT_TIMEOUT == client->state) {
  616. // waiting for reconnecting...
  617. vTaskDelay(client->wait_timeout_ms / 2 / portTICK_PERIOD_MS);
  618. } else if (WEBSOCKET_STATE_CLOSING == client->state &&
  619. (CLOSE_FRAME_SENT_BIT & xEventGroupGetBits(client->status_bits))) {
  620. ESP_LOGD(TAG, " Waiting for TCP connection to be closed by the server");
  621. int ret = esp_transport_ws_poll_connection_closed(client->transport, 1000);
  622. if (ret == 0) {
  623. // still waiting
  624. break;
  625. }
  626. if (ret < 0) {
  627. ESP_LOGW(TAG, "Connection terminated while waiting for clean TCP close");
  628. }
  629. client->run = false;
  630. client->state = WEBSOCKET_STATE_UNKNOW;
  631. esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_CLOSED, NULL, 0);
  632. break;
  633. }
  634. }
  635. esp_transport_close(client->transport);
  636. xEventGroupSetBits(client->status_bits, STOPPED_BIT);
  637. client->state = WEBSOCKET_STATE_UNKNOW;
  638. vTaskDelete(NULL);
  639. }
  640. esp_err_t esp_websocket_client_start(esp_websocket_client_handle_t client)
  641. {
  642. if (client == NULL) {
  643. return ESP_ERR_INVALID_ARG;
  644. }
  645. if (client->state >= WEBSOCKET_STATE_INIT) {
  646. ESP_LOGE(TAG, "The client has started");
  647. return ESP_FAIL;
  648. }
  649. if (xTaskCreate(esp_websocket_client_task, "websocket_task", client->config->task_stack, client, client->config->task_prio, &client->task_handle) != pdTRUE) {
  650. ESP_LOGE(TAG, "Error create websocket task");
  651. return ESP_FAIL;
  652. }
  653. xEventGroupClearBits(client->status_bits, STOPPED_BIT | CLOSE_FRAME_SENT_BIT);
  654. return ESP_OK;
  655. }
  656. esp_err_t esp_websocket_client_stop(esp_websocket_client_handle_t client)
  657. {
  658. if (client == NULL) {
  659. return ESP_ERR_INVALID_ARG;
  660. }
  661. if (!client->run) {
  662. ESP_LOGW(TAG, "Client was not started");
  663. return ESP_FAIL;
  664. }
  665. /* A running client cannot be stopped from the websocket task/event handler */
  666. TaskHandle_t running_task = xTaskGetCurrentTaskHandle();
  667. if (running_task == client->task_handle) {
  668. ESP_LOGE(TAG, "Client cannot be stopped from websocket task");
  669. return ESP_FAIL;
  670. }
  671. client->run = false;
  672. xEventGroupWaitBits(client->status_bits, STOPPED_BIT, false, true, portMAX_DELAY);
  673. client->state = WEBSOCKET_STATE_UNKNOW;
  674. return ESP_OK;
  675. }
  676. static int esp_websocket_client_send_close(esp_websocket_client_handle_t client, int code, const char *additional_data, int total_len, TickType_t timeout)
  677. {
  678. uint8_t *close_status_data = NULL;
  679. // RFC6455#section-5.5.1: The Close frame MAY contain a body (indicated by total_len >= 2)
  680. if (total_len >= 2) {
  681. close_status_data = calloc(1, total_len);
  682. ESP_WS_CLIENT_MEM_CHECK(TAG, close_status_data, return -1);
  683. // RFC6455#section-5.5.1: The first two bytes of the body MUST be a 2-byte representing a status
  684. uint16_t *code_network_order = (uint16_t *) close_status_data;
  685. *code_network_order = htons(code);
  686. memcpy(close_status_data + 2, additional_data, total_len - 2);
  687. }
  688. int ret = esp_websocket_client_send_with_opcode(client, WS_TRANSPORT_OPCODES_CLOSE, close_status_data, total_len, timeout);
  689. free(close_status_data);
  690. return ret;
  691. }
  692. static esp_err_t esp_websocket_client_close_with_optional_body(esp_websocket_client_handle_t client, bool send_body, int code, const char *data, int len, TickType_t timeout)
  693. {
  694. if (client == NULL) {
  695. return ESP_ERR_INVALID_ARG;
  696. }
  697. if (!client->run) {
  698. ESP_LOGW(TAG, "Client was not started");
  699. return ESP_FAIL;
  700. }
  701. /* A running client cannot be stopped from the websocket task/event handler */
  702. TaskHandle_t running_task = xTaskGetCurrentTaskHandle();
  703. if (running_task == client->task_handle) {
  704. ESP_LOGE(TAG, "Client cannot be stopped from websocket task");
  705. return ESP_FAIL;
  706. }
  707. if (send_body) {
  708. esp_websocket_client_send_close(client, code, data, len + 2, portMAX_DELAY); // len + 2 -> always sending the code
  709. } else {
  710. esp_websocket_client_send_close(client, 0, NULL, 0, portMAX_DELAY); // only opcode frame
  711. }
  712. // Set closing bit to prevent from sending PING frames while connected
  713. xEventGroupSetBits(client->status_bits, CLOSE_FRAME_SENT_BIT);
  714. if (STOPPED_BIT & xEventGroupWaitBits(client->status_bits, STOPPED_BIT, false, true, timeout)) {
  715. return ESP_OK;
  716. }
  717. // If could not close gracefully within timeout, stop the client and disconnect
  718. client->run = false;
  719. xEventGroupWaitBits(client->status_bits, STOPPED_BIT, false, true, portMAX_DELAY);
  720. client->state = WEBSOCKET_STATE_UNKNOW;
  721. return ESP_OK;
  722. }
  723. esp_err_t esp_websocket_client_close_with_code(esp_websocket_client_handle_t client, int code, const char *data, int len, TickType_t timeout)
  724. {
  725. return esp_websocket_client_close_with_optional_body(client, true, code, data, len, timeout);
  726. }
  727. esp_err_t esp_websocket_client_close(esp_websocket_client_handle_t client, TickType_t timeout)
  728. {
  729. return esp_websocket_client_close_with_optional_body(client, false, 0, NULL, 0, timeout);
  730. }
  731. int esp_websocket_client_send_text(esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout)
  732. {
  733. return esp_websocket_client_send_with_opcode(client, WS_TRANSPORT_OPCODES_TEXT, (const uint8_t *)data, len, timeout);
  734. }
  735. int esp_websocket_client_send_bin(esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout)
  736. {
  737. return esp_websocket_client_send_with_opcode(client, WS_TRANSPORT_OPCODES_BINARY, (const uint8_t *)data, len, timeout);
  738. }
  739. static int esp_websocket_client_send_with_opcode(esp_websocket_client_handle_t client, ws_transport_opcodes_t opcode, const uint8_t *data, int len, TickType_t timeout)
  740. {
  741. int need_write = len;
  742. int wlen = 0, widx = 0;
  743. int ret = ESP_FAIL;
  744. if (client == NULL || len < 0 ||
  745. (opcode != WS_TRANSPORT_OPCODES_CLOSE && (data == NULL || len <= 0))) {
  746. ESP_LOGE(TAG, "Invalid arguments");
  747. return ESP_FAIL;
  748. }
  749. if (xSemaphoreTakeRecursive(client->lock, timeout) != pdPASS) {
  750. ESP_LOGE(TAG, "Could not lock ws-client within %d timeout", timeout);
  751. return ESP_FAIL;
  752. }
  753. if (!esp_websocket_client_is_connected(client)) {
  754. ESP_LOGE(TAG, "Websocket client is not connected");
  755. goto unlock_and_return;
  756. }
  757. if (client->transport == NULL) {
  758. ESP_LOGE(TAG, "Invalid transport");
  759. goto unlock_and_return;
  760. }
  761. uint32_t current_opcode = opcode;
  762. while (widx < len || current_opcode) { // allow for sending "current_opcode" only message with len==0
  763. if (need_write > client->buffer_size) {
  764. need_write = client->buffer_size;
  765. } else {
  766. current_opcode |= WS_TRANSPORT_OPCODES_FIN;
  767. }
  768. memcpy(client->tx_buffer, data + widx, need_write);
  769. // send with ws specific way and specific opcode
  770. wlen = esp_transport_ws_send_raw(client->transport, current_opcode, (char *)client->tx_buffer, need_write,
  771. (timeout==portMAX_DELAY)? -1 : timeout * portTICK_PERIOD_MS);
  772. if (wlen < 0 || (wlen == 0 && need_write != 0)) {
  773. ret = wlen;
  774. ESP_LOGE(TAG, "Network error: esp_transport_write() returned %d, errno=%d", ret, errno);
  775. esp_websocket_client_abort_connection(client);
  776. goto unlock_and_return;
  777. }
  778. current_opcode = 0;
  779. widx += wlen;
  780. need_write = len - widx;
  781. }
  782. ret = widx;
  783. unlock_and_return:
  784. xSemaphoreGiveRecursive(client->lock);
  785. return ret;
  786. }
  787. bool esp_websocket_client_is_connected(esp_websocket_client_handle_t client)
  788. {
  789. if (client == NULL) {
  790. return false;
  791. }
  792. return client->state == WEBSOCKET_STATE_CONNECTED;
  793. }
  794. esp_err_t esp_websocket_register_events(esp_websocket_client_handle_t client,
  795. esp_websocket_event_id_t event,
  796. esp_event_handler_t event_handler,
  797. void *event_handler_arg)
  798. {
  799. if (client == NULL) {
  800. return ESP_ERR_INVALID_ARG;
  801. }
  802. return esp_event_handler_register_with(client->event_handle, WEBSOCKET_EVENTS, event, event_handler, event_handler_arg);
  803. }