summaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/OVR_OSX_HIDDevice.cpp
blob: 650182cbb944acac093f1370659a9cbde127cd54 (plain)
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
/************************************************************************************
Filename    :   OVR_OSX_HIDDevice.cpp
Content     :   OSX HID device implementation.
Created     :   February 26, 2013
Authors     :   Lee Cooper

Copyright   :   Copyright 2013 Oculus VR, Inc. All Rights reserved.

Licensed under the Oculus VR SDK License Version 2.0 (the "License"); 
you may not use the Oculus VR SDK except in compliance with the License, 
which is provided at the time of installation or download, or which 
otherwise accompanies this software in either electronic or hard copy form.

You may obtain a copy of the License at

http://www.oculusvr.com/licenses/LICENSE-2.0 

Unless required by applicable law or agreed to in writing, the Oculus VR SDK 
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*************************************************************************************/

#include "OVR_OSX_HIDDevice.h"

#include <IOKit/usb/IOUSBLib.h>

namespace OVR { namespace OSX {

static const UInt32 MAX_QUEUED_INPUT_REPORTS = 5;

//-------------------------------------------------------------------------------------
// **** OSX::DeviceManager

HIDDeviceManager::HIDDeviceManager(DeviceManager* manager)
 :  DevManager(manager)
{
    HIDManager = NULL;
}

HIDDeviceManager::~HIDDeviceManager()
{
}

CFRunLoopRef HIDDeviceManager::getRunLoop()
{
    if (DevManager != NULL)
    {
        return DevManager->pThread->GetRunLoop();
    }

    return CFRunLoopGetCurrent();
}

bool HIDDeviceManager::initializeManager()
{
    if (HIDManager != NULL)
    {
        return true;
    }

	HIDManager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);

    if (!HIDManager)
    {
        return false;
    }

    // Create a Matching Dictionary
    CFMutableDictionaryRef matchDict =
        CFDictionaryCreateMutable(kCFAllocatorDefault,
                                  2,
                                  &kCFTypeDictionaryKeyCallBacks,
                                  &kCFTypeDictionaryValueCallBacks);

    // Specify a device manufacturer in the Matching Dictionary
    UInt32 vendorId = Oculus_VendorId;
    CFNumberRef vendorIdRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &vendorId);
    CFDictionarySetValue(matchDict,
                         CFSTR(kIOHIDVendorIDKey),
                         vendorIdRef);
    // Register the Matching Dictionary to the HID Manager
    IOHIDManagerSetDeviceMatching(HIDManager, matchDict);
    CFRelease(vendorIdRef);
    CFRelease(matchDict);

    // Register a callback for USB device detection with the HID Manager
    IOHIDManagerRegisterDeviceMatchingCallback(HIDManager, &staticDeviceMatchingCallback, this);

    IOHIDManagerScheduleWithRunLoop(HIDManager, getRunLoop(), kCFRunLoopDefaultMode);

    return true;
}

bool HIDDeviceManager::Initialize()
{
    return initializeManager();
}

void HIDDeviceManager::Shutdown()
{
    OVR_ASSERT_LOG(HIDManager, ("Should have called 'Initialize' before 'Shutdown'."));
    CFRelease(HIDManager);

    LogText("OVR::OSX::HIDDeviceManager - shutting down.\n");
}

bool HIDDeviceManager::getIntProperty(IOHIDDeviceRef device, CFStringRef propertyName, SInt32* pResult)
{

    CFTypeRef ref = IOHIDDeviceGetProperty(device, propertyName);

    if (!ref)
    {
        return false;
    }

    if (CFGetTypeID(ref) != CFNumberGetTypeID())
    {
        return false;
    }

    CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, pResult);

    return true;
}

bool HIDDeviceManager::initVendorProductVersion(IOHIDDeviceRef device, HIDDeviceDesc* pDevDesc)
{

    if (!getVendorId(device, &(pDevDesc->VendorId)))
    {
        return false;
    }

    if (!getProductId(device, &(pDevDesc->ProductId)))
    {
        return false;
    }

    SInt32 result;
    if (!getIntProperty(device, CFSTR(kIOHIDVersionNumberKey), &result))
    {
        return false;
    }
    pDevDesc->VersionNumber = result;

    return true;
}

