-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLinkWireless.hpp
1933 lines (1646 loc) · 62.6 KB
/
LinkWireless.hpp
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
#ifndef LINK_WIRELESS_H
#define LINK_WIRELESS_H
// --------------------------------------------------------------------------
// A high level driver for the GBA Wireless Adapter.
// --------------------------------------------------------------------------
// Usage:
// - 1) Include this header in your main.cpp file and add:
// LinkWireless* linkWireless = new LinkWireless();
// - 2) Add the required interrupt service routines: (*)
// interrupt_init();
// interrupt_add(INTR_VBLANK, LINK_WIRELESS_ISR_VBLANK);
// interrupt_add(INTR_SERIAL, LINK_WIRELESS_ISR_SERIAL);
// interrupt_add(INTR_TIMER3, LINK_WIRELESS_ISR_TIMER);
// - 3) Initialize the library with:
// linkWireless->activate();
// - 4) Start a server:
// linkWireless->serve();
//
// // `getState()` should return SERVING now...
// // `currentPlayerId()` should return 0
// // `playerCount()` should return the number of active consoles
// - 5) Connect to a server:
// LinkWireless::Server servers[LINK_WIRELESS_MAX_SERVERS];
// u32 serverCount;
// linkWireless->getServers(servers, serverCount);
// if (serverCount == 0) return;
//
// linkWireless->connect(servers[0].id);
// while (linkWireless->getState() == LinkWireless::State::CONNECTING)
// linkWireless->keepConnecting();
//
// // `getState()` should return CONNECTED now...
// // `currentPlayerId()` should return 1, 2, 3, or 4 (the host is 0)
// // `playerCount()` should return the number of active consoles
// - 6) Send data:
// linkWireless->send(0x1234);
// - 7) Receive data:
// LinkWireless::Message messages[LINK_WIRELESS_QUEUE_SIZE];
// u32 receivedCount;
// linkWireless->receive(messages, receivedCount);
// - 8) Disconnect:
// linkWireless->activate();
// // (resets the adapter)
// --------------------------------------------------------------------------
// (*) libtonc's interrupt handler sometimes ignores interrupts due to a bug.
// That causes packet loss. You REALLY want to use libugba's instead.
// (see examples)
// --------------------------------------------------------------------------
#ifndef LINK_DEVELOPMENT
#pragma GCC system_header
#endif
#include "_link_common.hpp"
#include "LinkRawWireless.hpp"
#ifndef LINK_WIRELESS_QUEUE_SIZE
/**
* @brief Buffer size (how many incoming and outgoing messages the queues can
* store at max **per player**). The default value is `30`, which seems fine for
* most games.
* \warning This affects how much memory is allocated. With the default value,
* it's around `480` bytes. There's a double-buffered incoming queue and a
* double-buffered outgoing queue (to avoid data races).
* \warning You can approximate the usage with `LINK_WIRELESS_QUEUE_SIZE * 16`.
*/
#define LINK_WIRELESS_QUEUE_SIZE 30
#endif
#ifndef LINK_WIRELESS_MAX_SERVER_TRANSFER_LENGTH
/**
* @brief Max server transfer length per timer tick. Must be in the range
* `[6;21]`. The default value is `11`. Higher values will use the bandwidth
* more efficiently but also consume more CPU!
* \warning This is measured in words (1 message = 1 halfword). One word is used
* as a header, so a max transfer length of 11 could transfer up to 20 messages.
*/
#define LINK_WIRELESS_MAX_SERVER_TRANSFER_LENGTH 11
#endif
#ifndef LINK_WIRELESS_MAX_CLIENT_TRANSFER_LENGTH
/**
* @brief Max client transfer length per timer tick. Must be in the range
* `[2;4]`. The default value is `4`. Changing this is not recommended, it's
* already too low.
* \warning This is measured in words (1 message = 1 halfword). One halfword is
* used as a header, so a max transfer length of 4 could transfer up to 7
* messages.
*/
#define LINK_WIRELESS_MAX_CLIENT_TRANSFER_LENGTH 4
#endif
#ifndef LINK_WIRELESS_PUT_ISR_IN_IWRAM
/**
* @brief Put Interrupt Service Routines (ISR) in IWRAM (uncomment to enable).
* This can significantly improve performance due to its faster access, but it's
* disabled by default to conserve IWRAM space, which is limited.
* \warning If you enable this, make sure that `lib/iwram_code/LinkWireless.cpp`
* gets compiled! For example, in a Makefile-based project, verify that the
* directory is in your `SRCDIRS` list.
*/
// #define LINK_WIRELESS_PUT_ISR_IN_IWRAM
#endif
#ifndef LINK_WIRELESS_ENABLE_NESTED_IRQ
/**
* @brief Allow LINK_WIRELESS_ISR_* functions to be interrupted (uncomment to
* enable).
* This can be useful, for example, if your audio engine requires calling a
* VBlank handler with precise timing.
*/
// #define LINK_WIRELESS_ENABLE_NESTED_IRQ
#endif
// --- LINK_WIRELESS_PUT_ISR_IN_IWRAM knobs ---
#ifndef LINK_WIRELESS_PUT_ISR_IN_IWRAM_SERIAL
#define LINK_WIRELESS_PUT_ISR_IN_IWRAM_SERIAL 1
#endif
#ifndef LINK_WIRELESS_PUT_ISR_IN_IWRAM_TIMER
#define LINK_WIRELESS_PUT_ISR_IN_IWRAM_TIMER 1
#endif
#ifndef LINK_WIRELESS_PUT_ISR_IN_IWRAM_SERIAL_LEVEL
#define LINK_WIRELESS_PUT_ISR_IN_IWRAM_SERIAL_LEVEL "-Ofast"
#endif
#ifndef LINK_WIRELESS_PUT_ISR_IN_IWRAM_TIMER_LEVEL
#define LINK_WIRELESS_PUT_ISR_IN_IWRAM_TIMER_LEVEL "-Ofast"
#endif
//---
LINK_VERSION_TAG LINK_WIRELESS_VERSION = "vLinkWireless/v8.0.1";
#define LINK_WIRELESS_MAX_PLAYERS LINK_RAW_WIRELESS_MAX_PLAYERS
#define LINK_WIRELESS_MIN_PLAYERS 2
#define LINK_WIRELESS_MAX_SERVERS LINK_RAW_WIRELESS_MAX_SERVERS
#define LINK_WIRELESS_MAX_GAME_ID 0x7FFF
#define LINK_WIRELESS_MAX_GAME_NAME_LENGTH 14
#define LINK_WIRELESS_MAX_USER_NAME_LENGTH 8
#define LINK_WIRELESS_DEFAULT_TIMEOUT 10
#define LINK_WIRELESS_DEFAULT_INTERVAL 75
#define LINK_WIRELESS_DEFAULT_SEND_TIMER_ID 3
#define LINK_WIRELESS_RESET_IF_NEEDED \
if (!isEnabled) \
return false; \
if (linkRawWireless.getState() == State::NEEDS_RESET) \
if (!reset()) \
return false;
#ifdef LINK_WIRELESS_PUT_ISR_IN_IWRAM
#if LINK_WIRELESS_PUT_ISR_IN_IWRAM_SERIAL == 1
#define LINK_WIRELESS_SERIAL_ISR LINK_INLINE
#else
#define LINK_WIRELESS_SERIAL_ISR
#endif
#if LINK_WIRELESS_PUT_ISR_IN_IWRAM_TIMER == 1
#define LINK_WIRELESS_TIMER_ISR LINK_INLINE
#else
#define LINK_WIRELESS_TIMER_ISR
#endif
#define LINK_WIRELESS_ISR_FUNC(name, params, args, body) \
void name params; \
LINK_INLINE void _##name params body
#else
#define LINK_WIRELESS_SERIAL_ISR
#define LINK_WIRELESS_TIMER_ISR
#define LINK_WIRELESS_ISR_FUNC(name, params, args, body) \
void name params { \
_##name args; \
} \
LINK_INLINE void _##name params body
#endif
/**
* @brief A high level driver for the GBA Wireless Adapter.
*/
class LinkWireless {
private:
using u32 = Link::u32;
using u16 = Link::u16;
using u8 = Link::u8;
using vu8 = Link::vu8;
static constexpr auto BASE_FREQUENCY = Link::_TM_FREQ_1024;
static constexpr int BROADCAST_SEARCH_WAIT_FRAMES = 60;
static constexpr int MAX_PACKET_IDS_SERVER = 1 << 6;
static constexpr int MAX_PACKET_IDS_CLIENT = 1 << 4;
static constexpr int MAX_INFLIGHT_PACKETS_SERVER =
MAX_PACKET_IDS_SERVER / 2 - 1;
static constexpr int MAX_INFLIGHT_PACKETS_CLIENT =
MAX_PACKET_IDS_CLIENT / 2 - 1;
static constexpr int NO_ID_ASSIGNED_YET = 0xFF;
static constexpr u32 NO_ACK_RECEIVED_YET = 0xFFFFFFFF;
static constexpr int HAS_FIRST_MSG_MASK = 0b10000;
static constexpr int MAX_PLAYER_BITMAP_ENTRIES = 5;
static constexpr int PLAYER_ID_BITS = 3;
static constexpr int PLAYER_ID_MASK = 0b111;
static constexpr int BIT_HAS_MORE = 15;
public:
// #define LINK_WIRELESS_PROFILING_ENABLED
#ifdef LINK_WIRELESS_PROFILING_ENABLED
u32 vblankTime = 0;
u32 serialTime = 0;
u32 timerTime = 0;
u32 vblankIRQs = 0;
u32 serialIRQs = 0;
u32 timerIRQs = 0;
#endif
using State = LinkRawWireless::State;
using SignalLevelResponse = LinkRawWireless::SignalLevelResponse;
enum class Error {
// User errors
NONE = 0,
WRONG_STATE = 1,
GAME_NAME_TOO_LONG = 2,
USER_NAME_TOO_LONG = 3,
BUFFER_IS_FULL = 4,
// Communication errors
COMMAND_FAILED = 5,
CONNECTION_FAILED = 6,
SEND_DATA_FAILED = 7,
RECEIVE_DATA_FAILED = 8,
ACKNOWLEDGE_FAILED = 9,
TIMEOUT = 10,
REMOTE_TIMEOUT = 11,
BUSY_TRY_AGAIN = 12,
};
struct Message {
u16 data = 0;
u8 playerId = 0;
u8 packetId = NO_ID_ASSIGNED_YET;
};
struct Server {
u16 id = 0;
u16 gameId;
char gameName[LINK_WIRELESS_MAX_GAME_NAME_LENGTH + 1];
char userName[LINK_WIRELESS_MAX_USER_NAME_LENGTH + 1];
u8 currentPlayerCount;
bool isFull() { return currentPlayerCount == 0; }
};
/**
* @brief Constructs a new LinkWireless object.
* @param forwarding If `true`, the server forwards all messages to the
* clients. Otherwise, clients only see messages sent from the server
* (ignoring other peers).
* @param retransmission If `true`, the library handles retransmission for
* you, so there should be no packet loss.
* @param maxPlayers `(2~5)` Maximum number of allowed players.
* @param timeout Number of *frames* without receiving *any* data to reset the
* connection.
* @param interval Number of *1024-cycle ticks* (61.04μs) between transfers
* *(75 = 4.578ms)*. It's the interval of Timer #`sendTimerId`. Lower values
* will transfer faster but also consume more CPU.
* @param sendTimerId `(0~3)` GBA Timer to use for sending.
* \warning You can use `Link::perFrame(...)` to convert from *packets per
* frame* to *interval values*.
*/
explicit LinkWireless(bool forwarding = true,
bool retransmission = true,
u8 maxPlayers = LINK_WIRELESS_MAX_PLAYERS,
u32 timeout = LINK_WIRELESS_DEFAULT_TIMEOUT,
u16 interval = LINK_WIRELESS_DEFAULT_INTERVAL,
u8 sendTimerId = LINK_WIRELESS_DEFAULT_SEND_TIMER_ID) {
config.forwarding = forwarding;
config.retransmission = retransmission;
config.maxPlayers = maxPlayers;
config.timeout = timeout;
config.interval = interval;
config.sendTimerId = sendTimerId;
}
/**
* @brief Returns whether the library is active or not.
*/
[[nodiscard]] bool isActive() { return isEnabled; }
/**
* @brief Activates the library. When an adapter is connected, it changes the
* state to `AUTHENTICATED`. It can also be used to disconnect or reset the
* adapter.
*/
bool activate() {
LINK_READ_TAG(LINK_WIRELESS_VERSION);
static_assert(LINK_WIRELESS_QUEUE_SIZE >= 1);
static_assert(LINK_WIRELESS_MAX_SERVER_TRANSFER_LENGTH >= 6 &&
LINK_WIRELESS_MAX_SERVER_TRANSFER_LENGTH <= 21);
static_assert(LINK_WIRELESS_MAX_CLIENT_TRANSFER_LENGTH >= 2 &&
LINK_WIRELESS_MAX_CLIENT_TRANSFER_LENGTH <= 4);
LINK_BARRIER;
isEnabled = false;
LINK_BARRIER;
lastError = Error::NONE;
bool success = reset();
LINK_BARRIER;
isEnabled = true;
LINK_BARRIER;
return success;
}
/**
* @brief Restores the state from an existing connection on the Wireless
* Adapter hardware. This is useful, for example, after a fresh launch of a
* Multiboot game, to synchronize the library with the current state and
* avoid a reconnection. Returns whether the restoration was successful.
* On success, the state should be either `SERVING` or `CONNECTED`.
* \warning This should be used as a replacement for `activate()`.
*/
bool restoreExistingConnection() {
LINK_BARRIER;
isEnabled = false;
LINK_BARRIER;
resetState();
stopTimer();
startTimer();
if (!linkRawWireless.restoreExistingConnection() ||
linkRawWireless.sessionState.playerCount > config.maxPlayers) {
deactivate();
return false;
}
LINK_BARRIER;
isEnabled = true;
LINK_BARRIER;
return true;
}
/**
* @brief Puts the adapter into a low consumption mode and then deactivates
* the library. It returns a boolean indicating whether the transition to low
* consumption mode was successful.
* @param turnOff Whether the library should put the adapter in the low
* consumption mode or not before deactivation. Defaults to `true`.
*/
bool deactivate(bool turnOff = true) {
bool success = true;
if (turnOff)
success = activate() && linkRawWireless.bye();
lastError = Error::NONE;
isEnabled = false;
resetState();
stop();
return success;
}
/**
* @brief Starts broadcasting a server and changes the state to `SERVING`. You
* can optionally provide data that games will be able to read. If the adapter
* is already serving, this method only updates the broadcast data.
* @param gameName Game name. Maximum `14` characters + null terminator.
* @param userName User name. Maximum `8` characters + null terminator.
* @param gameId `(0 ~ 0x7FFF)` Game ID.
* \warning Updating broadcast data while serving can fail if the adapter is
* busy. In that case, this will return `false` and `getLastError()` will be
* `BUSY_TRY_AGAIN`.
*/
bool serve(const char* gameName = "",
const char* userName = "",
u16 gameId = LINK_WIRELESS_MAX_GAME_ID) {
LINK_WIRELESS_RESET_IF_NEEDED
if (linkRawWireless.getState() != State::AUTHENTICATED &&
linkRawWireless.getState() != State::SERVING)
return badRequest(Error::WRONG_STATE);
if (Link::strlen(gameName) > LINK_WIRELESS_MAX_GAME_NAME_LENGTH)
return badRequest(Error::GAME_NAME_TOO_LONG);
if (Link::strlen(userName) > LINK_WIRELESS_MAX_USER_NAME_LENGTH)
return badRequest(Error::USER_NAME_TOO_LONG);
isSendingSyncCommand = true;
if (isAsyncCommandActive())
return badRequest(Error::BUSY_TRY_AGAIN);
if (linkRawWireless.getState() != State::SERVING) {
if (!setup(config.maxPlayers))
return abort(Error::COMMAND_FAILED);
}
bool success = linkRawWireless.broadcast(gameName, userName, gameId, false);
if (linkRawWireless.getState() != State::SERVING)
success = success && linkRawWireless.startHost(false);
if (!success)
return abort(Error::COMMAND_FAILED);
LINK_BARRIER;
isSendingSyncCommand = false;
LINK_BARRIER;
return true;
}
/**
* @brief Closes the server while keeping the session active, to prevent new
* users from joining the room.
* \warning This action can fail if the adapter is busy. In that case,
* this will return `false` and `getLastError()` will be `BUSY_TRY_AGAIN`.
*/
bool closeServer() {
LINK_WIRELESS_RESET_IF_NEEDED
if (linkRawWireless.getState() != State::SERVING ||
linkRawWireless.sessionState.isServerClosed)
return badRequest(Error::WRONG_STATE);
isSendingSyncCommand = true;
if (isAsyncCommandActive())
return badRequest(Error::BUSY_TRY_AGAIN);
LinkRawWireless::PollConnectionsResponse response;
bool success = linkRawWireless.endHost(response);
if (!success)
return abort(Error::COMMAND_FAILED);
LINK_BARRIER;
isSendingSyncCommand = false;
LINK_BARRIER;
return true;
}
/**
* @brief Retrieves the signal level of each player (0-255). For hosts, the
* array will contain the signal level of each client in indexes 1-4. For
* clients, it will only include the index corresponding to the
* `currentPlayerId()`.
* @param response A structure that will be filled with the signal levels.
* \warning For clients, this action can fail if the adapter is busy. In that
* case, this will return `false` and `getLastError()` will be
* `BUSY_TRY_AGAIN`. For hosts, you already have this data, so it's free!
*/
bool getSignalLevel(SignalLevelResponse& response) {
LINK_WIRELESS_RESET_IF_NEEDED
if (!isSessionActive())
return badRequest(Error::WRONG_STATE);
if (linkRawWireless.getState() == LinkRawWireless::State::SERVING) {
for (u32 i = 0; i < LINK_WIRELESS_MAX_PLAYERS; i++)
response.signalLevels[i] = sessionState.signalLevel.level[i];
return true;
}
isSendingSyncCommand = true;
if (isAsyncCommandActive())
return badRequest(Error::BUSY_TRY_AGAIN);
bool success = linkRawWireless.getSignalLevel(response);
if (!success)
return abort(Error::COMMAND_FAILED);
LINK_BARRIER;
isSendingSyncCommand = false;
LINK_BARRIER;
return true;
}
/**
* @brief Fills the `servers` array with all the currently broadcasting
* servers.
* @param servers The array to be filled with data.
* @param serverCount The number to be filled with the number of found
* servers.
* \warning This action takes 1 second to complete.
* \warning For an async version, see `getServersAsyncStart()`.
*/
bool getServers(Server servers[], u32& serverCount) {
return getServers(servers, serverCount, []() {});
}
/**
* @brief Fills the `servers` array with all the currently broadcasting
* servers.
* @param servers The array to be filled with data.
* @param serverCount The number to be filled with the number of found
* servers.
* @param onWait A function which will be invoked each time VBlank starts.
* \warning This action takes 1 second to complete.
* \warning For an async version, see `getServersAsyncStart()`.
*/
template <typename F>
bool getServers(Server servers[], u32& serverCount, F onWait) {
serverCount = 0;
if (!getServersAsyncStart())
return false;
waitVBlanks(BROADCAST_SEARCH_WAIT_FRAMES, onWait);
if (!getServersAsyncEnd(servers, serverCount))
return false;
return true;
}
/**
* @brief Starts looking for broadcasting servers and changes the state to
* `SEARCHING`. After this, call `getServersAsyncEnd(...)` 1 second later.
*/
bool getServersAsyncStart() {
LINK_WIRELESS_RESET_IF_NEEDED
if (linkRawWireless.getState() != State::AUTHENTICATED)
return badRequest(Error::WRONG_STATE);
bool success = linkRawWireless.broadcastReadStart();
if (!success)
return abort(Error::COMMAND_FAILED);
return true;
}
/**
* @brief Fills the `servers` array with all the currently broadcasting
* servers. Changes the state to `AUTHENTICATED` again.
* @param servers The array to be filled with data.
* @param serverCount The number to be filled with the number of found
* servers.
*/
bool getServersAsyncEnd(Server servers[], u32& serverCount) {
serverCount = 0;
LINK_WIRELESS_RESET_IF_NEEDED
if (linkRawWireless.getState() != State::SEARCHING)
return badRequest(Error::WRONG_STATE);
LinkRawWireless::BroadcastReadPollResponse response;
bool success1 = linkRawWireless.broadcastReadPoll(response);
if (!success1)
return abort(Error::COMMAND_FAILED);
bool success2 = linkRawWireless.broadcastReadEnd();
if (!success2)
return abort(Error::COMMAND_FAILED);
auto foundServers = response.servers;
for (u32 i = 0; i < response.serversSize; i++) {
Server server;
server.id = foundServers[i].id;
server.gameId = foundServers[i].gameId;
for (u32 j = 0; j < LINK_WIRELESS_MAX_GAME_NAME_LENGTH + 1; j++)
server.gameName[j] = foundServers[i].gameName[j];
for (u32 j = 0; j < LINK_WIRELESS_MAX_USER_NAME_LENGTH + 1; j++)
server.userName[j] = foundServers[i].userName[j];
u8 nextClientNumber = foundServers[i].nextClientNumber;
server.currentPlayerCount =
nextClientNumber == 0xFF ? 0 : 1 + nextClientNumber;
servers[i] = server;
}
serverCount = response.serversSize;
return true;
}
/**
* @brief Starts a connection with `serverId` and changes the state to
* `CONNECTING`.
* @param serverId Device ID of the server.
*/
bool connect(u16 serverId) {
LINK_WIRELESS_RESET_IF_NEEDED
if (linkRawWireless.getState() != State::AUTHENTICATED)
return badRequest(Error::WRONG_STATE);
bool success = linkRawWireless.connect(serverId);
if (!success)
return abort(Error::COMMAND_FAILED);
return true;
}
/**
* @brief When connecting, this needs to be called until the state is
* `CONNECTED`. It assigns a player ID. Keep in mind that `isConnected()` and
* `playerCount()` won't be updated until the first message from the server
* arrives.
*/
bool keepConnecting() {
LINK_WIRELESS_RESET_IF_NEEDED
if (linkRawWireless.getState() != State::CONNECTING)
return badRequest(Error::WRONG_STATE);
LinkRawWireless::ConnectionStatus response;
bool success1 = linkRawWireless.keepConnecting(response);
if (!success1)
return abort(Error::COMMAND_FAILED);
if (response.phase == LinkRawWireless::ConnectionPhase::STILL_CONNECTING)
return true;
else if (response.phase == LinkRawWireless::ConnectionPhase::ERROR)
return abort(Error::COMMAND_FAILED);
auto success2 = linkRawWireless.finishConnection();
if (!success2)
return abort(Error::COMMAND_FAILED);
return true;
}
/**
* @brief Returns whether a `send(...)` call would fail due to the queue being
* full or not.
*/
bool canSend() { return !sessionState.newOutgoingMessages.isFull(); }
/**
* @brief Enqueues `data` to be sent to other nodes.
* @param data The value to be sent.
*/
bool send(u16 data) {
LINK_WIRELESS_RESET_IF_NEEDED
if (!isSessionActive())
return badRequest(Error::WRONG_STATE);
if (!canSend()) {
lastError = Error::BUFFER_IS_FULL;
return false;
}
Message message;
message.playerId = linkRawWireless.sessionState.currentPlayerId;
message.data = data;
sessionState.newOutgoingMessages.syncPush(message);
return true;
}
/**
* @brief Fills the `messages` array with incoming messages.
* @param messages The array to be filled with data.
* @param receivedCount The number to be filled with the number of received
* messages.
*/
bool receive(Message messages[], u32& receivedCount) {
receivedCount = 0;
if (!isSessionActive())
return false;
LINK_BARRIER;
sessionState.incomingMessages.startReading();
LINK_BARRIER;
while (!sessionState.incomingMessages.isEmpty()) {
auto message = sessionState.incomingMessages.pop();
if (message.playerId < LINK_WIRELESS_MAX_PLAYERS) {
messages[receivedCount] = message;
receivedCount++;
}
}
LINK_BARRIER;
sessionState.incomingMessages.stopReading();
LINK_BARRIER;
return true;
}
/**
* @brief Returns the current state.
* @return One of the enum values from `State`.
*/
[[nodiscard]] State getState() { return linkRawWireless.getState(); }
/**
* @brief Returns `true` if the player count is higher than `1`.
*/
[[nodiscard]] bool isConnected() {
return linkRawWireless.sessionState.playerCount > 1;
}
/**
* @brief Returns `true` if the state is `SERVING` or `CONNECTED`.
*/
[[nodiscard]] bool isSessionActive() {
return linkRawWireless.getState() == State::SERVING ||
linkRawWireless.getState() == State::CONNECTED;
}
/**
* @brief Returns `true` if the server was closed with `closeServer()`.
*/
[[nodiscard]] bool isServerClosed() {
return linkRawWireless.sessionState.isServerClosed;
}
/**
* @brief Returns the number of connected players (`1~5`).
*/
[[nodiscard]] u8 playerCount() {
return linkRawWireless.sessionState.playerCount;
}
/**
* @brief Returns the current player ID (`0~4`).
*/
[[nodiscard]] u8 currentPlayerId() {
return linkRawWireless.sessionState.currentPlayerId;
}
/**
* @brief Returns whether the internal queue lost messages at some point due
* to being full. This can happen if your queue size is too low, if you
* receive too much data without calling `receive(...)` enough times, or if
* excessive `receive(...)` calls prevent the ISR from copying data. After
* this call, the overflow flag is cleared if `clear` is `true` (default
* behavior).
*/
bool didQueueOverflow(bool clear = true) {
bool overflowReceive = sessionState.newIncomingMessages.overflow;
bool overflowForwardedMessage = sessionState.outgoingMessages.overflow;
if (clear) {
sessionState.newIncomingMessages.overflow = false;
sessionState.outgoingMessages.overflow = false;
}
return overflowReceive || overflowForwardedMessage;
}
/**
* @brief Resets other players' timeout count to `0`.
* \warning Call this if you changed `config.timeout`.
*/
void resetTimeout() {
if (!isEnabled)
return;
LINK_BARRIER;
sessionState.isResetTimeoutPending = true;
LINK_BARRIER;
}
/**
* @brief Restarts the send timer without disconnecting.
* \warning Call this if you changed `config.interval`.
*/
void resetTimer() {
if (!isEnabled)
return;
stopTimer();
startTimer();
}
/**
* @brief If one of the other methods returns `false`, you can inspect this to
* know the cause. After this call, the last error is cleared if `clear` is
* `true` (default behavior).
* @param clear Whether it should clear the error or not.
*/
Error getLastError(bool clear = true) {
Error error = lastError;
if (clear)
lastError = Error::NONE;
return error;
}
/**
* @brief Returns the number of total outgoing messages.
* \warning This is internal API!
*/
[[nodiscard]] u32 _getPendingCount() {
return sessionState.outgoingMessages.size();
}
/**
* @brief Returns the number of inflight outgoing messages.
* \warning This is internal API!
*/
[[nodiscard]] u32 _getInflightCount() { return sessionState.inflightCount; }
/**
* @brief Returns the number of forwarded outgoing messages.
* \warning This is internal API!
*/
[[nodiscard]] u32 _getForwardedCount() { return sessionState.forwardedCount; }
/**
* @brief Returns the last packet ID.
* \warning This is internal API!
*/
[[nodiscard]] u32 _lastPacketId() { return sessionState.lastPacketId; }
/**
* @brief Returns the last ACK received from player ID 1.
* \warning This is internal API!
*/
[[nodiscard]] u32 _lastAckFromClient1() {
return sessionState.lastAckFromClients[1];
}
/**
* @brief Returns the last packet ID received from player ID 1.
* \warning This is internal API!
*/
[[nodiscard]] u32 _lastPacketIdFromClient1() {
return sessionState.lastPacketIdFromClients[1];
}
/**
* @brief Returns the last ACK received from the server.
* \warning This is internal API!
*/
[[nodiscard]] u32 _lastAckFromServer() {
return sessionState.lastAckFromServer;
}
/**
* @brief Returns the last packet ID received from the server.
* \warning This is internal API!
*/
[[nodiscard]] u32 _lastPacketIdFromServer() {
return sessionState.lastPacketIdFromServer;
}
/**
* @brief Returns the next pending packet ID.
* \warning This is internal API!
*/
[[nodiscard]] u32 _nextPendingPacketId() {
return sessionState.outgoingMessages.isEmpty()
? 0
: sessionState.outgoingMessages.peek().packetId;
}
#ifdef LINK_RAW_WIRELESS_ENABLE_LOGGING
/**
* @brief Sets a logger function.
* \warning This is internal API!
*/
void _setLogger(LinkRawWireless::Logger logger) {
linkRawWireless.logger = logger;
}
#endif
/**
* @brief This method is called by the VBLANK interrupt handler.
* \warning This is internal API!
*/
#ifdef LINK_WIRELESS_ENABLE_NESTED_IRQ
LINK_NOINLINE void _onVBlank() {
#else
void _onVBlank() {
#endif
if (!isEnabled)
return;
#ifdef LINK_WIRELESS_ENABLE_NESTED_IRQ
if (interrupt) {
pendingVBlank = true;
return;
}
#endif
#ifdef LINK_WIRELESS_PROFILING_ENABLED
profileStart();
#endif
if (!isSessionActive())
return;
if (sessionState.isResetTimeoutPending) {
sessionState.recvTimeout = 0;
for (u32 i = 0; i < LINK_WIRELESS_MAX_PLAYERS; i++)
sessionState.msgTimeouts[i] = 0;
sessionState.isResetTimeoutPending = false;
}
if (isConnected() && !sessionState.recvFlag)
sessionState.recvTimeout++;
if (sessionState.recvTimeout >= config.timeout)
return (void)abort(Error::TIMEOUT);
if (!checkRemoteTimeouts())
return (void)abort(Error::REMOTE_TIMEOUT);
sessionState.recvFlag = false;
sessionState.signalLevelCalled = false;
#ifdef LINK_WIRELESS_PROFILING_ENABLED
vblankTime += profileStop();
vblankIRQs++;
#endif
}
/**
* @brief This method is called by the SERIAL interrupt handler.
* \warning This is internal API!
*/
LINK_WIRELESS_ISR_FUNC(_onSerial, (), (), {
#ifdef LINK_WIRELESS_ENABLE_NESTED_IRQ
interrupt = true;
LINK_BARRIER;
// (nested interrupts are enabled by LinkRawWireless::_onSerial(...))
#endif
___onSerial();
#ifdef LINK_WIRELESS_ENABLE_NESTED_IRQ
irqEnd();
#endif
})
/**
* @brief This method is called by the TIMER interrupt handler.
* \warning This is internal API!
*/
LINK_WIRELESS_ISR_FUNC(_onTimer, (), (), {
#ifdef LINK_WIRELESS_ENABLE_NESTED_IRQ
if (interrupt)
return;
interrupt = true;
LINK_BARRIER;
Link::_REG_IME = 1;
#endif
___onTimer();
#ifdef LINK_WIRELESS_ENABLE_NESTED_IRQ
irqEnd();
#endif
})
struct Config {
bool forwarding;
bool retransmission;
u8 maxPlayers;
u32 timeout; // can be changed in realtime, but call `resetTimeout()`
u16 interval; // can be changed in realtime, but call `resetTimer()`
u8 sendTimerId;
};
/**
* @brief LinkWireless configuration.
* \warning `deactivate()` first, change the config, and `activate()` again!
*/
Config config;
#ifndef LINK_WIRELESS_DEBUG_MODE
private:
#endif
using MessageQueue = Link::Queue<Message, LINK_WIRELESS_QUEUE_SIZE>;
struct SignalLevel {
vu8 level[LINK_WIRELESS_MAX_PLAYERS] = {};
};
struct SessionState {
MessageQueue incomingMessages; // read by user, write by irq&user
MessageQueue outgoingMessages; // read and write by irq
MessageQueue newIncomingMessages; // read and write by irq
MessageQueue newOutgoingMessages; // read by irq, write by user&irq
SignalLevel signalLevel; // write by irq, read by any
u32 recvTimeout = 0; // (~= LinkCable::IRQTimeout)
u32 msgTimeouts[LINK_WIRELESS_MAX_PLAYERS]; // (~= LinkCable::msgTimeouts)
bool recvFlag = false; // (~= LinkCable::IRQFlag)
bool msgFlags[LINK_WIRELESS_MAX_PLAYERS]; // (~= LinkCable::msgFlags)
bool signalLevelCalled = false;
bool sendReceiveLatch = false; // true = send ; false = receive
bool shouldWaitForServer = false;
bool didReceiveFirstPacketFromServer = false;
u32 inflightCount = 0;
u32 forwardedCount = 0;
u32 lastPacketId = 0;
u32 lastPacketIdFromServer = 0;
u32 lastAckFromServer = 0;
u32 lastPacketIdFromClients[LINK_WIRELESS_MAX_PLAYERS];
u32 lastAckFromClients[LINK_WIRELESS_MAX_PLAYERS];
int lastHeartbeatFromClients[LINK_WIRELESS_MAX_PLAYERS];
int localHeartbeat = -1;
volatile bool isResetTimeoutPending = false;
};
struct TransferHeader {