forked from afska/gba-link-connection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkWireless.h
1468 lines (1217 loc) · 41.7 KB
/
LinkWireless.h
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_MAX_TRANSFER_LENGTH];
// 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 can cause packet loss. You might want to use libugba's instead.
// (see examples)
// --------------------------------------------------------------------------
// `send(...)` restrictions:
// - 0xFFFF is a reserved value, so don't use it!
// --------------------------------------------------------------------------
#include <tonc_core.h>
#include <string>
#include "LinkGPIO.h"
#include "LinkSPI.h"
// #include <functional>
// Buffer size
#define LINK_WIRELESS_QUEUE_SIZE 30
// Max command response length
#define LINK_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH 50
// Max server transfer length
#define LINK_WIRELESS_MAX_SERVER_TRANSFER_LENGTH 20
// Max client transfer length
#define LINK_WIRELESS_MAX_CLIENT_TRANSFER_LENGTH 4
#define LINK_WIRELESS_MAX_PLAYERS 5
#define LINK_WIRELESS_MIN_PLAYERS 2
#define LINK_WIRELESS_END 0
#define LINK_WIRELESS_DEFAULT_TIMEOUT 8
#define LINK_WIRELESS_DEFAULT_REMOTE_TIMEOUT 10
#define LINK_WIRELESS_DEFAULT_INTERVAL 50
#define LINK_WIRELESS_DEFAULT_SEND_TIMER_ID 3
#define LINK_WIRELESS_BASE_FREQUENCY TM_FREQ_1024
#define LINK_WIRELESS_PACKET_ID_BITS 6
#define LINK_WIRELESS_MAX_PACKET_IDS (1 << LINK_WIRELESS_PACKET_ID_BITS)
#define LINK_WIRELESS_PACKET_ID_MASK (LINK_WIRELESS_MAX_PACKET_IDS - 1)
#define LINK_WIRELESS_MSG_PING 0xffff
#define LINK_WIRELESS_PING_WAIT 50
#define LINK_WIRELESS_TRANSFER_WAIT 15
#define LINK_WIRELESS_BROADCAST_SEARCH_WAIT_FRAMES 60
#define LINK_WIRELESS_CMD_TIMEOUT 100
#define LINK_WIRELESS_MAX_GAME_NAME_LENGTH 14
#define LINK_WIRELESS_MAX_USER_NAME_LENGTH 8
#define LINK_WIRELESS_LOGIN_STEPS 9
#define LINK_WIRELESS_COMMAND_HEADER 0x9966
#define LINK_WIRELESS_RESPONSE_ACK 0x80
#define LINK_WIRELESS_DATA_REQUEST 0x80000000
#define LINK_WIRELESS_SETUP_MAGIC 0x003c0420
#define LINK_WIRELESS_STILL_CONNECTING 0x01000000
#define LINK_WIRELESS_BROADCAST_LENGTH 6
#define LINK_WIRELESS_BROADCAST_RESPONSE_LENGTH \
(1 + LINK_WIRELESS_BROADCAST_LENGTH)
#define LINK_WIRELESS_MAX_TRANSFER_LENGTH 20
#define LINK_WIRELESS_MAX_SERVERS \
(LINK_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH / \
LINK_WIRELESS_BROADCAST_RESPONSE_LENGTH)
#define LINK_WIRELESS_COMMAND_HELLO 0x10
#define LINK_WIRELESS_COMMAND_SETUP 0x17
#define LINK_WIRELESS_COMMAND_BROADCAST 0x16
#define LINK_WIRELESS_COMMAND_START_HOST 0x19
#define LINK_WIRELESS_COMMAND_ACCEPT_CONNECTIONS 0x1a
#define LINK_WIRELESS_COMMAND_BROADCAST_READ_START 0x1c
#define LINK_WIRELESS_COMMAND_BROADCAST_READ_POLL 0x1d
#define LINK_WIRELESS_COMMAND_BROADCAST_READ_END 0x1e
#define LINK_WIRELESS_COMMAND_CONNECT 0x1f
#define LINK_WIRELESS_COMMAND_IS_FINISHED_CONNECT 0x20
#define LINK_WIRELESS_COMMAND_FINISH_CONNECTION 0x21
#define LINK_WIRELESS_COMMAND_SEND_DATA 0x24
#define LINK_WIRELESS_COMMAND_RECEIVE_DATA 0x26
#define LINK_WIRELESS_BARRIER asm volatile("" ::: "memory")
#define LINK_WIRELESS_RESET_IF_NEEDED \
if (!isEnabled) \
return false; \
if (state == NEEDS_RESET) \
if (!reset()) \
return false;
static volatile char LINK_WIRELESS_VERSION[] = "LinkWireless/v5.0.2";
void LINK_WIRELESS_ISR_VBLANK();
void LINK_WIRELESS_ISR_SERIAL();
void LINK_WIRELESS_ISR_TIMER();
const u16 LINK_WIRELESS_LOGIN_PARTS[] = {0x494e, 0x494e, 0x544e, 0x544e, 0x4e45,
0x4e45, 0x4f44, 0x4f44, 0x8001};
const u16 LINK_WIRELESS_TIMER_IRQ_IDS[] = {IRQ_TIMER0, IRQ_TIMER1, IRQ_TIMER2,
IRQ_TIMER3};
class LinkWireless {
public:
// std::function<void(std::string str)> debug;
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,
WEIRD_PLAYER_ID = 6,
SEND_DATA_FAILED = 7,
RECEIVE_DATA_FAILED = 8,
ACKNOWLEDGE_FAILED = 9,
TIMEOUT = 10,
REMOTE_TIMEOUT = 11
};
struct Message {
u32 packetId = 0;
u16 data;
u8 playerId = 0;
};
struct Server {
u16 id = 0;
std::string gameName;
std::string userName;
};
explicit LinkWireless(
bool forwarding = true,
bool retransmission = true,
u8 maxPlayers = LINK_WIRELESS_MAX_PLAYERS,
u32 timeout = LINK_WIRELESS_DEFAULT_TIMEOUT,
u32 remoteTimeout = LINK_WIRELESS_DEFAULT_REMOTE_TIMEOUT,
u16 interval = LINK_WIRELESS_DEFAULT_INTERVAL,
u8 sendTimerId = LINK_WIRELESS_DEFAULT_SEND_TIMER_ID) {
this->config.forwarding = forwarding;
this->config.retransmission = retransmission;
this->config.maxPlayers = maxPlayers;
this->config.timeout = timeout;
this->config.remoteTimeout = remoteTimeout;
this->config.interval = interval;
this->config.sendTimerId = LINK_WIRELESS_DEFAULT_SEND_TIMER_ID;
}
bool isActive() { return isEnabled; }
bool activate() {
lastError = NONE;
isEnabled = false;
LINK_WIRELESS_BARRIER;
bool success = reset();
LINK_WIRELESS_BARRIER;
isEnabled = true;
return success;
}
void deactivate() {
lastError = NONE;
isEnabled = false;
resetState();
stop();
}
bool serve(std::string gameName = "", std::string userName = "") {
LINK_WIRELESS_RESET_IF_NEEDED
if (state != AUTHENTICATED) {
lastError = WRONG_STATE;
return false;
}
if (gameName.length() > LINK_WIRELESS_MAX_GAME_NAME_LENGTH) {
lastError = GAME_NAME_TOO_LONG;
return false;
}
if (userName.length() > LINK_WIRELESS_MAX_GAME_NAME_LENGTH) {
lastError = USER_NAME_TOO_LONG;
return false;
}
gameName.append(LINK_WIRELESS_MAX_GAME_NAME_LENGTH - gameName.length(), 0);
userName.append(LINK_WIRELESS_MAX_USER_NAME_LENGTH - userName.length(), 0);
addData(buildU32(buildU16(gameName[1], gameName[0]), buildU16(0x02, 0x02)),
true);
addData(buildU32(buildU16(gameName[5], gameName[4]),
buildU16(gameName[3], gameName[2])));
addData(buildU32(buildU16(gameName[9], gameName[8]),
buildU16(gameName[7], gameName[6])));
addData(buildU32(buildU16(gameName[13], gameName[12]),
buildU16(gameName[11], gameName[10])));
addData(buildU32(buildU16(userName[3], userName[2]),
buildU16(userName[1], userName[0])));
addData(buildU32(buildU16(userName[7], userName[6]),
buildU16(userName[5], userName[4])));
bool success = sendCommand(LINK_WIRELESS_COMMAND_BROADCAST, true).success &&
sendCommand(LINK_WIRELESS_COMMAND_START_HOST).success;
if (!success) {
reset();
lastError = COMMAND_FAILED;
return false;
}
wait(LINK_WIRELESS_TRANSFER_WAIT);
state = SERVING;
return true;
}
bool getServers(Server servers[]) {
return getServers(servers, []() {});
}
template <typename F>
bool getServers(Server servers[], F onWait) {
if (!getServersAsyncStart())
return false;
waitVBlanks(LINK_WIRELESS_BROADCAST_SEARCH_WAIT_FRAMES, onWait);
if (!getServersAsyncEnd(servers))
return false;
return true;
}
bool getServersAsyncStart() {
LINK_WIRELESS_RESET_IF_NEEDED
if (state != AUTHENTICATED) {
lastError = WRONG_STATE;
return false;
}
bool success =
sendCommand(LINK_WIRELESS_COMMAND_BROADCAST_READ_START).success;
if (!success) {
reset();
lastError = COMMAND_FAILED;
return false;
}
state = SEARCHING;
return true;
}
bool getServersAsyncEnd(Server servers[]) {
LINK_WIRELESS_RESET_IF_NEEDED
if (state != SEARCHING) {
lastError = WRONG_STATE;
return false;
}
auto result = sendCommand(LINK_WIRELESS_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(LINK_WIRELESS_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];
recoverName(server.gameName, result.responses[start + 1], false);
recoverName(server.gameName, result.responses[start + 2]);
recoverName(server.gameName, result.responses[start + 3]);
recoverName(server.gameName, result.responses[start + 4]);
recoverName(server.userName, result.responses[start + 5]);
recoverName(server.userName, result.responses[start + 6]);
servers[i] = server;
}
state = AUTHENTICATED;
return true;
}
bool connect(u16 serverId) {
LINK_WIRELESS_RESET_IF_NEEDED
if (state != AUTHENTICATED) {
lastError = WRONG_STATE;
return false;
}
addData(serverId, true);
bool success = sendCommand(LINK_WIRELESS_COMMAND_CONNECT, true).success;
if (!success) {
reset();
lastError = COMMAND_FAILED;
return false;
}
state = CONNECTING;
return true;
}
bool keepConnecting() {
LINK_WIRELESS_RESET_IF_NEEDED
if (state != CONNECTING) {
lastError = WRONG_STATE;
return false;
}
auto result1 = sendCommand(LINK_WIRELESS_COMMAND_IS_FINISHED_CONNECT);
if (!result1.success || result1.responsesSize == 0) {
reset();
lastError = COMMAND_FAILED;
return false;
}
if (result1.responses[0] == LINK_WIRELESS_STILL_CONNECTING)
return true;
u8 assignedPlayerId = 1 + (u8)msB32(result1.responses[0]);
if (assignedPlayerId >= LINK_WIRELESS_MAX_PLAYERS) {
reset();
lastError = WEIRD_PLAYER_ID;
return false;
}
auto result2 = sendCommand(LINK_WIRELESS_COMMAND_FINISH_CONNECTION);
if (!result2.success) {
reset();
lastError = COMMAND_FAILED;
return false;
}
sessionState.currentPlayerId = assignedPlayerId;
state = CONNECTED;
return true;
}
bool send(u16 data, int _author = -1) {
LINK_WIRELESS_RESET_IF_NEEDED
if (!isSessionActive()) {
lastError = WRONG_STATE;
return false;
}
if (!_canSend()) {
if (_author < 0)
lastError = BUFFER_IS_FULL;
return false;
}
Message message;
message.playerId = _author >= 0 ? _author : sessionState.currentPlayerId;
message.data = data;
LINK_WIRELESS_BARRIER;
isAddingMessage = true;
LINK_WIRELESS_BARRIER;
sessionState.tmpMessagesToSend.push(message);
LINK_WIRELESS_BARRIER;
isAddingMessage = false;
LINK_WIRELESS_BARRIER;
return true;
}
bool receive(Message messages[]) {
if (!isEnabled || state == NEEDS_RESET || !isSessionActive())
return false;
LINK_WIRELESS_BARRIER;
isReadingMessages = true;
LINK_WIRELESS_BARRIER;
u32 i = 0;
while (!sessionState.incomingMessages.isEmpty()) {
auto message = sessionState.incomingMessages.pop();
messages[i] = message;
forwardMessageIfNeeded(message);
i++;
}
LINK_WIRELESS_BARRIER;
isReadingMessages = false;
LINK_WIRELESS_BARRIER;
return true;
}
State getState() { return state; }
bool isConnected() { return sessionState.playerCount > 1; }
bool isSessionActive() { return state == SERVING || state == CONNECTED; }
u8 playerCount() { return sessionState.playerCount; }
u8 currentPlayerId() { return sessionState.currentPlayerId; }
Error getLastError(bool clear = true) {
Error error = lastError;
if (clear)
lastError = NONE;
return error;
}
~LinkWireless() {
delete linkSPI;
delete linkGPIO;
}
bool _canSend() { return !sessionState.outgoingMessages.isFull(); }
u32 _getPendingCount() { return sessionState.outgoingMessages.size(); }
u32 _lastPacketId() { return sessionState.lastPacketId; }
u32 _lastConfirmationFromClient1() {
return sessionState.lastConfirmationFromClients[1];
}
u32 _lastPacketIdFromClient1() {
return sessionState.lastPacketIdFromClients[1];
}
u32 _lastConfirmationFromServer() {
return sessionState.lastConfirmationFromServer;
}
u32 _lastPacketIdFromServer() { return sessionState.lastPacketIdFromServer; }
u32 _nextPendingPacketId() {
return sessionState.outgoingMessages.isEmpty()
? 0
: sessionState.outgoingMessages.peek().packetId;
}
void _onVBlank() {
if (!isEnabled)
return;
if (!isSessionActive()) {
copyState();
return;
}
if (isConnected() && sessionState.frameRecvCount == 0)
sessionState.recvTimeout++;
sessionState.frameRecvCount = 0;
sessionState.acceptCalled = false;
sessionState.pingSent = false;
copyState();
}
void _onSerial() {
if (!isEnabled)
return;
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();
}
}
}
void _onTimer() {
if (!isEnabled)
return;
if (!isSessionActive())
return;
if (sessionState.recvTimeout >= config.timeout) {
reset();
lastError = TIMEOUT;
return;
}
if (!asyncCommand.isActive)
acceptConnectionsOrSendData();
}
private:
struct Config {
bool forwarding;
bool retransmission;
u8 maxPlayers;
u32 timeout;
u32 remoteTimeout;
u32 interval;
u32 sendTimerId;
};
class MessageQueue {
public:
void push(Message item) {
if (isFull())
return;
rear = (rear + 1) % LINK_WIRELESS_QUEUE_SIZE;
arr[rear] = item;
count++;
}
Message pop() {
if (isEmpty())
return Message{};
auto x = arr[front];
front = (front + 1) % LINK_WIRELESS_QUEUE_SIZE;
count--;
return x;
}
Message peek() {
if (isEmpty())
return Message{};
return arr[front];
}
template <typename F>
void forEach(F action) {
int currentFront = front;
for (u32 i = 0; i < count; i++) {
if (!action(arr[currentFront]))
return;
currentFront = (currentFront + 1) % LINK_WIRELESS_QUEUE_SIZE;
}
}
void clear() {
while (!isEmpty())
pop();
}
int size() { return count; }
bool isEmpty() { return size() == 0; }
bool isFull() { return size() == LINK_WIRELESS_QUEUE_SIZE; }
private:
Message arr[LINK_WIRELESS_QUEUE_SIZE];
vs32 front = 0;
vs32 rear = -1;
vu32 count = 0;
};
struct SessionState {
MessageQueue incomingMessages; // read by user, write by irq&user
MessageQueue outgoingMessages; // read and write by irq
MessageQueue tmpMessagesToReceive; // read and write by irq
MessageQueue tmpMessagesToSend; // read by irq, write by user&irq
u32 timeouts[LINK_WIRELESS_MAX_PLAYERS];
u32 recvTimeout = 0;
u32 frameRecvCount = 0;
bool acceptCalled = false;
bool pingSent = false;
bool sendReceiveLatch = false;
bool shouldWaitForServer = false;
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 : LINK_WIRELESS_PACKET_ID_BITS;
unsigned int isConfirmation : 1;
unsigned int playerId : 3;
unsigned int clientCount : 2;
unsigned int dataChecksum : 4;
};
union MessageHeaderSerializer {
MessageHeader asStruct;
u16 asInt;
};
struct LoginMemory {
u16 previousGBAData = 0xffff;
u16 previousAdapterData = 0xffff;
};
struct CommandResult {
bool success = false;
u32 responses[LINK_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH];
u32 responsesSize = 0;
};
struct AsyncCommand {
enum State { PENDING, COMPLETED };
enum Step {
COMMAND_HEADER,
COMMAND_PARAMETERS,
RESPONSE_REQUEST,
DATA_REQUEST
};
u8 type;
u32 parameters[LINK_WIRELESS_MAX_SERVER_TRANSFER_LENGTH];
u32 responses[LINK_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH];
CommandResult result;
State state;
Step step;
u32 sentParameters, totalParameters;
u32 receivedResponses, totalResponses;
bool isActive;
};
SessionState sessionState;
AsyncCommand asyncCommand;
Config config;
LinkSPI* linkSPI = new LinkSPI();
LinkGPIO* linkGPIO = new LinkGPIO();
State state = NEEDS_RESET;
u32 nextCommandData[LINK_WIRELESS_MAX_SERVER_TRANSFER_LENGTH];
u32 nextCommandDataSize = 0;
volatile bool isReadingMessages = false;
volatile bool isAddingMessage = false;
volatile bool isPendingClearActive = false;
Error lastError = NONE;
bool isEnabled = false;
void forwardMessageIfNeeded(Message& message) {
if (state == SERVING && config.forwarding && sessionState.playerCount > 2)
send(message.data, message.playerId);
}
void processAsyncCommand() { // (irq only)
if (!asyncCommand.result.success) {
if (asyncCommand.type == LINK_WIRELESS_COMMAND_SEND_DATA)
lastError = SEND_DATA_FAILED;
else if (asyncCommand.type == LINK_WIRELESS_COMMAND_RECEIVE_DATA)
lastError = RECEIVE_DATA_FAILED;
else
lastError = COMMAND_FAILED;
reset();
return;
}
asyncCommand.isActive = false;
switch (asyncCommand.type) {
case LINK_WIRELESS_COMMAND_ACCEPT_CONNECTIONS: {
// Accept connections (end)
sessionState.playerCount = 1 + asyncCommand.result.responsesSize;
break;
}
case LINK_WIRELESS_COMMAND_SEND_DATA: {
// Send data (end)
if (state == CONNECTED)
sessionState.shouldWaitForServer = true;
sessionState.sendReceiveLatch = !sessionState.sendReceiveLatch;
break;
}
case LINK_WIRELESS_COMMAND_RECEIVE_DATA: {
// Receive data (end)
sessionState.sendReceiveLatch =
sessionState.shouldWaitForServer || !sessionState.sendReceiveLatch;
if (asyncCommand.result.responsesSize == 0)
break;
sessionState.frameRecvCount++;
sessionState.recvTimeout = 0;
sessionState.shouldWaitForServer = false;
trackRemoteTimeouts();
if (!addIncomingMessagesFromData(asyncCommand.result))
return;
if (!checkRemoteTimeouts()) {
reset();
lastError = REMOTE_TIMEOUT;
return;
}
break;
}
default: {
}
}
}
void acceptConnectionsOrSendData() { // (irq only)
if (state == SERVING && !sessionState.acceptCalled &&
sessionState.playerCount < config.maxPlayers) {
// Accept connections (start)
sendCommandAsync(LINK_WIRELESS_COMMAND_ACCEPT_CONNECTIONS);
sessionState.acceptCalled = true;
} else if (state == CONNECTED || isConnected()) {
if (!sessionState.sendReceiveLatch || sessionState.shouldWaitForServer) {
// Receive data (start)
sendCommandAsync(LINK_WIRELESS_COMMAND_RECEIVE_DATA);
} else {
// Send data (start)
sendPendingData();
}
}
}
void sendPendingData() { // (irq only)
int lastPacketId = setDataFromOutgoingMessages();
sendCommandAsync(LINK_WIRELESS_COMMAND_SEND_DATA, true);
clearOutgoingMessagesIfNeeded(lastPacketId);
}
int setDataFromOutgoingMessages() { // (irq only)
u32 maxTransferLength = getDeviceTransferLength();
addData(0, true);
if (config.retransmission)
addConfirmations();
else
addPingMessageIfNeeded();
int lastPacketId = -1;
sessionState.outgoingMessages.forEach(
[this, maxTransferLength, &lastPacketId](Message message) {
u16 header = buildMessageHeader(message.playerId, message.packetId,
buildChecksum(message.data));
u32 rawMessage = buildU32(header, message.data);
if (nextCommandDataSize /* -1 (wireless header) + 1 (rawMessage) */ >
maxTransferLength)
return false;
addData(rawMessage);
lastPacketId = message.packetId;
return true;
});
// (add wireless header)
u32 bytes = (nextCommandDataSize - 1) * 4;
nextCommandData[0] =
sessionState.currentPlayerId == 0
? bytes
: (1 << (3 + sessionState.currentPlayerId * 5)) * bytes;
return lastPacketId;
}
bool addIncomingMessagesFromData(CommandResult& result) { // (irq only)
for (u32 i = 1; i < result.responsesSize; i++) {
u32 rawMessage = result.responses[i];
u16 headerInt = msB32(rawMessage);
u16 data = lsB32(rawMessage);
MessageHeaderSerializer serializer;
serializer.asInt = headerInt;
MessageHeader header = serializer.asStruct;
u32 partialPacketId = header.partialPacketId;
bool isConfirmation = header.isConfirmation;
u8 remotePlayerId = header.playerId;
u8 remotePlayerCount = LINK_WIRELESS_MIN_PLAYERS + header.clientCount;
u32 checksum = header.dataChecksum;
bool isPing = data == LINK_WIRELESS_MSG_PING;
sessionState.timeouts[0] = 0;
sessionState.timeouts[remotePlayerId] = 0;
if (checksum != buildChecksum(data))
continue;
Message message;
message.packetId = partialPacketId;
message.data = data;
message.playerId = remotePlayerId;
if (!acceptMessage(message, isConfirmation, remotePlayerCount) || isPing)
continue;
if (config.retransmission && isConfirmation) {
if (!handleConfirmation(message))
continue;
} else {
sessionState.tmpMessagesToReceive.push(message);
}
}
return true;
}
bool acceptMessage(Message& message,
bool isConfirmation,
u32 remotePlayerCount) { // (irq only)
if (state == SERVING) {
u32 expectedPacketId =
(sessionState.lastPacketIdFromClients[message.playerId] + 1) %
LINK_WIRELESS_MAX_PACKET_IDS;
if (config.retransmission && !isConfirmation &&
message.packetId != expectedPacketId)
return false;
if (!isConfirmation)
message.packetId =
++sessionState.lastPacketIdFromClients[message.playerId];
} else {
u32 expectedPacketId = (sessionState.lastPacketIdFromServer + 1) %
LINK_WIRELESS_MAX_PACKET_IDS;
if (config.retransmission && !isConfirmation &&
message.packetId != expectedPacketId)
return false;
sessionState.playerCount = remotePlayerCount;
if (!isConfirmation)
message.packetId = ++sessionState.lastPacketIdFromServer;
}
bool isMessageFromCurrentPlayer =
!isConfirmation && message.playerId == sessionState.currentPlayerId;
return !isMessageFromCurrentPlayer;
}
void clearOutgoingMessagesIfNeeded(int lastPacketId) { // (irq only)
if (!config.retransmission && lastPacketId > -1)
removeConfirmedMessages(lastPacketId);
}
void addPingMessageIfNeeded() { // (irq only)
if (sessionState.outgoingMessages.isEmpty() && !sessionState.pingSent) {
Message pingMessage;
pingMessage.packetId = newPacketId();
pingMessage.playerId = sessionState.currentPlayerId;
pingMessage.data = LINK_WIRELESS_MSG_PING;
sessionState.outgoingMessages.push(pingMessage);
sessionState.pingSent = true;
}
}
void addConfirmations() { // (irq only)
if (state == SERVING) {
if (config.maxPlayers > 2 &&
(sessionState.lastPacketIdFromClients[1] == 0 ||
sessionState.lastPacketIdFromClients[2] == 0 ||
sessionState.lastPacketIdFromClients[3] == 0 ||
sessionState.lastPacketIdFromClients[4] == 0)) {
u32 lastPacketId = sessionState.lastPacketId;
u16 header = buildConfirmationHeader(0, lastPacketId);
u32 rawMessage = buildU32(header, lastPacketId & 0xffff);
addData(rawMessage);
}
for (int i = 0; i < config.maxPlayers - 1; i++) {
u32 confirmationData = sessionState.lastPacketIdFromClients[1 + i];
u16 header = buildConfirmationHeader(1 + i, confirmationData);
u32 rawMessage = buildU32(header, confirmationData & 0xffff);
addData(rawMessage);
}
} else {
u32 confirmationData = sessionState.lastPacketIdFromServer;
u16 header = buildConfirmationHeader(sessionState.currentPlayerId,
confirmationData);
u32 rawMessage = buildU32(header, confirmationData & 0xffff);
addData(rawMessage);
}
}
bool handleConfirmation(Message confirmation) { // (irq only)
u32 confirmationData = (confirmation.packetId << 16) | confirmation.data;
if (state == CONNECTED) {
if (confirmation.playerId == 0 &&
!sessionState.didReceiveLastPacketIdFromServer) {
sessionState.lastPacketIdFromServer = confirmationData;
sessionState.didReceiveLastPacketIdFromServer = true;
} else if (confirmation.playerId == sessionState.currentPlayerId) {
handleServerConfirmation(confirmationData);
} else {
return false;
}
} else {
handleClientConfirmation(confirmationData, confirmation.playerId);
}
return true;
}
void handleServerConfirmation(u32 confirmationData) { // (irq only)
sessionState.lastConfirmationFromServer = confirmationData;
removeConfirmedMessages(confirmationData);
}
void handleClientConfirmation(u32 confirmationData,
u8 playerId) { // (irq only)
sessionState.lastConfirmationFromClients[playerId] = confirmationData;
u32 min = 0xffffffff;
for (int i = 0; i < config.maxPlayers - 1; i++) {
u32 confirmationData = sessionState.lastConfirmationFromClients[1 + i];
if (confirmationData > 0 && confirmationData < min)
min = confirmationData;
}
if (min < 0xffffffff)
removeConfirmedMessages(min);
}
void removeConfirmedMessages(u32 confirmationData) { // (irq only)
while (!sessionState.outgoingMessages.isEmpty() &&
sessionState.outgoingMessages.peek().packetId <= confirmationData)
sessionState.outgoingMessages.pop();