bool HIDDeviceManager::initUsage(IOHIDDeviceRef device, HIDDeviceDesc* pDevDesc)
{

    SInt32 result;

    if (!getIntProperty(device, CFSTR(kIOHIDPrimaryUsagePageKey), &result))
    {
        return false;
    }

    pDevDesc->UsagePage = result;


    if (!getIntProperty(device, CFSTR(kIOHIDPrimaryUsageKey), &result))
    {
        return false;
    }

    pDevDesc->Usage = result;

    return true;
}

bool HIDDeviceManager::initSerialNumber(IOHIDDeviceRef device, HIDDeviceDesc* pDevDesc)
{
    return getSerialNumberString(device, &(pDevDesc->SerialNumber));
}

bool HIDDeviceManager::initStrings(IOHIDDeviceRef device, HIDDeviceDesc* pDevDesc)
{

    // Regardless of whether they fail we'll try and get the remaining.
    getStringProperty(device, CFSTR(kIOHIDManufacturerKey), &(pDevDesc->Manufacturer));
    getStringProperty(device, CFSTR(kIOHIDProductKey), &(pDevDesc->Product));

    return true;
}

bool HIDDeviceManager::getStringProperty(IOHIDDeviceRef device,
                                         CFStringRef propertyName,
                                         String* pResult)
{

    CFStringRef str = (CFStringRef) IOHIDDeviceGetProperty(device, propertyName);

    if (!str)
    {
        return false;
    }

    CFIndex length = CFStringGetLength(str);
    CFRange range = CFRangeMake(0, length);

    // Test the conversion first to get required buffer size.
    CFIndex bufferLength;
    CFIndex numberOfChars = CFStringGetBytes(str,
                                             range,
                                             kCFStringEncodingUTF8,
                                             (char) '?',
                                             FALSE,
                                             NULL,
                                             0,
                                             &bufferLength);

    if (numberOfChars == 0)
    {
        return false;
    }

    // Now allocate buffer.
    char* buffer = new char[bufferLength+1];

    numberOfChars = CFStringGetBytes(str,
                                     range,
                                     kCFStringEncodingUTF8,
                                     (char) '?',
                                     FALSE,
                                     (UInt8*) buffer,
                                     bufferLength,
                                     NULL);
    OVR_ASSERT_LOG(numberOfChars != 0, ("CFStringGetBytes failed."));

    buffer[bufferLength] = '\0';
    *pResult = String(buffer);

    return true;
}

bool HIDDeviceManager::getVendorId(IOHIDDeviceRef device, UInt16* pResult)
{
    SInt32 result;

    if (!getIntProperty(device, CFSTR(kIOHIDVendorIDKey), &result))
    {
        return false;
    }

    *pResult = result;

    return true;
}

bool HIDDeviceManager::getProductId(IOHIDDeviceRef device, UInt16* pResult)
{
    SInt32 result;

    if (!getIntProperty(device, CFSTR(kIOHIDProductIDKey), &result))
    {
        return false;
    }

    *pResult = result;

    return true;
}

bool HIDDeviceManager::getLocationId(IOHIDDeviceRef device, SInt32* pResult)
{
    SInt32 result;

    if (!getIntProperty(device, CFSTR(kIOHIDLocationIDKey), &result))
    {
        return false;
    }

    *pResult = result;

    return true;
}

bool HIDDeviceManager::getSerialNumberString(IOHIDDeviceRef device, String* pResult)
{

    if (!getStringProperty(device, CFSTR(kIOHIDSerialNumberKey), pResult))
    {
        return false;
    }

    return true;
}

bool HIDDeviceManager::getPath(IOHIDDeviceRef device, String* pPath)
{

    String transport;
    if (!getStringProperty(device, CFSTR(kIOHIDTransportKey), &transport))
    {
        return false;
    }

    UInt16 vendorId;
    if (!getVendorId(device, &vendorId))
    {
        return false;
    }

    UInt16 productId;
    if (!getProductId(device, &productId))
    {
        return false;
    }

    String serialNumber;
	if (!getSerialNumberString(device, &serialNumber))
    {
        return false;
    }


    StringBuffer buffer;
    buffer.AppendFormat("%s:vid=%04hx:pid=%04hx:ser=%s",
                            transport.ToCStr(),
                            vendorId,
                            productId,
                            serialNumber.ToCStr());

    *pPath = String(buffer);

    return true;
}

