aboutsummaryrefslogtreecommitdiff
path: root/hidin/winNT_usb.c
blob: 0e361b78e232578d86f0aa5ec70b23253d25975a (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
/*
  hidin USB HID support stuff for Windows 2000 / XP

  Written by Olaf Matthes <olaf.matthes@gmx.de>

  This file contains the implementation for connecting to USB HID
  (Human Interface Device) devices. It provides several functions
  to open devices and to query information and capabilities. 

*/

#ifdef PD
#include "m_pd.h"	/* we need this because we want to print() to the PD console */
#include <stdio.h>
#else
#include "ext.h"	/* we need this because we want to print() to the Max window */
#endif
#include "hidin.h"


/*
 *  get information for a given device (HANDLE)
 *
 */

void getDeviceInfo(HANDLE deviceHandle)
{
    HIDD_ATTRIBUTES deviceAttributes;
	PWCHAR deviceName;
	ULONG length = 256;

	if(deviceHandle == INVALID_HANDLE_VALUE)
	{
		post("hidin: -- couldn't get device info due to an invalid handle");
		return;
	}

	if (!HidD_GetAttributes (deviceHandle, &deviceAttributes))
	{
		post("hidin: -- failed to get attributes");
		return;
	}
	else
	{
		// post("hidin: ** VendorID: 0x%x", deviceAttributes.VendorID);
		// post("hidin: ** ProductID: 0x%x", deviceAttributes.ProductID);
		// post("hidin: ** VersionNumber: 0x%x", deviceAttributes.VersionNumber);
	}

	deviceName = (PWCHAR)getbytes((short)(length));
 	if(!HidD_GetProductString (deviceHandle, deviceName, length))
	{
		freebytes(deviceName, (short)(length));
		return;
	}
	else
	{
		char name[256];
		int i = 0;
		wcstombs(name, deviceName, length);
		post("hidin: >> opening device: \"%s\"", name);
		freebytes(deviceName, (short)(length));
	}
    return;
}

/*
 *  find name of attached HID devices
 */
t_symbol *findDeviceName(DWORD deviceID)
{
	HANDLE deviceHandle;
	PWCHAR deviceName;
	ULONG length = 256;
	char name[256];	// this will be the return value
	int i = 0;

	deviceHandle = connectDeviceNumber(deviceID);

	if(deviceHandle != INVALID_HANDLE_VALUE)
	{
		deviceName = (PWCHAR)getbytes((short)(length));
 		if(!HidD_GetProductString (deviceHandle, deviceName, length))
		{
			freebytes(deviceName, (short)(length));
			sprintf(name, "Unknown (Device #%d)", deviceID + 1);
			return gensym(name);
		}
		else
		{
			wcstombs(name, deviceName, length);
			freebytes(deviceName, (short)(length));
		}

		CloseHandle(deviceHandle);

	    return gensym(name);
	}
	return gensym("Unsupported Device");
}

/*
 *  find number of attached HID devices
 */
int findHidDevices()
{
    HDEVINFO                            hardwareDeviceInfo;
    SP_INTERFACE_DEVICE_DATA            deviceInfoData;
    ULONG                               i;
    BOOLEAN                             done;
    GUID                                hidGuid;
    PSP_INTERFACE_DEVICE_DETAIL_DATA    functionClassDeviceData = NULL;
    ULONG                               predictedLength = 0;
    ULONG                               requiredLength = 0;
    ULONG								NumberDevices = 0;

    HidD_GetHidGuid (&hidGuid);

    //
    // Open a handle to the plug and play dev node.
    //
    hardwareDeviceInfo = SetupDiGetClassDevs ( &hidGuid,
                                               NULL, // Define no enumerator (global)
                                               NULL, // Define no
                                               (DIGCF_PRESENT | // Only Devices present
                                                DIGCF_DEVICEINTERFACE)); // Function class devices.

    //
    // Take a wild guess to start
    //
    
    NumberDevices = 4;
    done = FALSE;
    deviceInfoData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA);

    i=0;
    while (!done) 
    {
        NumberDevices *= 2;

        for (; i < NumberDevices; i++) 
        {
            if (SetupDiEnumDeviceInterfaces (hardwareDeviceInfo,
                                             0, // No care about specific PDOs
                                             &hidGuid,
                                             i,
                                             &deviceInfoData))
            {
                //
                // allocate a function class device data structure to receive the
                // goods about this particular device.
                //

                SetupDiGetDeviceInterfaceDetail (
                        hardwareDeviceInfo,
                        &deviceInfoData,
                        NULL, // probing so no output buffer yet
                        0, // probing so output buffer length of zero
                        &requiredLength,
                        NULL); // not interested in the specific dev-node


                predictedLength = requiredLength;

                functionClassDeviceData = malloc (predictedLength);
                if (functionClassDeviceData)
                {
                    functionClassDeviceData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);
                }
                else
                {
                    SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);
                    return 0;
                }

                //
                // Retrieve the information from Plug and Play.
                //

                if (! SetupDiGetDeviceInterfaceDetail (
                           hardwareDeviceInfo,
                           &deviceInfoData,
                           functionClassDeviceData,
                           predictedLength,
                           &requiredLength,
                           NULL)) 
                {
                    SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);
                    return 0;
                }
				//
				// get name of device
				//
				// HidDevices[i] = getbytes(1024 * sizeof(char));
            } 
            else
            {
                if (ERROR_NO_MORE_ITEMS == GetLastError()) 
                {
                    done = TRUE;
                    break;
                }
            }
        }
    }

    SetupDiDestroyDeviceInfoList (hardwareDeviceInfo);

    return (i);		// return number of devices
}


