esp_websocket_client.c 36 KB

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