forked from me-no-dev/AsyncTCP
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathAsyncTCP.cpp
1708 lines (1536 loc) · 43.8 KB
/
AsyncTCP.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: LGPL-3.0-or-later
// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
#include "Arduino.h"
#include "AsyncTCP.h"
extern "C" {
#include "lwip/dns.h"
#include "lwip/err.h"
#include "lwip/inet.h"
#include "lwip/opt.h"
#include "lwip/tcp.h"
}
#if CONFIG_ASYNC_TCP_USE_WDT
#include "esp_task_wdt.h"
#endif
// Required for:
// https://github.com/espressif/arduino-esp32/blob/3.0.3/libraries/Network/src/NetworkInterface.cpp#L37-L47
#if ESP_IDF_VERSION_MAJOR >= 5
#include <NetworkInterface.h>
#endif
#define TAG "AsyncTCP"
// https://github.com/espressif/arduino-esp32/issues/10526
#ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING
#define TCP_MUTEX_LOCK() \
if (!sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) { \
LOCK_TCPIP_CORE(); \
}
#define TCP_MUTEX_UNLOCK() \
if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) { \
UNLOCK_TCPIP_CORE(); \
}
#else // CONFIG_LWIP_TCPIP_CORE_LOCKING
#define TCP_MUTEX_LOCK()
#define TCP_MUTEX_UNLOCK()
#endif // CONFIG_LWIP_TCPIP_CORE_LOCKING
#define INVALID_CLOSED_SLOT -1
/*
TCP poll interval is specified in terms of the TCP coarse timer interval, which is called twice a second
https://github.com/espressif/esp-lwip/blob/2acf959a2bb559313cd2bf9306c24612ba3d0e19/src/core/tcp.c#L1895
*/
#define CONFIG_ASYNC_TCP_POLL_TIMER 1
/*
* TCP/IP Event Task
* */
typedef enum {
LWIP_TCP_SENT,
LWIP_TCP_RECV,
LWIP_TCP_FIN,
LWIP_TCP_ERROR,
LWIP_TCP_POLL,
LWIP_TCP_CLEAR,
LWIP_TCP_ACCEPT,
LWIP_TCP_CONNECTED,
LWIP_TCP_DNS
} lwip_tcp_event_t;
typedef struct {
lwip_tcp_event_t event;
void *arg;
union {
struct {
tcp_pcb *pcb;
int8_t err;
} connected;
struct {
int8_t err;
} error;
struct {
tcp_pcb *pcb;
uint16_t len;
} sent;
struct {
tcp_pcb *pcb;
pbuf *pb;
int8_t err;
} recv;
struct {
tcp_pcb *pcb;
int8_t err;
} fin;
struct {
tcp_pcb *pcb;
} poll;
struct {
AsyncClient *client;
} accept;
struct {
const char *name;
ip_addr_t addr;
} dns;
};
} lwip_tcp_event_packet_t;
static QueueHandle_t _async_queue = NULL;
static TaskHandle_t _async_service_task_handle = NULL;
static SemaphoreHandle_t _slots_lock = NULL;
static const int _number_of_closed_slots = CONFIG_LWIP_MAX_ACTIVE_TCP;
static uint32_t _closed_slots[_number_of_closed_slots];
static uint32_t _closed_index = []() {
_slots_lock = xSemaphoreCreateBinary();
configASSERT(_slots_lock); // Add sanity check
xSemaphoreGive(_slots_lock);
for (int i = 0; i < _number_of_closed_slots; ++i) {
_closed_slots[i] = 1;
}
return 1;
}();
static inline bool _init_async_event_queue() {
if (!_async_queue) {
_async_queue = xQueueCreate(CONFIG_ASYNC_TCP_QUEUE_SIZE, sizeof(lwip_tcp_event_packet_t *));
if (!_async_queue) {
return false;
}
}
return true;
}
static inline bool _send_async_event(lwip_tcp_event_packet_t **e, TickType_t wait = 0) {
return _async_queue && xQueueSend(_async_queue, e, wait) == pdPASS;
}
static inline bool _prepend_async_event(lwip_tcp_event_packet_t **e, TickType_t wait = 0) {
return _async_queue && xQueueSendToFront(_async_queue, e, wait) == pdPASS;
}
static inline bool _get_async_event(lwip_tcp_event_packet_t **e) {
while (true) {
if (!_async_queue) {
break;
}
#if CONFIG_ASYNC_TCP_USE_WDT
// need to return periodically to feed the dog
if (xQueueReceive(_async_queue, e, pdMS_TO_TICKS(1000)) != pdPASS) {
break;
}
#else
if (xQueueReceive(_async_queue, e, portMAX_DELAY) != pdPASS) {
break;
}
#endif
if ((*e)->event != LWIP_TCP_POLL) {
return true;
}
/*
Let's try to coalesce two (or more) consecutive poll events into one
this usually happens with poor implemented user-callbacks that are runs too long and makes poll events to stack in the queue
if consecutive user callback for a same connection runs longer that poll time then it will fill the queue with events until it deadlocks.
This is a workaround to mitigate such poor designs and won't let other events/connections to starve the task time.
It won't be effective if user would run multiple simultaneous long running callbacks due to message interleaving.
todo: implement some kind of fair dequeuing or (better) simply punish user for a bad designed callbacks by resetting hog connections
*/
lwip_tcp_event_packet_t *next_pkt = NULL;
while (xQueuePeek(_async_queue, &next_pkt, 0) == pdPASS) {
// if the next event that will come is a poll event for the same connection, we can discard it and continue
if (next_pkt->arg == (*e)->arg && next_pkt->event == LWIP_TCP_POLL) {
if (xQueueReceive(_async_queue, &next_pkt, 0) == pdPASS) {
free(next_pkt);
next_pkt = NULL;
log_d("coalescing polls, network congestion or async callbacks might be too slow!");
continue;
}
}
// quit while loop if next incoming event can't be discarded (not a poll event)
break;
}
/*
now we have to decide if to proceed with poll callback handler or discard it?
poor designed apps using asynctcp without proper dataflow control could flood the queue with interleaved pool/ack events.
I.e. on each poll app would try to generate more data to send, which in turn results in additional ack event triggering chain effect
for long connections. Or poll callback could take long time starving other connections. Anyway our goal is to keep the queue length
grows under control (if possible) and poll events are the safest to discard.
Let's discard poll events processing using linear-increasing probability curve when queue size grows over 3/4
Poll events are periodic and connection could get another chance next time
*/
if (uxQueueMessagesWaiting(_async_queue) > (rand() % CONFIG_ASYNC_TCP_QUEUE_SIZE / 4 + CONFIG_ASYNC_TCP_QUEUE_SIZE * 3 / 4)) {
free(*e);
*e = NULL;
log_d("discarding poll due to queue congestion");
continue; // continue main loop to dequeue next event which we know is not a poll event
}
return true; // queue not nearly full, caller can process the poll event
}
return false;
}
static bool _remove_events_with_arg(void *arg) {
if (!_async_queue) {
return false;
}
lwip_tcp_event_packet_t *first_packet = NULL;
lwip_tcp_event_packet_t *packet = NULL;
// figure out which is the first non-matching packet so we can keep the order
while (!first_packet) {
if (xQueueReceive(_async_queue, &first_packet, 0) != pdPASS) {
return false;
}
// discard packet if matching
if ((uintptr_t)first_packet->arg == (uintptr_t)arg) {
free(first_packet);
first_packet = NULL;
} else if (xQueueSend(_async_queue, &first_packet, 0) != pdPASS) {
// try to return first packet to the back of the queue
// we can't wait here if queue is full, because this call has been done from the only consumer task of this queue
// otherwise it would deadlock, we have to discard the event
free(first_packet);
first_packet = NULL;
return false;
}
}
while (xQueuePeek(_async_queue, &packet, 0) == pdPASS && packet != first_packet) {
if (xQueueReceive(_async_queue, &packet, 0) != pdPASS) {
return false;
}
if ((uintptr_t)packet->arg == (uintptr_t)arg) {
// remove matching event
free(packet);
packet = NULL;
// otherwise try to requeue it
} else if (xQueueSend(_async_queue, &packet, 0) != pdPASS) {
// we can't wait here if queue is full, because this call has been done from the only consumer task of this queue
// otherwise it would deadlock, we have to discard the event
free(packet);
packet = NULL;
return false;
}
}
return true;
}
static void _handle_async_event(lwip_tcp_event_packet_t *e) {
if (e->arg == NULL) {
// do nothing when arg is NULL
// ets_printf("event arg == NULL: 0x%08x\n", e->recv.pcb);
} else if (e->event == LWIP_TCP_CLEAR) {
_remove_events_with_arg(e->arg);
} else if (e->event == LWIP_TCP_RECV) {
// ets_printf("-R: 0x%08x\n", e->recv.pcb);
AsyncClient::_s_recv(e->arg, e->recv.pcb, e->recv.pb, e->recv.err);
} else if (e->event == LWIP_TCP_FIN) {
// ets_printf("-F: 0x%08x\n", e->fin.pcb);
AsyncClient::_s_fin(e->arg, e->fin.pcb, e->fin.err);
} else if (e->event == LWIP_TCP_SENT) {
// ets_printf("-S: 0x%08x\n", e->sent.pcb);
AsyncClient::_s_sent(e->arg, e->sent.pcb, e->sent.len);
} else if (e->event == LWIP_TCP_POLL) {
// ets_printf("-P: 0x%08x\n", e->poll.pcb);
AsyncClient::_s_poll(e->arg, e->poll.pcb);
} else if (e->event == LWIP_TCP_ERROR) {
// ets_printf("-E: 0x%08x %d\n", e->arg, e->error.err);
AsyncClient::_s_error(e->arg, e->error.err);
} else if (e->event == LWIP_TCP_CONNECTED) {
// ets_printf("C: 0x%08x 0x%08x %d\n", e->arg, e->connected.pcb, e->connected.err);
AsyncClient::_s_connected(e->arg, e->connected.pcb, e->connected.err);
} else if (e->event == LWIP_TCP_ACCEPT) {
// ets_printf("A: 0x%08x 0x%08x\n", e->arg, e->accept.client);
AsyncServer::_s_accepted(e->arg, e->accept.client);
} else if (e->event == LWIP_TCP_DNS) {
// ets_printf("D: 0x%08x %s = %s\n", e->arg, e->dns.name, ipaddr_ntoa(&e->dns.addr));
AsyncClient::_s_dns_found(e->dns.name, &e->dns.addr, e->arg);
}
free((void *)(e));
}
static void _async_service_task(void *pvParameters) {
#if CONFIG_ASYNC_TCP_USE_WDT
if (esp_task_wdt_add(NULL) != ESP_OK) {
log_w("Failed to add async task to WDT");
}
#endif
lwip_tcp_event_packet_t *packet = NULL;
for (;;) {
if (_get_async_event(&packet)) {
_handle_async_event(packet);
}
#if CONFIG_ASYNC_TCP_USE_WDT
esp_task_wdt_reset();
#endif
}
#if CONFIG_ASYNC_TCP_USE_WDT
esp_task_wdt_delete(NULL);
#endif
vTaskDelete(NULL);
_async_service_task_handle = NULL;
}
/*
static void _stop_async_task(){
if(_async_service_task_handle){
vTaskDelete(_async_service_task_handle);
_async_service_task_handle = NULL;
}
}
*/
static bool customTaskCreateUniversal(
TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t usStackDepth, void *const pvParameters, UBaseType_t uxPriority,
TaskHandle_t *const pxCreatedTask, const BaseType_t xCoreID
) {
#ifndef CONFIG_FREERTOS_UNICORE
if (xCoreID >= 0 && xCoreID < 2) {
return xTaskCreatePinnedToCore(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask, xCoreID);
} else {
#endif
return xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask);
#ifndef CONFIG_FREERTOS_UNICORE
}
#endif
}
static bool _start_async_task() {
if (!_init_async_event_queue()) {
return false;
}
if (!_async_service_task_handle) {
customTaskCreateUniversal(
_async_service_task, "async_tcp", CONFIG_ASYNC_TCP_STACK_SIZE, NULL, CONFIG_ASYNC_TCP_PRIORITY, &_async_service_task_handle, CONFIG_ASYNC_TCP_RUNNING_CORE
);
if (!_async_service_task_handle) {
return false;
}
}
return true;
}
/*
* LwIP Callbacks
* */
static int8_t _tcp_clear_events(void *arg) {
lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t));
if (!e) {
log_e("Failed to allocate event packet");
return ERR_MEM;
}
e->event = LWIP_TCP_CLEAR;
e->arg = arg;
if (!_prepend_async_event(&e)) {
free((void *)(e));
log_e("Failed to queue event: LWIP_TCP_CLEAR");
return ERR_TIMEOUT;
}
return ERR_OK;
}
static int8_t _tcp_connected(void *arg, tcp_pcb *pcb, int8_t err) {
// ets_printf("+C: 0x%08x\n", pcb);
lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t));
if (!e) {
log_e("Failed to allocate event packet");
return ERR_MEM;
}
e->event = LWIP_TCP_CONNECTED;
e->arg = arg;
e->connected.pcb = pcb;
e->connected.err = err;
if (!_prepend_async_event(&e)) {
free((void *)(e));
log_e("Failed to queue event: LWIP_TCP_CONNECTED");
tcp_abort(pcb);
return ERR_TIMEOUT;
}
return ERR_OK;
}
static int8_t _tcp_poll(void *arg, struct tcp_pcb *pcb) {
// throttle polling events queueing when event queue is getting filled up, let it handle _onack's
// log_d("qs:%u", uxQueueMessagesWaiting(_async_queue));
if (uxQueueMessagesWaiting(_async_queue) > (rand() % CONFIG_ASYNC_TCP_QUEUE_SIZE / 2 + CONFIG_ASYNC_TCP_QUEUE_SIZE / 4)) {
log_d("throttling");
return ERR_OK;
}
// ets_printf("+P: 0x%08x\n", pcb);
lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t));
if (!e) {
log_e("Failed to allocate event packet");
return ERR_MEM;
}
e->event = LWIP_TCP_POLL;
e->arg = arg;
e->poll.pcb = pcb;
// poll events are not critical 'cause those are repetitive, so we may not wait the queue in any case
if (!_send_async_event(&e, 0)) {
free((void *)(e));
log_e("Failed to queue event: LWIP_TCP_POLL");
tcp_abort(pcb);
return ERR_TIMEOUT;
}
return ERR_OK;
}
static int8_t _tcp_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *pb, int8_t err) {
lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t));
if (!e) {
log_e("Failed to allocate event packet");
return ERR_MEM;
}
e->arg = arg;
if (pb) {
// ets_printf("+R: 0x%08x\n", pcb);
e->event = LWIP_TCP_RECV;
e->recv.pcb = pcb;
e->recv.pb = pb;
e->recv.err = err;
} else {
// ets_printf("+F: 0x%08x\n", pcb);
e->event = LWIP_TCP_FIN;
e->fin.pcb = pcb;
e->fin.err = err;
// close the PCB in LwIP thread
AsyncClient::_s_lwip_fin(e->arg, e->fin.pcb, e->fin.err);
}
if (!_send_async_event(&e)) {
free((void *)(e));
log_e("Failed to queue event: LWIP_TCP_RECV or LWIP_TCP_FIN");
tcp_abort(pcb);
return ERR_TIMEOUT;
}
return ERR_OK;
}
static int8_t _tcp_sent(void *arg, struct tcp_pcb *pcb, uint16_t len) {
// ets_printf("+S: 0x%08x\n", pcb);
lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t));
if (!e) {
log_e("Failed to allocate event packet");
return ERR_MEM;
}
e->event = LWIP_TCP_SENT;
e->arg = arg;
e->sent.pcb = pcb;
e->sent.len = len;
if (!_send_async_event(&e)) {
free((void *)(e));
log_e("Failed to queue event: LWIP_TCP_SENT");
tcp_abort(pcb);
return ERR_TIMEOUT;
}
return ERR_OK;
}
static void _tcp_error(void *arg, int8_t err) {
// ets_printf("+E: 0x%08x\n", arg);
lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t));
if (!e) {
log_e("Failed to allocate event packet");
return;
}
e->event = LWIP_TCP_ERROR;
e->arg = arg;
e->error.err = err;
if (!_send_async_event(&e)) {
free((void *)(e));
log_e("Failed to queue event: LWIP_TCP_ERROR");
}
}
static void _tcp_dns_found(const char *name, struct ip_addr *ipaddr, void *arg) {
lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t));
if (!e) {
log_e("Failed to allocate event packet");
return;
}
// ets_printf("+DNS: name=%s ipaddr=0x%08x arg=%x\n", name, ipaddr, arg);
e->event = LWIP_TCP_DNS;
e->arg = arg;
e->dns.name = name;
if (ipaddr) {
memcpy(&e->dns.addr, ipaddr, sizeof(struct ip_addr));
} else {
memset(&e->dns.addr, 0, sizeof(e->dns.addr));
}
if (!_send_async_event(&e)) {
free((void *)(e));
log_e("Failed to queue event: LWIP_TCP_DNS");
}
}
// Used to switch out from LwIP thread
static int8_t _tcp_accept(void *arg, AsyncClient *client) {
lwip_tcp_event_packet_t *e = (lwip_tcp_event_packet_t *)malloc(sizeof(lwip_tcp_event_packet_t));
if (!e) {
log_e("Failed to allocate event packet");
return ERR_MEM;
}
e->event = LWIP_TCP_ACCEPT;
e->arg = arg;
e->accept.client = client;
if (!_prepend_async_event(&e)) {
free((void *)(e));
log_e("Failed to queue event: LWIP_TCP_ACCEPT");
client->abort();
return ERR_TIMEOUT;
}
return ERR_OK;
}
/*
* TCP/IP API Calls
* */
#include "lwip/priv/tcpip_priv.h"
typedef struct {
struct tcpip_api_call_data call;
tcp_pcb *pcb;
int8_t closed_slot;
int8_t err;
union {
struct {
const char *data;
size_t size;
uint8_t apiflags;
} write;
size_t received;
struct {
ip_addr_t *addr;
uint16_t port;
tcp_connected_fn cb;
} connect;
struct {
ip_addr_t *addr;
uint16_t port;
} bind;
uint8_t backlog;
};
} tcp_api_call_t;
static err_t _tcp_output_api(struct tcpip_api_call_data *api_call_msg) {
tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg;
msg->err = ERR_CONN;
if (msg->closed_slot == INVALID_CLOSED_SLOT || !_closed_slots[msg->closed_slot]) {
msg->err = tcp_output(msg->pcb);
} else {
log_e("pcb was closed before reaching LwIP task");
}
return msg->err;
}
static esp_err_t _tcp_output(tcp_pcb *pcb, int8_t closed_slot) {
if (!pcb) {
return ERR_CONN;
}
tcp_api_call_t msg;
msg.pcb = pcb;
msg.closed_slot = closed_slot;
tcpip_api_call(_tcp_output_api, (struct tcpip_api_call_data *)&msg);
return msg.err;
}
static err_t _tcp_write_api(struct tcpip_api_call_data *api_call_msg) {
tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg;
msg->err = ERR_CONN;
if (msg->closed_slot == INVALID_CLOSED_SLOT || !_closed_slots[msg->closed_slot]) {
msg->err = tcp_write(msg->pcb, msg->write.data, msg->write.size, msg->write.apiflags);
} else {
log_e("pcb was closed before reaching LwIP task");
}
return msg->err;
}
static esp_err_t _tcp_write(tcp_pcb *pcb, int8_t closed_slot, const char *data, size_t size, uint8_t apiflags) {
if (!pcb) {
return ERR_CONN;
}
tcp_api_call_t msg;
msg.pcb = pcb;
msg.closed_slot = closed_slot;
msg.write.data = data;
msg.write.size = size;
msg.write.apiflags = apiflags;
tcpip_api_call(_tcp_write_api, (struct tcpip_api_call_data *)&msg);
return msg.err;
}
static err_t _tcp_recved_api(struct tcpip_api_call_data *api_call_msg) {
tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg;
msg->err = ERR_CONN;
if (msg->closed_slot == INVALID_CLOSED_SLOT || !_closed_slots[msg->closed_slot]) {
// if(msg->closed_slot != INVALID_CLOSED_SLOT && !_closed_slots[msg->closed_slot]) {
// if(msg->closed_slot != INVALID_CLOSED_SLOT) {
msg->err = 0;
tcp_recved(msg->pcb, msg->received);
} else {
log_e("pcb was closed before reaching LwIP task");
}
return msg->err;
}
static esp_err_t _tcp_recved(tcp_pcb *pcb, int8_t closed_slot, size_t len) {
if (!pcb) {
return ERR_CONN;
}
tcp_api_call_t msg;
msg.pcb = pcb;
msg.closed_slot = closed_slot;
msg.received = len;
tcpip_api_call(_tcp_recved_api, (struct tcpip_api_call_data *)&msg);
return msg.err;
}
static err_t _tcp_close_api(struct tcpip_api_call_data *api_call_msg) {
tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg;
msg->err = ERR_CONN;
if (msg->closed_slot == INVALID_CLOSED_SLOT || !_closed_slots[msg->closed_slot]) {
msg->err = tcp_close(msg->pcb);
} else {
log_e("pcb was closed before reaching LwIP task");
}
return msg->err;
}
static esp_err_t _tcp_close(tcp_pcb *pcb, int8_t closed_slot) {
if (!pcb) {
return ERR_CONN;
}
tcp_api_call_t msg;
msg.pcb = pcb;
msg.closed_slot = closed_slot;
tcpip_api_call(_tcp_close_api, (struct tcpip_api_call_data *)&msg);
return msg.err;
}
static err_t _tcp_abort_api(struct tcpip_api_call_data *api_call_msg) {
tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg;
msg->err = ERR_CONN;
if (msg->closed_slot == INVALID_CLOSED_SLOT || !_closed_slots[msg->closed_slot]) {
tcp_abort(msg->pcb);
} else {
log_e("pcb was closed before reaching LwIP task");
}
return msg->err;
}
static esp_err_t _tcp_abort(tcp_pcb *pcb, int8_t closed_slot) {
if (!pcb) {
return ERR_CONN;
}
tcp_api_call_t msg;
msg.pcb = pcb;
msg.closed_slot = closed_slot;
tcpip_api_call(_tcp_abort_api, (struct tcpip_api_call_data *)&msg);
return msg.err;
}
static err_t _tcp_connect_api(struct tcpip_api_call_data *api_call_msg) {
tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg;
msg->err = tcp_connect(msg->pcb, msg->connect.addr, msg->connect.port, msg->connect.cb);
return msg->err;
}
static esp_err_t _tcp_connect(tcp_pcb *pcb, int8_t closed_slot, ip_addr_t *addr, uint16_t port, tcp_connected_fn cb) {
if (!pcb) {
return ESP_FAIL;
}
tcp_api_call_t msg;
msg.pcb = pcb;
msg.closed_slot = closed_slot;
msg.connect.addr = addr;
msg.connect.port = port;
msg.connect.cb = cb;
tcpip_api_call(_tcp_connect_api, (struct tcpip_api_call_data *)&msg);
return msg.err;
}
static err_t _tcp_bind_api(struct tcpip_api_call_data *api_call_msg) {
tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg;
msg->err = tcp_bind(msg->pcb, msg->bind.addr, msg->bind.port);
return msg->err;
}
static esp_err_t _tcp_bind(tcp_pcb *pcb, ip_addr_t *addr, uint16_t port) {
if (!pcb) {
return ESP_FAIL;
}
tcp_api_call_t msg;
msg.pcb = pcb;
msg.closed_slot = -1;
msg.bind.addr = addr;
msg.bind.port = port;
tcpip_api_call(_tcp_bind_api, (struct tcpip_api_call_data *)&msg);
return msg.err;
}
static err_t _tcp_listen_api(struct tcpip_api_call_data *api_call_msg) {
tcp_api_call_t *msg = (tcp_api_call_t *)api_call_msg;
msg->err = 0;
msg->pcb = tcp_listen_with_backlog(msg->pcb, msg->backlog);
return msg->err;
}
static tcp_pcb *_tcp_listen_with_backlog(tcp_pcb *pcb, uint8_t backlog) {
if (!pcb) {
return NULL;
}
tcp_api_call_t msg;
msg.pcb = pcb;
msg.closed_slot = -1;
msg.backlog = backlog ? backlog : 0xFF;
tcpip_api_call(_tcp_listen_api, (struct tcpip_api_call_data *)&msg);
return msg.pcb;
}
/*
Async TCP Client
*/
AsyncClient::AsyncClient(tcp_pcb *pcb)
: _connect_cb(0), _connect_cb_arg(0), _discard_cb(0), _discard_cb_arg(0), _sent_cb(0), _sent_cb_arg(0), _error_cb(0), _error_cb_arg(0), _recv_cb(0),
_recv_cb_arg(0), _pb_cb(0), _pb_cb_arg(0), _timeout_cb(0), _timeout_cb_arg(0), _poll_cb(0), _poll_cb_arg(0), _ack_pcb(true), _tx_last_packet(0),
_rx_timeout(0), _rx_last_ack(0), _ack_timeout(CONFIG_ASYNC_TCP_MAX_ACK_TIME), _connect_port(0), prev(NULL), next(NULL) {
_pcb = pcb;
_closed_slot = INVALID_CLOSED_SLOT;
if (_pcb) {
_rx_last_packet = millis();
tcp_arg(_pcb, this);
tcp_recv(_pcb, &_tcp_recv);
tcp_sent(_pcb, &_tcp_sent);
tcp_err(_pcb, &_tcp_error);
tcp_poll(_pcb, &_tcp_poll, CONFIG_ASYNC_TCP_POLL_TIMER);
if (!_allocate_closed_slot()) {
_close();
}
}
}
AsyncClient::~AsyncClient() {
if (_pcb) {
_close();
}
_free_closed_slot();
}
/*
* Operators
* */
AsyncClient &AsyncClient::operator=(const AsyncClient &other) {
if (_pcb) {
_close();
}
_pcb = other._pcb;
_closed_slot = other._closed_slot;
if (_pcb) {
_rx_last_packet = millis();
tcp_arg(_pcb, this);
tcp_recv(_pcb, &_tcp_recv);
tcp_sent(_pcb, &_tcp_sent);
tcp_err(_pcb, &_tcp_error);
tcp_poll(_pcb, &_tcp_poll, CONFIG_ASYNC_TCP_POLL_TIMER);
}
return *this;
}
bool AsyncClient::operator==(const AsyncClient &other) {
return _pcb == other._pcb;
}
AsyncClient &AsyncClient::operator+=(const AsyncClient &other) {
if (next == NULL) {
next = (AsyncClient *)(&other);
next->prev = this;
} else {
AsyncClient *c = next;
while (c->next != NULL) {
c = c->next;
}
c->next = (AsyncClient *)(&other);
c->next->prev = c;
}
return *this;
}
/*
* Callback Setters
* */
void AsyncClient::onConnect(AcConnectHandler cb, void *arg) {
_connect_cb = cb;
_connect_cb_arg = arg;
}
void AsyncClient::onDisconnect(AcConnectHandler cb, void *arg) {
_discard_cb = cb;
_discard_cb_arg = arg;
}
void AsyncClient::onAck(AcAckHandler cb, void *arg) {
_sent_cb = cb;
_sent_cb_arg = arg;
}
void AsyncClient::onError(AcErrorHandler cb, void *arg) {
_error_cb = cb;
_error_cb_arg = arg;
}
void AsyncClient::onData(AcDataHandler cb, void *arg) {
_recv_cb = cb;
_recv_cb_arg = arg;
}
void AsyncClient::onPacket(AcPacketHandler cb, void *arg) {
_pb_cb = cb;
_pb_cb_arg = arg;
}
void AsyncClient::onTimeout(AcTimeoutHandler cb, void *arg) {
_timeout_cb = cb;
_timeout_cb_arg = arg;
}
void AsyncClient::onPoll(AcConnectHandler cb, void *arg) {
_poll_cb = cb;
_poll_cb_arg = arg;
}
/*
* Main Public Methods
* */
bool AsyncClient::_connect(ip_addr_t addr, uint16_t port) {
if (_pcb) {
log_d("already connected, state %d", _pcb->state);
return false;
}
if (!_start_async_task()) {
log_e("failed to start task");
return false;
}
if (!_allocate_closed_slot()) {
log_e("failed to allocate: closed slot full");
return false;
}
TCP_MUTEX_LOCK();
tcp_pcb *pcb = tcp_new_ip_type(addr.type);
if (!pcb) {
TCP_MUTEX_UNLOCK();
log_e("pcb == NULL");
return false;
}
tcp_arg(pcb, this);
tcp_err(pcb, &_tcp_error);
tcp_recv(pcb, &_tcp_recv);
tcp_sent(pcb, &_tcp_sent);
tcp_poll(pcb, &_tcp_poll, CONFIG_ASYNC_TCP_POLL_TIMER);
TCP_MUTEX_UNLOCK();
esp_err_t err = _tcp_connect(pcb, _closed_slot, &addr, port, (tcp_connected_fn)&_tcp_connected);
return err == ESP_OK;
}
bool AsyncClient::connect(const IPAddress &ip, uint16_t port) {
ip_addr_t addr;
#if ESP_IDF_VERSION_MAJOR < 5
addr.u_addr.ip4.addr = ip;
addr.type = IPADDR_TYPE_V4;
#else
ip.to_ip_addr_t(&addr);
#endif
return _connect(addr, port);
}
#if LWIP_IPV6 && ESP_IDF_VERSION_MAJOR < 5
bool AsyncClient::connect(const IPv6Address &ip, uint16_t port) {
auto ipaddr = static_cast<const uint32_t *>(ip);
ip_addr_t addr = IPADDR6_INIT(ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]);
return _connect(addr, port);
}
#endif
bool AsyncClient::connect(const char *host, uint16_t port) {
ip_addr_t addr;
if (!_start_async_task()) {
log_e("failed to start task");
return false;
}
TCP_MUTEX_LOCK();
err_t err = dns_gethostbyname(host, &addr, (dns_found_callback)&_tcp_dns_found, this);
TCP_MUTEX_UNLOCK();
if (err == ERR_OK) {
#if ESP_IDF_VERSION_MAJOR < 5
#if LWIP_IPV6
if (addr.type == IPADDR_TYPE_V6) {
return connect(IPv6Address(addr.u_addr.ip6.addr), port);
}
return connect(IPAddress(addr.u_addr.ip4.addr), port);
#else
return connect(IPAddress(addr.addr), port);
#endif
#else
return _connect(addr, port);
#endif
} else if (err == ERR_INPROGRESS) {
_connect_port = port;
return true;
}
log_d("error: %d", err);
return false;
}
void AsyncClient::close(bool now) {
if (_pcb) {
_tcp_recved(_pcb, _closed_slot, _rx_ack_len);
}
_close();
}
int8_t AsyncClient::abort() {
if (_pcb) {
_tcp_abort(_pcb, _closed_slot);
_pcb = NULL;
}
return ERR_ABRT;
}
size_t AsyncClient::space() {
if ((_pcb != NULL) && (_pcb->state == ESTABLISHED)) {
return tcp_sndbuf(_pcb);
}
return 0;
}
size_t AsyncClient::add(const char *data, size_t size, uint8_t apiflags) {
if (!_pcb || size == 0 || data == NULL) {
return 0;
}
size_t room = space();
if (!room) {
return 0;
}
size_t will_send = (room < size) ? room : size;
int8_t err = ERR_OK;
err = _tcp_write(_pcb, _closed_slot, data, will_send, apiflags);
if (err != ERR_OK) {
return 0;
}
return will_send;
}
bool AsyncClient::send() {
auto backup = _tx_last_packet;
_tx_last_packet = millis();
if (_tcp_output(_pcb, _closed_slot) == ERR_OK) {
return true;
}
_tx_last_packet = backup;
return false;
}
size_t AsyncClient::ack(size_t len) {
if (len > _rx_ack_len) {
len = _rx_ack_len;
}
if (len) {
_tcp_recved(_pcb, _closed_slot, len);
}
_rx_ack_len -= len;
return len;
}
void AsyncClient::ackPacket(struct pbuf *pb) {
if (!pb) {
return;
}
_tcp_recved(_pcb, _closed_slot, pb->len);
pbuf_free(pb);
}
/*
* Main Private Methods
* */