/*
 *  connect to Ith USB device (count starting with 0)
 */

HANDLE connectDeviceNumber(DWORD deviceIndex)
{
    GUID hidGUID;
    HDEVINFO hardwareDeviceInfoSet;
    SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
    PSP_INTERFACE_DEVICE_DETAIL_DATA deviceDetail;
    ULONG requiredSize;
    HANDLE deviceHandle = INVALID_HANDLE_VALUE;
    DWORD result;

    //Get the HID GUID value - used as mask to get list of devices
    HidD_GetHidGuid (&hidGUID);

    //Get a list of devices matching the criteria (hid interface, present)
    hardwareDeviceInfoSet = SetupDiGetClassDevs (&hidGUID,
                                                 NULL, // Define no enumerator (global)
                                                 NULL, // Define no
                                                 (DIGCF_PRESENT | // Only Devices present
                                                 DIGCF_DEVICEINTERFACE)); // Function class devices.

    deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

    //Go through the list and get the interface data
    result = SetupDiEnumDeviceInterfaces (hardwareDeviceInfoSet,
                                          NULL, //infoData,
                                          &hidGUID, //interfaceClassGuid,
                                          deviceIndex, 
                                          &deviceInterfaceData);

    /* Failed to get a device - possibly the index is larger than the number of devices */
    if (result == FALSE)
    {
        SetupDiDestroyDeviceInfoList (hardwareDeviceInfoSet);
		post("hidin: -- failed to get specified device number");
        return INVALID_HANDLE_VALUE;
    }

    //Get the details with null values to get the required size of the buffer
    SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfoSet,
                                     &deviceInterfaceData,
                                     NULL, //interfaceDetail,
                                     0, //interfaceDetailSize,
                                     &requiredSize,
                                     0); //infoData))

    //Allocate the buffer
    deviceDetail = (PSP_INTERFACE_DEVICE_DETAIL_DATA)malloc(requiredSize);
    deviceDetail->cbSize = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA);

    //Fill the buffer with the device details
    if (!SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfoSet,
                                          &deviceInterfaceData,
                                          deviceDetail,
                                          requiredSize,
                                          &requiredSize,
                                          NULL)) 
    {
        SetupDiDestroyDeviceInfoList (hardwareDeviceInfoSet);
        free (deviceDetail);
		post("hidin: -- failed to get device info");
        return INVALID_HANDLE_VALUE;
    }

#if 1
    //Open file on the device (read only)
	deviceHandle = CreateFile 
					(deviceDetail->DevicePath,
					GENERIC_READ,
					FILE_SHARE_READ|FILE_SHARE_WRITE,
					(LPSECURITY_ATTRIBUTES)NULL,
					OPEN_EXISTING,
					FILE_FLAG_OVERLAPPED,
					NULL);
#else
    //Open file on the device (read & write)
	deviceHandle = CreateFile 
					(deviceDetail->DevicePath, 
					GENERIC_READ|GENERIC_WRITE, 
					FILE_SHARE_READ|FILE_SHARE_WRITE, 
					(LPSECURITY_ATTRIBUTES)NULL,
					OPEN_EXISTING, 
					FILE_FLAG_OVERLAPPED, // was 0
					NULL);
