-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLinkRawWireless.hpp
1238 lines (1056 loc) · 35.1 KB
/
LinkRawWireless.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_RAW_WIRELESS_H
#define LINK_RAW_WIRELESS_H
// --------------------------------------------------------------------------
// A low level driver for the GBA Wireless Adapter.
// --------------------------------------------------------------------------
// - Advanced usage only!
// - If you're building a game, use `LinkWireless`.
// --------------------------------------------------------------------------
#ifndef LINK_DEVELOPMENT
#pragma GCC system_header
#endif
#include "_link_common.hpp"
#include <array>
#include <cstring>
#include "LinkGPIO.hpp"
#include "LinkSPI.hpp"
/**
* @brief Enable logging.
* \warning Set `linkRawWireless->logger` and uncomment to enable!
*/
// #define LINK_RAW_WIRELESS_ENABLE_LOGGING
static volatile char LINK_RAW_WIRELESS_VERSION[] = "LinkRawWireless/v7.0.2";
#define LINK_RAW_WIRELESS_MAX_PLAYERS 5
#define LINK_RAW_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH 30
#define LINK_RAW_WIRELESS_MAX_CLIENT_TRANSFER_LENGTH 4
#define LINK_RAW_WIRELESS_MAX_GAME_ID 0x7fff
#define LINK_RAW_WIRELESS_MAX_GAME_NAME_LENGTH 14
#define LINK_RAW_WIRELESS_MAX_USER_NAME_LENGTH 8
#define LINK_RAW_WIRELESS_MAX_COMMAND_TRANSFER_LENGTH 23
#ifdef LINK_RAW_WIRELESS_ENABLE_LOGGING
#include <string>
#define LRWLOG(str) logger(str)
#else
#define LRWLOG(str)
#endif
/**
* @brief A low level driver for the GBA Wireless Adapter.
* \warning Advanced usage only!
* \warning If you're building a game, use `LinkWireless`.
*/
class LinkRawWireless {
private:
using u32 = unsigned int;
using u16 = unsigned short;
using u8 = unsigned char;
static constexpr int PING_WAIT = 50;
static constexpr int TRANSFER_WAIT = 15;
static constexpr int CMD_TIMEOUT = 10;
static constexpr int LOGIN_STEPS = 9;
static constexpr int COMMAND_HEADER = 0x9966;
static constexpr int RESPONSE_ACK = 0x80;
static constexpr u32 DATA_REQUEST = 0x80000000;
static constexpr int SETUP_MAGIC = 0x003c0000;
static constexpr int WAIT_STILL_CONNECTING = 0x01000000;
static constexpr int BROADCAST_LENGTH = 6;
static constexpr int BROADCAST_RESPONSE_LENGTH = 1 + BROADCAST_LENGTH;
static constexpr int MAX_SERVERS =
LINK_RAW_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH / BROADCAST_RESPONSE_LENGTH;
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_SLOT_STATUS = 0x14;
static constexpr int COMMAND_ACCEPT_CONNECTIONS = 0x1a;
static constexpr int COMMAND_END_HOST = 0x1b;
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_SEND_DATA_AND_WAIT = 0x25;
static constexpr int COMMAND_RECEIVE_DATA = 0x26;
static constexpr int COMMAND_WAIT = 0x27;
static constexpr int COMMAND_BYE = 0x3d;
static constexpr u16 LOGIN_PARTS[] = {0x494e, 0x494e, 0x544e, 0x544e, 0x4e45,
0x4e45, 0x4f44, 0x4f44, 0x8001};
public:
#ifdef LINK_RAW_WIRELESS_ENABLE_LOGGING
typedef void (*Logger)(std::string);
Logger logger = [](std::string str) {};
#endif
enum State {
NEEDS_RESET,
AUTHENTICATED,
SEARCHING,
SERVING,
CONNECTING,
CONNECTED
};
struct CommandResult {
bool success = false;
u32 responses[LINK_RAW_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH];
u32 responsesSize = 0;
};
struct RemoteCommand {
bool success = false;
u8 commandId = 0;
u32 params[LINK_RAW_WIRELESS_MAX_COMMAND_TRANSFER_LENGTH];
u32 paramsSize = 0;
};
struct Server {
u16 id = 0;
u16 gameId;
char gameName[LINK_RAW_WIRELESS_MAX_GAME_NAME_LENGTH + 1];
char userName[LINK_RAW_WIRELESS_MAX_USER_NAME_LENGTH + 1];
u8 nextClientNumber;
bool isFull() { return nextClientNumber == 0xff; }
};
struct ConnectedClient {
u16 deviceId = 0;
u8 clientNumber = 0;
};
struct SlotStatusResponse {
u8 nextClientNumber = 0;
std::array<ConnectedClient, LINK_RAW_WIRELESS_MAX_PLAYERS>
connectedClients = {};
u32 connectedClientsSize = 0;
};
struct AcceptConnectionsResponse {
std::array<ConnectedClient, LINK_RAW_WIRELESS_MAX_PLAYERS>
connectedClients = {};
u32 connectedClientsSize = 0;
};
struct BroadcastReadPollResponse {
std::array<Server, MAX_SERVERS> servers;
u32 serversSize = 0;
};
enum ConnectionPhase { STILL_CONNECTING, ERROR, SUCCESS };
struct ConnectionStatus {
ConnectionPhase phase = STILL_CONNECTING;
u8 assignedClientNumber = 0;
};
struct ReceiveDataResponse {
u32 sentBytes[LINK_RAW_WIRELESS_MAX_PLAYERS];
u32 data[LINK_RAW_WIRELESS_MAX_COMMAND_TRANSFER_LENGTH];
u32 dataSize = 0;
};
/**
* @brief Returns whether the library is active or not.
*/
[[nodiscard]] bool isActive() { return isEnabled; }
/**
* @brief Activates the library.
* Returns whether initialization was successful or not.
*/
bool activate() {
isEnabled = false;
bool success = reset(true);
isEnabled = true;
return success;
}
/**
* @brief Deactivates the library.
*/
bool deactivate() {
bool success = sendCommand(COMMAND_BYE).success;
isEnabled = false;
resetState();
stop();
return success;
}
/**
* @brief Calls the Setup (`0x17`) command.
* @param maxPlayers `(2~5)` Maximum players in hosted rooms. Clients should
* set this to `0`.
* @param maxTransmissions Number of transmissions before marking a player as
* disconnected. `0` means infinite retransmissions.
* @param waitTimeout Timeout of the *waiting commands*, in frames (16.6ms).
* `0` means no timeout.
* @param magic A part of the protocol that hasn't been reverse-engineered
* yet. For now, it's magic (`0x003c0000`).
*/
bool setup(u8 maxPlayers = LINK_RAW_WIRELESS_MAX_PLAYERS,
u8 maxTransmissions = 4,
u8 waitTimeout = 32,
u32 magic = SETUP_MAGIC) {
u32 config =
(u32)(magic |
(((LINK_RAW_WIRELESS_MAX_PLAYERS - maxPlayers) & 0b11) << 16) |
(maxTransmissions << 8) | waitTimeout);
return sendCommand(COMMAND_SETUP, {config}, 1).success;
}
/**
* @brief Calls the Broadcast (`0x16`) command.
* @param gameName Game name. Maximum `14` characters + null terminator.
* @param userName User name. Maximum `8` characters + null terminator.
* @param gameId `(0 ~ 0x7FFF)` Game ID.
*/
bool broadcast(const char* gameName = "",
const char* userName = "",
u16 gameId = LINK_RAW_WIRELESS_MAX_GAME_ID) {
if (std::strlen(gameName) > LINK_RAW_WIRELESS_MAX_GAME_NAME_LENGTH) {
LRWLOG("! game name too long");
return false;
}
if (std::strlen(userName) > LINK_RAW_WIRELESS_MAX_USER_NAME_LENGTH) {
LRWLOG("! user name too long");
return false;
}
char finalGameName[LINK_RAW_WIRELESS_MAX_GAME_NAME_LENGTH + 1];
char finalUserName[LINK_RAW_WIRELESS_MAX_USER_NAME_LENGTH + 1];
copyName(finalGameName, gameName, LINK_RAW_WIRELESS_MAX_GAME_NAME_LENGTH);
copyName(finalUserName, userName, LINK_RAW_WIRELESS_MAX_USER_NAME_LENGTH);
bool success =
sendCommand(
COMMAND_BROADCAST,
{buildU32(buildU16(finalGameName[1], finalGameName[0]), gameId),
buildU32(buildU16(finalGameName[5], finalGameName[4]),
buildU16(finalGameName[3], finalGameName[2])),
buildU32(buildU16(finalGameName[9], finalGameName[8]),
buildU16(finalGameName[7], finalGameName[6])),
buildU32(buildU16(finalGameName[13], finalGameName[12]),
buildU16(finalGameName[11], finalGameName[10])),
buildU32(buildU16(finalUserName[3], finalUserName[2]),
buildU16(finalUserName[1], finalUserName[0])),
buildU32(buildU16(finalUserName[7], finalUserName[6]),
buildU16(finalUserName[5], finalUserName[4]))},
BROADCAST_LENGTH)
.success;
if (!success) {
reset();
return false;
}
return true;
}
/**
* @brief Calls the StartHost (`0x19`) command.
*/
bool startHost() {
bool success = sendCommand(COMMAND_START_HOST).success;
if (!success) {
reset();
return false;
}
wait(TRANSFER_WAIT);
LRWLOG("state = SERVING");
state = SERVING;
return true;
}
/**
* @brief Calls the SlotStatus (`0x14`) command.
* @param response A structure that will be filled with the response data.
*/
bool getSlotStatus(SlotStatusResponse& response) {
auto result = sendCommand(COMMAND_SLOT_STATUS);
if (!result.success) {
reset();
return false;
}
response.connectedClientsSize = 0;
for (u32 i = 0; i < result.responsesSize; i++) {
if (i == 0) {
response.nextClientNumber = (u8)lsB32(result.responses[i]);
} else {
response.connectedClients[response.connectedClientsSize++] =
ConnectedClient{.deviceId = lsB32(result.responses[i]),
.clientNumber = (u8)msB32(result.responses[i])};
}
}
return true;
}
/**
* @brief Calls the AcceptConnections (`0x1a`) command.
* @param response A structure that will be filled with the response data.
*/
bool acceptConnections(AcceptConnectionsResponse& response) {
auto result = sendCommand(COMMAND_ACCEPT_CONNECTIONS);
if (!result.success) {
reset();
return false;
}
response.connectedClientsSize = 0;
for (u32 i = 0; i < result.responsesSize; i++) {
response.connectedClients[response.connectedClientsSize++] =
ConnectedClient{.deviceId = lsB32(result.responses[i]),
.clientNumber = (u8)msB32(result.responses[i])};
}
u8 oldPlayerCount = sessionState.playerCount;
sessionState.playerCount = 1 + result.responsesSize;
if (sessionState.playerCount != oldPlayerCount)
LRWLOG("now: " + std::to_string(sessionState.playerCount) + " players");
return true;
}
/**
* @brief Calls the EndHost (`0x1b`) command.
* @param response A structure that will be filled with the response data.
*/
bool endHost(AcceptConnectionsResponse& response) {
auto result = sendCommand(COMMAND_END_HOST);
if (!result.success) {
reset();
return false;
}
response.connectedClientsSize = 0;
for (u32 i = 0; i < result.responsesSize; i++) {
response.connectedClients[response.connectedClientsSize++] =
ConnectedClient{.deviceId = lsB32(result.responses[i]),
.clientNumber = (u8)msB32(result.responses[i])};
}
u8 oldPlayerCount = sessionState.playerCount;
sessionState.playerCount = 1 + result.responsesSize;
if (sessionState.playerCount != oldPlayerCount)
LRWLOG("now: " + std::to_string(sessionState.playerCount) + " players");
return true;
}
/**
* @brief Calls the BroadcastRead1 (`0x1c`) command.
*/
bool broadcastReadStart() {
bool success = sendCommand(COMMAND_BROADCAST_READ_START).success;
if (!success) {
reset();
return false;
}
LRWLOG("state = SEARCHING");
state = SEARCHING;
return true;
}
/**
* @brief Calls the BroadcastRead2 (`0x1d`) command.
*/
bool broadcastReadPoll(BroadcastReadPollResponse& response) {
auto result = sendCommand(COMMAND_BROADCAST_READ_POLL);
bool success =
result.success && result.responsesSize % BROADCAST_RESPONSE_LENGTH == 0;
if (!success) {
reset();
return false;
}
u32 totalBroadcasts = result.responsesSize / BROADCAST_RESPONSE_LENGTH;
response.serversSize = 0;
for (u32 i = 0; i < totalBroadcasts; i++) {
u32 start = BROADCAST_RESPONSE_LENGTH * i;
Server server;
server.id = (u16)result.responses[start];
server.gameId =
result.responses[start + 1] & LINK_RAW_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';
server.nextClientNumber = (result.responses[start] >> 16) & 0xff;
response.servers[response.serversSize++] = server;
}
return true;
}
/**
* @brief Calls the BroadcastRead3 (`0x1e`) command.
*/
bool broadcastReadEnd() {
bool success = sendCommand(COMMAND_BROADCAST_READ_END).success;
if (!success) {
reset();
return false;
}
LRWLOG("state = AUTHENTICATED");
state = AUTHENTICATED;
return true;
}
/**
* @brief Calls the Connect (`0x1f`) command.
* @param serverId Device ID of the server.
*/
bool connect(u16 serverId) {
bool success = sendCommand(COMMAND_CONNECT, {serverId}, 1).success;
if (!success) {
reset();
return false;
}
LRWLOG("state = CONNECTING");
state = CONNECTING;
return true;
}
/**
* @brief Calls the IsFinishedConnect (`0x20`) command.
* @param response A structure that will be filled with the response data.
*/
bool keepConnecting(ConnectionStatus& response) {
auto result = sendCommand(COMMAND_IS_FINISHED_CONNECT);
if (!result.success || result.responsesSize == 0) {
if (result.responsesSize == 0)
LRWLOG("! empty response");
reset();
return false;
}
if (result.responses[0] == WAIT_STILL_CONNECTING) {
response.phase = STILL_CONNECTING;
return true;
}
u8 assignedPlayerId = 1 + (u8)msB32(result.responses[0]);
if (assignedPlayerId >= LINK_RAW_WIRELESS_MAX_PLAYERS) {
LRWLOG("! connection failed (1)");
reset();
response.phase = ERROR;
return false;
}
response.phase = SUCCESS;
response.assignedClientNumber = (u8)msB32(result.responses[0]);
return true;
}
/**
* @brief Calls the FinishConnection (`0x21`) command.
*/
bool finishConnection() {
auto result = sendCommand(COMMAND_FINISH_CONNECTION);
if (!result.success || result.responsesSize == 0) {
if (result.responsesSize == 0)
LRWLOG("! empty response");
reset();
return false;
}
u16 status = msB32(result.responses[0]);
if ((msB16(status) & 1) == 1) {
LRWLOG("! connection failed (2)");
reset();
return false;
}
u8 assignedPlayerId = 1 + (u8)status;
sessionState.currentPlayerId = assignedPlayerId;
LRWLOG("state = CONNECTED");
state = CONNECTED;
return true;
}
/**
* @brief Calls the SendData (`0x24`) command.
* @param data The values to be sent.
* @param dataSize The number of 32-bit values in the `data` array.
* @param _bytes The number of BYTES to send. If `0`, the method will use
* `dataSize * 4` instead.
*/
bool sendData(
std::array<u32, LINK_RAW_WIRELESS_MAX_COMMAND_TRANSFER_LENGTH> data,
u32 dataSize,
u32 _bytes = 0) {
u32 bytes = _bytes == 0 ? dataSize * 4 : _bytes;
u32 header = sessionState.currentPlayerId == 0
? bytes
: (bytes << (3 + sessionState.currentPlayerId * 5));
for (u32 i = dataSize; i > 0; i--)
data[i] = data[i - 1];
data[0] = header;
dataSize++;
LRWLOG("using header " + toHex(header));
bool success = sendCommand(COMMAND_SEND_DATA, data, dataSize).success;
if (!success) {
reset();
return false;
}
return true;
}
/**
* @brief Calls the SendDataAndWait (`0x25`) command.
* @param data The values to be sent.
* @param dataSize The number of 32-bit values in the `data` array.
* @param remoteCommand A structure that will be filled with the remote
* command from the adapter.
* @param _bytes The number of BYTES to send. If `0`, the method will use
* `dataSize * 4` instead.
*/
bool sendDataAndWait(
std::array<u32, LINK_RAW_WIRELESS_MAX_COMMAND_TRANSFER_LENGTH> data,
u32 dataSize,
RemoteCommand& remoteCommand,
u32 _bytes = 0) {
u32 bytes = _bytes == 0 ? dataSize * 4 : _bytes;
u32 header = sessionState.currentPlayerId == 0
? bytes
: (bytes << (3 + sessionState.currentPlayerId * 5));
for (u32 i = dataSize; i > 0; i--)
data[i] = data[i - 1];
data[0] = header;
dataSize++;
LRWLOG("using header " + toHex(header));
if (!sendCommand(COMMAND_SEND_DATA_AND_WAIT, data, dataSize, true)
.success) {
reset();
return false;
}
remoteCommand = receiveCommandFromAdapter();
return remoteCommand.success;
}
/**
* @brief Calls the ReceiveData (`0x26`) command.
* @param response A structure that will be filled with the response data.
*/
bool receiveData(ReceiveDataResponse& response) {
auto result = sendCommand(COMMAND_RECEIVE_DATA);
for (u32 i = 0; i < result.responsesSize; i++)
response.data[i] = result.responses[i];
response.dataSize = result.responsesSize;
if (!result.success) {
reset();
return false;
}
for (u32 i = 0; i < LINK_RAW_WIRELESS_MAX_PLAYERS; i++)
response.sentBytes[i] = 0;
if (response.dataSize > 0) {
u32 header = response.data[0];
for (u32 i = 1; i < response.dataSize; i++)
response.data[i - 1] = response.data[i];
response.dataSize--;
response.sentBytes[0] = header & 0b1111111;
response.sentBytes[1] = (header >> 8) & 0b11111;
response.sentBytes[2] = (header >> 13) & 0b11111;
response.sentBytes[3] = (header >> 18) & 0b11111;
response.sentBytes[4] = (header >> 23) & 0b11111;
}
return true;
}
/**
* @brief Calls the Wait (`0x27`) command.
* @param remoteCommand A structure that will be filled with the remote
* command from the adapter.
*/
bool wait(RemoteCommand& remoteCommand) {
if (!sendCommand(COMMAND_WAIT, {}, 0, true).success) {
reset();
return false;
}
remoteCommand = receiveCommandFromAdapter();
return remoteCommand.success;
}
/**
* @brief Calls an arbitrary command and returns the response.
* @param type The ID of the command.
* @param params The command parameters.
* @param length The number of 32-bit values in the `params` array.
* @param invertsClock Whether this command inverts the clock or not (Wait).
*/
CommandResult sendCommand(
u8 type,
std::array<u32, LINK_RAW_WIRELESS_MAX_COMMAND_TRANSFER_LENGTH> params =
{},
u16 length = 0,
bool invertsClock = false) {
CommandResult result;
u32 command = buildCommand(type, length);
u32 r;
LRWLOG("sending command 0x" + toHex(command));
if ((r = transfer(command)) != DATA_REQUEST) {
logExpectedButReceived(DATA_REQUEST, r);
return result;
}
u32 parameterCount = 0;
for (u32 i = 0; i < length; i++) {
u32 param = params[i];
LRWLOG("sending param" + std::to_string(parameterCount) + ": 0x" +
toHex(param));
if ((r = transfer(param)) != DATA_REQUEST) {
logExpectedButReceived(DATA_REQUEST, r);
return result;
}
parameterCount++;
}
LRWLOG("sending response request");
u32 response = invertsClock
? transferAndStartClockInversionACK(DATA_REQUEST)
: transfer(DATA_REQUEST);
u16 header = msB32(response);
u16 data = lsB32(response);
u8 responses = msB16(data);
u8 ack = lsB16(data);
if (header != COMMAND_HEADER) {
LRWLOG("! expected HEADER 0x9966");
LRWLOG("! but received 0x" + toHex(header));
return result;
}
if (ack != type + RESPONSE_ACK) {
if (ack == 0xee && responses == 1 && !invertsClock) {
u8 __attribute__((unused)) code = (u8)transfer(DATA_REQUEST);
LRWLOG("! error received");
LRWLOG(code == 1 ? "! invalid state" : "! unknown cmd");
} else {
LRWLOG("! expected ACK 0x" + toHex(type + RESPONSE_ACK));
LRWLOG("! but received 0x" + toHex(ack));
}
return result;
}
LRWLOG("ack ok! " + std::to_string(responses) + " responses");
if (!invertsClock) {
for (u32 i = 0; i < responses; i++) {
LRWLOG("response " + std::to_string(i + 1) + "/" +
std::to_string(responses) + ":");
u32 responseData = transfer(DATA_REQUEST);
result.responses[result.responsesSize++] = responseData;
LRWLOG("<< " + toHex(responseData));
}
}
result.success = true;
return result;
}
/**
* @brief Inverts the clock and waits until the adapter sends a command.
* Returns the remote command.
*/
RemoteCommand receiveCommandFromAdapter() {
RemoteCommand remoteCommand;
LRWLOG("setting SPI to SLAVE");
linkSPI->activate(LinkSPI::Mode::SLAVE);
LRWLOG("WAITING for adapter cmd");
u32 command =
linkSPI->transfer(DATA_REQUEST, []() { return false; }, false, true);
if (!reverseAcknowledge()) {
linkSPI->activate(LinkSPI::Mode::MASTER_2MBPS);
reset();
return remoteCommand;
}
u16 header = msB32(command);
u16 data = lsB32(command);
u8 params = msB16(data);
u8 commandId = lsB16(data);
if (header != COMMAND_HEADER) {
LRWLOG("! expected HEADER 0x9966");
LRWLOG("! but received 0x" + toHex(header));
linkSPI->activate(LinkSPI::Mode::MASTER_2MBPS);
reset();
return remoteCommand;
}
LRWLOG("received cmd: " + toHex(commandId) + " (" + std::to_string(params) +
" params)");
for (u32 i = 0; i < params; i++) {
LRWLOG("param " + std::to_string(i + 1) + "/" + std::to_string(params) +
":");
u32 paramData =
linkSPI->transfer(DATA_REQUEST, []() { return false; }, false, true);
if (!reverseAcknowledge()) {
linkSPI->activate(LinkSPI::Mode::MASTER_2MBPS);
reset();
return remoteCommand;
}
remoteCommand.params[remoteCommand.paramsSize++] = paramData;
LRWLOG("<< " + toHex(paramData));
}
wait(TRANSFER_WAIT);
LRWLOG("sending ack");
command = linkSPI->transfer(
(COMMAND_HEADER << 16) | ((commandId + RESPONSE_ACK) & 0xff),
[]() { return false; }, false, true);
if (!reverseAcknowledge(true)) {
linkSPI->activate(LinkSPI::Mode::MASTER_2MBPS);
reset();
return remoteCommand;
}
if (command != DATA_REQUEST) {
LRWLOG("! expected CMD request");
LRWLOG("! but received 0x" + toHex(command));
linkSPI->activate(LinkSPI::Mode::MASTER_2MBPS);
reset();
return remoteCommand;
}
LRWLOG("setting SPI to MASTER");
linkSPI->activate(LinkSPI::Mode::MASTER_2MBPS);
wait(TRANSFER_WAIT);
remoteCommand.success = true;
remoteCommand.commandId = commandId;
return remoteCommand;
}
/**
* @brief Returns the maximum number of transferrable 32-bit values.
* It's 23 for servers and 4 for clients.
*/
[[nodiscard]] u32 getDeviceTransferLength() {
return state == SERVING ? LINK_RAW_WIRELESS_MAX_COMMAND_TRANSFER_LENGTH
: LINK_RAW_WIRELESS_MAX_CLIENT_TRANSFER_LENGTH;
}
/**
* @brief Returns the current 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; }
~LinkRawWireless() {
delete linkSPI;
delete linkGPIO;
}
struct SessionState {
u8 playerCount = 1;
u8 currentPlayerId = 0;
};
struct LoginMemory {
u16 previousGBAData = 0xffff;
u16 previousAdapterData = 0xffff;
};
SessionState sessionState;
LinkSPI* linkSPI = new LinkSPI();
LinkGPIO* linkGPIO = new LinkGPIO();
State state = NEEDS_RESET;
volatile bool isEnabled = false;
/**
* @brief Copies a null-terminated `source` string to a `target` destination
* (up to `length` characters).
* @param target Target string.
* @param source Source string.
* @param length Number of characters.
*/
void copyName(char* target, const char* source, u32 length) {
u32 len = std::strlen(source);
for (u32 i = 0; i < length + 1; i++)
if (i < len)
target[i] = source[i];
else
target[i] = '\0';
}
/**
* @brief Recovers parts of the `name` of a Wireless Adapter room.
* @param name Target string.
* @param nameCursor Current position within `name`.
* @param word Current value.
* @param includeFirstTwoBytes Whether the first two bytes from `word` should
* be used.
*/
void recoverName(char* name,
u32& nameCursor,
u32 word,
bool includeFirstTwoBytes = true) {
u32 character = 0;
if (includeFirstTwoBytes) {
character = lsB16(lsB32(word));
if (character > 0)
name[nameCursor++] = character;
character = msB16(lsB32(word));
if (character > 0)
name[nameCursor++] = character;
}
character = lsB16(msB32(word));
if (character > 0)
name[nameCursor++] = character;
character = msB16(msB32(word));
if (character > 0)
name[nameCursor++] = character;
}
/**
* @brief Resets the adapter
* @param initialize Whether it's an initialization (first time) or not.
*/
bool reset(bool initialize = false) {
resetState();
if (initialize)
stop();
return initialize && start();
}
/**
* @brief Resets all the state.
*/
void resetState() {
LRWLOG("state = NEEDS_RESET");
this->state = NEEDS_RESET;
this->sessionState.playerCount = 1;
this->sessionState.currentPlayerId = 0;
}
/**
* @brief Stops the communication.
*/
void stop() { linkSPI->deactivate(); }
/**
* @brief Starts the communication.
*/
bool start() {
pingAdapter();
LRWLOG("setting SPI to 256Kbps");
linkSPI->activate(LinkSPI::Mode::MASTER_256KBPS);
if (!login())
return false;
wait(TRANSFER_WAIT);
LRWLOG("sending HELLO command");
if (!sendCommand(COMMAND_HELLO).success)
return false;
LRWLOG("setting SPI to 2Mbps");
linkSPI->activate(LinkSPI::Mode::MASTER_2MBPS);
LRWLOG("state = AUTHENTICATED");
state = AUTHENTICATED;
return true;
}
/**
* @brief Sends the signal to reset the adapter.
*/
void pingAdapter() {
linkGPIO->reset();
LRWLOG("setting SO as OUTPUT");
linkGPIO->setMode(LinkGPIO::Pin::SO, LinkGPIO::Direction::OUTPUT);
LRWLOG("setting SD as OUTPUT");
linkGPIO->setMode(LinkGPIO::Pin::SD, LinkGPIO::Direction::OUTPUT);
LRWLOG("setting SD = HIGH");
linkGPIO->writePin(LinkGPIO::SD, true);
wait(PING_WAIT);
LRWLOG("setting SD = LOW");
linkGPIO->writePin(LinkGPIO::SD, false);
}
/**
* @brief Sends the login sequence to the adapter.
*/
bool login() {
LoginMemory memory;
LRWLOG("sending initial login packet");
if (!exchangeLoginPacket(LOGIN_PARTS[0], 0, memory))
return false;
for (u32 i = 0; i < LOGIN_STEPS; i++) {
LRWLOG("sending login packet " + std::to_string(i + 1) + "/" +
std::to_string(LOGIN_STEPS));
if (!exchangeLoginPacket(LOGIN_PARTS[i], LOGIN_PARTS[i], memory))
return false;
}
return true;
}
/**
* @brief Exchanges part of the login sequence with the adapter.
* @param data The value to be sent.
* @param expectedResponse The expected response.
* @param memory A structure that holds memory of the previous values.
*/
bool exchangeLoginPacket(u16 data,
u16 expectedResponse,
LoginMemory& memory) {
u32 packet = buildU32(~memory.previousAdapterData, data);
u32 response = transfer(packet, false);
if (msB32(response) != expectedResponse ||
lsB32(response) != (u16)~memory.previousGBAData) {
logExpectedButReceived(
buildU32(expectedResponse, (u16)~memory.previousGBAData), response);
return false;
}
memory.previousGBAData = data;
memory.previousAdapterData = expectedResponse;
return true;
}
/**
* @brief Builds a 32-bit value representing the command.
* @param type The ID of the command.