-
Notifications
You must be signed in to change notification settings - Fork 0
/
wiimote.cpp
executable file
·2808 lines (2486 loc) · 88.7 KB
/
wiimote.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
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
// _______________________________________________________________________________
//
// - WiiYourself! - native C++ Wiimote library v1.15
// (c) gl.tter 2007-10 - http://gl.tter.org
//
// see License.txt for conditions of use. see History.txt for change log.
// _______________________________________________________________________________
//
// wiimote.cpp (tab = 4 spaces
#include <stdio.h>
// VC-specifics:
#ifdef _MSC_VER
// disable warning "C++ exception handler used, but unwind semantics are not enabled."
// in <xstring> (I don't use it - or just enable C++ exceptions)
# pragma warning(disable: 4530)
// auto-link with the necessary libs
# pragma comment(lib, "setupapi.lib")
# pragma comment(lib, "hid.lib") // for HID API (from DDK)
# pragma comment(lib, "winmm.lib") // for timeGetTime()
#endif // _MSC_VER
#include "wiimote.h"
#include <setupapi.h>
extern "C" {
# ifdef __MINGW32__
# include <ddk/hidsdi.h>// from WinDDK
# else
# include <hidsdi.h>
# endif
}
#include <sys/types.h> // for _stat
#include <sys/stat.h> // "
#include <process.h> // for _beginthreadex()
#ifdef __BORLANDC__
# include <cmath.h> // for orientation
#else
# include <math.h> // "
#endif
#include <mmreg.h> // for WAVEFORMATEXTENSIBLE
#include <mmsystem.h> // for timeGetTime()
// apparently not defined in some compilers:
#ifndef min
# define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
// ------------------------------------------------------------------------------------
// helpers
// ------------------------------------------------------------------------------------
template<class T> inline T sign (const T& val) { return (val<0)? T(-1) : T(1); }
template<class T> inline T square(const T& val) { return val*val; }
#define ARRAY_ENTRIES(array) (sizeof(array)/sizeof(array[0]))
// ------------------------------------------------------------------------------------
// Tracing & Debugging
// ------------------------------------------------------------------------------------
#define PREFIX _T("WiiYourself! : ")
// comment these to auto-strip their code from the library:
// (they currently use OutputDebugString() via _TRACE() - change to suit)
#if (_MSC_VER >= 1400) // VC 2005+ (earlier versions don't support variable args)
# define TRACE(fmt, ...) _TRACE(PREFIX fmt _T("\n"), __VA_ARGS__)
# define WARN(fmt, ...) _TRACE(PREFIX _T("* ") fmt _T(" *") _T("\n"), __VA_ARGS__)
#elif defined(__MINGW32__)
# define TRACE(fmt, ...) _TRACE(PREFIX fmt _T("\n") , ##__VA_ARGS__)
# define WARN(fmt, ...) _TRACE(PREFIX _T("* ") fmt _T(" *") _T("\n") , ##__VA_ARGS__)
#endif
// uncomment any of these for deeper debugging:
//#define DEEP_TRACE(fmt, ...) _TRACE(PREFIX _T("|") fmt _T("\n"), __VA_ARGS__) // VC 2005+
//#define DEEP_TRACE(fmt, ...) _TRACE(PREFIX _T("|") fmt _T("\n") , ##__VA_ARGS__) // mingw
//#define BEEP_DEBUG_READS
//#define BEEP_DEBUG_WRITES
//#define BEEP_ON_ORIENTATION_ESTIMATE
//#define BEEP_ON_PERIODIC_STATUSREFRESH
// internals: auto-strip code from the macros if they weren't defined
#ifndef TRACE
# define TRACE
#endif
#ifndef DEEP_TRACE
# define DEEP_TRACE
#endif
#ifndef WARN
# define WARN
#endif
// ------------------------------------------------------------------------------------
static void _cdecl _TRACE (const TCHAR* fmt, ...)
{
static TCHAR buffer[256];
if (!fmt) return;
va_list argptr;
va_start (argptr, fmt);
#if (_MSC_VER >= 1400) // VC 2005+
_vsntprintf_s(buffer, ARRAY_ENTRIES(buffer), _TRUNCATE, fmt, argptr);
#else
_vsntprintf (buffer, ARRAY_ENTRIES(buffer), fmt, argptr);
#endif
va_end (argptr);
OutputDebugString(buffer);
}
// ------------------------------------------------------------------------------------
// wiimote
// ------------------------------------------------------------------------------------
// class statics
HMODULE wiimote::HidDLL = NULL;
unsigned wiimote::_TotalCreated = 0;
unsigned wiimote::_TotalConnected = 0;
hidwrite_ptr wiimote::_HidD_SetOutputReport = NULL;
// (keep in sync with 'speaker_freq'):
const unsigned wiimote::FreqLookup [TOTAL_FREQUENCIES] =
{ 0, 4200, 3920, 3640, 3360,
3130, 2940, 2760, 2610, 2470 };
const TCHAR* wiimote::ButtonNameFromBit [TOTAL_BUTTON_BITS] =
{ _T("Left") , _T("Right"), _T("Down"), _T("Up"),
_T("Plus") , _T("??") , _T("??") , _T("??") ,
_T("Two") , _T("One") , _T("B") , _T("A") ,
_T("Minus"), _T("??") , _T("??") , _T("Home") };
const TCHAR* wiimote::ClassicButtonNameFromBit [TOTAL_BUTTON_BITS] =
{ _T("??") , _T("TrigR") , _T("Plus") , _T("Home"),
_T("Minus"), _T("TrigL") , _T("Down") , _T("Right") ,
_T("Up") , _T("Left") , _T("ZR") , _T("X") ,
_T("A") , _T("Y") , _T("B") , _T("ZL") };
// ------------------------------------------------------------------------------------
wiimote::wiimote ()
:
DataRead (CreateEvent(NULL, FALSE, FALSE, NULL)),
Handle (INVALID_HANDLE_VALUE),
ReportType (IN_BUTTONS),
bStatusReceived (false), // for output method detection
bConnectInProgress (true ),
bInitInProgress (false),
bEnablingMotionPlus (false),
bConnectionLost (false), // set if write fails after connection
bMotionPlusDetected (false),
bMotionPlusEnabled (false),
bMotionPlusExtension (false),
bCalibrateAtRest (false),
bUseHIDwrite (false), // if OS supports it
ChangedCallback (NULL),
CallbackTriggerFlags (CHANGED_ALL),
InternalChanged (NO_CHANGE),
CurrentSample (NULL),
HIDwriteThread (NULL),
ReadParseThread (NULL),
SampleThread (NULL),
AsyncRumbleThread (NULL),
AsyncRumbleTimeout (0),
UniqueID (0) // not _guaranteed_ unique, see comments in header
#ifdef ID2_FROM_DEVICEPATH // (see comments in header)
// UniqueID2 (0)
#endif
{
_ASSERT(DataRead != INVALID_HANDLE_VALUE);
// if this is the first wiimote object, detect & enable HID write support
if(++_TotalCreated == 1)
{
HidDLL = LoadLibrary(_T("hid.dll"));
_ASSERT(HidDLL);
if(!HidDLL)
WARN(_T("Couldn't load hid.dll - shouldn't happen!"));
else{
_HidD_SetOutputReport = (hidwrite_ptr)
GetProcAddress(HidDLL, "HidD_SetOutputReport");
if(_HidD_SetOutputReport)
TRACE(_T("OS supports HID writes."));
else
TRACE(_T("OS doesn't support HID writes."));
}
}
// clear our public and private state data completely (including deadzones)
Clear (true);
Internal.Clear(true);
// and the state recording vars
memset(&Recording, 0, sizeof(Recording));
// for overlapped IO (Read/WriteFile)
memset(&Overlapped, 0, sizeof(Overlapped));
Overlapped.hEvent = DataRead;
Overlapped.Offset =
Overlapped.OffsetHigh = 0;
// for async HID output method
InitializeCriticalSection(&HIDwriteQueueLock);
// for polling
InitializeCriticalSection(&StateLock);
// request millisecond timer accuracy
timeBeginPeriod(1);
}
// ------------------------------------------------------------------------------------
wiimote::~wiimote ()
{
Disconnect();
// events & critical sections are kept open for the lifetime of the object,
// so tidy them up here:
if(DataRead != INVALID_HANDLE_VALUE)
CloseHandle(DataRead);
DeleteCriticalSection(&HIDwriteQueueLock);
DeleteCriticalSection(&StateLock);
// tidy up timer accuracy request
timeEndPeriod(1);
// release HID DLL (for dynamic HID write method)
if((--_TotalCreated == 0) && HidDLL)
{
FreeLibrary(HidDLL);
HidDLL = NULL;
_HidD_SetOutputReport = NULL;
}
}
// ------------------------------------------------------------------------------------
bool wiimote::Connect (unsigned wiimote_index, bool force_hidwrites)
{
if(wiimote_index == FIRST_AVAILABLE)
TRACE(_T("Connecting first available Wiimote:"));
else
TRACE(_T("Connecting Wiimote %u:"), wiimote_index);
// auto-disconnect if user is being naughty
if(IsConnected())
Disconnect();
// get the GUID of the HID class
GUID guid;
HidD_GetHidGuid(&guid);
// get a handle to all devices that are part of the HID class
// Brian: Fun fact: DIGCF_PRESENT worked on my machine just fine. I reinstalled
// Vista, and now it no longer finds the Wiimote with that parameter enabled...
HDEVINFO dev_info = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_DEVICEINTERFACE);// | DIGCF_PRESENT);
if(!dev_info) {
WARN(_T("couldn't get device info"));
return false;
}
// enumerate the devices
SP_DEVICE_INTERFACE_DATA didata;
didata.cbSize = sizeof(didata);
unsigned index = 0;
unsigned wiimotes_found = 0;
while(SetupDiEnumDeviceInterfaces(dev_info, NULL, &guid, index, &didata))
{
// get the buffer size for this device detail instance
DWORD req_size = 0;
SetupDiGetDeviceInterfaceDetail(dev_info, &didata, NULL, 0, &req_size, NULL);
// (bizarre way of doing it) create a buffer large enough to hold the
// fixed-size detail struct components, and the variable string size
SP_DEVICE_INTERFACE_DETAIL_DATA *didetail =
(SP_DEVICE_INTERFACE_DETAIL_DATA*) new BYTE[req_size];
_ASSERT(didetail);
didetail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
// now actually get the detail struct
if(!SetupDiGetDeviceInterfaceDetail(dev_info, &didata, didetail,
req_size, &req_size, NULL)) {
WARN(_T("couldn't get devinterface info for %u"), index);
break;
}
// open a shared handle to the device to query it (this will succeed even
// if the wiimote is already Connect()'ed)
DEEP_TRACE(_T(".. querying device %s"), didetail->DevicePath);
Handle = CreateFile(didetail->DevicePath, 0, FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
if(Handle == INVALID_HANDLE_VALUE) {
DEEP_TRACE(_T(".... failed with err %x (probably harmless)."),
GetLastError());
goto skip;
}
// get the device attributes
HIDD_ATTRIBUTES attrib;
attrib.Size = sizeof(attrib);
if(HidD_GetAttributes(Handle, &attrib))
{
// is this a wiimote?
if((attrib.VendorID != VID) || (attrib.ProductID != PID))
goto skip;
// yes, but is it the one we're interested in?
++wiimotes_found;
if((wiimote_index != FIRST_AVAILABLE) &&
(wiimote_index != wiimotes_found))
goto skip;
// the wiimote is installed, but it may not be currently paired:
if(wiimote_index == FIRST_AVAILABLE)
TRACE(_T(".. opening Wiimote %u:"), wiimotes_found);
else
TRACE(_T(".. opening:"));
// re-open the handle, but this time we don't allow write sharing
// (that way subsequent calls can still _discover_ wiimotes above, but
// will correctly fail here if they're already connected)
CloseHandle(Handle);
// note this also means that if another application has already opened
// the device, the library can no longer connect it (this may happen
// with software that enumerates all joysticks in the system, because
// even though the wiimote is not a standard joystick (and can't
// be read as such), it unfortunately announces itself to the OS
// as one. The SDL library was known to do grab wiimotes like this.
// If you cannot stop the application from doing it, you may change the
// call below to open the device in full shared mode - but then the
// library can no longer detect if you've already connected a device
// and will allow you to connect it twice! So be careful ...
Handle = CreateFile(didetail->DevicePath, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ,
NULL, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, NULL);
if(Handle == INVALID_HANDLE_VALUE) {
TRACE(_T(".... failed with err %x"), GetLastError());
goto skip;
}
// clear the wiimote state & buffers
Clear (false); // preserves existing deadzones
Internal.Clear(false); // "
InternalChanged = NO_CHANGE;
memset(ReadBuff , 0, sizeof(ReadBuff));
bConnectionLost = false;
bConnectInProgress = true; // don't parse extensions or request regular
// updates until complete
// enable async reading
BeginAsyncRead();
// autodetect which write method the Bluetooth stack supports,
// by requesting the wiimote status report:
if(force_hidwrites && !_HidD_SetOutputReport) {
TRACE(_T(".. can't force HID writes (not supported)"));
force_hidwrites = false;
}
if(force_hidwrites)
TRACE(_T(".. (HID writes forced)"));
else{
// - try WriteFile() first as it's the most efficient (it uses
// harware interrupts where possible and is async-capable):
bUseHIDwrite = false;
RequestStatusReport();
// and wait for the report to arrive:
DWORD last_time = timeGetTime();
while(!bStatusReceived && ((timeGetTime()-last_time) < 500))
Sleep(10);
TRACE(_T(".. WriteFile() %s."), bStatusReceived? _T("succeeded") :
_T("failed"));
}
// try HID write method (if supported)
if(!bStatusReceived && _HidD_SetOutputReport)
{
bUseHIDwrite = true;
RequestStatusReport();
// wait for the report to arrive:
DWORD last_time = timeGetTime();
while(!bStatusReceived && ((timeGetTime()-last_time) < 500))
Sleep(10);
// did we get it?
TRACE(_T(".. HID write %s."), bStatusReceived? _T("succeeded") :
_T("failed"));
}
// still failed?
if(!bStatusReceived) {
WARN(_T("output failed - wiimote is not connected (or confused)."));
Disconnect();
goto skip;
}
//Sleep(500);
// reset it
Reset();
// read the wiimote calibration info
ReadCalibration();
// allow the result(s) to come in (so that the caller can immediately test
// MotionPlusConnected()
Sleep(300); // note, don't need it on my system, better to be safe though
// connected succesfully:
_TotalConnected++;
// use the first incomding analogue sensor values as the 'at rest'
// offsets (only supports the Balance Board currently)
bCalibrateAtRest = true;
// refresh the public state from the internal one (so that everything
// is available straight away
RefreshState();
// attempt to construct a unique hardware ID from the calibration
// data bytes (this is obviously not guaranteed to be unique across
// all devices, but may work fairly well in practice... ?)
memcpy(&UniqueID, &CalibrationInfo, sizeof(CalibrationInfo));
//_ASSERT(UniqueID != 0); // if this fires, the calibration data didn't
// arrive - this shouldn't happen
#ifdef ID2_FROM_DEVICEPATH // (see comments in header)
// create a 2nd alternative id by simply adding all the characters
// in the device path to create a single number
UniqueID2 = 0;
for(unsigned index=0; index<_tcslen(didetail->DevicePath); index++)
UniqueID2 += didetail->DevicePath[index];
#endif
// and show when we want to trigger the next periodic status request
// (for battery level and connection loss detection)
NextStatusTime = timeGetTime() + REQUEST_STATUS_EVERY_MS;
NextMPlusDetectTime = timeGetTime() + DETECT_MPLUS_EVERY_MS;
MPlusDetectCount = DETECT_MPLUS_COUNT;
// tidy up
delete[] (BYTE*)didetail;
break;
}
skip:
// tidy up
delete[] (BYTE*)didetail;
if(Handle != INVALID_HANDLE_VALUE) {
CloseHandle(Handle);
Handle = INVALID_HANDLE_VALUE;
}
// if this was the specified wiimote index, abort
if((wiimote_index != FIRST_AVAILABLE) &&
(wiimote_index == (wiimotes_found-1)))
break;
index++;
}
// clean up our list
SetupDiDestroyDeviceInfoList(dev_info);
bConnectInProgress = false;
if(IsConnected()) {
TRACE(_T(".. connected!"));
// notify the callbacks (if requested to do so)
if(CallbackTriggerFlags & CONNECTED)
{
ChangedNotifier(CONNECTED, Internal);
if(ChangedCallback)
ChangedCallback(*this, CONNECTED, Internal);
}
return true;
}
TRACE(_T(".. connection failed."));
return false;
}
// ------------------------------------------------------------------------------------
void wiimote::CalibrateAtRest ()
{
_ASSERT(IsConnected());
if(!IsConnected())
return;
// the app calls this to remove 'at rest' offsets from the analogue sensor
// values (currently only works for the Balance Board):
if(IsBalanceBoard()) {
TRACE(_T(".. removing 'at rest' BBoard offsets."));
Internal.BalanceBoard.AtRestKg = Internal.BalanceBoard.Kg;
RefreshState();
}
}
// ------------------------------------------------------------------------------------
void wiimote::Disconnect ()
{
if(Handle == INVALID_HANDLE_VALUE)
return;
TRACE(_T("Disconnect()."));
if(IsConnected())
{
_ASSERT(_TotalConnected > 0); // sanity
_TotalConnected--;
if(!bConnectionLost)
Reset();
}
CloseHandle(Handle);
Handle = INVALID_HANDLE_VALUE;
UniqueID = 0;
#ifdef ID2_FROM_DEVICEPATH // (see comments in header)
UniqueID2 = 0;
#endif
// close the read thread
if(ReadParseThread) {
// unblock it so it can realise we're closing and exit straight away
SetEvent(DataRead);
WaitForSingleObject(ReadParseThread, 3000);
CloseHandle(ReadParseThread);
ReadParseThread = NULL;
}
// close the rumble thread
if(AsyncRumbleThread) {
WaitForSingleObject(AsyncRumbleThread, 3000);
CloseHandle(AsyncRumbleThread);
AsyncRumbleThread = NULL;
AsyncRumbleTimeout = 0;
}
// and the sample streaming thread
if(SampleThread) {
WaitForSingleObject(SampleThread, 3000);
CloseHandle(SampleThread);
SampleThread = NULL;
}
#ifndef USE_DYNAMIC_HIDQUEUE
HID.Deallocate();
#endif
bStatusReceived = false;
// and clear the state
Clear (false); // (preserves deadzones)
Internal.Clear(false); // "
InternalChanged = NO_CHANGE;
}
// ------------------------------------------------------------------------------------
void wiimote::Reset ()
{
TRACE(_T("Resetting wiimote."));
if(bMotionPlusEnabled)
DisableMotionPlus();
// stop updates (by setting report type to non-continuous, buttons-only)
if(IsBalanceBoard())
SetReportType(IN_BUTTONS_BALANCE_BOARD, false);
else
SetReportType(IN_BUTTONS, false);
SetRumble (false);
SetLEDs (0x00);
// MuteSpeaker (true);
EnableSpeaker(false);
Sleep(150); // avoids loosing the extension calibration data on Connect()
}
// ------------------------------------------------------------------------------------
unsigned __stdcall wiimote::ReadParseThreadfunc (void* param)
{
// this thread waits for the async ReadFile() to deliver data & parses it.
// it also requests periodic status updates, deals with connection loss
// and ends state recordings with a specific duration:
_ASSERT(param);
wiimote &remote = *(wiimote*)param;
OVERLAPPED &overlapped = remote.Overlapped;
unsigned exit_code = 0; // (success)
while(1)
{
// wait until the overlapped read completes, or the timeout is reached:
DWORD wait = WaitForSingleObject(overlapped.hEvent, 500);
// before we deal with the result, let's do some housekeeping:
// if we were recently Disconect()ed, exit now
if(remote.Handle == INVALID_HANDLE_VALUE) {
DEEP_TRACE(_T("read thread: wiimote was disconnected"));
break;
}
// ditto if the connection was lost (eg. through a failed write)
if(remote.bConnectionLost)
{
connection_lost:
TRACE(_T("read thread: connection to wiimote was lost"));
remote.Disconnect();
remote.InternalChanged = (state_change_flags)
(remote.InternalChanged | CONNECTION_LOST);
// report via the callback (if any)
if(remote.CallbackTriggerFlags & CONNECTION_LOST)
{
remote.ChangedNotifier(CONNECTION_LOST, remote.Internal);
if(remote.ChangedCallback)
remote.ChangedCallback(remote, CONNECTION_LOST, remote.Internal);
}
break;
}
DWORD time = timeGetTime();
// periodic events (but not if we're streaming audio,
// we don't want to cause a glitch)
if(remote.IsConnected() && !remote.bInitInProgress &&
!remote.IsPlayingAudio())
{
// status request due?
if(time > remote.NextStatusTime)
{
#ifdef BEEP_ON_PERIODIC_STATUSREFRESH
Beep(2000,50);
#endif
remote.RequestStatusReport();
// and schedule the next one
remote.NextStatusTime = time + REQUEST_STATUS_EVERY_MS;
}
// motion plus detection due?
if(!remote.IsBalanceBoard() &&
// !remote.bConnectInProgress &&
!remote.bMotionPlusExtension &&
(remote.Internal.ExtensionType != MOTION_PLUS) &&
(remote.Internal.ExtensionType != PARTIALLY_INSERTED) &&
(time > remote.NextMPlusDetectTime))
{
remote.DetectMotionPlusExtensionAsync();
// we try several times in quick succession before the next
// delay:
if(--remote.MPlusDetectCount == 0) {
remote.NextMPlusDetectTime = time + DETECT_MPLUS_EVERY_MS;
remote.MPlusDetectCount = DETECT_MPLUS_COUNT;
#ifdef _DEBUG
TRACE(_T("--"));
#endif
}
}
}
// if we're state recording and have reached the specified duration, stop
if(remote.Recording.bEnabled && (remote.Recording.EndTimeMS != UNTIL_STOP) &&
(time >= remote.Recording.EndTimeMS))
remote.Recording.bEnabled = false;
// now handle the wait result:
// did the wait time out?
if(wait == WAIT_TIMEOUT) {
DEEP_TRACE(_T("read thread: timed out"));
continue; // wait again
}
// did an error occurr?
if(wait != WAIT_OBJECT_0) {
DEEP_TRACE(_T("read thread: error waiting!"));
remote.bConnectionLost = true;
// deal with it straight away to avoid a longer delay
goto connection_lost;
}
// data was received:
#ifdef BEEP_DEBUG_READS
Beep(500,1);
#endif
DWORD read = 0;
// get the data read result
GetOverlappedResult(remote.Handle, &overlapped, &read, TRUE);
// if we read data, parse it
if(read) {
DEEP_TRACE(_T("read thread: parsing data"));
remote.OnReadData(read);
}
else
DEEP_TRACE(_T("read thread: didn't get any data??"));
}
TRACE(_T("(ending read thread)"));
#ifdef BEEP_DEBUG_READS
if(exit_code != 0)
Beep(200,1000);
#endif
return exit_code;
}
// ------------------------------------------------------------------------------------
bool wiimote::BeginAsyncRead ()
{
// (this is also called before we're fully connected)
if(Handle == INVALID_HANDLE_VALUE)
return false;
DEEP_TRACE(_T(".. starting async read"));
#ifdef BEEP_DEBUG_READS
Beep(1000,1);
#endif
DWORD read;
if (!ReadFile(Handle, ReadBuff, REPORT_LENGTH, &read, &Overlapped)) {
DWORD err = GetLastError();
if(err != ERROR_IO_PENDING) {
DEEP_TRACE(_T(".... ** ReadFile() failed! **"));
return false;
}
}
// launch the completion wait/callback thread
if(!ReadParseThread) {
ReadParseThread = (HANDLE)_beginthreadex(NULL, 0, ReadParseThreadfunc,
this, 0, NULL);
DEEP_TRACE(_T(".... creating read thread"));
_ASSERT(ReadParseThread);
if(!ReadParseThread)
return false;
SetThreadPriority(ReadParseThread, WORKER_THREAD_PRIORITY);
}
// if ReadFile completed while we called, signal the thread to proceed
if(read) {
DEEP_TRACE(_T(".... got data right away"));
SetEvent(DataRead);
}
return true;
}
// ------------------------------------------------------------------------------------
void wiimote::OnReadData (DWORD bytes_read)
{
_ASSERT(bytes_read == REPORT_LENGTH);
// copy our input buffer
BYTE buff [REPORT_LENGTH];
memcpy(buff, ReadBuff, bytes_read);
// start reading again
BeginAsyncRead();
// parse it
ParseInput(buff);
}
// ------------------------------------------------------------------------------------
void wiimote::SetReportType (input_report type, bool continuous)
{
_ASSERT(IsConnected());
if(!IsConnected())
return;
// the balance board only uses one type of report
_ASSERT(!IsBalanceBoard() || type == IN_BUTTONS_BALANCE_BOARD);
if(IsBalanceBoard() && (type != IN_BUTTONS_BALANCE_BOARD))
return;
#ifdef TRACE
#define TYPE2NAME(_type) (type==_type)? _T(#_type)
const TCHAR* name = TYPE2NAME(IN_BUTTONS) :
TYPE2NAME(IN_BUTTONS_ACCEL_IR) :
TYPE2NAME(IN_BUTTONS_ACCEL_EXT) :
TYPE2NAME(IN_BUTTONS_ACCEL_IR_EXT) :
TYPE2NAME(IN_BUTTONS_BALANCE_BOARD) :
_T("(unknown??)");
TRACE(_T("ReportType: %s (%s)"), name, (continuous? _T("continuous") :
_T("non-continuous")));
#endif
ReportType = type;
switch(type)
{
case IN_BUTTONS_ACCEL_IR:
EnableIR(wiimote_state::ir::EXTENDED);
break;
case IN_BUTTONS_ACCEL_IR_EXT:
EnableIR(wiimote_state::ir::BASIC);
break;
default:
DisableIR();
break;
}
BYTE buff [REPORT_LENGTH] = {0};
buff[0] = OUT_TYPE;
buff[1] = (continuous ? 0x04 : 0x00) | GetRumbleBit();
buff[2] = (BYTE)type;
WriteReport(buff);
// Sleep(15);
}
// ------------------------------------------------------------------------------------
void wiimote::SetLEDs (BYTE led_bits)
{
_ASSERT(IsConnected());
if(!IsConnected() || bInitInProgress)
return;
_ASSERT(led_bits <= 0x0f);
led_bits &= 0xf;
BYTE buff [REPORT_LENGTH] = {0};
buff[0] = OUT_LEDs;
buff[1] = (led_bits<<4) | GetRumbleBit();
WriteReport(buff);
Internal.LED.Bits = led_bits;
}
// ------------------------------------------------------------------------------------
void wiimote::SetRumble (bool on)
{
_ASSERT(IsConnected());
if(!IsConnected())
return;
if(Internal.bRumble == on)
return;
Internal.bRumble = on;
// if we're streaming audio, we don't need to send a report (sending it makes
// the audio glitch, and the rumble bit is sent with every report anyway)
if(IsPlayingAudio())
return;
BYTE buff [REPORT_LENGTH] = {0};
buff[0] = OUT_STATUS;
buff[1] = on? 0x01 : 0x00;
WriteReport(buff);
}
// ------------------------------------------------------------------------------------
unsigned __stdcall wiimote::AsyncRumbleThreadfunc (void* param)
{
// auto-disables rumble after x milliseconds:
_ASSERT(param);
wiimote &remote = *(wiimote*)param;
while(remote.IsConnected())
{
if(remote.AsyncRumbleTimeout)
{
DWORD current_time = timeGetTime();
if(current_time >= remote.AsyncRumbleTimeout)
{
if(remote.Internal.bRumble)
remote.SetRumble(false);
remote.AsyncRumbleTimeout = 0;
}
Sleep(1);
}
else
Sleep(4);
}
return 0;
}
// ------------------------------------------------------------------------------------
void wiimote::RumbleForAsync (unsigned milliseconds)
{
// rumble for a fixed amount of time
_ASSERT(IsConnected());
if(!IsConnected())
return;
SetRumble(true);
// show how long thread should wait to disable rumble again
// (it it's currently rumbling it will just extend the time)
AsyncRumbleTimeout = timeGetTime() + milliseconds;
// create the thread?
if(AsyncRumbleThread)
return;
AsyncRumbleThread = (HANDLE)_beginthreadex(NULL, 0, AsyncRumbleThreadfunc, this,
0, NULL);
_ASSERT(AsyncRumbleThread);
if(!AsyncRumbleThread) {
WARN(_T("couldn't create rumble thread!"));
return;
}
SetThreadPriority(AsyncRumbleThread, WORKER_THREAD_PRIORITY);
}
// ------------------------------------------------------------------------------------
void wiimote::RequestStatusReport ()
{
// (this can be called before we're fully connected)
_ASSERT(Handle != INVALID_HANDLE_VALUE);
if(Handle == INVALID_HANDLE_VALUE)
return;
BYTE buff [REPORT_LENGTH] = {0};
buff[0] = OUT_STATUS;
buff[1] = GetRumbleBit();
WriteReport(buff);
}
// ------------------------------------------------------------------------------------
bool wiimote::ReadAddress (int address, short size)
{
// asynchronous
BYTE buff [REPORT_LENGTH] = {0};
buff[0] = OUT_READMEMORY;
buff[1] = (BYTE)(((address & 0xff000000) >> 24) | GetRumbleBit());
buff[2] = (BYTE)( (address & 0x00ff0000) >> 16);
buff[3] = (BYTE)( (address & 0x0000ff00) >> 8);
buff[4] = (BYTE)( (address & 0x000000ff));
buff[5] = (BYTE)( (size & 0xff00 ) >> 8);
buff[6] = (BYTE)( (size & 0xff));
return WriteReport(buff);
}
// ------------------------------------------------------------------------------------
void wiimote::WriteData (int address, BYTE size, const BYTE* buff)
{
// asynchronous
BYTE write [REPORT_LENGTH] = {0};
write[0] = OUT_WRITEMEMORY;
write[1] = (BYTE)(((address & 0xff000000) >> 24) | GetRumbleBit());
write[2] = (BYTE)( (address & 0x00ff0000) >> 16);
write[3] = (BYTE)( (address & 0x0000ff00) >> 8);
write[4] = (BYTE)( (address & 0x000000ff));
write[5] = size;
memcpy(write+6, buff, size);
WriteReport(write);
}
// ------------------------------------------------------------------------------------
int wiimote::ParseInput (BYTE* buff)
{
int changed = 0;
// lock our internal state (so RefreshState() is blocked until we're done
EnterCriticalSection(&StateLock);
switch(buff[0])
{
case IN_BUTTONS:
DEEP_TRACE(_T(".. parsing buttons."));
changed |= ParseButtons(buff);
break;
case IN_BUTTONS_ACCEL:
DEEP_TRACE(_T(".. parsing buttons/accel."));
changed |= ParseButtons(buff);
if(!IsBalanceBoard())
changed |= ParseAccel(buff);
break;
case IN_BUTTONS_ACCEL_EXT:
DEEP_TRACE(_T(".. parsing extenion/accel."));
changed |= ParseButtons(buff);
changed |= ParseExtension(buff, 6);
if(!IsBalanceBoard())
changed |= ParseAccel(buff);
break;
case IN_BUTTONS_ACCEL_IR:
DEEP_TRACE(_T(".. parsing ir/accel."));
changed |= ParseButtons(buff);
if(!IsBalanceBoard()) {
changed |= ParseAccel(buff);
changed |= ParseIR(buff);
}
break;
case IN_BUTTONS_ACCEL_IR_EXT:
DEEP_TRACE(_T(".. parsing ir/extenion/accel."));
changed |= ParseButtons(buff);
changed |= ParseExtension(buff, 16);
if(!IsBalanceBoard()) {
changed |= ParseAccel(buff);
changed |= ParseIR (buff);
}
break;
case IN_BUTTONS_BALANCE_BOARD:
DEEP_TRACE(_T(".. parsing buttson/balance."));
changed |= ParseButtons(buff);
changed |= ParseExtension(buff, 3);
break;
case IN_READADDRESS:
DEEP_TRACE(_T(".. parsing read address."));
changed |= ParseButtons (buff);
changed |= ParseReadAddress(buff);
break;
case IN_STATUS:
DEEP_TRACE(_T(".. parsing status."));
changed |= ParseStatus(buff);
// show that we received the status report (used for output method
// detection during Connect())
bStatusReceived = true;
break;
default:
DEEP_TRACE(_T(".. ** unknown input ** (happens)."));
///_ASSERT(0);
//Debug.WriteLine("Unknown report type: " + type.ToString());
LeaveCriticalSection(&StateLock);
return false;
}
// if we're recording and some state we care about has changed, insert it into
// the state history
if(Recording.bEnabled && (changed & Recording.TriggerFlags))
{
DEEP_TRACE(_T(".. adding state to history"));
state_event event;
event.time_ms = timeGetTime();
event.state = *(wiimote_state*)this;
Recording.StateHistory->push_back(event);
}
// for polling: show which state has changed since the last RefreshState()