-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLinkRawWireless.hpp
1774 lines (1499 loc) · 52.2 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.
// --------------------------------------------------------------------------
// Usage:
// - There's one method for every supported Wireless Adapter command:
// - `setup` = `0x17`
// - `getSystemStatus` = `0x13`
// - `broadcast` = `0x16`
// - `startHost` = `0x19`
// - `getSignalLevel` = `0x11`
// - `getSlotStatus` = `0x14`
// - `pollConnections` = `0x1A`
// - `endHost` = `0x1B`
// - `broadcastReadStart` = `0x1C`
// - `broadcastReadPoll` = `0x1D`
// - `broadcastReadEnd` = `0x1E`
// - `connect` = `0x1F`
// - `keepConnecting` = `0x20`
// - `finishConnection` = `0x21`
// - `sendData` = `0x24`
// - `sendDataAndWait` = `0x25`
// - `receiveData` = `0x26`
// - `wait` = `0x27`
// - `disconnectClient` = `0x30`
// - `bye` = `0x3D`
// - Use `sendCommand(...)` to send arbitrary commands.
// - Use `sendCommandAsync(...)` to send arbitrary commands asynchronously.
// - This requires setting `LINK_RAW_WIRELESS_ISR_SERIAL` as the `SERIAL`
// interrupt handler.
// - After calling this method, call `getAsyncState()` and
// `getAsyncCommandResult()`.
// - Do not call any other methods until the async state is `IDLE` again, or
// the adapter will desync!
// - When sending arbitrary commands, the responses are not parsed. The
// exceptions are SendData and ReceiveData, which have these helpers:
// - `getSendDataHeaderFor(...)`
// - `getReceiveDataResponse(...)`
// --------------------------------------------------------------------------
// considerations:
// - advanced usage only; if you're building a game, use `LinkWireless`!
// --------------------------------------------------------------------------
#ifndef LINK_DEVELOPMENT
#pragma GCC system_header
#endif
#include "_link_common.hpp"
#include "LinkGPIO.hpp"
#include "LinkSPI.hpp"
#ifndef LINK_RAW_WIRELESS_ENABLE_LOGGING
/**
* @brief Enable logging.
* \warning Set `linkRawWireless->logger` and uncomment to enable!
* \warning This option #include`s std::string!
*/
// #define LINK_RAW_WIRELESS_ENABLE_LOGGING
#endif
LINK_VERSION_TAG LINK_RAW_WIRELESS_VERSION = "vLinkRawWireless/v8.0.1";
#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
#define LINK_RAW_WIRELESS_BROADCAST_LENGTH 6
#define LINK_RAW_WIRELESS_BROADCAST_RESPONSE_LENGTH \
(1 + LINK_RAW_WIRELESS_BROADCAST_LENGTH)
#define LINK_RAW_WIRELESS_MAX_SERVERS \
(LINK_RAW_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH / \
LINK_RAW_WIRELESS_BROADCAST_LENGTH)
#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.
*/
class LinkRawWireless {
private:
using u32 = Link::u32;
using u16 = Link::u16;
using u8 = Link::u8;
using vu8 = Link::vu8;
public:
static constexpr int PING_WAIT = 50;
static constexpr int TRANSFER_WAIT = 15;
static constexpr int MICRO_WAIT = 2;
#ifdef LINK_RAW_WIRELESS_ENABLE_LOGGING
static constexpr int CMD_TIMEOUT = 228;
#else
static constexpr int CMD_TIMEOUT = 15;
#endif
static constexpr int MAX_TRANSFER_BYTES_SERVER = 87;
static constexpr int MAX_TRANSFER_BYTES_CLIENT = 16;
static constexpr int LOGIN_STEPS = 10;
static constexpr int LOGIN_JUNK_STEPS = 2;
static constexpr int COMMAND_HEADER_VALUE = 0x9966;
static constexpr int RESPONSE_ACK = 0x80;
static constexpr u32 DATA_REQUEST_VALUE = 0x80000000;
static constexpr int SETUP_MAGIC = 0x003c0000;
static constexpr int WAIT_STILL_CONNECTING = 0x01000000;
static constexpr int COMMAND_HELLO = 0x10;
static constexpr int COMMAND_SETUP = 0x17;
static constexpr int COMMAND_SYSTEM_STATUS = 0x13;
static constexpr int COMMAND_BROADCAST = 0x16;
static constexpr int COMMAND_START_HOST = 0x19;
static constexpr int COMMAND_SIGNAL_LEVEL = 0x11;
static constexpr int COMMAND_SLOT_STATUS = 0x14;
static constexpr int COMMAND_POLL_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_CONNECTION_COMPLETE = 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_DISCONNECT_CLIENT = 0x30;
static constexpr int COMMAND_BYE = 0x3d;
static constexpr int EVENT_WAIT_TIMEOUT = 0x27;
static constexpr int EVENT_DATA_AVAILABLE = 0x28;
static constexpr int EVENT_DISCONNECTED = 0x29;
static constexpr u16 LOGIN_PARTS[] = {0x494E, 0x494E, 0x494E, 0x544E, 0x544E,
0x4E45, 0x4E45, 0x4F44, 0x4F44, 0x8001};
#ifdef LINK_RAW_WIRELESS_ENABLE_LOGGING
typedef void (*Logger)(std::string);
Logger logger = [](std::string str) {};
#endif
enum class State {
NEEDS_RESET = 0,
AUTHENTICATED = 1,
SEARCHING = 2,
SERVING = 3,
CONNECTING = 4,
CONNECTED = 5
};
struct CommandResult {
bool success = false;
u8 commandId = 0;
u32 data[LINK_RAW_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH];
u32 dataSize = 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 SystemStatusResponse {
u16 deviceId = 0;
u8 currentPlayerId = 0;
State adapterState = State::AUTHENTICATED;
bool isServerClosed = false;
};
struct SignalLevelResponse {
u8 signalLevels[LINK_RAW_WIRELESS_MAX_PLAYERS] = {};
};
struct SlotStatusResponse {
u8 nextClientNumber = 0;
ConnectedClient connectedClients[LINK_RAW_WIRELESS_MAX_PLAYERS] = {};
u32 connectedClientsSize = 0;
};
struct PollConnectionsResponse {
ConnectedClient connectedClients[LINK_RAW_WIRELESS_MAX_PLAYERS] = {};
u32 connectedClientsSize = 0;
};
struct BroadcastReadPollResponse {
Server servers[LINK_RAW_WIRELESS_MAX_SERVERS] = {};
u32 serversSize = 0;
};
enum class ConnectionPhase { STILL_CONNECTING, ERROR, SUCCESS };
struct ConnectionStatus {
ConnectionPhase phase = ConnectionPhase::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;
};
enum class AsyncState { IDLE, WORKING, READY };
/**
* @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(bool _stopFirst = true) {
LINK_READ_TAG(LINK_RAW_WIRELESS_VERSION);
LINK_BARRIER;
isEnabled = false;
LINK_BARRIER;
bool success = reset(_stopFirst);
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();
LINK_BARRIER;
isEnabled = true;
LINK_BARRIER;
_LRWLOG_("setting SPI to 2Mbps");
linkSPI.activate(LinkSPI::Mode::MASTER_2MBPS);
_LRWLOG_("analyzing system status");
SystemStatusResponse systemStatus;
if (!getSystemStatus(systemStatus)) {
deactivate();
return false;
}
if (systemStatus.adapterState == State::SERVING) {
_LRWLOG_("restoring SERVING state");
SlotStatusResponse slotStatus;
if (!getSlotStatus(slotStatus)) {
deactivate();
return false;
}
state = State::SERVING;
sessionState.isServerClosed = systemStatus.isServerClosed;
} else if (systemStatus.adapterState == State::CONNECTED) {
_LRWLOG_("restoring CONNECTED state");
state = State::CONNECTED;
} else {
_LRWLOG_("! invalid adapter state");
deactivate();
return false;
}
LINK_BARRIER;
sessionState.currentPlayerId = systemStatus.currentPlayerId;
LINK_BARRIER;
_LRWLOG_("restored ok!");
return true;
}
/**
* @brief Deactivates the library.
*/
void deactivate() {
isEnabled = false;
_resetState();
stop();
}
/**
* @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) {
if (!isEnabled)
return false;
u32 config =
(u32)(magic |
(((LINK_RAW_WIRELESS_MAX_PLAYERS - maxPlayers) & 0b11) << 16) |
(maxTransmissions << 8) | waitTimeout);
u32 params[1] = {config};
return sendCommand(COMMAND_SETUP, params, 1).success;
}
/**
* @brief Calls the SystemStatus (`0x13`) command.
* @param response A structure that will be filled with the response data.
*/
bool getSystemStatus(SystemStatusResponse& response) {
if (!isEnabled)
return false;
auto result = sendCommand(COMMAND_SYSTEM_STATUS);
if (!result.success || result.dataSize == 0) {
if (result.dataSize == 0)
_LRWLOG_("! empty response");
_resetState();
return false;
}
u32 status = result.data[0];
response.deviceId = Link::lsB32(status);
u8 slot = Link::lsB16(Link::msB32(status)) & 0b1111;
LINK_BARRIER;
response.currentPlayerId = slot == 0b0001 ? 1
: slot == 0b0010 ? 2
: slot == 0b0100 ? 3
: slot == 0b1000 ? 4
: 0;
LINK_BARRIER;
u8 adapterState = Link::msB16(Link::msB32(status));
response.isServerClosed = false;
switch (adapterState) {
case 1: {
response.adapterState = State::SERVING;
response.isServerClosed = true;
break;
}
case 2: {
response.adapterState = State::SERVING;
break;
}
case 3: {
response.adapterState = State::SEARCHING;
break;
}
case 4: {
response.adapterState = State::CONNECTING;
break;
}
case 5: {
response.adapterState = State::CONNECTED;
break;
}
default: {
response.adapterState = State::AUTHENTICATED;
break;
}
}
return true;
}
/**
* @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,
bool _validateNames = true) {
if (!isEnabled)
return false;
if (_validateNames &&
Link::strlen(gameName) > LINK_RAW_WIRELESS_MAX_GAME_NAME_LENGTH) {
_LRWLOG_("! game name too long");
return false;
}
if (_validateNames &&
Link::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);
u32 params[LINK_RAW_WIRELESS_BROADCAST_LENGTH] = {
Link::buildU32(Link::buildU16(finalGameName[1], finalGameName[0]),
gameId),
Link::buildU32(Link::buildU16(finalGameName[5], finalGameName[4]),
Link::buildU16(finalGameName[3], finalGameName[2])),
Link::buildU32(Link::buildU16(finalGameName[9], finalGameName[8]),
Link::buildU16(finalGameName[7], finalGameName[6])),
Link::buildU32(Link::buildU16(finalGameName[13], finalGameName[12]),
Link::buildU16(finalGameName[11], finalGameName[10])),
Link::buildU32(Link::buildU16(finalUserName[3], finalUserName[2]),
Link::buildU16(finalUserName[1], finalUserName[0])),
Link::buildU32(Link::buildU16(finalUserName[7], finalUserName[6]),
Link::buildU16(finalUserName[5], finalUserName[4]))};
bool success = sendCommand(COMMAND_BROADCAST, params,
LINK_RAW_WIRELESS_BROADCAST_LENGTH)
.success;
if (!success) {
_resetState();
return false;
}
return true;
}
/**
* @brief Calls the StartHost (`0x19`) command.
* @param wait Whether the function should wait the recommended time or not.
*/
bool startHost(bool wait = true) {
if (!isEnabled)
return false;
bool success = sendCommand(COMMAND_START_HOST).success;
if (!success) {
_resetState();
return false;
}
if (wait)
Link::wait(TRANSFER_WAIT);
_LRWLOG_("state = SERVING");
state = State::SERVING;
_LRWLOG_("server OPEN");
sessionState.isServerClosed = false;
return true;
}
/**
* @brief Calls the SignalLevel (`0x11`) command.
* @param response A structure that will be filled with the response data.
*/
bool getSignalLevel(SignalLevelResponse& response) {
if (!isEnabled)
return false;
auto result = sendCommand(COMMAND_SIGNAL_LEVEL);
if (!result.success || result.dataSize == 0) {
if (result.dataSize == 0)
_LRWLOG_("! empty response");
_resetState();
return false;
}
u32 levels = result.data[0];
for (u32 i = 1; i < LINK_RAW_WIRELESS_MAX_PLAYERS; i++)
response.signalLevels[i] = (levels >> ((i - 1) * 8)) & 0xFF;
return true;
}
/**
* @brief Calls the SlotStatus (`0x14`) command.
* @param response A structure that will be filled with the response data.
*/
bool getSlotStatus(SlotStatusResponse& response) {
if (!isEnabled)
return false;
auto result = sendCommand(COMMAND_SLOT_STATUS);
if (!result.success) {
_resetState();
return false;
}
response.connectedClientsSize = 0;
for (u32 i = 0; i < result.dataSize; i++) {
if (i == 0) {
response.nextClientNumber = (u8)Link::lsB32(result.data[i]);
} else {
response.connectedClients[response.connectedClientsSize++] =
ConnectedClient{.deviceId = Link::lsB32(result.data[i]),
.clientNumber = (u8)Link::msB32(result.data[i])};
}
}
LINK_BARRIER;
u8 oldPlayerCount = sessionState.playerCount;
sessionState.playerCount = 1 + response.connectedClientsSize;
if (sessionState.playerCount != oldPlayerCount)
_LRWLOG_("now: " + std::to_string(sessionState.playerCount) + " players");
LINK_BARRIER;
return true;
}
/**
* @brief Calls the PollConnections (`0x1A`) command.
* @param response A structure that will be filled with the response data.
*/
bool pollConnections(PollConnectionsResponse& response) {
if (!isEnabled)
return false;
auto result = sendCommand(COMMAND_POLL_CONNECTIONS);
if (!result.success) {
_resetState();
return false;
}
response.connectedClientsSize = 0;
for (u32 i = 0; i < result.dataSize; i++) {
response.connectedClients[response.connectedClientsSize++] =
ConnectedClient{.deviceId = Link::lsB32(result.data[i]),
.clientNumber = (u8)Link::msB32(result.data[i])};
}
LINK_BARRIER;
u8 oldPlayerCount = sessionState.playerCount;
sessionState.playerCount = 1 + result.dataSize;
if (sessionState.playerCount != oldPlayerCount)
_LRWLOG_("now: " + std::to_string(sessionState.playerCount) + " players");
LINK_BARRIER;
return true;
}
/**
* @brief Calls the EndHost (`0x1B`) command.
* @param response A structure that will be filled with the response data.
*/
bool endHost(PollConnectionsResponse& response) {
if (!isEnabled)
return false;
auto result = sendCommand(COMMAND_END_HOST);
if (!result.success) {
_resetState();
return false;
}
response.connectedClientsSize = 0;
for (u32 i = 0; i < result.dataSize; i++) {
response.connectedClients[response.connectedClientsSize++] =
ConnectedClient{.deviceId = Link::lsB32(result.data[i]),
.clientNumber = (u8)Link::msB32(result.data[i])};
}
LINK_BARRIER;
u8 oldPlayerCount = sessionState.playerCount;
sessionState.playerCount = 1 + result.dataSize;
if (sessionState.playerCount != oldPlayerCount)
_LRWLOG_("now: " + std::to_string(sessionState.playerCount) + " players");
LINK_BARRIER;
_LRWLOG_("server CLOSED");
sessionState.isServerClosed = true;
return true;
}
/**
* @brief Calls the BroadcastReadStart (`0x1C`) command.
*/
bool broadcastReadStart() {
if (!isEnabled)
return false;
bool success = sendCommand(COMMAND_BROADCAST_READ_START).success;
if (!success) {
_resetState();
return false;
}
_LRWLOG_("state = SEARCHING");
state = State::SEARCHING;
return true;
}
/**
* @brief Calls the BroadcastReadPoll (`0x1D`) command.
* @param response A structure that will be filled with the response data.
*/
bool broadcastReadPoll(BroadcastReadPollResponse& response) {
if (!isEnabled)
return false;
auto result = sendCommand(COMMAND_BROADCAST_READ_POLL);
bool success =
result.success &&
result.dataSize % LINK_RAW_WIRELESS_BROADCAST_RESPONSE_LENGTH == 0;
if (!success) {
_resetState();
return false;
}
u32 totalBroadcasts =
result.dataSize / LINK_RAW_WIRELESS_BROADCAST_RESPONSE_LENGTH;
response.serversSize = 0;
for (u32 i = 0; i < totalBroadcasts; i++) {
u32 start = LINK_RAW_WIRELESS_BROADCAST_RESPONSE_LENGTH * i;
Server server;
server.id = (u16)result.data[start];
server.gameId = result.data[start + 1] & LINK_RAW_WIRELESS_MAX_GAME_ID;
u32 gameI = 0, userI = 0;
recoverName(server.gameName, gameI, result.data[start + 1], false);
recoverName(server.gameName, gameI, result.data[start + 2]);
recoverName(server.gameName, gameI, result.data[start + 3]);
recoverName(server.gameName, gameI, result.data[start + 4]);
recoverName(server.userName, userI, result.data[start + 5]);
recoverName(server.userName, userI, result.data[start + 6]);
server.gameName[gameI] = '\0';
server.userName[userI] = '\0';
server.nextClientNumber = (result.data[start] >> 16) & 0xFF;
response.servers[response.serversSize++] = server;
}
return true;
}
/**
* @brief Calls the BroadcastReadEnd (`0x1E`) command.
*/
bool broadcastReadEnd() {
if (!isEnabled)
return false;
bool success = sendCommand(COMMAND_BROADCAST_READ_END).success;
if (!success) {
_resetState();
return false;
}
_LRWLOG_("state = AUTHENTICATED");
state = State::AUTHENTICATED;
return true;
}
/**
* @brief Calls the Connect (`0x1F`) command.
* @param serverId Device ID of the server.
*/
bool connect(u16 serverId) {
if (!isEnabled)
return false;
u32 params[1] = {serverId};
bool success = sendCommand(COMMAND_CONNECT, params, 1).success;
if (!success) {
_resetState();
return false;
}
_LRWLOG_("state = CONNECTING");
state = State::CONNECTING;
return true;
}
/**
* @brief Calls the IsConnectionComplete (`0x20`) command.
* @param response A structure that will be filled with the response data.
*/
bool keepConnecting(ConnectionStatus& response) {
if (!isEnabled)
return false;
auto result = sendCommand(COMMAND_IS_CONNECTION_COMPLETE);
if (!result.success || result.dataSize == 0) {
if (result.dataSize == 0)
_LRWLOG_("! empty response");
_resetState();
return false;
}
if (result.data[0] == WAIT_STILL_CONNECTING) {
response.phase = ConnectionPhase::STILL_CONNECTING;
return true;
}
u8 assignedPlayerId = 1 + (u8)Link::msB32(result.data[0]);
if (assignedPlayerId >= LINK_RAW_WIRELESS_MAX_PLAYERS) {
_LRWLOG_("! connection failed (1)");
_resetState();
response.phase = ConnectionPhase::ERROR;
return false;
}
response.phase = ConnectionPhase::SUCCESS;
response.assignedClientNumber = (u8)Link::msB32(result.data[0]);
return true;
}
/**
* @brief Calls the FinishConnection (`0x21`) command.
*/
bool finishConnection() {
if (!isEnabled)
return false;
auto result = sendCommand(COMMAND_FINISH_CONNECTION);
if (!result.success || result.dataSize == 0) {
if (result.dataSize == 0)
_LRWLOG_("! empty response");
_resetState();
return false;
}
u16 status = Link::msB32(result.data[0]);
if ((Link::msB16(status) & 1) == 1) {
_LRWLOG_("! connection failed (2)");
_resetState();
return false;
}
LINK_BARRIER;
u8 assignedPlayerId = 1 + (u8)status;
sessionState.currentPlayerId = assignedPlayerId;
LINK_BARRIER;
_LRWLOG_("state = CONNECTED");
state = 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(const u32* data, u32 dataSize, u32 _bytes = 0) {
if (!isEnabled)
return false;
u32 bytes = _bytes == 0 ? dataSize * 4 : _bytes;
u32 header = getSendDataHeaderFor(bytes);
_LRWLOG_("using header " + toHex(header));
u32 rawData[LINK_RAW_WIRELESS_MAX_COMMAND_TRANSFER_LENGTH];
rawData[0] = header;
for (u32 i = 0; i < dataSize; i++)
rawData[i + 1] = data[i];
bool success =
sendCommand(COMMAND_SEND_DATA, rawData, 1 + dataSize).success;
if (!success) {
_resetState();
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(const u32* data,
u32 dataSize,
CommandResult& remoteCommand,
u32 _bytes = 0) {
if (!isEnabled)
return false;
u32 bytes = _bytes == 0 ? dataSize * 4 : _bytes;
u32 header = getSendDataHeaderFor(bytes);
_LRWLOG_("using header " + toHex(header));
u32 rawData[LINK_RAW_WIRELESS_MAX_COMMAND_TRANSFER_LENGTH];
rawData[0] = header;
for (u32 i = 0; i < dataSize; i++)
rawData[i + 1] = data[i];
if (!sendCommand(COMMAND_SEND_DATA_AND_WAIT, rawData, 1 + dataSize, true)
.success) {
_resetState();
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) {
if (!isEnabled)
return false;
auto result = sendCommand(COMMAND_RECEIVE_DATA);
if (!result.success) {
_resetState();
return false;
}
return getReceiveDataResponse(result, response);
}
/**
* @brief Calls the Wait (`0x27`) command.
* @param remoteCommand A structure that will be filled with the remote
* command from the adapter.
*/
bool wait(CommandResult& remoteCommand) {
if (!isEnabled)
return false;
if (!sendCommand(COMMAND_WAIT, {}, 0, true).success) {
_resetState();
return false;
}
remoteCommand = receiveCommandFromAdapter();
return remoteCommand.success;
}
/**
* @brief Calls the DisconnectClient (`0x30`) command.
*/
bool disconnectClient(bool client0,
bool client1,
bool client2,
bool client3) {
if (!isEnabled)
return false;
u32 bitfield =
(client0 << 0) | (client1 << 1) | (client2 << 2) | (client3 << 3);
return sendCommand(COMMAND_DISCONNECT_CLIENT, &bitfield, 1).success;
}
/**
* @brief Calls the Bye (`0x3D`) command.
*/
bool bye() {
if (!isEnabled)
return false;
return sendCommand(COMMAND_BYE).success;
}
/**
* @brief Returns the header for the commands 0x24 and 0x25.
* @param bytes The number of bytes of the command.
*/
u32 getSendDataHeaderFor(u32 bytes) {
return sessionState.currentPlayerId == 0
? bytes
: (bytes << (3 + sessionState.currentPlayerId * 5));
}
/**
* @brief Returns the parsed response of a 0x26 command.
* @param result The raw response returned by the command call.
* @param response A structure that will be filled with the response data.
*/
bool getReceiveDataResponse(CommandResult& result,
ReceiveDataResponse& response) {
for (u32 i = 0; i < LINK_RAW_WIRELESS_MAX_PLAYERS; i++)
response.sentBytes[i] = 0;
response.dataSize = result.dataSize > 0 ? result.dataSize - 1 : 0;
if (result.dataSize == 0)
return true;
for (u32 i = 1; i < result.dataSize; i++)
response.data[i - 1] = result.data[i];
u32 header = result.data[0];
response.sentBytes[0] =
Link::_min(header & 0b1111111, MAX_TRANSFER_BYTES_SERVER);
response.sentBytes[1] =
Link::_min((header >> 8) & 0b11111, MAX_TRANSFER_BYTES_CLIENT);
response.sentBytes[2] =
Link::_min((header >> 13) & 0b11111, MAX_TRANSFER_BYTES_CLIENT);
response.sentBytes[3] =
Link::_min((header >> 18) & 0b11111, MAX_TRANSFER_BYTES_CLIENT);
response.sentBytes[4] =
Link::_min((header >> 23) & 0b11111, MAX_TRANSFER_BYTES_CLIENT);
return true;
}
/**
* @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).
* \warning If it `invertsClock`, call `receiveCommandFromAdapter()` on
* finish.
*/
CommandResult sendCommand(u8 type,
const u32* 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_VALUE) {
logExpectedButReceived(DATA_REQUEST_VALUE, 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_VALUE) {
logExpectedButReceived(DATA_REQUEST_VALUE, r);
return result;
}
parameterCount++;
}
_LRWLOG_("sending response request");
u32 response = transfer(DATA_REQUEST_VALUE);
u16 header = Link::msB32(response);
u16 data = Link::lsB32(response);
u8 responses = Link::_min(Link::msB16(data),
LINK_RAW_WIRELESS_MAX_COMMAND_RESPONSE_LENGTH);
u8 ack = Link::lsB16(data);
if (header != COMMAND_HEADER_VALUE) {
_LRWLOG_("! expected HEADER 0x9966");