Repository navigation
Expand file tree
/
Copy pathRF24Client.cpp
More file actions
1766 lines (1481 loc) · 49.5 KB
/
Copy pathRF24Client.cpp
File metadata and controls
1766 lines (1481 loc) · 49.5 KB
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
/*
RF24Client.cpp - Arduino implementation of a uIP wrapper class.
Copyright (c) 2014 tmrh20@gmail.com, github.com/TMRh20
Copyright (c) 2013 Norbert Truchsess <norbert.truchsess@t-online.de>
All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "RF24Ethernet.h"
#if USE_LWIP == 2
#include <zephyr/kernel.h>
#include <zephyr/net/socket.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <zephyr/net/net_if.h>
#include <zephyr/posix/sys/ioctl.h>
#ifdef __cplusplus
extern "C" {
#endif
struct net_if* rf24_netif_get_iface(void);
#ifdef __cplusplus
}
#endif
RF24Client* RF24Client::g_rf24client_instance = nullptr;
int RF24Client::_socket;
uint32_t RF24Client::serverConnectionTimeout;
uint8_t RF24Client::peekBuffer[64];
#endif
#if USE_LWIP < 1
#define UIP_TCP_PHYH_LEN UIP_LLH_LEN + UIP_IPTCPH_LEN
uip_userdata_t RF24Client::all_data[UIP_CONNS];
#elif USE_LWIP == 1
// #define LWIP_ERR_T uint32_t
//
#if !defined ETHERNET_USING_LWIP_ARDUINO
#include <lwip/tcp.h>
#include "lwip/tcpip.h"
#include "lwip/timeouts.h"
#else
#include "lwip/include/lwip/tcp.h"
#include "lwip/include/lwip/tcpip.h"
#endif
#include "RF24Ethernet.h"
/** \cond */
RF24Client::ConnectState* RF24Client::gState[2];
char* RF24Client::incomingData[2];
uint16_t RF24Client::dataSize[2];
struct tcp_pcb* RF24Client::myPcb;
uint32_t RF24Client::clientConnectionTimeout;
uint32_t RF24Client::serverConnectionTimeout;
uint32_t RF24Client::simpleCounter;
bool RF24Client::activeState;
int32_t RF24Client::accepts;
/***************************************************************************************************/
// Called when the remote host acknowledges receipt of data
err_t RF24Client::sent_callback(void* arg, struct tcp_pcb* tpcb, u16_t len)
{
ConnectState* state = (ConnectState*)arg;
if (state != nullptr) {
state->serverTimer = millis();
state->clientTimer = millis();
IF_ETH_DEBUG_L1(Serial.println("Client: Sent cb"););
state->result = ERR_OK;
}
return ERR_OK;
}
/***************************************************************************************************/
err_t RF24Client::blocking_write(struct tcp_pcb* fpcb, ConnectState* fstate, const char* data, size_t len)
{
if (fpcb == nullptr) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Client: Tx with no fpcb"););
return ERR_CLSD;
}
if (!fstate->connected) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Client: Tx with no connection"););
return ERR_CLSD;
}
const uint32_t timeoutStart = millis();
if (len > tcp_sndbuf(fpcb)) {
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_APPLY_LOCK();
}
#endif
tcp_output(fpcb);
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_REMOVE_LOCK();
}
#endif
}
while (len > tcp_sndbuf(fpcb)) {
Ethernet.update();
if (!fstate->connected || myPcb != fpcb) {
return ERR_CLSD;
}
if (millis() - timeoutStart > serverConnectionTimeout) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.println("Client: TCP Send Buffer full"););
return ERR_BUF;
}
}
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_APPLY_LOCK();
}
#endif
size_t written = 0;
while (written < len) {
size_t segment = fpcb->snd_wnd_max / 2 < fpcb->mss ? fpcb->snd_wnd_max / 2 : fpcb->mss;
if (segment < 1) {
segment = 1;
}
const size_t piece = (len - written) < segment ? (len - written) : segment;
err_t err = tcp_write(fpcb, data + written, piece, TCP_WRITE_FLAG_COPY);
if (err == ERR_OK) {
written += piece;
continue;
}
if (err != ERR_MEM) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Client: BLK Write fail 2: "); Serial.println((int)err););
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_REMOVE_LOCK();
}
#endif
return err;
}
// ERR_MEM: lwIP's send queue is full. That is not an error: send what is queued and wait
tcp_output(fpcb);
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_REMOVE_LOCK();
}
#endif
Ethernet.update();
if (!fstate->connected || myPcb != fpcb) {
return ERR_CLSD;
}
if (millis() - timeoutStart > serverConnectionTimeout) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.println("Client: TCP Send queue full"););
return ERR_BUF;
}
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_APPLY_LOCK();
}
#endif
}
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_REMOVE_LOCK();
}
#endif
Ethernet.update();
return ERR_OK;
}
/***************************************************************************************************/
void RF24Client::error_callback(void* arg, err_t err)
{
ConnectState* state = (ConnectState*)arg;
if (state != nullptr) {
state->result = err;
state->connected = false;
dataSize[state->stateActiveID] = 0;
if (state->stateActiveID == activeState) {
myPcb = nullptr;
}
}
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Client: Err cb: "); Serial.println((int)err););
}
/***************************************************************************************************/
err_t RF24Client::srecv_callback(void* arg, struct tcp_pcb* tpcb, struct pbuf* p, err_t err)
{
ConnectState* state = (ConnectState*)arg;
if (state != nullptr) {
state->serverTimer = millis();
}
if (p == nullptr) {
if (state != nullptr) {
state->connected = false;
}
if (tpcb != nullptr) {
if (tcp_close(tpcb) != ERR_OK) {
if (myPcb == tpcb) {
myPcb = nullptr;
}
tcp_abort(tpcb);
tpcb = nullptr;
return ERR_ABRT;
}
if (myPcb == tpcb) {
myPcb = nullptr;
}
tpcb = nullptr;
}
return ERR_OK;
}
if (err != ERR_OK || state == nullptr) {
if (p)
pbuf_free(p);
return ERR_OK;
}
bool id = state->stateActiveID;
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Server: Copy data to "); Serial.println(state->stateActiveID););
struct pbuf* q = p;
uint16_t acked = 0;
if (dataSize[id] + p->tot_len > INCOMING_DATA_SIZE) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.println("Client: recv - Out of incoming buffer space"););
return ERR_MEM;
}
while (q != nullptr) {
memcpy(&incomingData[id][dataSize[id]], q->payload, q->len);
dataSize[id] += q->len;
acked += q->len;
q = q->next;
}
if (tpcb != nullptr && acked > 0) {
tcp_recved(tpcb, acked);
}
if (p) {
pbuf_free(p);
}
return ERR_OK;
}
/***************************************************************************************************/
err_t RF24Client::recv_callback(void* arg, struct tcp_pcb* tpcb, struct pbuf* p, err_t err)
{
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.println("Client: Recv cb"););
ConnectState* state = (ConnectState*)arg;
if (p == nullptr) {
if (state != nullptr) {
state->connected = false;
}
if (tpcb != nullptr) {
if (tcp_close(tpcb) != ERR_OK) {
if (myPcb == tpcb) {
myPcb = nullptr;
}
tcp_abort(tpcb);
tpcb = nullptr;
return ERR_ABRT;
}
if (myPcb == tpcb) {
myPcb = nullptr;
}
tpcb = nullptr;
}
return err;
}
if (err != ERR_OK || state == nullptr) {
if (p)
pbuf_free(p);
return err;
}
if (state != nullptr) {
state->clientTimer = millis();
}
bool id = state->stateActiveID;
struct pbuf* q = p;
uint16_t acked = 0;
if (dataSize[id] + p->tot_len > INCOMING_DATA_SIZE) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.println("Client: recv - Out of incoming buffer space"););
return ERR_MEM;
}
while (q != nullptr) {
memcpy(&incomingData[id][dataSize[id]], q->payload, q->len);
dataSize[id] += q->len;
acked += q->len;
q = q->next;
}
if (tpcb != nullptr && acked > 0) {
tcp_recved(tpcb, acked);
}
if (p) {
pbuf_free(p);
}
return ERR_OK;
}
/***************************************************************************************************/
//void RF24Client::setConnectionTimeout(uint32_t timeout)
//{
// clientConnectionTimeout = timeout;
//}
/***************************************************************************************************/
err_t RF24Client::clientTimeouts(void* arg, struct tcp_pcb* tpcb)
{
ConnectState* state = (ConnectState*)arg;
if (state != nullptr) {
if (millis() - state->clientTimer > state->cConnectionTimeout) {
if (tpcb->state == ESTABLISHED || tpcb->state == SYN_SENT || tpcb->state == SYN_RCVD) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.println("Client: Closed Client PCB TIMEOUT"););
err_t err = tcp_close(tpcb);
state->result = err;
state->connected = false;
}
}
}
return ERR_OK;
}
/***************************************************************************************************/
err_t RF24Client::serverTimeouts(void* arg, struct tcp_pcb* tpcb)
{
ConnectState* state = (ConnectState*)arg;
if (state != nullptr && tpcb != nullptr) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Server: Stimeout cb "); Serial.println(millis() - state->serverTimer););
state->result = ERR_OK;
if (millis() - state->serverTimer > state->sConnectionTimeout) {
//if (tpcb->state == ESTABLISHED || tpcb->state == SYN_SENT || tpcb->state == SYN_RCVD) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.println("Server: Closed Server PCB TIMEOUT "););
state->result = tcp_close(tpcb);
state->closeTimer = millis();
dataSize[activeState] = 0;
state->connected = false;
if (state->result != ERR_OK) {
if (myPcb == tpcb) {
tcp_arg(myPcb, nullptr);
myPcb = nullptr;
}
tcp_arg(tpcb, nullptr);
tcp_abort(tpcb);
tpcb = nullptr;
return ERR_ABRT;
}
myPcb = nullptr;
return state->result;
// }
}
return state->result;
}
return ERR_CLSD;
}
/***************************************************************************************************/
err_t RF24Client::closed_port(void* arg, struct tcp_pcb* tpcb)
{
ConnectState* state = (ConnectState*)arg;
if (state != nullptr) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Server: Client Poll Cb ID: "); Serial.println(state->identifier));
}
if (myPcb == nullptr) {
if (state != nullptr && tpcb != nullptr) {
if ((tpcb->state == ESTABLISHED || tpcb->state == SYN_SENT || tpcb->state == SYN_RCVD)) {
if (state->backlogWasAccepted == false) {
state->backlogWasAccepted = true;
state->connectTimestamp = millis();
state->connected = true;
accepts--;
myPcb = tpcb;
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Server: ACCEPT delayed PCB "); Serial.println(state->identifier););
tcp_backlog_accepted(tpcb);
activeState = state->stateActiveID;
return ERR_OK;
}
}
}
}
if (tpcb != nullptr) {
if (state != nullptr) {
if (millis() - state->connectTimestamp > state->sConnectionTimeout * 2) {
if ((tpcb->state == ESTABLISHED || tpcb->state == SYN_SENT || tpcb->state == SYN_RCVD)) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Server: Close off delayed PCB function 1, ID: "); Serial.println(state->identifier););
if (state->backlogWasAccepted == false) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.println("Server: With backlog accepted"););
tcp_backlog_accepted(tpcb);
state->backlogWasAccepted = true;
accepts--;
}
state->result = tcp_close(tpcb);
state->connected = false;
if (state->result == ERR_OK) {
state->closeTimer = millis();
}
else {
tcp_abort(tpcb);
tpcb = nullptr;
return ERR_ABRT;
}
return state->result;
}
}
}
}
return ERR_OK;
}
/**************************************************************************************************/
err_t RF24Client::accept(void* arg, struct tcp_pcb* tpcb, err_t err)
{
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Server: Accept cb, ID: "); Serial.println(simpleCounter + 1););
if (tpcb == nullptr) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Server: Accepted conn, but no tpcb from: "); Serial.println(ip4addr_ntoa(ip_2_ip4(&tpcb->remote_ip))););
return ERR_CLSD;
}
if (tpcb != nullptr) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Server: Client connect from: "); Serial.println(ip4addr_ntoa(ip_2_ip4(&tpcb->remote_ip))););
}
bool actState = activeState;
if (myPcb != nullptr) {
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print("Server: Accept w/already connected: Accepted_Conns - Delayed_Conns == "); Serial.println(accepts););
tcp_backlog_delayed(tpcb);
accepts++;
tcp_poll(tpcb, closed_port, 5);
actState = !activeState;
gState[actState]->connected = false;
gState[actState]->backlogWasAccepted = false;
}
else {
myPcb = tpcb;
tcp_poll(tpcb, serverTimeouts, 8);
activeState = !activeState;
actState = activeState;
gState[actState]->connected = true;
gState[actState]->backlogWasAccepted = true;
}
dataSize[actState] = 0;
simpleCounter += 1;
gState[actState]->stateActiveID = actState;
gState[actState]->identifier = simpleCounter;
gState[actState]->sConnectionTimeout = serverConnectionTimeout;
gState[actState]->connectTimestamp = millis();
gState[actState]->serverTimer = millis();
tcp_arg(tpcb, RF24Client::gState[actState]);
tcp_recv(tpcb, srecv_callback);
tcp_sent(tpcb, sent_callback);
tcp_err(tpcb, error_callback);
return ERR_OK;
}
/***************************************************************************************************/
err_t RF24Client::closeConn(void* arg, struct tcp_pcb* tpcb)
{
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.println("Client: Immediate close"););
if (tpcb != nullptr) {
tcp_close(tpcb);
}
return ERR_OK;
}
/***************************************************************************************************/
// Callback triggered by lwIP when handshake completes
err_t RF24Client::on_connected(void* arg, struct tcp_pcb* tpcb, err_t err)
{
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.println("Client: Conn cb"););
ConnectState* state = (ConnectState*)arg;
if (state != nullptr) {
/*if (state->cConnectionTimeout > 0) {
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if(Ethernet.useCoreLocking){if(Ethernet.useCoreLocking){ ETHERNET_APPLY_LOCK(); } }
#endif
tcp_poll(tpcb, clientTimeouts, 30);
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if(Ethernet.useCoreLocking){ ETHERNET_REMOVE_LOCK(); }
#endif
}*/
state->cConnectionTimeout = clientConnectionTimeout;
state->clientTimer = millis();
state->result = err;
if (err == ERR_OK) {
state->connected = true;
}
else {
state->connected = false;
}
}
return err;
}
/** \endcond */
#endif // USE_LWIP == 1
/***************************************************************************************************/
#if USE_LWIP < 1
RF24Client::RF24Client() : data(NULL)
{
}
#elif USE_LWIP == 1
RF24Client::RF24Client() : data(0)
{
}
#elif USE_LWIP == 2
RF24Client::RF24Client() : data(0), _lastError(0)
{
g_rf24client_instance = this;
}
#endif
/*************************************************************/
#if USE_LWIP < 1
RF24Client::RF24Client(uip_userdata_t* conn_data) : data(conn_data)
{
}
#else
/** \cond */
RF24Client::RF24Client(uint32_t data) : data(0)
{
}
/** \endcond */
#endif
/*************************************************************/
uint8_t RF24Client::connected()
{
#if USE_LWIP < 1
return (data && (data->packets_in != 0 || (data->state & UIP_CLIENT_CONNECTED))) ? 1 : 0;
#elif USE_LWIP == 1
if (gState[activeState] != nullptr) {
return gState[activeState]->connected || dataSize[activeState] > 0;
}
return 0;
#elif USE_LWIP == 2
if (_socket < 0) {
return 0;
}
RF24Ethernet.update();
// 1. If we already established the connection before, track via standard POLLIN/errors
if (connectionEstablished) {
struct zsock_pollfd pfd {};
pfd.fd = _socket;
pfd.events = ZSOCK_POLLIN;
int rc = zsock_poll(&pfd, 1, 0);
if (rc < 0)
return 0;
if (rc > 0) {
if (pfd.revents & (ZSOCK_POLLHUP | ZSOCK_POLLERR | ZSOCK_POLLNVAL)) {
connectionEstablished = false;
if (_socket >= 0) {
zsock_close(_socket);
_socket = -1;
}
return 0;
}
if (pfd.revents & ZSOCK_POLLIN) {
uint8_t dummy;
int n = zsock_recv(_socket, &dummy, 1, ZSOCK_MSG_PEEK | ZSOCK_MSG_DONTWAIT);
if (n == 0) { // Remote peer closed connection (FIN)
connectionEstablished = false;
if (_socket >= 0) {
zsock_close(_socket);
_socket = -1;
}
return 0;
}
}
}
return 1;
}
// 2. Handshake Phase: Check if the background connect has finished
struct zsock_pollfd pfd {};
pfd.fd = _socket;
pfd.events = ZSOCK_POLLOUT; // A successful non-blocking connect makes the socket writable
int rc = zsock_poll(&pfd, 1, 0);
if (rc < 0) {
return 0; // Poll failed
}
// If poll returns 0, the handshake is still actively processing in the background (EINPROGRESS)
if (rc == 0) {
return 0;
}
// The socket state changed. Let's see if it's an error or a success.
if (pfd.revents & (ZSOCK_POLLERR | ZSOCK_POLLHUP)) {
if (_socket >= 0) {
zsock_close(_socket);
_socket = -1;
}
return 0; // Failed to connect
}
if (pfd.revents & ZSOCK_POLLOUT) {
// Double-check the socket's internal error state to confirm success
int error = 0;
socklen_t len = sizeof(error);
int ret = zsock_getsockopt(_socket, SOL_SOCKET, SO_ERROR, &error, &len);
if (ret < 0 || error != 0) {
if (_socket >= 0) {
zsock_close(_socket);
_socket = -1;
}
return 0; // The handshake failed behind the scenes (e.g. Connection Refused)
}
// Connection successfully established!
connectionEstablished = true;
return 1;
}
if (_socket >= 0) {
zsock_close(_socket);
_socket = -1;
}
return 0;
#endif
}
/*************************************************************/
int RF24Client::connect(IPAddress ip, uint16_t port)
{
#if USE_LWIP < 1
#if UIP_ACTIVE_OPEN > 0
// do{
stop();
uip_ipaddr_t ipaddr;
uip_ip_addr(ipaddr, ip);
struct uip_conn* conn = uip_connect(&ipaddr, htons(port));
if (conn)
{
#if UIP_CONNECTION_TIMEOUT > 0
uint32_t timeout = millis();
#endif
while ((conn->tcpstateflags & UIP_TS_MASK) != UIP_CLOSED)
{
Ethernet.update();
if ((conn->tcpstateflags & UIP_TS_MASK) == UIP_ESTABLISHED)
{
data = (uip_userdata_t*)conn->appstate;
IF_RF24ETHERNET_DEBUG_CLIENT(Serial.print(millis()); Serial.print(F(" connected, state: ")); Serial.print(data->state); Serial.print(F(", first packet in: ")); Serial.println(data->packets_in););
return 1;
}
#if UIP_CONNECTION_TIMEOUT > 0
if ((millis() - timeout) > UIP_CONNECTION_TIMEOUT)
{
conn->tcpstateflags = UIP_CLOSED;
break;
}
#endif
}
}
// delay(25);
// }while(millis()-timer < 175);
#endif // Active open enabled
#elif USE_LWIP == 1
if (myPcb != nullptr) {
_stop();
return ERR_CLSD;
}
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_APPLY_LOCK();
}
#endif
if (myPcb == nullptr) {
myPcb = tcp_new();
}
if (!myPcb) {
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_REMOVE_LOCK();
}
#endif
return 0;
}
dataSize[activeState] = 0;
memset(incomingData[activeState], 0, INCOMING_DATA_SIZE);
gState[activeState]->connected = false;
gState[activeState]->result = 0;
tcp_arg(myPcb, gState[activeState]);
tcp_err(myPcb, error_callback);
tcp_recv(myPcb, recv_callback);
tcp_sent(myPcb, sent_callback);
//tcp_poll(myPcb, clientTimeouts, 30);
err_t err = ERR_OK;
ip_addr_t myIp;
IP_ADDR4(&myIp, ip[0], ip[1], ip[2], ip[3]);
err = tcp_connect(myPcb, &myIp, port, on_connected);
if (err != ERR_OK || gState[activeState]->result != ERR_OK) {
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_REMOVE_LOCK();
}
#endif
stop();
return ERR_CLSD;
}
#if defined RF24ETHERNET_CORE_REQUIRES_LOCKING
if (Ethernet.useCoreLocking) {
ETHERNET_REMOVE_LOCK();
}
#endif
const uint32_t timeoutStart = millis();
// Simulate blocking by looping until the callback sets 'connected'
while (!gState[activeState]->connected && millis() - timeoutStart < 5000) {
Ethernet.update();
}
if (clientConnectionTimeout > 0) {
gState[activeState]->clientPollingSetup = 1;
}
return gState[activeState]->connected;
#elif USE_LWIP == 2
if (port == 0)
return -EINVAL;
int sock = zsock_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
return -errno;
}
// --- CRITICAL FIX 1: Set the socket to non-blocking BEFORE connecting ---
int flags = zsock_fcntl(sock, F_GETFL, 0);
if (flags < 0) {
int e = errno;
zsock_close(sock);
return -e;
}
zsock_fcntl(sock, F_SETFL, flags | O_NONBLOCK);
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
char ipstr[16];
snprintf(ipstr, sizeof(ipstr), "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
if (net_addr_pton(AF_INET, ipstr, &addr.sin_addr) < 0) {
zsock_close(sock);
return -EINVAL;
}
int rc = zsock_connect(sock, (const struct sockaddr*)&addr, sizeof(addr));
if (rc == 0) {
_socket = sock; // <-- save it here
_lastError = 0;
IF_RF24ETHERNET_DEBUG_CLIENT(printk("CONNECT OK fd=%d\n", _socket));
RF24Server::connectionActive = true;
return 1;
}
if (errno != EINPROGRESS) {
int e = errno;
zsock_close(sock);
return -e;
}
// --- CRITICAL FIX 2: Use Zephyr's native uptime timer instead of Arduino's millis() ---
int64_t start_time = k_uptime_get();
// Loop for up to 5000 milliseconds (5 seconds)
while (k_uptime_get() - start_time < 5000) {
// 1) Service RF24 every iteration
RF24Ethernet.update();
// 2) Non-blocking check of connect completion
struct zsock_pollfd pfd = {
.fd = sock,
.events = ZSOCK_POLLOUT,
.revents = 0,
};
rc = zsock_poll(&pfd, 1, 0); // zero timeout
if (rc < 0) {
int e = errno;
zsock_close(sock);
return -e;
}
if (rc > 0 && (pfd.revents & (ZSOCK_POLLOUT | ZSOCK_POLLERR | ZSOCK_POLLHUP))) {
int soerr = 0;
socklen_t slen = sizeof(soerr);
if (zsock_getsockopt(sock, SOL_SOCKET, SO_ERROR, &soerr, &slen) < 0) {
int e = errno;
zsock_close(sock);
return -e;
}
if (soerr == 0) {
// Remove O_NONBLOCK flag to cleanly destroy blocking context
zsock_fcntl(sock, F_SETFL, flags & ~O_NONBLOCK);
_socket = sock; // <-- save it here
_lastError = 0;
IF_RF24ETHERNET_DEBUG_CLIENT(printk("CONNECT OK fd=%d\n", _socket));
RF24Server::connectionActive = true;
return 1;
}
zsock_fcntl(sock, F_SETFL, flags & ~O_NONBLOCK);
zsock_close(sock);
return -soerr;
}
// --- CRITICAL FIX 3: Use Zephyr's native kernel sleep to yield CPU time ---
// This yields execution to Zephyr's network workqueues, timers, and scheduler threads
k_msleep(2);
}
// Timed out cleanup
zsock_fcntl(sock, F_SETFL, flags & ~O_NONBLOCK);
zsock_close(sock);
return -ETIMEDOUT;
return 0;
#endif
return 0;
}
/*************************************************************/
#if USE_LWIP == 1
void dnsCallback(const char* name, const ip_addr_t* ipaddr, void* callback_arg)
{
}
#endif
/*************************************************************/
int RF24Client::connect(const char* host, uint16_t port)
{
// Look up the host first
int ret = 0;
#if UIP_UDP
DNSClient dns;
IPAddress remote_addr;
dns.begin(RF24EthernetClass::_dnsServerAddress);
ret = dns.getHostByName(host, remote_addr);
if (ret == 1)
{
#if defined(ETH_DEBUG_L1) || defined(RF24ETHERNET_DEBUG_DNS)
Serial.println(F("*UIP Got DNS*"));
#endif
return connect(remote_addr, port);
}
#elif RF24ETHERNET_USE_UDP
DNSClient dns;
IPAddress remote_addr;
dns.begin(RF24EthernetClass::_dnsServerAddress);
ret = dns.getHostByName(host, remote_addr);
if (ret == 1)
{
#if defined(ETH_DEBUG_L1) || defined(RF24ETHERNET_DEBUG_DNS)
Serial.println(F("*lwIP Got DNS*"));
#endif
return connect(remote_addr, port);
}
#else // ! UIP_UDP
// Do something with the input parameters to prevent compile time warnings
if (host) {
};
if (port) {
};
#endif // ! UIP_UDP
#if defined(ETH_DEBUG_L1) || defined(RF24ETHERNET_DEBUG_DNS)
Serial.println(F("* DNS fail*"));
#endif
return 0;
}
/*************************************************************/
void RF24Client::stop()
{
#if USE_LWIP < 1
if (data && data->state)