bool HIDDeviceManager::Enumerate(HIDEnumerateVisitor* enumVisitor)
{
    if (!initializeManager())
    {
        return false;
    }


	CFSetRef deviceSet = IOHIDManagerCopyDevices(HIDManager);
    if (!deviceSet)
        return false;

	CFIndex deviceCount = CFSetGetCount(deviceSet);

    // Allocate a block of memory and read the set into it.
    IOHIDDeviceRef* devices = (IOHIDDeviceRef*) OVR_ALLOC(sizeof(IOHIDDeviceRef) * deviceCount);
    CFSetGetValues(deviceSet, (const void **) devices);


    // Iterate over devices.
    for (CFIndex deviceIndex = 0; deviceIndex < deviceCount; deviceIndex++)
    {
        IOHIDDeviceRef hidDev = devices[deviceIndex];

        if (!hidDev)
        {
            continue;
        }

        HIDDeviceDesc devDesc;

        if (getPath(hidDev, &(devDesc.Path)) &&
            initVendorProductVersion(hidDev, &devDesc) &&
            enumVisitor->MatchVendorProduct(devDesc.VendorId, devDesc.ProductId) &&
            initUsage(hidDev, &devDesc))
        {
            initStrings(hidDev, &devDesc);
            initSerialNumber(hidDev, &devDesc);

            // Look for the device to check if it is already opened.
            Ptr<DeviceCreateDesc> existingDevice = DevManager->FindHIDDevice(devDesc, true);
            // if device exists and it is opened then most likely the CreateHIDFile
            // will fail; therefore, we just set Enumerated to 'true' and continue.
            if (existingDevice && existingDevice->pDevice)
            {
                existingDevice->Enumerated = true;
                continue;
            }

            // open the device temporarily for startup communication
            if (IOHIDDeviceOpen(hidDev, kIOHIDOptionsTypeSeizeDevice) == kIOReturnSuccess)
            {
                // Construct minimal device that the visitor callback can get feature reports from.
                OSX::HIDDevice device(this, hidDev);

                enumVisitor->Visit(device, devDesc);

                IOHIDDeviceClose(hidDev, kIOHIDOptionsTypeSeizeDevice);
            }
        }
    }

    OVR_FREE(devices);
    CFRelease(deviceSet);

    return true;
}

OVR::HIDDevice* HIDDeviceManager::Open(const String& path)
{

    Ptr<OSX::HIDDevice> device = *new OSX::HIDDevice(this);

    if (!device->HIDInitialize(path))
    {
        return NULL;
    }

    device->AddRef();

    return device;
}

bool HIDDeviceManager::getFullDesc(IOHIDDeviceRef device, HIDDeviceDesc* desc)
{

    if (!initVendorProductVersion(device, desc))
    {
        return false;
    }

    if (!initUsage(device, desc))
    {
        return false;
    }

    if (!initSerialNumber(device, desc))
    {
        return false;
    }

    initStrings(device, desc);

    return true;
}

// New USB device specified in the matching dictionary has been added (callback function)
void HIDDeviceManager::staticDeviceMatchingCallback(void *inContext,
                                                    IOReturn inResult,
                                                    void *inSender,
                                                    IOHIDDeviceRef inIOHIDDeviceRef)
{
    HIDDeviceManager* hidMgr = static_cast<HIDDeviceManager*>(inContext);
    HIDDeviceDesc hidDevDesc;
    hidMgr->getPath(inIOHIDDeviceRef, &hidDevDesc.Path);
    hidMgr->getFullDesc(inIOHIDDeviceRef, &hidDevDesc);

    hidMgr->DevManager->DetectHIDDevice(hidDevDesc);
}

//-------------------------------------------------------------------------------------
// **** OSX::HIDDevice

HIDDevice::HIDDevice(HIDDeviceManager* manager)
 :  HIDManager(manager), InMinimalMode(false)
{
    Device = NULL;
    RepluggedNotificationPort = 0;
}

// This is a minimal constructor used during enumeration for us to pass
// a HIDDevice to the visit function (so that it can query feature reports).
HIDDevice::HIDDevice(HIDDeviceManager* manager, IOHIDDeviceRef device)
:   HIDManager(manager), Device(device), InMinimalMode(true)
{
    RepluggedNotificationPort = 0;
}

HIDDevice::~HIDDevice()
{
    if (!InMinimalMode)
    {
        HIDShutdown();
    }
}