#endif

	if(deviceHandle == INVALID_HANDLE_VALUE)
	{
		int err = GetLastError();
		LPVOID lpMsgBuf;
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL);
		post("hidin: -- could not get device #%i: %s", deviceIndex + 1, (LPCTSTR)lpMsgBuf);
		if(err == ERROR_ACCESS_DENIED)
			post("hidin: -- can not read from mouse and keyboard");
		LocalFree(lpMsgBuf);
 	}

    SetupDiDestroyDeviceInfoList (hardwareDeviceInfoSet);
    free (deviceDetail);
    return deviceHandle;
}

/*
 *  connect to USB device specified through VendorID, ProductID and VersionNumber
 *
 */

HANDLE connectDeviceName(DWORD *vendorID, DWORD *productID, DWORD *versionNumber)
{
    HANDLE deviceHandle = INVALID_HANDLE_VALUE;
    DWORD index = 0;
    HIDD_ATTRIBUTES deviceAttributes;
    BOOL matched = FALSE;

    while (!matched && (deviceHandle = connectDeviceNumber(index)) != INVALID_HANDLE_VALUE)
    {
        if (!HidD_GetAttributes (deviceHandle, &deviceAttributes))
            return INVALID_HANDLE_VALUE;

        if ((vendorID == 0 || deviceAttributes.VendorID == *vendorID) &&
            (productID == 0 || deviceAttributes.ProductID == *productID) &&
            (versionNumber == 0 || deviceAttributes.VersionNumber == *versionNumber))
            return deviceHandle; /* matched */
        
        CloseHandle (deviceHandle); /* not a match - close and try again */

        index++;
    }

    return INVALID_HANDLE_VALUE;
}


/*
 *  get device capabilities
 *
 */
void getDeviceCapabilities(t_hid_device *hid)
{
	// Get the Capabilities structure for the device.
	PHIDP_PREPARSED_DATA	preparsedData;
	HIDP_CAPS		        capabilities;

	if(hid->device == INVALID_HANDLE_VALUE)
	{
		post("hidin: -- couldn't get device capabilities due to an invalid handle");
		return;
	}

	/*
		API function: HidD_GetPreparsedData
		Returns: a pointer to a buffer containing the information about the device's capabilities.
		Requires: A handle returned by CreateFile.
		There's no need to access the buffer directly,
		but HidP_GetCaps and other API functions require a pointer to the buffer.
	*/

	HidD_GetPreparsedData(hid->device, &preparsedData);

	/* get the device attributes */
    // HidD_GetAttributes (hid->device, &hid->attributes);

	/*
		API function: HidP_GetCaps
		Learn the device's capabilities.
		For standard devices such as joysticks, you can find out the specific
		capabilities of the device.
		For a custom device, the software will probably know what the device is capable of,
		and the call only verifies the information.
		Requires: the pointer to the buffer returned by HidD_GetPreparsedData.
		Returns: a Capabilities structure containing the information.
	*/
	
	HidP_GetCaps(preparsedData, &capabilities);

	// Display the capabilities

	hid->caps = capabilities;
	hid->ppd = preparsedData;
	// No need for PreparsedData any more, so free the memory it's using.
	// HidD_FreePreparsedData(preparsedData);
}

/*
 *  Given a struct _hid_device, obtain a read report and unpack the values
 *  into the InputData array.
 */
int readHid(t_hid_device *hidDevice)
{
	long value = 0, ret;
	long bytesRead;

    if(!ReadFile(hidDevice->device,
                 hidDevice->inputReportBuffer,
                 hidDevice->caps.InputReportByteLength,
                 &bytesRead,
                 NULL)) 
    {
		int err = GetLastError();
		LPVOID lpMsgBuf;
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL);
		post("hidin: -- could not read from device: %s", (LPCTSTR)lpMsgBuf);
		LocalFree(lpMsgBuf);
        return 0;
    }
	// we need: bytesRead == hidDevice->caps.InputReportByteLength

    return bytesRead;
}

/*
 *  Given a struct _hid_device, obtain a read report and unpack the values
 *  into the InputData array.
 */
int readHidOverlapped(t_hid_device *hidDevice)
{
	long value = 0, ret;
	long bytesRead;

    if(!ReadFile(hidDevice->device,
                 hidDevice->inputReportBuffer,
                 hidDevice->caps.InputReportByteLength,
                 &bytesRead,
                 (LPOVERLAPPED) &hidDevice->overlapped)) 
    {
        return 0;
    }
    return bytesRead;
}



