esp_websocket_client.c 36 KB

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