bool HIDDevice::HIDInitialize(const String& path)
{

    DevDesc.Path = path;

    if (!openDevice())
    {
        LogText("OVR::OSX::HIDDevice - Failed to open HIDDevice: %s", path.ToCStr());
        return false;
    }

    // Setup notification for when a device is unplugged and plugged back in.
    if (!setupDevicePluggedInNotification())
    {
        LogText("OVR::OSX::HIDDevice - Failed to setup notification for when device plugged back in.");
        closeDevice(false);
        return false;
    }

    HIDManager->DevManager->pThread->AddTicksNotifier(this);


    LogText("OVR::OSX::HIDDevice - Opened '%s'\n"
            "                    Manufacturer:'%s'  Product:'%s'  Serial#:'%s'\n",
            DevDesc.Path.ToCStr(),
            DevDesc.Manufacturer.ToCStr(), DevDesc.Product.ToCStr(),
            DevDesc.SerialNumber.ToCStr());

    return true;
}

bool HIDDevice::initInfo()
{
    // Device must have been successfully opened.
    OVR_ASSERT(Device);


    // Get report lengths.
    SInt32 bufferLength;
    bool getResult = HIDManager->getIntProperty(Device, CFSTR(kIOHIDMaxInputReportSizeKey), &bufferLength);
    OVR_ASSERT(getResult);
    InputReportBufferLength = (UInt16) bufferLength;

    getResult = HIDManager->getIntProperty(Device, CFSTR(kIOHIDMaxOutputReportSizeKey), &bufferLength);
    OVR_ASSERT(getResult);
    OutputReportBufferLength = (UInt16) bufferLength;

    getResult = HIDManager->getIntProperty(Device, CFSTR(kIOHIDMaxFeatureReportSizeKey), &bufferLength);
    OVR_ASSERT(getResult);
    FeatureReportBufferLength = (UInt16) bufferLength;


    if (ReadBufferSize < InputReportBufferLength)
    {
        OVR_ASSERT_LOG(false, ("Input report buffer length is bigger than read buffer."));
        return false;
    }

    // Get device desc.
    if (!HIDManager->getFullDesc(Device, &DevDesc))
    {
        OVR_ASSERT_LOG(false, ("Failed to get device desc while initializing device."));
        return false;
    }

    return true;
}

void HIDDevice::staticDeviceAddedCallback(void* pContext, io_iterator_t iterator)
{
    HIDDevice* pDevice = (HIDDevice*) pContext;
    pDevice->deviceAddedCallback(iterator);
}

void HIDDevice::deviceAddedCallback(io_iterator_t iterator)
{

    if (Device == NULL)
    {
        if (openDevice())
        {
            LogText("OVR::OSX::HIDDevice - Reopened device : %s", DevDesc.Path.ToCStr());

            Ptr<DeviceCreateDesc> existingHIDDev = HIDManager->DevManager->FindHIDDevice(DevDesc, true);
            if (existingHIDDev && existingHIDDev->pDevice)
            {
                HIDManager->DevManager->CallOnDeviceAdded(existingHIDDev);
            }
        }
    }

    // Reset callback.
    while (IOIteratorNext(iterator))
        ;
}