BOOLEAN getFeature (t_hid_device *HidDevice)
/*++
RoutineDescription:
   Given a struct _HID_DEVICE, fill in the feature data structures with
   all features on the device.  May issue multiple HidD_GetFeature() calls to
   deal with multiple report IDs.
--*/
{
    ULONG     Index;
    t_hid_data *pData;
    BOOLEAN   FeatureStatus;
    BOOLEAN   Status;

    /*
    // As with writing data, the IsDataSet value in all the structures should be
    //    set to FALSE to indicate that the value has yet to have been set
    */

    pData = HidDevice->featureData;

    for (Index = 0; Index < HidDevice->featureDataLength; Index++, pData++) 
    {
        pData->IsDataSet = FALSE;
    }

    /*
    // Next, each structure in the HID_DATA buffer is filled in with a value
    //   that is retrieved from one or more calls to HidD_GetFeature.  The 
    //   number of calls is equal to the number of reportIDs on the device
    */

    Status = TRUE; 
    pData = HidDevice->featureData;

    for (Index = 0; Index < HidDevice->featureDataLength; Index++, pData++) 
    {
        /*
        // If a value has yet to have been set for this structure, build a report
        //    buffer with its report ID as the first byte of the buffer and pass
        //    it in the HidD_GetFeature call.  Specifying the report ID in the
        //    first specifies which report is actually retrieved from the device.
        //    The rest of the buffer should be zeroed before the call
        */

        if (!pData->IsDataSet) 
        {
            memset(HidDevice->featureReportBuffer, 0x00, HidDevice->caps.FeatureReportByteLength);

            HidDevice->featureReportBuffer[0] = (UCHAR) pData -> ReportID;

            FeatureStatus = HidD_GetFeature (HidDevice->device,
                                              HidDevice->featureReportBuffer,
                                              HidDevice->caps.FeatureReportByteLength);

            /*
            // If the return value is TRUE, scan through the rest of the HID_DATA
            //    structures and fill whatever values we can from this report
            */


            if (FeatureStatus) 
            {
                FeatureStatus = unpackReport ( HidDevice->featureReportBuffer,
                                           HidDevice->caps.FeatureReportByteLength,
                                           HidP_Feature,
                                           HidDevice->featureData,
                                           HidDevice->featureDataLength,
                                           HidDevice->ppd);
            }

            Status = Status && FeatureStatus;
        }
   }

   return (Status);
}


BOOLEAN
unpackReport (
   PCHAR                ReportBuffer,
   USHORT               ReportBufferLength,
   HIDP_REPORT_TYPE     ReportType,
   t_hid_data           *Data,
   ULONG                DataLength,
   PHIDP_PREPARSED_DATA Ppd
)
/*++
Routine Description:
   Given ReportBuffer representing a report from a HID device where the first
   byte of the buffer is the report ID for the report, extract all the HID_DATA
   in the Data list from the given report.
--*/
{
    ULONG       numUsages; // Number of usages returned from GetUsages.
    ULONG       i;
    UCHAR       reportID;
    ULONG       Index;
    ULONG       nextUsage;

    reportID = ReportBuffer[0];

    for (i = 0; i < DataLength; i++, Data++) 
    {
        if (reportID == Data->ReportID) 
        {
            if (Data->IsButtonData) 
            {
                numUsages = Data->ButtonData.MaxUsageLength;

                Data->Status = HidP_GetUsages (ReportType,
                                               Data->UsagePage,
                                               0, // All collections
                                               Data->ButtonData.Usages,
                                               &numUsages,
                                               Ppd,
                                               ReportBuffer,
                                               ReportBufferLength);


                //
                // Get usages writes the list of usages into the buffer
                // Data->ButtonData.Usages newUsage is set to the number of usages
                // written into this array.
                // A usage cannot not be defined as zero, so we'll mark a zero
                // following the list of usages to indicate the end of the list of
                // usages
                //
                // NOTE: One anomaly of the GetUsages function is the lack of ability
                //        to distinguish the data for one ButtonCaps from another
                //        if two different caps structures have the same UsagePage
                //        For instance:
                //          Caps1 has UsagePage 07 and UsageRange of 0x00 - 0x167
                //          Caps2 has UsagePage 07 and UsageRange of 0xe0 - 0xe7
                //
                //        However, calling GetUsages for each of the data structs
                //          will return the same list of usages.  It is the 
                //          responsibility of the caller to set in the HID_DEVICE
                //          structure which usages actually are valid for the
                //          that structure. 
                //      

                /*
                // Search through the usage list and remove those that 
                //    correspond to usages outside the define ranged for this
                //    data structure.
                */
                
                for (Index = 0, nextUsage = 0; Index < numUsages; Index++) 
                {
                    if (Data->ButtonData.UsageMin <= Data->ButtonData.Usages[Index] &&
                            Data -> ButtonData.Usages[Index] <= Data->ButtonData.UsageMax) 
                    {
                        Data->ButtonData.Usages[nextUsage++] = Data->ButtonData.Usages[Index];
                        
                    }
                }

                if (nextUsage < Data -> ButtonData.MaxUsageLength) 
                {
                    Data->ButtonData.Usages[nextUsage] = 0;
                }
            }
            else 
            {
                Data->Status = HidP_GetUsageValue (
                                                ReportType,
                                                Data->UsagePage,
                                                0,               // All Collections.
                                                Data->ValueData.Usage,
                                                &Data->ValueData.Value,
                                                Ppd,
                                                ReportBuffer,
                                                ReportBufferLength);

                Data->Status = HidP_GetScaledUsageValue (
                                                       ReportType,
                                                       Data->UsagePage,
                                                       0, // All Collections.
                                                       Data->ValueData.Usage,
                                                       &Data->ValueData.ScaledValue,
                                                       Ppd,
                                                       ReportBuffer,
                                                       ReportBufferLength);
            } 
            Data->IsDataSet = TRUE;
        }
    }
    return (TRUE);
}


