esp_websocket_client.c 36 KB

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