bool HIDDevice::openDevice()
{

    // Have to iterate through devices again to generate paths.
	CFSetRef deviceSet = IOHIDManagerCopyDevices(HIDManager->HIDManager);
	CFIndex deviceCount = CFSetGetCount(deviceSet);

    // Allocate a block of memory and read the set into it.
    IOHIDDeviceRef* devices = (IOHIDDeviceRef*) OVR_ALLOC(sizeof(IOHIDDeviceRef) * deviceCount);
    CFSetGetValues(deviceSet, (const void **) devices);


    // Iterate over devices.
    IOHIDDeviceRef device = NULL;

    for (CFIndex deviceIndex = 0; deviceIndex < deviceCount; deviceIndex++)
    {
        IOHIDDeviceRef tmpDevice = devices[deviceIndex];

        if (!tmpDevice)
        {
            continue;
        }

        String path;
        if (!HIDManager->getPath(tmpDevice, &path))
        {
            continue;
        }

        if (path == DevDesc.Path)
        {
            device = tmpDevice;
            break;
        }
    }


    OVR_FREE(devices);

    if (!device)
    {
        CFRelease(deviceSet);
        return false;
    }

    // Attempt to open device.
    if (IOHIDDeviceOpen(device, kIOHIDOptionsTypeSeizeDevice)
        != kIOReturnSuccess)
    {
        CFRelease(deviceSet);
        return false;
    }

    // Retain the device before we release the set.
    CFRetain(device);
    CFRelease(deviceSet);


    Device = device;


    if (!initInfo())
    {
        IOHIDDeviceClose(Device, kIOHIDOptionsTypeSeizeDevice);
        CFRelease(Device);
        Device = NULL;
        return false;
    }


    // Setup the Run Loop and callbacks.
    IOHIDDeviceScheduleWithRunLoop(Device,
                                   HIDManager->getRunLoop(),
                                   kCFRunLoopDefaultMode);

    IOHIDDeviceRegisterInputReportCallback(Device,
                                           ReadBuffer,
                                           ReadBufferSize,
                                           staticHIDReportCallback,
                                           this);

    IOHIDDeviceRegisterRemovalCallback(Device,
                                       staticDeviceRemovedCallback,
                                       this);

    return true;
}

void HIDDevice::HIDShutdown()
{

    HIDManager->DevManager->pThread->RemoveTicksNotifier(this);

    if (Device != NULL) // Device may already have been closed if unplugged.
    {
        closeDevice(false);
    }

    IOObjectRelease(RepluggedNotification);
    if (RepluggedNotificationPort)
        IONotificationPortDestroy(RepluggedNotificationPort);

    LogText("OVR::OSX::HIDDevice - HIDShutdown '%s'\n", DevDesc.Path.ToCStr());
}

bool HIDDevice::setupDevicePluggedInNotification()
{

    // Setup notification when devices are plugged in.
    RepluggedNotificationPort = IONotificationPortCreate(kIOMasterPortDefault);

    CFRunLoopSourceRef notificationRunLoopSource =
        IONotificationPortGetRunLoopSource(RepluggedNotificationPort);

    CFRunLoopAddSource(HIDManager->getRunLoop(),
                       notificationRunLoopSource,
                       kCFRunLoopDefaultMode);

    CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);

    // Have to specify vendorId and productId. Doesn't seem to accept additional
    // things like serial number.
    SInt32 vendorId = DevDesc.VendorId;
    CFNumberRef numberRef = CFNumberCreate(kCFAllocatorDefault,
                                           kCFNumberSInt32Type,
                                           &vendorId);
    CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID), numberRef);
    CFRelease(numberRef);

    SInt32 deviceProductId = DevDesc.ProductId;
    numberRef = CFNumberCreate(kCFAllocatorDefault,
                               kCFNumberSInt32Type,
                               &deviceProductId);
    CFDictionarySetValue(matchingDict, CFSTR(kUSBProductID), numberRef);
    CFRelease(numberRef);

    kern_return_t result =
            IOServiceAddMatchingNotification(RepluggedNotificationPort,
                                             kIOMatchedNotification,
                                             matchingDict,
                                             staticDeviceAddedCallback,
                                             this,
                                             &RepluggedNotification);

    if (result != KERN_SUCCESS)
    {
        CFRelease(RepluggedNotificationPort);
        RepluggedNotificationPort = 0;
        return false;
    }

    // Iterate through to arm.
    while (IOIteratorNext(RepluggedNotification))
    {
	}

    return true;
}

void HIDDevice::closeDevice(bool wasUnplugged)
{
    OVR_ASSERT(Device != NULL);

    if (!wasUnplugged)
    {
        // Clear the registered callbacks.
        IOHIDDeviceRegisterInputReportCallback(Device,
                                               ReadBuffer,
                                               InputReportBufferLength,
                                               NULL,
                                               this);

        IOHIDDeviceRegisterRemovalCallback(Device, NULL, this);

        IOHIDDeviceUnscheduleFromRunLoop(Device,
                                         HIDManager->getRunLoop(),
                                         kCFRunLoopDefaultMode);
        IOHIDDeviceClose(Device, kIOHIDOptionsTypeNone);
    }

	CFRelease(Device);
    Device = NULL;

    LogText("OVR::OSX::HIDDevice - HID Device Closed '%s'\n", DevDesc.Path.ToCStr());
}

