-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLinkWireless.hpp
1957 lines (1655 loc) · 56.3 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: (*)
// irq_init(NULL);
// irq_add(II_VBLANK, LINK_WIRELESS_ISR_VBLANK);
// irq_add(II_SERIAL, LINK_WIRELESS_ISR_SERIAL);
// irq_add(II_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];
// linkWireless->getServers(servers);
// if (servers[0].id == LINK_WIRELESS_END) 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];
// linkWireless->receive(messages);
// if (messages[0].packetId != LINK_WIRELESS_END) {
// // ...
// }
// - 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)
// --------------------------------------------------------------------------
// `send(...)` restrictions:
// - 0xFFFF is a reserved value, so don't use it!
// --------------------------------------------------------------------------
#ifndef LINK_DEVELOPMENT
#pragma GCC system_header
#endif
#include "_link_common.hpp"
#include <cstring>
#include "LinkGPIO.hpp"
#include "LinkSPI.hpp"
// #include <string>
// #include <functional>
#ifndef LINK_WIRELESS_QUEUE_SIZE
/**
* @brief Buffer size (how many incoming and outgoing messages the queues can
* store at max). 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 `960` 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 * 32`.
*/
#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;20]`. The default value is `20`, but you might want to set it a bit lower
* to reduce CPU usage.
*/
#define LINK_WIRELESS_MAX_SERVER_TRANSFER_LENGTH 20
#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.
*/
#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 `LinkWireless.cpp` gets compiled!
* For example, in a Makefile-based project, verify that the file 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.
* \warning This won't produce any effect if `LINK_WIRELESS_PUT_ISR_IN_IWRAM` is
* disabled.
*/
// #define LINK_WIRELESS_ENABLE_NESTED_IRQ
#endif
#ifndef LINK_WIRELESS_USE_SEND_RECEIVE_LATCH
/**
* @brief Use send/receive latch (uncomment to enable).
* This makes it alternate between sends and receives on each timer tick
* (instead of doing both things). Enabling it will introduce some latency but
* also reduce overall CPU usage.
*/
// #define LINK_WIRELESS_USE_SEND_RECEIVE_LATCH
#endif
#ifndef LINK_WIRELESS_TWO_PLAYERS_ONLY
/**
* @brief Optimize the library for two players (uncomment to enable).
* This will make the code smaller and use less CPU. It will also let you
* "misuse" 5 bits from the packet header to send small packets really fast
* (e.g. pressed keys) without confirmation, using the `QUICK_SEND` and
* `QUICK_RECEIVE` properties.
*/
// #define LINK_WIRELESS_TWO_PLAYERS_ONLY
#endif
static volatile char LINK_WIRELESS_VERSION[] = "LinkWireless/v7.0.1";
#define LINK_WIRELESS_MAX_PLAYERS 5
#define LINK_WIRELESS_MIN_PLAYERS 2
#define LINK_WIRELESS_END 0
#define LINK_WIRELESS_MAX_COMMAND_TRANSFER_LENGTH 22
#define LINK_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH 30
#define LINK_WIRELESS_BROADCAST_LENGTH 6
#define LINK_WIRELESS_BROADCAST_RESPONSE_LENGTH \
(1 + LINK_WIRELESS_BROADCAST_LENGTH)
#define LINK_WIRELESS_MAX_SERVERS \
(LINK_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH / \
LINK_WIRELESS_BROADCAST_RESPONSE_LENGTH)
#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 50
#define LINK_WIRELESS_DEFAULT_SEND_TIMER_ID 3
#define LINK_WIRELESS_BARRIER asm volatile("" ::: "memory")
#define LINK_WIRELESS_CODE_IWRAM \
__attribute__((section(".iwram"), target("arm"), noinline))
#define LINK_WIRELESS_ALWAYS_INLINE inline __attribute__((always_inline))
#define LINK_WIRELESS_RESET_IF_NEEDED \
if (!isEnabled) \
return false; \
if (state == NEEDS_RESET) \
if (!reset()) \
return false;
/**
* @brief A high level driver for the GBA Wireless Adapter.
*/
class LinkWireless {
private:
using u32 = unsigned int;
using u16 = unsigned short;
using u8 = unsigned char;
using vu32 = volatile unsigned int;
using vs32 = volatile signed int;
using s8 = signed char;
static constexpr auto BASE_FREQUENCY = Link::_TM_FREQ_1024;
#ifdef LINK_WIRELESS_TWO_PLAYERS_ONLY
static constexpr int PACKET_ID_BITS = 5;
#else
static constexpr int PACKET_ID_BITS = 6;
#endif
static constexpr int MAX_PACKET_IDS = (1 << PACKET_ID_BITS);
static constexpr int PACKET_ID_MASK = (MAX_PACKET_IDS - 1);
static constexpr int MSG_PING = 0xffff;
static constexpr int PING_WAIT = 50;
static constexpr int TRANSFER_WAIT = 15;
static constexpr int BROADCAST_SEARCH_WAIT_FRAMES = 60;
static constexpr int CMD_TIMEOUT = 10;
static constexpr int LOGIN_STEPS = 9;
static constexpr int COMMAND_HEADER_VALUE = 0x9966;
static constexpr int RESPONSE_ACK_VALUE = 0x80;
static constexpr u32 DATA_REQUEST_VALUE = 0x80000000;
static constexpr int SETUP_MAGIC = 0x003c0420;
static constexpr int SETUP_MAX_PLAYERS_BIT = 16;
static constexpr int WAIT_STILL_CONNECTING = 0x01000000;
static constexpr int COMMAND_HELLO = 0x10;
static constexpr int COMMAND_SETUP = 0x17;
static constexpr int COMMAND_BROADCAST = 0x16;
static constexpr int COMMAND_START_HOST = 0x19;
static constexpr int COMMAND_ACCEPT_CONNECTIONS = 0x1a;
static constexpr int COMMAND_BROADCAST_READ_START = 0x1c;
static constexpr int COMMAND_BROADCAST_READ_POLL = 0x1d;
static constexpr int COMMAND_BROADCAST_READ_END = 0x1e;
static constexpr int COMMAND_CONNECT = 0x1f;
static constexpr int COMMAND_IS_FINISHED_CONNECT = 0x20;
static constexpr int COMMAND_FINISH_CONNECTION = 0x21;
static constexpr int COMMAND_SEND_DATA = 0x24;
static constexpr int COMMAND_RECEIVE_DATA = 0x26;
static constexpr int COMMAND_BYE = 0x3d;
static constexpr u16 LOGIN_PARTS[] = {0x494e, 0x494e, 0x544e, 0x544e, 0x4e45,
0x4e45, 0x4f44, 0x4f44, 0x8001};
public:
#ifdef LINK_WIRELESS_TWO_PLAYERS_ONLY
u32 QUICK_SEND = 0;
u32 QUICK_RECEIVE = 0;
#endif
// std::function<void(std::string str)> debug;
// #define PROFILING_ENABLED
#ifdef PROFILING_ENABLED
u32 lastVBlankTime = 0;
u32 lastSerialTime = 0;
u32 lastTimerTime = 0;
u32 lastFrameSerialIRQs = 0;
u32 lastFrameTimerIRQs = 0;
u32 serialIRQCount = 0;
u32 timerIRQCount = 0;
#endif
enum State {
NEEDS_RESET,
AUTHENTICATED,
SEARCHING,
SERVING,
CONNECTING,
CONNECTED
};
enum 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 {
u32 packetId = 0;
u16 data;
u8 playerId = 0;
};
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 Maximum number of allowed players. If your game only
* supports -for example- two players, set this to `2` as it will make
* transfers faster.
* @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
* *(50 = 3.052ms)*. It's the interval of Timer #`sendTimerId`. Lower values
* will transfer faster but also consume more CPU.
* @param sendTimerId 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) {
#ifdef LINK_WIRELESS_TWO_PLAYERS_ONLY
maxPlayers = 2;
#endif
this->config.forwarding = forwarding;
this->config.retransmission = retransmission;
this->config.maxPlayers = maxPlayers;
this->config.timeout = timeout;
this->config.interval = interval;
this->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() {
lastError = NONE;
isEnabled = false;
LINK_WIRELESS_BARRIER;
bool success = reset();
LINK_WIRELESS_BARRIER;
isEnabled = true;
return success;
}
/**
* @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) {
activate();
success = sendCommand(COMMAND_BYE).success;
}
lastError = 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 (state != AUTHENTICATED && state != SERVING) {
lastError = WRONG_STATE;
return false;
}
if (std::strlen(gameName) > LINK_WIRELESS_MAX_GAME_NAME_LENGTH) {
lastError = GAME_NAME_TOO_LONG;
return false;
}
if (std::strlen(userName) > LINK_WIRELESS_MAX_GAME_NAME_LENGTH) {
lastError = USER_NAME_TOO_LONG;
return false;
}
isSendingSyncCommand = true;
if (asyncCommand.isActive) {
lastError = BUSY_TRY_AGAIN;
isSendingSyncCommand = false;
return false;
}
char finalGameName[LINK_WIRELESS_MAX_GAME_NAME_LENGTH + 1];
char finalUserName[LINK_WIRELESS_MAX_USER_NAME_LENGTH + 1];
copyName(finalGameName, gameName, LINK_WIRELESS_MAX_GAME_NAME_LENGTH);
copyName(finalUserName, userName, LINK_WIRELESS_MAX_USER_NAME_LENGTH);
if (state != SERVING)
setup(config.maxPlayers);
addData(buildU32(buildU16(finalGameName[1], finalGameName[0]),
gameId & LINK_WIRELESS_MAX_GAME_ID),
true);
addData(buildU32(buildU16(finalGameName[5], finalGameName[4]),
buildU16(finalGameName[3], finalGameName[2])));
addData(buildU32(buildU16(finalGameName[9], finalGameName[8]),
buildU16(finalGameName[7], finalGameName[6])));
addData(buildU32(buildU16(finalGameName[13], finalGameName[12]),
buildU16(finalGameName[11], finalGameName[10])));
addData(buildU32(buildU16(finalUserName[3], finalUserName[2]),
buildU16(finalUserName[1], finalUserName[0])));
addData(buildU32(buildU16(finalUserName[7], finalUserName[6]),
buildU16(finalUserName[5], finalUserName[4])));
bool success = sendCommand(COMMAND_BROADCAST, true).success;
if (state != SERVING)
success = success && sendCommand(COMMAND_START_HOST).success;
if (!success) {
reset();
lastError = COMMAND_FAILED;
return false;
}
wait(TRANSFER_WAIT);
state = SERVING;
return true;
}
/**
* @brief Fills the `servers` array with all the currently broadcasting
* servers.
* @param servers The array to be filled with data.
* \warning This action takes 1 second to complete.
* \warning For an async version, see `getServersAsyncStart()`.
*/
bool getServers(Server servers[]) {
return getServers(servers, []() {});
}
/**
* @brief Fills the `servers` array with all the currently broadcasting
* servers.
* @param servers The array to be filled with data.
* @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[], F onWait) {
if (!getServersAsyncStart())
return false;
waitVBlanks(BROADCAST_SEARCH_WAIT_FRAMES, onWait);
if (!getServersAsyncEnd(servers))
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 (state != AUTHENTICATED) {
lastError = WRONG_STATE;
return false;
}
bool success = sendCommand(COMMAND_BROADCAST_READ_START).success;
if (!success) {
reset();
lastError = COMMAND_FAILED;
return false;
}
state = SEARCHING;
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.
*/
bool getServersAsyncEnd(Server servers[]) {
LINK_WIRELESS_RESET_IF_NEEDED
if (state != SEARCHING) {
lastError = WRONG_STATE;
return false;
}
auto result = sendCommand(COMMAND_BROADCAST_READ_POLL);
bool success1 =
result.success &&
result.responsesSize % LINK_WIRELESS_BROADCAST_RESPONSE_LENGTH == 0;
if (!success1) {
reset();
lastError = COMMAND_FAILED;
return false;
}
bool success2 = sendCommand(COMMAND_BROADCAST_READ_END).success;
if (!success2) {
reset();
lastError = COMMAND_FAILED;
return false;
}
u32 totalBroadcasts =
result.responsesSize / LINK_WIRELESS_BROADCAST_RESPONSE_LENGTH;
for (u32 i = 0; i < totalBroadcasts; i++) {
u32 start = LINK_WIRELESS_BROADCAST_RESPONSE_LENGTH * i;
Server server;
server.id = (u16)result.responses[start];
server.gameId = result.responses[start + 1] & LINK_WIRELESS_MAX_GAME_ID;
u32 gameI = 0, userI = 0;
recoverName(server.gameName, gameI, result.responses[start + 1], false);
recoverName(server.gameName, gameI, result.responses[start + 2]);
recoverName(server.gameName, gameI, result.responses[start + 3]);
recoverName(server.gameName, gameI, result.responses[start + 4]);
recoverName(server.userName, userI, result.responses[start + 5]);
recoverName(server.userName, userI, result.responses[start + 6]);
server.gameName[gameI] = '\0';
server.userName[userI] = '\0';
u8 connectedClients = (result.responses[start] >> 16) & 0xff;
server.currentPlayerCount =
connectedClients == 0xff ? 0 : (1 + connectedClients);
servers[i] = server;
}
state = AUTHENTICATED;
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 (state != AUTHENTICATED) {
lastError = WRONG_STATE;
return false;
}
addData(serverId, true);
bool success = sendCommand(COMMAND_CONNECT, true).success;
if (!success) {
reset();
lastError = COMMAND_FAILED;
return false;
}
state = CONNECTING;
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 (state != CONNECTING) {
lastError = WRONG_STATE;
return false;
}
auto result1 = sendCommand(COMMAND_IS_FINISHED_CONNECT);
if (!result1.success || result1.responsesSize == 0) {
reset();
lastError = COMMAND_FAILED;
return false;
}
if (result1.responses[0] == WAIT_STILL_CONNECTING)
return true;
u8 assignedPlayerId = 1 + (u8)msB32(result1.responses[0]);
if (assignedPlayerId >= LINK_WIRELESS_MAX_PLAYERS) {
reset();
lastError = CONNECTION_FAILED;
return false;
}
auto result2 = sendCommand(COMMAND_FINISH_CONNECTION);
if (!result2.success) {
reset();
lastError = COMMAND_FAILED;
return false;
}
sessionState.currentPlayerId = assignedPlayerId;
state = CONNECTED;
return true;
}
/**
* @brief Enqueues `data` to be sent to other nodes.
* @param data The value to be sent.
*/
bool send(u16 data, int _author = -1) {
LINK_WIRELESS_RESET_IF_NEEDED
if (!isSessionActive()) {
lastError = WRONG_STATE;
return false;
}
if (!_canAddNewMessage()) {
if (_author < 0)
lastError = BUFFER_IS_FULL;
return false;
}
Message message;
message.playerId = _author >= 0 ? _author : sessionState.currentPlayerId;
message.data = data;
sessionState.newOutgoingMessages.syncPush(message);
return true;
}
/**
* @brief Fills the `messages` array with incoming messages, forwarding if
* needed.
* @param messages The array to be filled with data.
*/
bool receive(Message messages[]) {
if (!isSessionActive())
return false;
LINK_WIRELESS_BARRIER;
sessionState.incomingMessages.startReading();
LINK_WIRELESS_BARRIER;
u32 i = 0;
while (!sessionState.incomingMessages.isEmpty()) {
auto message = sessionState.incomingMessages.pop();
messages[i] = message;
#ifndef LINK_WIRELESS_TWO_PLAYERS_ONLY
forwardMessageIfNeeded(message);
#endif
i++;
}
LINK_WIRELESS_BARRIER;
sessionState.incomingMessages.stopReading();
LINK_WIRELESS_BARRIER;
return true;
}
/**
* @brief Returns the current state.
* @return One of the enum values from `LinkWireless::State`.
*/
[[nodiscard]] State getState() { return state; }
/**
* @brief Returns `true` if the player count is higher than `1`.
*/
[[nodiscard]] bool isConnected() { return sessionState.playerCount > 1; }
/**
* @brief Returns `true` if the state is `SERVING` or `CONNECTED`.
*/
[[nodiscard]] bool isSessionActive() {
return state == SERVING || state == CONNECTED;
}
/**
* @brief Returns the number of connected players.
*/
[[nodiscard]] u8 playerCount() { return sessionState.playerCount; }
/**
* @brief Returns the current player ID.
*/
[[nodiscard]] u8 currentPlayerId() { return sessionState.currentPlayerId; }
/**
* @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 = NONE;
return error;
}
~LinkWireless() {
delete linkSPI;
delete linkGPIO;
}
/**
* @brief Returns whether it's running an async command or not.
* \warning This is internal API!
*/
[[nodiscard]] bool _hasActiveAsyncCommand() { return asyncCommand.isActive; }
/**
* @brief Returns whether there's room for sending messages or not.
* \warning This is internal API!
*/
[[nodiscard]] bool _canSend() {
return !sessionState.outgoingMessages.isFull();
}
/**
* @brief Returns whether there's room for scheduling new messages or not.
* \warning This is internal API!
*/
[[nodiscard]] bool _canAddNewMessage() {
return !sessionState.newOutgoingMessages.isFull();
}
/**
* @brief Returns the number of pending outgoing messages.
* \warning This is internal API!
*/
[[nodiscard]] u32 _getPendingCount() {
return sessionState.outgoingMessages.size();
}
/**
* @brief Returns the last packet ID.
* \warning This is internal API!
*/
[[nodiscard]] u32 _lastPacketId() { return sessionState.lastPacketId; }
/**
* @brief Returns the last confirmation received from player ID 1.
* \warning This is internal API!
*/
[[nodiscard]] u32 _lastConfirmationFromClient1() {
return sessionState.lastConfirmationFromClients[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 confirmation received from the server.
* \warning This is internal API!
*/
[[nodiscard]] u32 _lastConfirmationFromServer() {
return sessionState.lastConfirmationFromServer;
}
/**
* @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;
}
/**
* @brief This method is called by the VBLANK interrupt handler.
* \warning This is internal API!
*/
#ifdef LINK_WIRELESS_ENABLE_NESTED_IRQ
__attribute__((noinline)) void _onVBlank() {
#else
void _onVBlank() {
#endif
if (!isEnabled)
return;
#ifdef LINK_WIRELESS_PUT_ISR_IN_IWRAM
#ifdef LINK_WIRELESS_ENABLE_NESTED_IRQ
if (interrupt) {
pendingVBlank = true;
return;
}
#endif
#endif
#ifdef PROFILING_ENABLED
profileStart();
#endif
if (!isSessionActive())
return;
if (isConnected() && !sessionState.recvFlag)
sessionState.recvTimeout++;
if (sessionState.recvTimeout >= config.timeout) {
reset();
lastError = TIMEOUT;
return;
}
#ifndef LINK_WIRELESS_TWO_PLAYERS_ONLY
trackRemoteTimeouts();
if (!checkRemoteTimeouts()) {
reset();
lastError = REMOTE_TIMEOUT;
return;
}
#endif
sessionState.recvFlag = false;
sessionState.acceptCalled = false;
sessionState.pingSent = false;
#ifdef PROFILING_ENABLED
lastVBlankTime = profileStop();
lastFrameSerialIRQs = serialIRQCount;
lastFrameTimerIRQs = timerIRQCount;
serialIRQCount = 0;
timerIRQCount = 0;
#endif
}
#ifdef LINK_WIRELESS_PUT_ISR_IN_IWRAM
void _onSerial();
void _onTimer();
#else
void _onSerial() { __onSerial(); }
void _onTimer() { __onTimer(); }
#endif
/**
* @brief This method is called by the SERIAL interrupt handler.
* \warning This is internal API!
*/
LINK_WIRELESS_ALWAYS_INLINE void __onSerial() {
if (!isEnabled)
return;
#ifdef PROFILING_ENABLED
profileStart();
#endif
linkSPI->_onSerial(true);
bool hasNewData = linkSPI->getAsyncState() == LinkSPI::AsyncState::READY;
if (hasNewData) {
if (!acknowledge()) {
reset();
lastError = ACKNOWLEDGE_FAILED;
return;
}
} else
return;
u32 newData = linkSPI->getAsyncData();
if (!isSessionActive())
return;
if (asyncCommand.isActive) {
if (asyncCommand.state == AsyncCommand::State::PENDING) {
updateAsyncCommand(newData);
if (asyncCommand.state == AsyncCommand::State::COMPLETED)
processAsyncCommand();
}
}
#ifdef PROFILING_ENABLED
lastSerialTime = profileStop();
serialIRQCount++;
#endif
}
/**
* @brief This method is called by the TIMER interrupt handler.
* \warning This is internal API!
*/
LINK_WIRELESS_ALWAYS_INLINE void __onTimer() {
if (!isEnabled)
return;
#ifdef PROFILING_ENABLED
profileStart();
#endif
if (!isSessionActive())
return;
if (!asyncCommand.isActive)
acceptConnectionsOrTransferData();
#ifdef PROFILING_ENABLED
lastTimerTime = profileStop();
timerIRQCount++;
#endif
}
struct Config {
bool forwarding;
bool retransmission;
u8 maxPlayers;
u32 timeout;
u32 interval;
u32 sendTimerId;
};
/**
* @brief LinkWireless configuration.
* \warning `deactivate()` first, change the config, and `activate()` again!
*/
Config config;
private:
using MessageQueue = Link::Queue<Message, LINK_WIRELESS_QUEUE_SIZE, false>;
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
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 acceptCalled = false;
bool pingSent = false;
#ifdef LINK_WIRELESS_USE_SEND_RECEIVE_LATCH
bool sendReceiveLatch = false; // true = send ; false = receive
bool shouldWaitForServer = false;
#endif
u8 playerCount = 1;
u8 currentPlayerId = 0;
bool didReceiveLastPacketIdFromServer = false;
u32 lastPacketId = 0;
u32 lastPacketIdFromServer = 0;
u32 lastConfirmationFromServer = 0;
u32 lastPacketIdFromClients[LINK_WIRELESS_MAX_PLAYERS];
u32 lastConfirmationFromClients[LINK_WIRELESS_MAX_PLAYERS];
};
struct MessageHeader {
unsigned int partialPacketId : PACKET_ID_BITS;
unsigned int isConfirmation : 1;
#ifdef LINK_WIRELESS_TWO_PLAYERS_ONLY
unsigned int playerId : 1;
unsigned int quickData : 5;
#else
unsigned int playerId : 3;
unsigned int clientCount : 2;
#endif
unsigned int dataChecksum : 4;
};
union MessageHeaderSerializer {