/
WiimoteReal.cpp
919 lines (772 loc) · 23 KB
/
WiimoteReal.cpp
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
// Copyright 2010 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <unordered_set>
#include "Core/HW/WiimoteReal/WiimoteReal.h"
#include "Common/ChunkFile.h"
#include "Common/CommonTypes.h"
#include "Common/IniFile.h"
#include "Common/StringUtil.h"
#include "Common/Thread.h"
#include "Core/ConfigManager.h"
#include "Core/Core.h"
#include "Core/HW/WiimoteEmu/WiimoteEmu.h"
#include "Core/HW/WiimoteEmu/WiimoteHid.h"
#include "Core/HW/WiimoteReal/IOAndroid.h"
#include "Core/HW/WiimoteReal/IOLinux.h"
#include "Core/HW/WiimoteReal/IOWin.h"
#include "Core/HW/WiimoteReal/IOdarwin.h"
#include "Core/HW/WiimoteReal/IOhidapi.h"
#include "Core/Host.h"
#include "InputCommon/InputConfig.h"
#include "SFML/Network.hpp"
unsigned int g_wiimote_sources[MAX_BBMOTES];
namespace WiimoteReal
{
void TryToConnectBalanceBoard(Wiimote*);
void TryToConnectWiimote(Wiimote*);
void HandleWiimoteDisconnect(int index);
static bool g_real_wiimotes_initialized = false;
// This is used to store connected Wiimotes' IDs, so we don't connect
// more than once to the same device.
static std::unordered_set<std::string> s_known_ids;
static std::mutex s_known_ids_mutex;
std::mutex g_wiimotes_mutex;
Wiimote* g_wiimotes[MAX_BBMOTES];
WiimoteScanner g_wiimote_scanner;
Wiimote::Wiimote()
: m_index(), m_last_input_report(), m_channel(0), m_last_connect_request_counter(0),
m_rumble_state()
{
}
void Wiimote::Shutdown()
{
StopThread();
ClearReadQueue();
m_write_reports.Clear();
}
// to be called from CPU thread
void Wiimote::WriteReport(Report rpt)
{
if (rpt.size() >= 3)
{
bool const new_rumble_state = (rpt[2] & 0x1) != 0;
// If this is a rumble report and the rumble state didn't change, ignore.
if (WM_RUMBLE == rpt[1] && new_rumble_state == m_rumble_state)
return;
m_rumble_state = new_rumble_state;
}
m_write_reports.Push(std::move(rpt));
IOWakeup();
}
// to be called from CPU thread
void Wiimote::QueueReport(u8 rpt_id, const void* _data, unsigned int size)
{
auto const data = static_cast<const u8*>(_data);
Report rpt(size + 2);
rpt[0] = WM_SET_REPORT | WM_BT_OUTPUT;
rpt[1] = rpt_id;
std::copy_n(data, size, rpt.begin() + 2);
WriteReport(std::move(rpt));
}
void Wiimote::DisableDataReporting()
{
m_last_input_report.clear();
// This probably accomplishes nothing.
wm_report_mode rpt = {};
rpt.mode = WM_REPORT_CORE;
rpt.all_the_time = 0;
rpt.continuous = 0;
rpt.rumble = 0;
QueueReport(WM_REPORT_MODE, &rpt, sizeof(rpt));
}
void Wiimote::EnableDataReporting(u8 mode)
{
m_last_input_report.clear();
wm_report_mode rpt = {};
rpt.mode = mode;
rpt.all_the_time = 1;
rpt.continuous = 1;
QueueReport(WM_REPORT_MODE, &rpt, sizeof(rpt));
}
void Wiimote::SetChannel(u16 channel)
{
m_channel = channel;
}
void Wiimote::ClearReadQueue()
{
Report rpt;
// The "Clear" function isn't thread-safe :/
while (m_read_reports.Pop(rpt))
{
}
}
void Wiimote::ControlChannel(const u16 channel, const void* const data, const u32 size)
{
// Check for custom communication
if (channel == 99)
{
if (m_really_disconnect)
DisconnectInternal();
}
else
{
InterruptChannel(channel, data, size);
const hid_packet* const hidp = (hid_packet*)data;
if (hidp->type == HID_TYPE_SET_REPORT)
{
u8 handshake_ok = HID_HANDSHAKE_SUCCESS;
Core::Callback_WiimoteInterruptChannel(m_index, channel, &handshake_ok, sizeof(handshake_ok));
}
}
}
void Wiimote::InterruptChannel(const u16 channel, const void* const _data, const u32 size)
{
// first interrupt/control channel sent
if (channel != m_channel)
{
m_channel = channel;
ClearReadQueue();
EmuStart();
}
auto const data = static_cast<const u8*>(_data);
Report rpt(data, data + size);
WiimoteEmu::Wiimote* const wm =
static_cast<WiimoteEmu::Wiimote*>(::Wiimote::GetConfig()->GetController(m_index));
// Convert output DATA packets to SET_REPORT packets.
// Nintendo Wiimotes work without this translation, but 3rd
// party ones don't.
if (rpt[0] == 0xa2)
{
rpt[0] = WM_SET_REPORT | WM_BT_OUTPUT;
}
// Disallow games from turning off all of the LEDs.
// It makes Wiimote connection status confusing.
if (rpt[1] == WM_LEDS)
{
auto& leds_rpt = *reinterpret_cast<wm_leds*>(&rpt[2]);
if (0 == leds_rpt.leds)
{
// Turn on ALL of the LEDs.
leds_rpt.leds = 0xf;
}
}
else if (rpt[1] == WM_WRITE_SPEAKER_DATA && (!SConfig::GetInstance().m_WiimoteEnableSpeaker ||
(!wm->m_status.speaker || wm->m_speaker_mute)))
{
// Translate speaker data reports into rumble reports.
rpt[1] = WM_RUMBLE;
// Keep only the rumble bit.
rpt[2] &= 0x1;
rpt.resize(3);
}
WriteReport(std::move(rpt));
}
void Wiimote::Read()
{
Report rpt(MAX_PAYLOAD);
auto const result = IORead(rpt.data());
if (result > 0 && m_channel > 0)
{
if (SConfig::GetInstance().iBBDumpPort > 0 && m_index == WIIMOTE_BALANCE_BOARD)
{
static sf::UdpSocket Socket;
Socket.send((char*)rpt.data(), rpt.size(), sf::IpAddress::LocalHost,
SConfig::GetInstance().iBBDumpPort);
}
// Add it to queue
rpt.resize(result);
m_read_reports.Push(std::move(rpt));
}
else if (0 == result)
{
ERROR_LOG(WIIMOTE, "Wiimote::IORead failed. Disconnecting Wiimote %d.", m_index + 1);
DisconnectInternal();
}
}
bool Wiimote::Write()
{
// nothing written, but this is not an error
if (m_write_reports.Empty())
return true;
Report const& rpt = m_write_reports.Front();
if (SConfig::GetInstance().iBBDumpPort > 0 && m_index == WIIMOTE_BALANCE_BOARD)
{
static sf::UdpSocket Socket;
Socket.send((char*)rpt.data(), rpt.size(), sf::IpAddress::LocalHost,
SConfig::GetInstance().iBBDumpPort);
}
int ret = IOWrite(rpt.data(), rpt.size());
m_write_reports.Pop();
if (!m_write_reports.Empty())
IOWakeup();
return ret != 0;
}
bool Wiimote::IsBalanceBoard()
{
if (!ConnectInternal())
return false;
// Initialise the extension by writing 0x55 to 0xa400f0, then writing 0x00 to 0xa400fb.
static const u8 init_extension_rpt1[MAX_PAYLOAD] = {
WM_SET_REPORT | WM_BT_OUTPUT, WM_WRITE_DATA, 0x04, 0xa4, 0x00, 0xf0, 0x01, 0x55};
static const u8 init_extension_rpt2[MAX_PAYLOAD] = {
WM_SET_REPORT | WM_BT_OUTPUT, WM_WRITE_DATA, 0x04, 0xa4, 0x00, 0xfb, 0x01, 0x00};
static const u8 status_report[] = {WM_SET_REPORT | WM_BT_OUTPUT, WM_REQUEST_STATUS, 0};
if (!IOWrite(init_extension_rpt1, sizeof(init_extension_rpt1)) ||
!IOWrite(init_extension_rpt2, sizeof(init_extension_rpt2)))
{
ERROR_LOG(WIIMOTE, "IsBalanceBoard(): Failed to initialise extension.");
return false;
}
int ret = IOWrite(status_report, sizeof(status_report));
u8 buf[MAX_PAYLOAD];
while (ret != 0)
{
ret = IORead(buf);
if (ret == -1)
continue;
switch (buf[1])
{
case WM_STATUS_REPORT:
{
const auto* status = reinterpret_cast<wm_status_report*>(&buf[2]);
// A Balance Board has a Balance Board extension.
if (!status->extension)
return false;
// Read two bytes from 0xa400fe to identify the extension.
static const u8 identify_ext_rpt[] = {
WM_SET_REPORT | WM_BT_OUTPUT, WM_READ_DATA, 0x04, 0xa4, 0x00, 0xfe, 0x02, 0x00};
ret = IOWrite(identify_ext_rpt, sizeof(identify_ext_rpt));
break;
}
case WM_READ_DATA_REPLY:
{
const auto* reply = reinterpret_cast<wm_read_data_reply*>(&buf[2]);
if (Common::swap16(reply->address) != 0x00fe)
{
ERROR_LOG(WIIMOTE, "IsBalanceBoard(): Received unexpected data reply for address %X",
Common::swap16(reply->address));
return false;
}
// A Balance Board ext can be identified by checking for 0x0402.
return reply->data[0] == 0x04 && reply->data[1] == 0x02;
}
case WM_ACK_DATA:
{
const auto* ack = reinterpret_cast<wm_acknowledge*>(&buf[2]);
if (ack->reportID == WM_READ_DATA && ack->errorID != 0x00)
{
WARN_LOG(WIIMOTE, "Failed to read from 0xa400fe, assuming Wiimote is not a Balance Board.");
return false;
}
}
}
}
return false;
}
static bool IsDataReport(const Report& rpt)
{
return rpt.size() >= 2 && rpt[1] >= WM_REPORT_CORE;
}
// Returns the next report that should be sent
const Report& Wiimote::ProcessReadQueue()
{
// Pop through the queued reports
while (m_read_reports.Pop(m_last_input_report))
{
if (!IsDataReport(m_last_input_report))
{
// A non-data report, use it.
return m_last_input_report;
// Forget the last data report as it may be of the wrong type
// or contain outdated button data
// or it's not supposed to be sent at this time
// It's just easier to be correct this way and it's probably not horrible.
}
}
// If the last report wasn't a data report it's irrelevant.
if (!IsDataReport(m_last_input_report))
m_last_input_report.clear();
// If it was a data report, we repeat that until something else comes in.
return m_last_input_report;
}
void Wiimote::Update()
{
if (!IsConnected())
{
HandleWiimoteDisconnect(m_index);
return;
}
// Pop through the queued reports
const Report& rpt = ProcessReadQueue();
// Send the report
if (!rpt.empty() && m_channel > 0)
{
Core::Callback_WiimoteInterruptChannel(m_index, m_channel, rpt.data(), (u32)rpt.size());
}
}
void Wiimote::ConnectOnInput()
{
if (m_last_connect_request_counter > 0)
{
--m_last_connect_request_counter;
return;
}
const Report& rpt = ProcessReadQueue();
if (rpt.size() >= 4)
{
switch (rpt[1])
{
case WM_REPORT_CORE:
case WM_REPORT_CORE_ACCEL:
case WM_REPORT_CORE_EXT8:
case WM_REPORT_CORE_ACCEL_IR12:
case WM_REPORT_CORE_EXT19:
case WM_REPORT_CORE_ACCEL_EXT16:
case WM_REPORT_CORE_IR10_EXT9:
case WM_REPORT_CORE_ACCEL_IR10_EXT6:
case WM_REPORT_INTERLEAVE1:
case WM_REPORT_INTERLEAVE2:
// check any button without checking accelerometer data
if ((rpt[2] & 0x1F) != 0 || (rpt[3] & 0x9F) != 0)
{
Host_ConnectWiimote(m_index, true);
// see WiimoteEmu::Wiimote::ConnectOnInput(), same idea here
m_last_connect_request_counter = 100;
}
break;
default:
break;
}
}
}
void Wiimote::Prepare()
{
m_need_prepare.Set();
IOWakeup();
}
bool Wiimote::PrepareOnThread()
{
// core buttons, no continuous reporting
u8 static const mode_report[] = {WM_SET_REPORT | WM_BT_OUTPUT, WM_REPORT_MODE, 0, WM_REPORT_CORE};
// Set the active LEDs and turn on rumble.
u8 static led_report[] = {WM_SET_REPORT | WM_BT_OUTPUT, WM_LEDS, 0};
led_report[2] = u8(WIIMOTE_LED_1 << (m_index % WIIMOTE_BALANCE_BOARD) | 0x1);
// Turn off rumble
u8 static const rumble_report[] = {WM_SET_REPORT | WM_BT_OUTPUT, WM_RUMBLE, 0};
// Request status report
u8 static const req_status_report[] = {WM_SET_REPORT | WM_BT_OUTPUT, WM_REQUEST_STATUS, 0};
// TODO: check for sane response?
return (IOWrite(mode_report, sizeof(mode_report)) && IOWrite(led_report, sizeof(led_report)) &&
(Common::SleepCurrentThread(200), IOWrite(rumble_report, sizeof(rumble_report))) &&
IOWrite(req_status_report, sizeof(req_status_report)));
}
void Wiimote::EmuStart()
{
DisableDataReporting();
EnablePowerAssertionInternal();
}
void Wiimote::EmuStop()
{
m_channel = 0;
DisableDataReporting();
NOTICE_LOG(WIIMOTE, "Stopping Wiimote data reporting.");
DisablePowerAssertionInternal();
}
void Wiimote::EmuResume()
{
WiimoteEmu::Wiimote* const wm =
static_cast<WiimoteEmu::Wiimote*>(::Wiimote::GetConfig()->GetController(m_index));
m_last_input_report.clear();
wm_report_mode rpt = {};
rpt.mode = wm->m_reporting_mode;
rpt.all_the_time = 1;
rpt.continuous = 1;
QueueReport(WM_REPORT_MODE, &rpt, sizeof(rpt));
NOTICE_LOG(WIIMOTE, "Resuming Wiimote data reporting.");
EnablePowerAssertionInternal();
}
void Wiimote::EmuPause()
{
m_last_input_report.clear();
wm_report_mode rpt = {};
rpt.mode = WM_REPORT_CORE;
rpt.all_the_time = 0;
rpt.continuous = 0;
QueueReport(WM_REPORT_MODE, &rpt, sizeof(rpt));
NOTICE_LOG(WIIMOTE, "Pausing Wiimote data reporting.");
DisablePowerAssertionInternal();
}
static unsigned int CalculateConnectedWiimotes()
{
std::lock_guard<std::mutex> lk(g_wiimotes_mutex);
unsigned int connected_wiimotes = 0;
for (unsigned int i = 0; i < MAX_WIIMOTES; ++i)
if (g_wiimotes[i])
++connected_wiimotes;
return connected_wiimotes;
}
static unsigned int CalculateWantedWiimotes()
{
std::lock_guard<std::mutex> lk(g_wiimotes_mutex);
// Figure out how many real Wiimotes are required
unsigned int wanted_wiimotes = 0;
for (unsigned int i = 0; i < MAX_WIIMOTES; ++i)
if (WIIMOTE_SRC_REAL & g_wiimote_sources[i] && !g_wiimotes[i])
++wanted_wiimotes;
return wanted_wiimotes;
}
static unsigned int CalculateWantedBB()
{
std::lock_guard<std::mutex> lk(g_wiimotes_mutex);
unsigned int wanted_bb = 0;
if (WIIMOTE_SRC_REAL & g_wiimote_sources[WIIMOTE_BALANCE_BOARD] &&
!g_wiimotes[WIIMOTE_BALANCE_BOARD])
++wanted_bb;
return wanted_bb;
}
void WiimoteScanner::StartThread()
{
if (m_scan_thread_running.IsSet())
return;
m_scan_thread_running.Set();
m_scan_thread = std::thread(&WiimoteScanner::ThreadFunc, this);
}
void WiimoteScanner::StopThread()
{
if (m_scan_thread_running.TestAndClear())
{
SetScanMode(WiimoteScanMode::DO_NOT_SCAN);
m_scan_thread.join();
}
}
void WiimoteScanner::SetScanMode(WiimoteScanMode scan_mode)
{
m_scan_mode.store(scan_mode);
m_scan_mode_changed_event.Set();
}
bool WiimoteScanner::IsReady() const
{
return std::any_of(m_scanner_backends.begin(), m_scanner_backends.end(),
[](const auto& backend) { return backend->IsReady(); });
}
void WiimoteScanner::AddScannerBackend(std::unique_ptr<WiimoteScannerBackend> backend)
{
m_scanner_backends.emplace_back(std::move(backend));
}
static void CheckForDisconnectedWiimotes()
{
std::lock_guard<std::mutex> lk(g_wiimotes_mutex);
for (unsigned int i = 0; i < MAX_BBMOTES; ++i)
if (g_wiimotes[i] && !g_wiimotes[i]->IsConnected())
HandleWiimoteDisconnect(i);
}
void WiimoteScanner::ThreadFunc()
{
Common::SetCurrentThreadName("Wiimote Scanning Thread");
NOTICE_LOG(WIIMOTE, "Wiimote scanning thread has started.");
while (m_scan_thread_running.IsSet())
{
m_scan_mode_changed_event.WaitFor(std::chrono::milliseconds(500));
CheckForDisconnectedWiimotes();
if (m_scan_mode.load() == WiimoteScanMode::DO_NOT_SCAN)
continue;
for (const auto& backend : m_scanner_backends)
{
if (CalculateWantedWiimotes() != 0 || CalculateWantedBB() != 0)
{
std::vector<Wiimote*> found_wiimotes;
Wiimote* found_board = nullptr;
backend->FindWiimotes(found_wiimotes, found_board);
{
if (!g_real_wiimotes_initialized)
continue;
std::lock_guard<std::mutex> lk(g_wiimotes_mutex);
std::for_each(found_wiimotes.begin(), found_wiimotes.end(), TryToConnectWiimote);
if (found_board)
TryToConnectBalanceBoard(found_board);
}
}
else
{
backend->Update(); // Does stuff needed to detect disconnects on Windows
}
}
if (m_scan_mode.load() == WiimoteScanMode::SCAN_ONCE)
m_scan_mode.store(WiimoteScanMode::DO_NOT_SCAN);
}
NOTICE_LOG(WIIMOTE, "Wiimote scanning thread has stopped.");
}
bool Wiimote::Connect(int index)
{
m_index = index;
m_need_prepare.Set();
if (!m_run_thread.IsSet())
{
StartThread();
m_thread_ready_event.Wait();
}
return IsConnected();
}
void Wiimote::StartThread()
{
m_wiimote_thread = std::thread(&Wiimote::ThreadFunc, this);
}
void Wiimote::StopThread()
{
if (!m_run_thread.TestAndClear())
return;
IOWakeup();
m_wiimote_thread.join();
}
void Wiimote::ThreadFunc()
{
Common::SetCurrentThreadName("Wiimote Device Thread");
bool ok = ConnectInternal();
if (!ok)
{
// try again, it might take a moment to settle
Common::SleepCurrentThread(100);
ok = ConnectInternal();
}
m_thread_ready_event.Set();
m_run_thread.Set();
if (!ok)
{
return;
}
// main loop
while (IsConnected() && m_run_thread.IsSet())
{
if (m_need_prepare.TestAndClear() && !PrepareOnThread())
{
ERROR_LOG(WIIMOTE, "Wiimote::PrepareOnThread failed. Disconnecting Wiimote %d.",
m_index + 1);
break;
}
if (!Write())
{
ERROR_LOG(WIIMOTE, "Wiimote::Write failed. Disconnecting Wiimote %d.", m_index + 1);
break;
}
Read();
}
DisconnectInternal();
}
int Wiimote::GetIndex() const
{
return m_index;
}
void LoadSettings()
{
std::string ini_filename = File::GetUserPath(D_CONFIG_IDX) + WIIMOTE_INI_NAME ".ini";
IniFile inifile;
inifile.Load(ini_filename);
for (unsigned int i = 0; i < MAX_WIIMOTES; ++i)
{
std::string secname("Wiimote");
secname += (char)('1' + i);
IniFile::Section& sec = *inifile.GetOrCreateSection(secname);
sec.Get("Source", &g_wiimote_sources[i], i ? WIIMOTE_SRC_NONE : WIIMOTE_SRC_EMU);
}
std::string secname("BalanceBoard");
IniFile::Section& sec = *inifile.GetOrCreateSection(secname);
sec.Get("Source", &g_wiimote_sources[WIIMOTE_BALANCE_BOARD], WIIMOTE_SRC_NONE);
}
// config dialog calls this when some settings change
void Initialize(::Wiimote::InitializeMode init_mode)
{
if (!g_real_wiimotes_initialized)
{
s_known_ids.clear();
g_wiimote_scanner.AddScannerBackend(std::make_unique<WiimoteScannerLinux>());
g_wiimote_scanner.AddScannerBackend(std::make_unique<WiimoteScannerAndroid>());
g_wiimote_scanner.AddScannerBackend(std::make_unique<WiimoteScannerWindows>());
g_wiimote_scanner.AddScannerBackend(std::make_unique<WiimoteScannerDarwin>());
g_wiimote_scanner.AddScannerBackend(std::make_unique<WiimoteScannerHidapi>());
g_wiimote_scanner.StartThread();
}
if (SConfig::GetInstance().m_WiimoteContinuousScanning &&
!SConfig::GetInstance().m_bt_passthrough_enabled)
g_wiimote_scanner.SetScanMode(WiimoteScanMode::CONTINUOUSLY_SCAN);
else
g_wiimote_scanner.SetScanMode(WiimoteScanMode::DO_NOT_SCAN);
// wait for connection because it should exist before state load
if (init_mode == ::Wiimote::InitializeMode::DO_WAIT_FOR_WIIMOTES)
{
int timeout = 100;
g_wiimote_scanner.SetScanMode(WiimoteScanMode::SCAN_ONCE);
while (CalculateWantedWiimotes() > CalculateConnectedWiimotes() && timeout)
{
Common::SleepCurrentThread(100);
timeout--;
}
}
if (g_real_wiimotes_initialized)
return;
NOTICE_LOG(WIIMOTE, "WiimoteReal::Initialize");
g_real_wiimotes_initialized = true;
}
// called on emulation shutdown
void Stop()
{
for (auto& wiimote : g_wiimotes)
if (wiimote && wiimote->IsConnected())
wiimote->EmuStop();
}
// called when the Dolphin app exits
void Shutdown()
{
g_real_wiimotes_initialized = false;
g_wiimote_scanner.StopThread();
NOTICE_LOG(WIIMOTE, "WiimoteReal::Shutdown");
std::lock_guard<std::mutex> lk(g_wiimotes_mutex);
for (unsigned int i = 0; i < MAX_BBMOTES; ++i)
HandleWiimoteDisconnect(i);
}
void Resume()
{
for (auto& wiimote : g_wiimotes)
if (wiimote && wiimote->IsConnected())
wiimote->EmuResume();
}
void Pause()
{
for (auto& wiimote : g_wiimotes)
if (wiimote && wiimote->IsConnected())
wiimote->EmuPause();
}
void ChangeWiimoteSource(unsigned int index, int source)
{
g_wiimote_sources[index] = source;
{
// kill real connection (or swap to different slot)
std::lock_guard<std::mutex> lk(g_wiimotes_mutex);
Wiimote* wm = g_wiimotes[index];
if (wm)
{
g_wiimotes[index] = nullptr;
// First see if we can use this real Wiimote in another slot.
TryToConnectWiimote(wm);
}
// else, just disconnect the Wiimote
HandleWiimoteDisconnect(index);
}
// reconnect to the emulator
Host_ConnectWiimote(index, false);
if (WIIMOTE_SRC_EMU & source)
Host_ConnectWiimote(index, true);
}
static bool TryToConnectWiimoteToSlot(Wiimote* wm, unsigned int i)
{
if (WIIMOTE_SRC_REAL & g_wiimote_sources[i] && !g_wiimotes[i])
{
if (wm->Connect(i))
{
NOTICE_LOG(WIIMOTE, "Connected to Wiimote %i.", i + 1);
g_wiimotes[i] = wm;
Host_ConnectWiimote(i, true);
std::lock_guard<std::mutex> lk(s_known_ids_mutex);
s_known_ids.insert(wm->GetId());
}
return true;
}
return false;
}
void TryToConnectWiimote(Wiimote* wm)
{
for (unsigned int i = 0; i < MAX_WIIMOTES; ++i)
{
if (TryToConnectWiimoteToSlot(wm, i))
{
wm = nullptr;
break;
}
}
delete wm;
}
void TryToConnectBalanceBoard(Wiimote* wm)
{
if (TryToConnectWiimoteToSlot(wm, WIIMOTE_BALANCE_BOARD))
{
wm = nullptr;
}
delete wm;
}
void HandleWiimoteDisconnect(int index)
{
Wiimote* wm = nullptr;
std::swap(wm, g_wiimotes[index]);
if (wm)
{
std::lock_guard<std::mutex> lk(s_known_ids_mutex);
s_known_ids.erase(wm->GetId());
delete wm;
NOTICE_LOG(WIIMOTE, "Disconnected Wiimote %i.", index + 1);
}
}
// This is called from the GUI thread
void Refresh()
{
if (!SConfig::GetInstance().m_WiimoteContinuousScanning)
g_wiimote_scanner.SetScanMode(WiimoteScanMode::SCAN_ONCE);
}
void InterruptChannel(int _WiimoteNumber, u16 _channelID, const void* _pData, u32 _Size)
{
std::lock_guard<std::mutex> lk(g_wiimotes_mutex);
if (g_wiimotes[_WiimoteNumber])
g_wiimotes[_WiimoteNumber]->InterruptChannel(_channelID, _pData, _Size);
}
void ControlChannel(int _WiimoteNumber, u16 _channelID, const void* _pData, u32 _Size)
{
std::lock_guard<std::mutex> lk(g_wiimotes_mutex);
if (g_wiimotes[_WiimoteNumber])
g_wiimotes[_WiimoteNumber]->ControlChannel(_channelID, _pData, _Size);
}
// Read the Wiimote once
void Update(int wiimote_number)
{
// Try to get a lock and return without doing anything if we fail
// This avoids blocking the CPU thread
if (!g_wiimotes_mutex.try_lock())
return;
if (g_wiimotes[wiimote_number])
g_wiimotes[wiimote_number]->Update();
// Wiimote::Update() may remove the Wiimote if it was disconnected.
if (!g_wiimotes[wiimote_number])
{
Host_ConnectWiimote(wiimote_number, false);
}
g_wiimotes_mutex.unlock();
}
void ConnectOnInput(int wiimote_number)
{
if (!g_wiimotes_mutex.try_lock())
return;
if (g_wiimotes[wiimote_number])
g_wiimotes[wiimote_number]->ConnectOnInput();
g_wiimotes_mutex.unlock();
}
void StateChange(EMUSTATE_CHANGE newState)
{
// TODO: disable/enable auto reporting, maybe
}
bool IsValidDeviceName(const std::string& name)
{
return "Nintendo RVL-CNT-01" == name || "Nintendo RVL-CNT-01-TR" == name ||
IsBalanceBoardName(name);
}
bool IsBalanceBoardName(const std::string& name)
{
return "Nintendo RVL-WBC-01" == name;
}
// This is called from the scanner backends (currently on the scanner thread).
bool IsNewWiimote(const std::string& identifier)
{
std::lock_guard<std::mutex> lk(s_known_ids_mutex);
return s_known_ids.count(identifier) == 0;
}
}; // end of namespace