void HIDDevice::staticHIDReportCallback(void* pContext,
                                        IOReturn result,
                                        void* pSender,
                                        IOHIDReportType reportType,
                                        uint32_t reportId,
                                        uint8_t* pReport,
                                        CFIndex reportLength)
{
    HIDDevice* pDevice = (HIDDevice*) pContext;
    return pDevice->hidReportCallback(pReport, (UInt32)reportLength);
}

void HIDDevice::hidReportCallback(const UByte* pData, UInt32 length)
{

    // We got data.
    if (Handler)
    {
        Handler->OnInputReport(pData, length);
    }
}

void HIDDevice::staticDeviceRemovedCallback(void* pContext, IOReturn result, void* pSender)
{
    HIDDevice* pDevice = (HIDDevice*) pContext;
    pDevice->deviceRemovedCallback();
}

void HIDDevice::deviceRemovedCallback()
{
    Ptr<HIDDevice> _this(this); // prevent from release
    
    Ptr<DeviceCreateDesc> existingHIDDev = HIDManager->DevManager->FindHIDDevice(DevDesc, true);
    if (existingHIDDev && existingHIDDev->pDevice)
    {
        HIDManager->DevManager->CallOnDeviceRemoved(existingHIDDev);
    }
    closeDevice(true);
}

CFStringRef HIDDevice::generateRunLoopModeString(IOHIDDeviceRef device)
{
    const UInt32 safeBuffSize = 256;
    char nameBuff[safeBuffSize];
    OVR_sprintf(nameBuff, safeBuffSize, "%016lX", device);

    return CFStringCreateWithCString(NULL, nameBuff, kCFStringEncodingASCII);
}

bool HIDDevice::SetFeatureReport(UByte* data, UInt32 length)
{

    if (!Device)
        return false;

    UByte reportID = data[0];

    if (reportID == 0)
    {
        // Not using reports so remove from data packet.
        data++;
        length--;
    }

	IOReturn result = IOHIDDeviceSetReport( Device,
                                            kIOHIDReportTypeFeature,
                                            reportID,
                                            data,
                                            length);

    return (result == kIOReturnSuccess);
}

bool HIDDevice::GetFeatureReport(UByte* data, UInt32 length)
{
    if (!Device)
        return false;

    CFIndex bufferLength = length;

    // Report id is in first byte of the buffer.
	IOReturn result = IOHIDDeviceGetReport(Device, kIOHIDReportTypeFeature, data[0], data, &bufferLength);

    return (result == kIOReturnSuccess);
}

UInt64 HIDDevice::OnTicks(UInt64 ticksMks)
{

    if (Handler)
    {
        return Handler->OnTicks(ticksMks);
    }

    return DeviceManagerThread::Notifier::OnTicks(ticksMks);
}

HIDDeviceManager* HIDDeviceManager::CreateInternal(OSX::DeviceManager* devManager)
{

    if (!System::IsInitialized())
    {
        // Use custom message, since Log is not yet installed.
        OVR_DEBUG_STATEMENT(Log::GetDefaultLog()->
                            LogMessage(Log_Debug, "HIDDeviceManager::Create failed - OVR::System not initialized"); );
        return 0;
    }

    Ptr<OSX::HIDDeviceManager> manager = *new OSX::HIDDeviceManager(devManager);

    if (manager)
    {
        if (manager->Initialize())
        {
            manager->AddRef();
        }
        else
        {
            manager.Clear();
        }
    }

    return manager.GetPtr();
}

} // namespace OSX

//-------------------------------------------------------------------------------------
// ***** Creation

// Creates a new HIDDeviceManager and initializes OVR.
HIDDeviceManager* HIDDeviceManager::Create()
{
    OVR_ASSERT_LOG(false, ("Standalone mode not implemented yet."));

    if (!System::IsInitialized())
    {
        // Use custom message, since Log is not yet installed.
        OVR_DEBUG_STATEMENT(Log::GetDefaultLog()->
            LogMessage(Log_Debug, "HIDDeviceManager::Create failed - OVR::System not initialized"); );
        return 0;
    }

    Ptr<OSX::HIDDeviceManager> manager = *new OSX::HIDDeviceManager(NULL);

    if (manager)
    {
        if (manager->Initialize())
        {
            manager->AddRef();
        }
        else
        {
            manager.Clear();
        }
    }

    return manager.GetPtr();
}

} // namespace OVR