summaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/OVR_Win32_HIDDevice.cpp
blob: 28a47f003a7d3df47359ee57f92a3492b25e5db5 (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
/************************************************************************************

Filename    :   OVR_Win32_HIDDevice.cpp
Content     :   Win32 HID device implementation.
Created     :   February 22, 2013
Authors     :   Lee Cooper

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

Use of this software is subject to the terms of the Oculus license
agreement provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.

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

#include "OVR_Win32_HIDDevice.h"
#include "OVR_Win32_DeviceManager.h"

#include "Kernel/OVR_System.h"
#include "Kernel/OVR_Log.h"

namespace OVR { namespace Win32 {

//-------------------------------------------------------------------------------------
// HIDDevicePathWrapper is a simple class used to extract HID device file path
// through SetupDiGetDeviceInterfaceDetail. We use a class since this is a bit messy.
class HIDDevicePathWrapper
{
    SP_INTERFACE_DEVICE_DETAIL_DATA_A* pData;
public:
    HIDDevicePathWrapper() : pData(0) { }
    ~HIDDevicePathWrapper() { if (pData) OVR_FREE(pData); }

    const char* GetPath() const { return pData ? pData->DevicePath : 0; }

    bool InitPathFromInterfaceData(HDEVINFO hdevInfoSet, SP_DEVICE_INTERFACE_DATA* pidata);
};

bool HIDDevicePathWrapper::InitPathFromInterfaceData(HDEVINFO hdevInfoSet, SP_DEVICE_INTERFACE_DATA* pidata)
{
    DWORD detailSize = 0;
    // SetupDiGetDeviceInterfaceDetailA returns "not enough buffer error code"
    // doe size request. Just check valid size.
    SetupDiGetDeviceInterfaceDetailA(hdevInfoSet, pidata, NULL, 0, &detailSize, NULL);
    if (!detailSize ||
        ((pData = (SP_INTERFACE_DEVICE_DETAIL_DATA_A*)OVR_ALLOC(detailSize)) == 0))
        return false;
    pData->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA_A);

    if (!SetupDiGetDeviceInterfaceDetailA(hdevInfoSet, pidata, pData, detailSize, NULL, NULL))
        return false;
    return true;
}


//-------------------------------------------------------------------------------------
// **** Win32::DeviceManager

HIDDeviceManager::HIDDeviceManager(DeviceManager* manager)
 :  Manager(manager)
{
    hHidLib = ::LoadLibraryA("hid.dll");
    OVR_ASSERT_LOG(hHidLib, ("Couldn't load Win32 'hid.dll'."));

    OVR_RESOLVE_HIDFUNC(HidD_GetHidGuid);
    OVR_RESOLVE_HIDFUNC(HidD_SetNumInputBuffers);
    OVR_RESOLVE_HIDFUNC(HidD_GetFeature);
    OVR_RESOLVE_HIDFUNC(HidD_SetFeature);
    OVR_RESOLVE_HIDFUNC(HidD_GetAttributes);
    OVR_RESOLVE_HIDFUNC(HidD_GetManufacturerString);
    OVR_RESOLVE_HIDFUNC(HidD_GetProductString);
    OVR_RESOLVE_HIDFUNC(HidD_GetSerialNumberString);
    OVR_RESOLVE_HIDFUNC(HidD_GetPreparsedData);   
    OVR_RESOLVE_HIDFUNC(HidD_FreePreparsedData);  
    OVR_RESOLVE_HIDFUNC(HidP_GetCaps);    

    if (HidD_GetHidGuid)
        HidD_GetHidGuid(&HidGuid);
}

HIDDeviceManager::~HIDDeviceManager()
{
    ::FreeLibrary(hHidLib);
}

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

void HIDDeviceManager::Shutdown()
{   
    LogText("OVR::Win32::HIDDeviceManager - shutting down.\n");
}

bool HIDDeviceManager::Enumerate(HIDEnumerateVisitor* enumVisitor)
{
    HDEVINFO                 hdevInfoSet;
    SP_DEVICE_INTERFACE_DATA interfaceData;
    interfaceData.cbSize = sizeof(interfaceData);

    // Get handle to info data set describing all available HIDs.
    hdevInfoSet = SetupDiGetClassDevsA(&HidGuid, NULL, NULL, DIGCF_INTERFACEDEVICE | DIGCF_PRESENT);
    if (hdevInfoSet == INVALID_HANDLE_VALUE)
        return false;

    for(int deviceIndex = 0;
        SetupDiEnumDeviceInterfaces(hdevInfoSet, NULL, &HidGuid, deviceIndex, &interfaceData);
        deviceIndex++)
    {
        // For each device, we extract its file path and open it to get attributes,
        // such as vendor and product id. If anything goes wrong, we move onto next device.
        HIDDevicePathWrapper pathWrapper;
        if (!pathWrapper.InitPathFromInterfaceData(hdevInfoSet, &interfaceData))
            continue;

        // Look for the device to check if it is already opened.
        Ptr<DeviceCreateDesc> existingDevice = Manager->FindDevice(pathWrapper.GetPath());
        // 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 device in non-exclusive mode for detection...
        HANDLE hidDev = CreateHIDFile(pathWrapper.GetPath(), false);
        if (hidDev == INVALID_HANDLE_VALUE)
            continue;

        HIDDeviceDesc devDesc;
        devDesc.Path = pathWrapper.GetPath();
        if (initVendorProductVersion(hidDev, &devDesc) &&
            enumVisitor->MatchVendorProduct(devDesc.VendorId, devDesc.ProductId) &&
            initUsage(hidDev, &devDesc))
        {
            initStrings(hidDev, &devDesc);

            // Construct minimal device that the visitor callback can get feature reports from.
            Win32::HIDDevice device(this, hidDev);
            enumVisitor->Visit(device, devDesc);
        }

        ::CloseHandle(hidDev);
    }

    SetupDiDestroyDeviceInfoList(hdevInfoSet);
    return true;
}

bool HIDDeviceManager::GetHIDDeviceDesc(const String& path, HIDDeviceDesc* pdevDesc) const
{
    // open device in non-exclusive mode for detection...
    HANDLE hidDev = CreateHIDFile(path, false);
    if (hidDev == INVALID_HANDLE_VALUE)
        return false;

    pdevDesc->Path = path;
    getFullDesc(hidDev, pdevDesc);

    ::CloseHandle(hidDev);
    return true;
}

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

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

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

    return NULL;
}

bool HIDDeviceManager::getFullDesc(HANDLE hidDev, HIDDeviceDesc* desc) const
{

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

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

    initStrings(hidDev, desc);

    return true;
}

bool HIDDeviceManager::initVendorProductVersion(HANDLE hidDev, HIDDeviceDesc* desc) const
{
    HIDD_ATTRIBUTES attr;
    attr.Size = sizeof(attr);
    if (!HidD_GetAttributes(hidDev, &attr))
        return false;
    desc->VendorId      = attr.VendorID;
    desc->ProductId     = attr.ProductID;
    desc->VersionNumber = attr.VersionNumber;
    return true;
}

bool HIDDeviceManager::initUsage(HANDLE hidDev, HIDDeviceDesc* desc) const
{
    bool                 result = false;
    HIDP_CAPS            caps;
    HIDP_PREPARSED_DATA* preparsedData = 0;

    if (!HidD_GetPreparsedData(hidDev, &preparsedData))
        return false;

    if (HidP_GetCaps(preparsedData, &caps) == HIDP_STATUS_SUCCESS)
    {
        desc->Usage                  = caps.Usage;
        desc->UsagePage              = caps.UsagePage;
        result = true;
    }
    HidD_FreePreparsedData(preparsedData);
    return result;
}

void HIDDeviceManager::initStrings(HANDLE hidDev, HIDDeviceDesc* desc) const
{
    // Documentation mentions 126 as being the max for USB.
    wchar_t strBuffer[196];

    // HidD_Get*String functions return nothing in buffer on failure,
    // so it's ok to do this without further error checking.
    strBuffer[0] = 0;
    HidD_GetManufacturerString(hidDev, strBuffer, sizeof(strBuffer));
    desc->Manufacturer = strBuffer;

    strBuffer[0] = 0;
    HidD_GetProductString(hidDev, strBuffer, sizeof(strBuffer));
    desc->Product = strBuffer;

    strBuffer[0] = 0;
    HidD_GetSerialNumberString(hidDev, strBuffer, sizeof(strBuffer));
    desc->SerialNumber = strBuffer;
}

//-------------------------------------------------------------------------------------
// **** Win32::HIDDevice

HIDDevice::HIDDevice(HIDDeviceManager* manager)
 : HIDManager(manager), inMinimalMode(false), Device(0), ReadRequested(false)
{
    memset(&ReadOverlapped, 0, sizeof(OVERLAPPED));
}

// 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, HANDLE device)
 : HIDManager(manager), inMinimalMode(true), Device(device), ReadRequested(true)
{
    memset(&ReadOverlapped, 0, sizeof(OVERLAPPED));
}

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

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

    DevDesc.Path = path;

    if (!openDevice())
    {
        LogText("OVR::Win32::HIDDevice - Failed to open HIDDevice: ", path);
        return false;
    }


    HIDManager->Manager->pThread->AddTicksNotifier(this);
    HIDManager->Manager->pThread->AddMessageNotifier(this);

    LogText("OVR::Win32::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.
    HIDP_PREPARSED_DATA* preparsedData = 0;
    if (!HIDManager->HidD_GetPreparsedData(Device, &preparsedData))
    {
        return false;
    }

    HIDP_CAPS caps;
    if (HIDManager->HidP_GetCaps(preparsedData, &caps) != HIDP_STATUS_SUCCESS)
    {
        HIDManager->HidD_FreePreparsedData(preparsedData);
        return false;
    }

    InputReportBufferLength  = caps.InputReportByteLength;
    OutputReportBufferLength = caps.OutputReportByteLength;
    FeatureReportBufferLength= caps.FeatureReportByteLength;
    HIDManager->HidD_FreePreparsedData(preparsedData);

    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;
}

bool HIDDevice::openDevice()
{
    memset(&ReadOverlapped, 0, sizeof(OVERLAPPED));

    Device = HIDManager->CreateHIDFile(DevDesc.Path.ToCStr());
    if (Device == INVALID_HANDLE_VALUE)
    {
        OVR_DEBUG_LOG(("Failed 'CreateHIDFile' while opening device, error = 0x%X.", 
			::GetLastError()));
        Device = 0;
        return false;
    }

    if (!HIDManager->HidD_SetNumInputBuffers(Device, 128))
    {
        OVR_ASSERT_LOG(false, ("Failed 'HidD_SetNumInputBuffers' while initializing device."));
        ::CloseHandle(Device);
        Device = 0;
        return false;
    }


    // Create a manual-reset non-signaled event.
    ReadOverlapped.hEvent = ::CreateEvent(0, TRUE, FALSE, 0);

    if (!ReadOverlapped.hEvent)
    {
        OVR_ASSERT_LOG(false, ("Failed to create event."));
        ::CloseHandle(Device);
        Device = 0;
        return false;
    }

    if (!initInfo())
    {
        OVR_ASSERT_LOG(false, ("Failed to get HIDDevice info."));

        ::CloseHandle(ReadOverlapped.hEvent);
        memset(&ReadOverlapped, 0, sizeof(OVERLAPPED));

        ::CloseHandle(Device);
        Device = 0;
        return false;
    }

    if (!initializeRead())
    {
        OVR_ASSERT_LOG(false, ("Failed to get intialize read for HIDDevice."));

        ::CloseHandle(ReadOverlapped.hEvent);
        memset(&ReadOverlapped, 0, sizeof(OVERLAPPED));

        ::CloseHandle(Device);
        Device = 0;
        return false;
    }

    return true;
}

void HIDDevice::HIDShutdown()
{   

    HIDManager->Manager->pThread->RemoveTicksNotifier(this);
    HIDManager->Manager->pThread->RemoveMessageNotifier(this);

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

bool HIDDevice::initializeRead()
{

    if (!ReadRequested)
    {        
        HIDManager->Manager->pThread->AddOverlappedEvent(this, ReadOverlapped.hEvent);
        ReadRequested = true;
    }

    // Read resets the event...
    while(::ReadFile(Device, ReadBuffer, InputReportBufferLength, 0, &ReadOverlapped))
    {
        processReadResult();
    }

    if (GetLastError() != ERROR_IO_PENDING)
    {
        // Some other error (such as unplugged).
        closeDeviceOnIOError();
        return false;
    }

    return true;
}

bool HIDDevice::processReadResult()
{

    OVR_ASSERT(ReadRequested);

    DWORD bytesRead = 0;

    if (GetOverlappedResult(Device, &ReadOverlapped, &bytesRead, FALSE))
    {
        // We've got data.
        if (Handler)
        {
            Handler->OnInputReport(ReadBuffer, bytesRead);
        }

        // TBD: Not needed?
        // Event should be reset by Read call...
        ReadOverlapped.Pointer = 0;
        ReadOverlapped.Internal = 0;
        ReadOverlapped.InternalHigh = 0;
        return true;
    }
    else
    {
        if (GetLastError() != ERROR_IO_PENDING)
        {
            closeDeviceOnIOError();
            return false;
        }
    }

    return false;
}

void HIDDevice::closeDevice()
{
    if (ReadRequested)
    {
        HIDManager->Manager->pThread->RemoveOverlappedEvent(this, ReadOverlapped.hEvent);
        ReadRequested = false;
        // Must call this to avoid Win32 assertion; CloseHandle is not enough.
        ::CancelIo(Device);
    }

    ::CloseHandle(ReadOverlapped.hEvent);
    memset(&ReadOverlapped, 0, sizeof(OVERLAPPED));

    ::CloseHandle(Device);
    Device = 0;
}

void HIDDevice::closeDeviceOnIOError()
{
    LogText("OVR::Win32::HIDDevice - Lost connection to '%s'\n", DevDesc.Path.ToCStr());
    closeDevice();
}

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

    return HIDManager->HidD_SetFeature(Device, data, (ULONG) length) != FALSE;
}

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

	return HIDManager->HidD_GetFeature(Device, data, (ULONG) length) != FALSE;
}

void HIDDevice::OnOverlappedEvent(HANDLE hevent)
{
    OVR_UNUSED(hevent);
    OVR_ASSERT(hevent == ReadOverlapped.hEvent);

    if (processReadResult()) 
    {
        // Proceed to read again.
        initializeRead();
    }
}

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

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

bool HIDDevice::OnDeviceMessage(DeviceMessageType messageType, 
								const String& devicePath,
								bool* error)
{

    // Is this the correct device?
    if (DevDesc.Path.CompareNoCase(devicePath) != 0)
    {
        return false;
    }

    if (messageType == DeviceMessage_DeviceAdded && !Device)
    {
        // A closed device has been re-added. Try to reopen.
        if (!openDevice())
        {
            LogError("OVR::Win32::HIDDevice - Failed to reopen a device '%s' that was re-added.\n", devicePath.ToCStr());
			*error = true;
            return true;
        }

        LogText("OVR::Win32::HIDDevice - Reopened device '%s'\n", devicePath.ToCStr());
    }

    HIDHandler::HIDDeviceMessageType handlerMessageType = HIDHandler::HIDDeviceMessage_DeviceAdded;
    if (messageType == DeviceMessage_DeviceAdded)
    {
    }
    else if (messageType == DeviceMessage_DeviceRemoved)
    {
        handlerMessageType = HIDHandler::HIDDeviceMessage_DeviceRemoved;
    }
    else
    {
        OVR_ASSERT(0);		
    }

    if (Handler)
    {
        Handler->OnDeviceMessage(handlerMessageType);
    }

	*error = false;
    return true;
}

HIDDeviceManager* HIDDeviceManager::CreateInternal(Win32::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<Win32::HIDDeviceManager> manager = *new Win32::HIDDeviceManager(devManager);

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

    return manager.GetPtr();
}

} // namespace Win32

//-------------------------------------------------------------------------------------
// ***** 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<Win32::HIDDeviceManager> manager = *new Win32::HIDDeviceManager(NULL);

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

    return manager.GetPtr();
}

} // namespace OVR