BOOLEAN
packReport (
   PCHAR                ReportBuffer,
   USHORT               ReportBufferLength,
   HIDP_REPORT_TYPE     ReportType,
   t_hid_data           *Data,
   ULONG                DataLength,
   PHIDP_PREPARSED_DATA Ppd
   )
/*++
Routine Description:
   This routine takes in a list of HID_DATA structures (DATA) and builds 
      in ReportBuffer the given report for all data values in the list that 
      correspond to the report ID of the first item in the list.  

   For every data structure in the list that has the same report ID as the first
      item in the list will be set in the report.  Every data item that is 
      set will also have it's IsDataSet field marked with TRUE.

   A return value of FALSE indicates an unexpected error occurred when setting
      a given data value.  The caller should expect that assume that no values
      within the given data structure were set.

   A return value of TRUE indicates that all data values for the given report
      ID were set without error.
--*/
{
    ULONG       numUsages; // Number of usages to set for a given report.
    ULONG       i;
    ULONG       CurrReportID;

    /*
    // All report buffers that are initially sent need to be zero'd out
    */

    memset (ReportBuffer, (UCHAR) 0, ReportBufferLength);

    /*
    // Go through the data structures and set all the values that correspond to
    //   the CurrReportID which is obtained from the first data structure 
    //   in the list
    */

    CurrReportID = Data -> ReportID;

    for (i = 0; i < DataLength; i++, Data++) 
    {
        /*
        // There are two different ways to determine if we set the current data
        //    structure: 
        //    1) Store the report ID were using and only attempt to set those
        //        data structures that correspond to the given report ID.  This
        //        example shows this implementation.
        //
        //    2) Attempt to set all of the data structures and look for the 
        //        returned status value of HIDP_STATUS_INVALID_REPORT_ID.  This 
        //        error code indicates that the given usage exists but has a 
        //        different report ID than the report ID in the current report 
        //        buffer
        */

        if (Data -> ReportID == CurrReportID) 
        {
            if (Data->IsButtonData) 
            {
                numUsages = Data->ButtonData.MaxUsageLength;
                Data->Status = HidP_SetUsages (ReportType,
                                               Data->UsagePage,
                                               0, // All collections
                                               Data->ButtonData.Usages,
                                               &numUsages,
                                               Ppd,
                                               ReportBuffer,
                                               ReportBufferLength);
            }
            else
            {
                Data->Status = HidP_SetUsageValue (ReportType,
                                                   Data->UsagePage,
                                                   0, // All Collections.
                                                   Data->ValueData.Usage,
                                                   Data->ValueData.Value,
                                                   Ppd,
                                                   ReportBuffer,
                                                   ReportBufferLength);
            }

            if (HIDP_STATUS_SUCCESS != Data->Status)
            {
                return FALSE;
            }
        }
    }   

    /*
    // At this point, all data structures that have the same ReportID as the
    //    first one will have been set in the given report.  Time to loop 
    //    through the structure again and mark all of those data structures as
    //    having been set.
    */

    for (i = 0; i < DataLength; i++, Data++) 
    {
        if (CurrReportID == Data -> ReportID)
        {
            Data -> IsDataSet = TRUE;
        }
    }
    return (TRUE);
}