+/rtos

git clone https://git.julia.blue/+/rtos

Joseph RyanRe-add usblib files83915e3

master
76.3 KiB2308 linesraw
1//*****************************************************************************
2//
3// usbdhid.c - USB HID device class driver.
4//
5// Copyright (c) 2008-2017 Texas Instruments Incorporated.  All rights reserved.
6// Software License Agreement
7//
8// Texas Instruments (TI) is supplying this software for use solely and
9// exclusively on TI's microcontroller products. The software is owned by
10// TI and/or its suppliers, and is protected under applicable copyright
11// laws. You may not combine this software with "viral" open-source
12// software in order to form a larger program.
13//
14// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
15// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
16// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
18// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
19// DAMAGES, FOR ANY REASON WHATSOEVER.
20//
21// This is part of revision 2.1.4.178 of the Tiva USB Library.
22//
23//*****************************************************************************
24
25#include "usblib/device/usbdhid.h"
26#include "tivaware/hw_memmap.h"
27#include "tivaware/hw_types.h"
28#include "tivaware/rom.h"
29#include "tivaware/rom_map.h"
30#include "tivaware/usb.h"
31#include "usblib/device/usbdevice.h"
32#include "usblib/usbhid.h"
33#include "usblib/usblib.h"
34#include "usblib/usblibpriv.h"
35#include <stdbool.h>
36#include <stdint.h>
37
38#define ASSERT(X)
39
40//*****************************************************************************
41//
42//! \addtogroup hid_device_class_api
43//! @{
44//
45//*****************************************************************************
46
47//*****************************************************************************
48//
49// The subset of endpoint status flags that we consider to be reception
50// errors.  These are passed to the client via USB_EVENT_ERROR if seen.
51//
52//*****************************************************************************
53#define USB_RX_ERROR_FLAGS                                                     \
54    (USBERR_DEV_RX_DATA_ERROR | USBERR_DEV_RX_OVERRUN | USBERR_DEV_RX_FIFO_FULL)
55
56//*****************************************************************************
57//
58// Marker used to indicate that a given HID descriptor cannot be found in the
59// client-supplied list.
60//
61//*****************************************************************************
62#define HID_NOT_FOUND 0xFFFFFFFF
63
64//*****************************************************************************
65//
66// Flags that may appear in ui16DeferredOpFlags to indicate some operation that
67// has been requested but could not be processed at the time it was received.
68// Each deferred operation is defined as the bit number that should be set in
69// tHIDInstance->ui16DeferredOpFlags to indicate that the operation is pending.
70//
71//*****************************************************************************
72#define HID_DO_PACKET_RX 5
73#define HID_DO_SEND_IDLE_REPORT 6
74
75//*****************************************************************************
76//
77// Endpoints to use for each of the required endpoints in the driver.
78//
79//*****************************************************************************
80#define INT_IN_ENDPOINT USB_EP_3
81#define INT_OUT_ENDPOINT USB_EP_3
82
83//*****************************************************************************
84//
85// Device Descriptor.  This is stored in RAM to allow several fields to be
86// changed at runtime based on the client's requirements.
87//
88//*****************************************************************************
89uint8_t g_pui8HIDDeviceDescriptor[] = {
90    18,                    // Size of this structure.
91    USB_DTYPE_DEVICE,      // Type of this structure.
92    USBShort(0x110),       // USB version 1.1 (if we say 2.0, hosts assume
93                           // high-speed - see USB 2.0 spec 9.2.6.6)
94    USB_CLASS_DEVICE,      // USB Device Class
95    0,                     // USB Device Sub-class
96    USB_HID_PROTOCOL_NONE, // USB Device protocol
97    USBDHID_MAX_PACKET,    // Maximum packet size for default pipe.
98    USBShort(0),           // Vendor ID (VID).
99    USBShort(0),           // Product ID (PID).
100    USBShort(0x100),       // Device Version BCD.
101    1,                     // Manufacturer string identifier.
102    2,                     // Product string identifier.
103    3,                     // Product serial number.
104    1                      // Number of configurations.
105};
106
107//*****************************************************************************
108//
109// Forward references for device handler callbacks
110//
111//*****************************************************************************
112static void HandleGetDescriptor(void* pvHIDInstance, tUSBRequest* psUSBRequest);
113static void HandleRequest(void* pvHIDInstance, tUSBRequest* psUSBRequest);
114static void HandleConfigChange(void* pvHIDInstance, uint32_t ui32Info);
115static void HandleEP0DataReceived(void* pvHIDInstance, uint32_t ui32Info);
116static void HandleEP0DataSent(void* pvHIDInstance, uint32_t ui32Info);
117static void HandleReset(void* pvHIDInstance);
118static void HandleSuspend(void* pvHIDInstance);
119static void HandleResume(void* pvHIDInstance);
120static void HandleDisconnect(void* pvHIDInstance);
121static void HandleEndpoints(void* pvHIDInstance, uint32_t ui32Status);
122static void HandleDevice(void* pvHIDInstance, uint32_t ui32Request,
123                         void* pvRequestData);
124
125//*****************************************************************************
126//
127// The device information structure for the USB HID devices.
128//
129//*****************************************************************************
130const tCustomHandlers g_sHIDHandlers = {
131    //
132    // GetDescriptor
133    //
134    HandleGetDescriptor,
135
136    //
137    // RequestHandler
138    //
139    HandleRequest,
140
141    //
142    // InterfaceChange
143    //
144    0,
145
146    //
147    // ConfigChange
148    //
149    HandleConfigChange,
150
151    //
152    // DataReceived
153    //
154    HandleEP0DataReceived,
155
156    //
157    // DataSentCallback
158    //
159    HandleEP0DataSent,
160
161    //
162    // ResetHandler
163    //
164    HandleReset,
165
166    //
167    // SuspendHandler
168    //
169    HandleSuspend,
170
171    //
172    // ResumeHandler
173    //
174    HandleResume,
175
176    //
177    // DisconnectHandler
178    //
179    HandleDisconnect,
180
181    //
182    // EndpointHandler
183    //
184    HandleEndpoints,
185
186    //
187    // Device handler.
188    //
189    HandleDevice};
190
191//*****************************************************************************
192//
193// Set or clear deferred operation flags in an "atomic" manner.
194//
195// \param pui16DeferredOp points to the flags variable which is to be modified.
196// \param ui16Bit indicates which bit number is to be set or cleared.
197// \param bSet indicates the state that the flag must be set to.  If \b true,
198// the flag is set, if \b false, the flag is cleared.
199//
200// This function safely sets or clears a bit in a flag variable.  The operation
201// makes use of bitbanding to ensure that the operation is atomic (no read-
202// modify-write is required).
203//
204// \return None.
205//
206//*****************************************************************************
207static void SetDeferredOpFlag(volatile uint16_t* pui16DeferredOp,
208                              uint16_t ui16Bit, bool bSet) {
209    //
210    // Set the flag bit to 1 or 0 using a bitband access.
211    //
212    HWREGBITH(pui16DeferredOp, ui16Bit) = bSet ? 1 : 0;
213}
214
215//*****************************************************************************
216//
217// This function is called to clear the counter used to keep track of the time
218// elapsed since a given report was last sent.
219//
220// \param psHIDDevice points to the HID device structure whose report timer is
221// to be cleared.
222// \param ui8ReportID is the first byte of the report to be sent.  If this
223// device offers more than one input report, this value is used to find the
224// relevant report timer structure in the psHIDDevice structure.
225//
226// \return None.
227//
228//*****************************************************************************
229static void ClearReportTimer(const tUSBDHIDDevice* psHIDDevice,
230                             uint8_t ui8ReportID) {
231    uint32_t ui32Loop;
232
233    if (psHIDDevice->ui8NumInputReports > 1) {
234        //
235        // We have more than 1 input report so the report must begin with a
236        // byte containing the report ID.  Scan the table we were provided
237        // when the device was initialized to find the entry for this report.
238        //
239        for (ui32Loop = 0; ui32Loop < psHIDDevice->ui8NumInputReports;
240             ui32Loop++) {
241            if (psHIDDevice->psReportIdle[ui32Loop].ui8ReportID ==
242                ui8ReportID) {
243                break;
244            }
245        }
246    } else {
247        ui32Loop = 0;
248    }
249
250    //
251    // If we drop out of the loop with an index less than ui8NumInputReports,
252    // we found the relevant report so clear its timer.
253    //
254    if (ui32Loop < psHIDDevice->ui8NumInputReports) {
255        psHIDDevice->psReportIdle[ui32Loop].ui32TimeSinceReportmS = 0;
256    }
257}
258
259//*****************************************************************************
260//
261// This function is called to clear the idle period timers for each input
262// report supported by the device.
263//
264// \param psHIDDevice points to the HID device structure whose timers are to be
265// cleared.
266// \param ui32TimemS is the elapsed time in milliseconds since the last call
267// to this function.
268//
269// \return None.
270//
271//*****************************************************************************
272static void ClearIdleTimers(const tUSBDHIDDevice* psHIDDevice) {
273    uint32_t ui32Loop;
274
275    //
276    // Clear the "time till next report" counters for each input report.
277    //
278    for (ui32Loop = 0; ui32Loop < psHIDDevice->ui8NumInputReports; ui32Loop++) {
279        psHIDDevice->psReportIdle[ui32Loop].ui16TimeTillNextmS =
280            psHIDDevice->psReportIdle[ui32Loop].ui8Duration4mS * 4;
281    }
282}
283
284//*****************************************************************************
285//
286// This function is called periodically to allow us to process the report idle
287// timers.
288//
289// \param psHIDDevice points to the HID device structure whose timers are to be
290// updated.
291// \param ui32ElapsedmS indicates the number of milliseconds that have elapsed
292// since the last call to this function.
293//
294// \return None.
295//
296//*****************************************************************************
297static void ProcessIdleTimers(const tUSBDHIDDevice* psHIDDevice,
298                              uint32_t ui32ElapsedmS) {
299    uint32_t ui32Loop, ui32SizeReport;
300    void* pvReport;
301    tHIDInstance* psInst;
302    bool bDeferred;
303
304    //
305    // Get our instance data pointer
306    //
307    psInst = &((tUSBDHIDDevice*)psHIDDevice)->sPrivateData;
308
309    //
310    // We have not had to defer any report transmissions yet.
311    //
312    bDeferred = false;
313
314    //
315    // Look at each of the input report idle timers in turn.
316    //
317    for (ui32Loop = 0; ui32Loop < psHIDDevice->ui8NumInputReports; ui32Loop++) {
318        //
319        // Update the time since the last report was sent.
320        //
321        psHIDDevice->psReportIdle[ui32Loop].ui32TimeSinceReportmS +=
322            ui32ElapsedmS;
323
324        //
325        // Is this timer running?
326        //
327        if (psHIDDevice->psReportIdle[ui32Loop].ui8Duration4mS) {
328            //
329            // Yes - is it about to expire?
330            //
331            if (psHIDDevice->psReportIdle[ui32Loop].ui16TimeTillNextmS <=
332                ui32ElapsedmS) {
333                //
334                // The timer is about to expire.  Can we send a report right
335                // now?
336                //
337                if ((psInst->iHIDTxState == eHIDStateIdle) &&
338                    (psInst->bSendInProgress == false)) {
339                    //
340                    // We can send a report so send a message to the
341                    // application to retrieve its latest report for
342                    // transmission to the host.
343                    //
344                    ui32SizeReport = psHIDDevice->pfnRxCallback(
345                        psHIDDevice->pvRxCBData, USBD_HID_EVENT_IDLE_TIMEOUT,
346                        psHIDDevice->psReportIdle[ui32Loop].ui8ReportID,
347                        &pvReport);
348
349                    //
350                    // Schedule the report for transmission.
351                    //
352                    USBDHIDReportWrite((void*)psHIDDevice, pvReport,
353                                       ui32SizeReport, true);
354
355                    //
356                    // Reload the timer for the next period.
357                    //
358                    psHIDDevice->psReportIdle[ui32Loop].ui16TimeTillNextmS =
359                        psHIDDevice->psReportIdle[ui32Loop].ui8Duration4mS * 4;
360                } else {
361                    //
362                    // We can't send the report straight away so flag it for
363                    // transmission as soon as the previous transmission ends.
364                    //
365                    psHIDDevice->psReportIdle[ui32Loop].ui16TimeTillNextmS = 0;
366                    bDeferred = true;
367                }
368            } else {
369                //
370                // The timer is not about to expire.  Update the time till the
371                // next report transmission.
372                //
373                psHIDDevice->psReportIdle[ui32Loop].ui16TimeTillNextmS -=
374                    ui32ElapsedmS;
375            }
376        }
377    }
378
379    //
380    // If we had to defer transmission of any report, remember this so that we
381    // will process it as soon as possible.
382    //
383    SetDeferredOpFlag(&psInst->ui16DeferredOpFlags, HID_DO_SEND_IDLE_REPORT,
384                      bDeferred);
385}
386
387static void SetIdleTimeout(const tUSBDHIDDevice* psHIDDevice,
388                           uint8_t ui8ReportID, uint8_t ui8Timeout4mS) {
389    uint32_t ui32Loop;
390    bool bReportNeeded;
391    tHIDReportIdle* psIdle;
392
393    //
394    // Remember that we have not found any report that needs to be sent
395    // immediately.
396    //
397    bReportNeeded = false;
398
399    //
400    // Search through all the input reports looking for ones that fit the
401    // requirements.
402    //
403    for (ui32Loop = 0; ui32Loop < psHIDDevice->ui8NumInputReports; ui32Loop++) {
404        psIdle = &psHIDDevice->psReportIdle[ui32Loop];
405
406        //
407        // If the report ID passed matches the report ID in the idle timer
408        // control structure or we were passed a report ID of zero, which
409        // indicates that all timers are to be set...
410        //
411        if (!ui8ReportID || (ui8ReportID == psIdle->ui8ReportID)) {
412            //
413            // Save the new duration for the idle timer.
414            //
415            psIdle->ui8Duration4mS = ui8Timeout4mS;
416
417            //
418            // Are we enabling the idle timer?  If so, fix up the time until it
419            // needs to fire.
420            //
421            if (ui8Timeout4mS) {
422                //
423                // Determine what the timeout is for this report given the time
424                // since the last report of this type was sent.
425                //
426                if (psIdle->ui32TimeSinceReportmS >=
427                    ((uint32_t)ui8Timeout4mS * 4)) {
428                    psIdle->ui16TimeTillNextmS = 0;
429                    bReportNeeded = true;
430                } else {
431                    psIdle->ui16TimeTillNextmS =
432                        (((uint16_t)ui8Timeout4mS * 4) -
433                         psIdle->ui32TimeSinceReportmS);
434                }
435            }
436        }
437    }
438
439    //
440    // If we get to here and bReportNeeded is true, this means we need to
441    // send back at least one of the input reports as soon as possible.  Try
442    // to do this immediately.
443    //
444    if (bReportNeeded) {
445        ProcessIdleTimers(psHIDDevice, 0);
446    }
447}
448
449//*****************************************************************************
450//
451// Find the idle timeout for a given HID input report.
452//
453// \param psHIDDevice points to the HID device whose report idle timeout is to
454// be found.
455// \param ui8ReportID identifies the report whose timeout is requested.  If 0,
456// the timeout for the first report is returns, regardless of its ID (or
457// whether it has one).
458//
459// This function returns the current idle timeout for a given HID input report.
460// The value returned is expressed in terms of 4mS intervals.  Convert to
461// milliseconds by multiplying by 4.  If the return value is 0, this indicates
462// that an infinite timeout is currently set and the device will not send the
463// report unless a state change occurs.
464//
465// \return Returns the current idle timeout for the given report.
466//
467//*****************************************************************************
468static uint32_t GetIdleTimeout(const tUSBDHIDDevice* psHIDDevice,
469                               uint8_t ui8ReportID) {
470    uint32_t ui32Loop;
471    tHIDReportIdle* psIdle;
472
473    //
474    // Search through all the input reports looking for ones that fit the
475    // requirements.
476    //
477    for (ui32Loop = 0; ui32Loop < psHIDDevice->ui8NumInputReports; ui32Loop++) {
478        psIdle = &psHIDDevice->psReportIdle[ui32Loop];
479
480        //
481        // If the report ID passed matches the report ID in the idle timer
482        // control structure or we were passed a report ID of zero, which
483        // indicates that all timers are to be set...
484        //
485        if (!ui8ReportID || (ui8ReportID == psIdle->ui8ReportID)) {
486            //
487            // We found a report matching the required ID or we were not passed
488            // an ID and we are looking at the first report information.
489            //
490            return ((uint32_t)psIdle->ui8Duration4mS);
491        }
492    }
493
494    //
495    // If we drop out, the report could not be found so we need to indicate
496    // an error.
497    //
498    return (HID_NOT_FOUND);
499}
500
501//*****************************************************************************
502//
503// Find the n-th HID class descriptor of a given type in the client-provided
504// descriptor table.
505//
506// \param psHIDDevice points to the HID device which is to be searched for the
507// required class descriptor.
508// \param ui8Type is the type of class descriptor being requested.  This will
509// be either USB_HID_DTYPE_REPORT or USB_HID_DTYPE_PHYSICAL.
510// \param ui32Index is the zero-based index of the descriptor that is being
511// requested.
512//
513// This function parses the supplied HID descriptor to find the index into the
514// sClassDescriptor array that corresponds to the requested descriptor.  If
515// a descriptor with the requested index does not exist, HID_NOT_FOUND will be
516// returned unless the request is for a physical descriptor and at least one
517// such descriptor exists.  In this case, the index returned will be for the
518// last physical descriptor (as required by the HID spec 7.1.1).
519//
520// \return Returns the index of the descriptor within the sClassDescriptor
521// of the tHIDDevice structure if found or HID_NOT_FOUND otherwise.
522//
523//*****************************************************************************
524static uint32_t FindHIDDescriptor(const tUSBDHIDDevice* psHIDDevice,
525                                  uint8_t ui8Type, uint32_t ui32Index,
526                                  uint32_t* pui32Len) {
527    bool bFoundType;
528    uint32_t ui32Loop, ui32Count, ui32LastFound;
529    const tHIDClassDescriptorInfo* psDesc;
530
531    //
532    // Remember that we have not found any descriptor with a matching type yet.
533    //
534    bFoundType = false;
535    ui32Count = 0;
536    ui32LastFound = 0;
537
538    //
539    // Walk through all the class descriptors looking for the one which
540    // matches the requested index and type.
541    //
542    for (ui32Loop = 0; ui32Loop < psHIDDevice->psHIDDescriptor->bNumDescriptors;
543         ui32Loop++) {
544        psDesc = &(psHIDDevice->psHIDDescriptor->sClassDescriptor[ui32Loop]);
545        if (psDesc->bDescriptorType == ui8Type) {
546            //
547            // We found a descriptor of the correct type.  Is this the
548            // correct index?
549            //
550            bFoundType = true;
551
552            //
553            // Is this the descriptor we are looking for?
554            //
555            if (ui32Count == ui32Index) {
556                //
557                // Yes - we found it so return the index and size to the
558                // caller.
559                //
560                *pui32Len = (uint32_t)psDesc->wDescriptorLength;
561                return (ui32Loop);
562            } else {
563                //
564                // Update our count and keep looking.  Remember where we were
565                // when we found this descriptor in case we need to return the
566                // last physical descriptor.
567                //
568                ui32Count++;
569                ui32LastFound = ui32Loop;
570            }
571        }
572    }
573
574    //
575    // If we drop out, we did not find the requested descriptor.  Now handle
576    // the special case of a physical descriptor - if we found any physical
577    // descriptors, return the last one.
578    //
579    if ((ui8Type == USB_HID_DTYPE_PHYSICAL) && bFoundType) {
580        //
581        // Get the length of the last descriptor we found.
582        //
583        psDesc =
584            &(psHIDDevice->psHIDDescriptor->sClassDescriptor[ui32LastFound]);
585        *pui32Len = (uint32_t)psDesc->wDescriptorLength;
586
587        //
588        // Return the index to the caller.
589        //
590        return (ui32LastFound);
591    } else {
592        //
593        // We could not find the descriptor so return an appropriate error.
594        //
595        return (HID_NOT_FOUND);
596    }
597}
598
599//*****************************************************************************
600//
601// Schedule transmission of the next packet forming part of an input report.
602//
603// \param psHIDInst points to the HID device instance whose input report is to
604// be sent.
605//
606// This function is called to transmit the next packet of an input report
607// passed to the driver via a call to USBDHIDReportWrite.  If any data remains
608// to be sent, a USB packet is written to the FIFO and scheduled for
609// transmission to the host.  The function ensures that reports are sent as
610// a sequence of full packets followed by either a single int16_t packet or a
611// packet with no data to indicate the end of the transaction.
612//
613//*****************************************************************************
614static int32_t ScheduleReportTransmission(tHIDInstance* psHIDInst) {
615    uint32_t ui32NumBytes;
616    uint8_t* pui8Data;
617    int32_t i32Retcode;
618
619    //
620    // Set the number of bytes to send this iteration.
621    //
622    ui32NumBytes =
623        (uint32_t)(psHIDInst->ui16InReportSize - psHIDInst->ui16InReportIndex);
624
625    //
626    // Limit individual transfers to the maximum packet size for the endpoint.
627    //
628    if (ui32NumBytes > USBDHID_MAX_PACKET) {
629        ui32NumBytes = USBDHID_MAX_PACKET;
630    }
631
632    //
633    // Where are we sending this data from?
634    //
635    pui8Data = psHIDInst->pui8InReportData + psHIDInst->ui16InReportIndex;
636
637    //
638    // Put the data in the correct FIFO.
639    //
640    i32Retcode =
641        MAP_USBEndpointDataPut(psHIDInst->ui32USBBase, psHIDInst->ui8INEndpoint,
642                               pui8Data, ui32NumBytes);
643
644    if (i32Retcode != -1) {
645        //
646        // Update the count and index ready for the next time round.
647        //
648        psHIDInst->ui16InReportIndex += ui32NumBytes;
649
650        //
651        // Send out the current data.
652        //
653        i32Retcode = MAP_USBEndpointDataSend(
654            psHIDInst->ui32USBBase, psHIDInst->ui8INEndpoint, USB_TRANS_IN);
655    }
656
657    //
658    // Tell the caller how we got on.
659    //
660    return (i32Retcode);
661}
662
663//*****************************************************************************
664//
665// Receives notifications related to data received from the host.
666//
667// \param psHIDDevice is the device instance whose endpoint is to be processed.
668// \param ui32Status is the USB interrupt status that caused this function to
669// be called.
670//
671// This function is called from HandleEndpoints for all interrupts signaling
672// the arrival of data on the interrupt OUT endpoint (in other words, whenever
673// the host has sent us a packet of data).  We inform the client that a packet
674// is available and, on return, check to see if the packet has been read.  If
675// not, we schedule another notification to the client for a later time.
676//
677// \return Returns \b true on success or \b false on failure.
678//
679//*****************************************************************************
680static bool ProcessDataFromHost(tUSBDHIDDevice* psHIDDevice,
681                                uint32_t ui32Status) {
682    uint32_t ui32EPStatus, ui32Size;
683    tHIDInstance* psInst;
684
685    //
686    // Get a pointer to our instance data.
687    //
688    psInst = &psHIDDevice->sPrivateData;
689
690    //
691    // Get the endpoint status to see why we were called.
692    //
693    ui32EPStatus = MAP_USBEndpointStatus(USB0_BASE, psInst->ui8OUTEndpoint);
694
695    //
696    // Clear the status bits.
697    //
698    MAP_USBDevEndpointStatusClear(USB0_BASE, psInst->ui8OUTEndpoint,
699                                  ui32EPStatus);
700
701    //
702    // Has a packet been received?
703    //
704    if (ui32EPStatus & USB_DEV_RX_PKT_RDY) {
705        //
706        // Set the flag we use to indicate that a packet read is pending.  This
707        // will be cleared if the packet is read.  If the client does not read
708        // the packet in the context of the USB_EVENT_RX_AVAILABLE callback,
709        // the event will be signaled later during tick processing.
710        //
711        SetDeferredOpFlag(&psInst->ui16DeferredOpFlags, HID_DO_PACKET_RX, true);
712
713        //
714        // How big is the packet we have just been sent?
715        //
716        ui32Size = MAP_USBEndpointDataAvail(psInst->ui32USBBase,
717                                            psInst->ui8OUTEndpoint);
718
719        //
720        // The receive channel is not blocked so let the caller know
721        // that a packet is waiting.  The parameters are set to indicate
722        // that the packet has not been read from the hardware FIFO yet.
723        //
724        psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData,
725                                   USB_EVENT_RX_AVAILABLE, ui32Size, (void*)0);
726    } else {
727        //
728        // No packet was received.  Some error must have been reported.  Check
729        // and pass this on to the client if necessary.
730        //
731        if (ui32EPStatus & USB_RX_ERROR_FLAGS) {
732            //
733            // This is an error we report to the client so...
734            //
735            psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData, USB_EVENT_ERROR,
736                                       (ui32EPStatus & USB_RX_ERROR_FLAGS),
737                                       (void*)0);
738        }
739        return (false);
740    }
741
742    return (true);
743}
744
745//*****************************************************************************
746//
747// Receives notifications related to data sent to the host.
748//
749// \param psHIDDevice is the device instance whose endpoint is to be processed.
750// \param ui32Status is the USB interrupt status that caused this function to
751// be called.
752//
753// This function is called from HandleEndpoints for all interrupts originating
754// from the interrupt IN endpoint (in other words, whenever data has been
755// transmitted to the USB host).  We examine the cause of the interrupt and,
756// if due to completion of a transmission, notify the client.
757//
758// \return Returns \b true on success or \b false on failure.
759//
760//*****************************************************************************
761static bool ProcessDataToHost(tUSBDHIDDevice* psHIDDevice,
762                              uint32_t ui32Status) {
763    tHIDInstance* psInst;
764    uint32_t ui32EPStatus;
765
766    //
767    // Get a pointer to our instance data.
768    //
769    psInst = &psHIDDevice->sPrivateData;
770
771    //
772    // Get the endpoint status to see why we were called.
773    //
774    ui32EPStatus =
775        MAP_USBEndpointStatus(psInst->ui32USBBase, psInst->ui8INEndpoint);
776
777    //
778    // Clear the status bits.
779    //
780    MAP_USBDevEndpointStatusClear(psInst->ui32USBBase, psInst->ui8INEndpoint,
781                                  ui32EPStatus);
782
783    //
784    // Our last packet was transmitted successfully.  Is there any more data to
785    // send or have we finished sending the whole report?  We know we finished
786    // if the ui16InReportIndex has reached the ui16InReportSize value.
787    //
788    if (psInst->ui16InReportSize == psInst->ui16InReportIndex) {
789        //
790        // We finished sending the last report so are idle once again.
791        //
792        psInst->iHIDTxState = eHIDStateIdle;
793
794        //
795        // Notify the client that the report transmission completed.
796        //
797        psHIDDevice->pfnTxCallback(psHIDDevice->pvTxCBData,
798                                   USB_EVENT_TX_COMPLETE,
799                                   psInst->ui16InReportSize, (void*)0);
800
801        //
802        // Do we have any reports to send as a result of idle timer timeouts?
803        //
804        if (psInst->ui16DeferredOpFlags & (1 << HID_DO_SEND_IDLE_REPORT)) {
805            //
806            // Yes - send reports for any timers that expired recently.
807            //
808            ProcessIdleTimers(psHIDDevice, 0);
809        }
810    } else {
811        //
812        // There must be more data or a zero length packet waiting to be sent
813        // so go ahead and do this.
814        //
815        ScheduleReportTransmission(psInst);
816    }
817
818    return (true);
819}
820
821//*****************************************************************************
822//
823// Called by the USB stack for any activity involving one of our endpoints
824// other than EP0.  This function is a fan out that merely directs the call to
825// the correct handler depending upon the endpoint and transaction direction
826// signaled in ui32Status.
827//
828//*****************************************************************************
829static void HandleEndpoints(void* pvHIDInstance, uint32_t ui32Status) {
830    tUSBDHIDDevice* psHIDInst;
831    tHIDInstance* psInst;
832
833    ASSERT(pvHIDInstance != 0);
834
835    //
836    // Determine if the serial device is in single or composite mode because
837    // the meaning of ui32Index is different in both cases.
838    //
839    psHIDInst = (tUSBDHIDDevice*)pvHIDInstance;
840    psInst = &psHIDInst->sPrivateData;
841
842    //
843    // Handler for the interrupt OUT data endpoint.
844    //
845    if (ui32Status & (0x10000 << USBEPToIndex(psInst->ui8OUTEndpoint))) {
846        //
847        // Data is being sent to us from the host.
848        //
849        ProcessDataFromHost(pvHIDInstance, ui32Status);
850    }
851
852    //
853    // Handler for the interrupt IN data endpoint.
854    //
855    if (ui32Status & (1 << USBEPToIndex(psInst->ui8INEndpoint))) {
856        ProcessDataToHost(pvHIDInstance, ui32Status);
857    }
858}
859
860//*****************************************************************************
861//
862// Called by the USB stack whenever a configuration change occurs.
863//
864//*****************************************************************************
865static void HandleConfigChange(void* pvHIDInstance, uint32_t ui32Info) {
866    tHIDInstance* psInst;
867    tUSBDHIDDevice* psHIDDevice;
868
869    ASSERT(pvHIDInstance != 0);
870
871    //
872    // Create the instance pointer.
873    //
874    psHIDDevice = pvHIDInstance;
875
876    //
877    // Get a pointer to our instance data.
878    //
879    psInst = &psHIDDevice->sPrivateData;
880
881    //
882    // Set all our endpoints to idle state.
883    //
884    psInst->iHIDRxState = eHIDStateIdle;
885    psInst->iHIDTxState = eHIDStateIdle;
886
887    //
888    // If we are not currently connected let the client know we are open for
889    // business.
890    //
891    if (!psInst->bConnected) {
892        //
893        // Pass the connected event to the client.
894        //
895        psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData, USB_EVENT_CONNECTED,
896                                   0, (void*)0);
897    }
898
899    //
900    // Clear the idle timers for each input report.
901    //
902    ClearIdleTimers(psHIDDevice);
903
904    //
905    // Remember that we are connected.
906    //
907    psInst->bConnected = true;
908}
909
910//*****************************************************************************
911//
912// Device instance specific handler.
913//
914//*****************************************************************************
915static void HandleDevice(void* pvHIDInstance, uint32_t ui32Request,
916                         void* pvRequestData) {
917    tHIDInstance* psInst;
918    uint8_t* pui8Data;
919    tUSBDHIDDevice* psHIDDevice;
920
921    psHIDDevice = (tUSBDHIDDevice*)pvHIDInstance;
922
923    //
924    // Create the serial instance data.
925    //
926    psInst = &((tUSBDHIDDevice*)pvHIDInstance)->sPrivateData;
927
928    //
929    // Create the int8_t array used by the events supported by the USB CDC
930    // serial class.
931    //
932    pui8Data = (uint8_t*)pvRequestData;
933
934    switch (ui32Request) {
935    //
936    // This was an interface change event.
937    //
938    case USB_EVENT_COMP_IFACE_CHANGE: {
939        psInst->ui8Interface = pui8Data[1];
940        break;
941    }
942
943    //
944    // This was an endpoint change event.
945    //
946    case USB_EVENT_COMP_EP_CHANGE: {
947        //
948        // Determine if this is an IN or OUT endpoint that has changed.
949        //
950        if (pui8Data[0] & USB_EP_DESC_IN) {
951            psInst->ui8INEndpoint = IndexToUSBEP((pui8Data[1] & 0x7f));
952        } else {
953            //
954            // Extract the new endpoint number.
955            //
956            psInst->ui8OUTEndpoint = IndexToUSBEP(pui8Data[1] & 0x7f);
957        }
958        break;
959    }
960    case USB_EVENT_LPM_RESUME: {
961        if (psHIDDevice->pfnRxCallback) {
962            //
963            // Pass the LPM resume event to the client.
964            //
965            psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData,
966                                       USB_EVENT_LPM_RESUME, 0, (void*)0);
967        }
968        break;
969    }
970    case USB_EVENT_LPM_SLEEP: {
971        if (psHIDDevice->pfnRxCallback) {
972            //
973            // Pass the LPM sleep event to the client.
974            //
975            psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData,
976                                       USB_EVENT_LPM_SLEEP, 0, (void*)0);
977        }
978        break;
979    }
980    case USB_EVENT_LPM_ERROR: {
981        if (psHIDDevice->pfnRxCallback) {
982            //
983            // Pass the LPM error event to the client.
984            //
985            psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData,
986                                       USB_EVENT_LPM_ERROR, 0, (void*)0);
987        }
988        break;
989    }
990    default: {
991        break;
992    }
993    }
994}
995
996//*****************************************************************************
997//
998// This function is called by the USB device stack whenever the device is
999// disconnected from the host.
1000//
1001//*****************************************************************************
1002static void HandleDisconnect(void* pvHIDInstance) {
1003    tUSBDHIDDevice* psHIDDevice;
1004
1005    ASSERT(pvHIDInstance != 0);
1006
1007    //
1008    // Create the instance pointer.
1009    //
1010    psHIDDevice = (tUSBDHIDDevice*)pvHIDInstance;
1011
1012    //
1013    // If we are not currently connected so let the client know we are open
1014    // for business.
1015    //
1016    if (psHIDDevice->sPrivateData.bConnected) {
1017        //
1018        // Pass the disconnected event to the client.
1019        //
1020        psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData,
1021                                   USB_EVENT_DISCONNECTED, 0, (void*)0);
1022    }
1023
1024    //
1025    // Remember that we are no longer connected.
1026    //
1027    psHIDDevice->sPrivateData.bConnected = false;
1028}
1029
1030//*****************************************************************************
1031//
1032// This function is called by the USB device stack whenever a request for a
1033// non-standard descriptor is received.
1034//
1035// \param pvHIDInstance is the instance data for this request.
1036// \param psUSBRequest points to the request received.
1037//
1038// This call parses the provided request structure and determines which
1039// descriptor is being requested.  Assuming the descriptor can be found, it is
1040// scheduled for transmission via endpoint zero.  If the descriptor cannot be
1041// found, the endpoint is stalled to indicate an error to the host.
1042//
1043//*****************************************************************************
1044static void HandleGetDescriptor(void* pvHIDInstance,
1045                                tUSBRequest* psUSBRequest) {
1046    uint32_t ui32Size, ui32Desc;
1047    const tUSBDHIDDevice* psHIDDevice;
1048
1049    ASSERT(pvHIDInstance != 0);
1050
1051    //
1052    // Which device are we dealing with?
1053    //
1054    psHIDDevice = pvHIDInstance;
1055
1056    //
1057    // Which type of class descriptor are we being asked for?
1058    //
1059    switch (psUSBRequest->wValue >> 8) {
1060    //
1061    // This is a request for a HID report or physical descriptor.
1062    //
1063    case USB_HID_DTYPE_REPORT:
1064    case USB_HID_DTYPE_PHYSICAL: {
1065        //
1066        // Find the index to the descriptor that is being queried.
1067        //
1068        ui32Size = 0;
1069        ui32Desc = FindHIDDescriptor(psHIDDevice, psUSBRequest->wValue >> 8,
1070                                     psUSBRequest->wValue & 0xFF, &ui32Size);
1071
1072        //
1073        // Did we find the descriptor?
1074        //
1075        if (ui32Desc == HID_NOT_FOUND) {
1076            //
1077            // No - stall the endpoint and return.
1078            //
1079            USBDCDStallEP0(0);
1080            return;
1081        }
1082
1083        //
1084        // If there is more data to send than the host requested then just
1085        // send the requested amount of data.
1086        //
1087        if (ui32Size > psUSBRequest->wLength) {
1088            ui32Size = psUSBRequest->wLength;
1089        }
1090
1091        //
1092        // Send the data via endpoint 0.
1093        //
1094        USBDCDSendDataEP0(
1095            0, (uint8_t*)psHIDDevice->ppui8ClassDescriptors[ui32Desc],
1096            ui32Size);
1097
1098        break;
1099    }
1100
1101    //
1102    // This is a request for the HID descriptor (as found in the
1103    // configuration descriptor following the relevant interface).
1104    //
1105    case USB_HID_DTYPE_HID: {
1106        //
1107        // How big is the HID descriptor?
1108        //
1109        ui32Size = (uint32_t)psHIDDevice->psHIDDescriptor->bLength;
1110
1111        //
1112        // If there is more data to send than the host requested then just
1113        // send the requested amount of data.
1114        //
1115        if (ui32Size > psUSBRequest->wLength) {
1116            ui32Size = psUSBRequest->wLength;
1117        }
1118
1119        //
1120        // Send the data via endpoint 0.
1121        //
1122        USBDCDSendDataEP0(0, (uint8_t*)psHIDDevice->psHIDDescriptor, ui32Size);
1123        break;
1124    }
1125
1126    //
1127    // This was an unknown request so stall.
1128    //
1129    default: {
1130        USBDCDStallEP0(0);
1131        break;
1132    }
1133    }
1134}
1135
1136//*****************************************************************************
1137//
1138// This function is called by the USB device stack whenever a non-standard
1139// request is received.
1140//
1141// \param pvHIDInstance is the instance data for this HID device.
1142// \param psUSBRequest points to the request received.
1143//
1144// This call parses the provided request structure.  Assuming the request is
1145// understood, it is handled and any required response generated.  If the
1146// request cannot be handled by this device class, endpoint zero is stalled to
1147// indicate an error to the host.
1148//
1149//*****************************************************************************
1150static void HandleRequest(void* pvHIDInstance, tUSBRequest* psUSBRequest) {
1151    tHIDInstance* psInst;
1152    uint8_t ui8Protocol;
1153    uint32_t ui32Size, ui32Timeout;
1154    uint8_t* pui8Report;
1155    tUSBDHIDDevice* psHIDDevice;
1156
1157    ASSERT(pvHIDInstance != 0);
1158
1159    //
1160    // Which device are we dealing with?
1161    //
1162    psHIDDevice = pvHIDInstance;
1163
1164    //
1165    // Get a pointer to our instance data.
1166    //
1167    psInst = &psHIDDevice->sPrivateData;
1168
1169    //
1170    // Make sure the request was for this interface.
1171    //
1172    if (psUSBRequest->wIndex != psInst->ui8Interface) {
1173        return;
1174    }
1175
1176    //
1177    // Determine the type of request.
1178    //
1179    switch (psUSBRequest->bRequest) {
1180    //
1181    // A Set Report request is received from the host when it sends an
1182    // Output report via endpoint 0.
1183    //
1184    case USBREQ_SET_REPORT: {
1185        //
1186        // Ask the application for a buffer large enough to hold the
1187        // report we are to be sent.
1188        //
1189        psInst->ui16OutReportSize = psUSBRequest->wLength;
1190        psInst->pui8OutReportData = (uint8_t*)psHIDDevice->pfnRxCallback(
1191            psHIDDevice->pvRxCBData, USBD_HID_EVENT_GET_REPORT_BUFFER,
1192            psUSBRequest->wValue, (void*)(uint32_t)(psUSBRequest->wLength));
1193
1194        //
1195        // Did the client provide us a buffer?
1196        //
1197        if (!psInst->pui8OutReportData) {
1198            //
1199            // The application could not provide us a buffer so stall the
1200            // request.
1201            //
1202            USBDCDStallEP0(0);
1203        } else {
1204            //
1205            // The client provided us a buffer to read the report into
1206            // so request the data from the host.
1207            //
1208
1209            //
1210            // Set the state to indicate we are waiting for data.
1211            //
1212            psInst->iHIDRxState = eHIDStateWaitData;
1213
1214            //
1215            // Now read the payload of the request.  We handle the actual
1216            // operation in the data callback once this data is received.
1217            //
1218            USBDCDRequestDataEP0(0, psInst->pui8OutReportData,
1219                                 (uint32_t)psUSBRequest->wLength);
1220
1221            //
1222            // Need to ACK the data on end point 0 in this case.  Do this
1223            // after requesting the data to prevent race conditions that
1224            // occur if you acknowledge before setting up to receive the
1225            // request data.
1226            //
1227            MAP_USBDevEndpointDataAck(psInst->ui32USBBase, USB_EP_0, false);
1228        }
1229
1230        break;
1231    }
1232
1233    //
1234    // A Get Report request is used by the host to poll a device for its
1235    // current state.
1236    //
1237    case USBREQ_GET_REPORT: {
1238        //
1239        // Get the latest report from the application.
1240        //
1241        ui32Size = psHIDDevice->pfnRxCallback(
1242            psHIDDevice->pvRxCBData, USBD_HID_EVENT_GET_REPORT,
1243            psUSBRequest->wValue, &pui8Report);
1244
1245        //
1246        // Need to ACK the data on end point 0 in this case.
1247        //
1248        MAP_USBDevEndpointDataAck(psInst->ui32USBBase, USB_EP_0, true);
1249
1250        //
1251        // ..then send back the requested report.
1252        //
1253        psInst->bGetRequestPending = true;
1254        USBDCDSendDataEP0(0, pui8Report, ui32Size);
1255
1256        break;
1257    }
1258
1259    //
1260    // A set IDLE request has been made.  This indicates to us how often a
1261    // given report should be sent back to the host in the absence of any
1262    // change in state of the device.
1263    //
1264    case USBREQ_SET_IDLE: {
1265        //
1266        // Set the idle timeout for the requested report(s).
1267        //
1268        SetIdleTimeout(psHIDDevice, psUSBRequest->wValue & 0xFF,
1269                       (psUSBRequest->wValue >> 8) & 0xFF);
1270
1271        //
1272        // Need to ACK the data on end point 0 in this case.
1273        //
1274        MAP_USBDevEndpointDataAck(psInst->ui32USBBase, USB_EP_0, true);
1275
1276        break;
1277    }
1278
1279    //
1280    // A get IDLE request has been made.  This request queries the current
1281    // idle timeout for a given report.
1282    //
1283    case USBREQ_GET_IDLE: {
1284        //
1285        // Determine the timeout for the requested report.
1286        //
1287        ui32Timeout = GetIdleTimeout(psHIDDevice, psUSBRequest->wValue);
1288
1289        if (ui32Timeout != HID_NOT_FOUND) {
1290            //
1291            // Need to ACK the data on end point 0 in this case.
1292            //
1293            MAP_USBDevEndpointDataAck(psInst->ui32USBBase, USB_EP_0, true);
1294
1295            //
1296            // Send our response to the host.
1297            //
1298            USBDCDSendDataEP0(0, (uint8_t*)&ui32Timeout, 1);
1299        } else {
1300            //
1301            // The report ID was not found so stall the endpoint.
1302            //
1303            USBDCDStallEP0(0);
1304        }
1305        break;
1306    }
1307
1308    //
1309    // Set either boot or report protocol for reports sent from the device.
1310    // This is only supported by devices in the boot subclass.
1311    //
1312    case USBREQ_SET_PROTOCOL: {
1313        if (psHIDDevice->ui8Subclass == USB_HID_SCLASS_BOOT) {
1314            //
1315            // We need to ACK the data on end point 0 in this case.
1316            //
1317            MAP_USBDevEndpointDataAck(psInst->ui32USBBase, USB_EP_0, true);
1318
1319            //
1320            // We are a boot subclass device so pass this on to the
1321            // application.
1322            //
1323            psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData,
1324                                       USBD_HID_EVENT_SET_PROTOCOL,
1325                                       psUSBRequest->wValue, (void*)0);
1326        } else {
1327            //
1328            // This is not a boot subclass device so stall the endpoint to
1329            // show that we don't support this request.
1330            //
1331            USBDCDStallEP0(0);
1332        }
1333        break;
1334    }
1335
1336    //
1337    // Inform the host of the protocol, boot or report, that is currently
1338    // in use.  This is only supported by devices in the boot subclass.
1339    //
1340    case USBREQ_GET_PROTOCOL: {
1341        if (psHIDDevice->ui8Subclass == USB_HID_SCLASS_BOOT) {
1342            //
1343            // We need to ACK the data on end point 0 in this case.
1344            //
1345            MAP_USBDevEndpointDataAck(psInst->ui32USBBase, USB_EP_0, true);
1346
1347            //
1348            // We are a boot subclass device so pass this on to the
1349            // application callback to get the answer.
1350            //
1351            ui8Protocol = (uint8_t)psHIDDevice->pfnRxCallback(
1352                psHIDDevice->pvRxCBData, USBD_HID_EVENT_GET_PROTOCOL, 0,
1353                (void*)0);
1354
1355            //
1356            // Send our response to the host.
1357            //
1358            USBDCDSendDataEP0(0, (uint8_t*)&ui8Protocol, 1);
1359        } else {
1360            //
1361            // This is not a boot subclass device so stall the endpoint to
1362            // show that we don't support this request.
1363            //
1364            USBDCDStallEP0(0);
1365        }
1366        break;
1367    }
1368
1369    //
1370    // This request was not recognized so stall.
1371    //
1372    default: {
1373        USBDCDStallEP0(0);
1374        break;
1375    }
1376    }
1377}
1378
1379//*****************************************************************************
1380//
1381// This function is called by the USB device stack whenever the data requested
1382// on endpoint zero is received.
1383//
1384//*****************************************************************************
1385static void HandleEP0DataReceived(void* pvHIDInstance, uint32_t ui32DataSize) {
1386    tHIDInstance* psInst;
1387    tUSBDHIDDevice* psHIDDevice;
1388
1389    ASSERT(pvHIDInstance != 0);
1390
1391    //
1392    // Which device are we dealing with?
1393    //
1394    psHIDDevice = pvHIDInstance;
1395
1396    //
1397    // If we were not passed any data, just return.
1398    //
1399    if (ui32DataSize == 0) {
1400        return;
1401    }
1402
1403    //
1404    // Get our instance data pointer.
1405    //
1406    psInst = &psHIDDevice->sPrivateData;
1407
1408    //
1409    // Make sure we are actually expecting something.
1410    //
1411    if (psInst->iHIDRxState != eHIDStateWaitData) {
1412        return;
1413    }
1414
1415    //
1416    // Change the endpoint state back to idle now that we have been passed
1417    // the data we were waiting for.
1418    //
1419    psInst->iHIDRxState = eHIDStateIdle;
1420
1421    //
1422    // The only things we ever request via endpoint zero are reports sent to
1423    // us via a Set_Report request.  Pass the newly received report on to
1424    // the client.
1425    //
1426    psHIDDevice->pfnRxCallback(
1427        psHIDDevice->pvRxCBData, USBD_HID_EVENT_SET_REPORT,
1428        psInst->ui16OutReportSize, psInst->pui8OutReportData);
1429}
1430
1431//*****************************************************************************
1432//
1433// This function is called by the USB device stack whenever the data sent on
1434// endpoint zero is received and acknowledged by the host.
1435//
1436//*****************************************************************************
1437static void HandleEP0DataSent(void* pvHIDInstance, uint32_t ui32Info) {
1438    tHIDInstance* psInst;
1439    tUSBDHIDDevice* psHIDDevice;
1440
1441    ASSERT(pvHIDInstance != 0);
1442
1443    //
1444    // Which device are we dealing with?
1445    //
1446    psHIDDevice = pvHIDInstance;
1447
1448    //
1449    // Get our instance data pointer.
1450    //
1451    psInst = &psHIDDevice->sPrivateData;
1452
1453    //
1454    // If we just sent a report in response to a Get_Report request, send an
1455    // event to the application telling it that the transmission completed.
1456    //
1457    if (psInst->bGetRequestPending) {
1458        //
1459        // Clear the flag now that we are sending the application callback.
1460        //
1461        psInst->bGetRequestPending = false;
1462
1463        psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData,
1464                                   USBD_HID_EVENT_REPORT_SENT, 0, (void*)0);
1465    }
1466
1467    return;
1468}
1469
1470//*****************************************************************************
1471//
1472// This function is called by the USB device stack whenever the device is
1473// reset.  If we are currently connected, send a disconnect event at this
1474// point.
1475//
1476//*****************************************************************************
1477static void HandleReset(void* pvHIDInstance) {
1478    ASSERT(pvHIDInstance != 0);
1479
1480    //
1481    // Merely call the disconnect handler.  This causes a disconnect message to
1482    // be sent to the client if we think we are currently connected.
1483    //
1484    HandleDisconnect(pvHIDInstance);
1485}
1486
1487//*****************************************************************************
1488//
1489// This function is called by the USB device stack whenever the bus is put into
1490// suspend state.
1491//
1492//*****************************************************************************
1493static void HandleSuspend(void* pvHIDInstance) {
1494    const tUSBDHIDDevice* psHIDDevice;
1495
1496    ASSERT(pvHIDInstance != 0);
1497
1498    //
1499    // Create the instance pointer.
1500    //
1501    psHIDDevice = (const tUSBDHIDDevice*)pvHIDInstance;
1502
1503    //
1504    // Pass the event on to the client.
1505    //
1506    psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData, USB_EVENT_SUSPEND, 0,
1507                               (void*)0);
1508}
1509
1510//*****************************************************************************
1511//
1512// This function is called by the USB device stack whenever the bus is taken
1513// out of suspend state.
1514//
1515//*****************************************************************************
1516static void HandleResume(void* pvHIDInstance) {
1517    const tUSBDHIDDevice* psHIDDevice;
1518
1519    ASSERT(pvHIDInstance != 0);
1520
1521    //
1522    // Create the instance pointer.
1523    //
1524    psHIDDevice = (const tUSBDHIDDevice*)pvHIDInstance;
1525
1526    //
1527    // Pass the event on to the client.
1528    //
1529    psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData, USB_EVENT_RESUME, 0,
1530                               (void*)0);
1531}
1532
1533//*****************************************************************************
1534//
1535// This function is called periodically and provides us with a time reference
1536// and method of implementing delayed or time-dependent operations.
1537//
1538// \param pvHIDInstance is the instance data for this request.
1539// \param ui32TimemS is the elapsed time in milliseconds since the last call
1540// to this function.
1541//
1542// \return None.
1543//
1544//*****************************************************************************
1545static void HIDTickHandler(void* pvHIDInstance, uint32_t ui32TimemS) {
1546    tHIDInstance* psInst;
1547    uint32_t ui32Size;
1548    tUSBDHIDDevice* psHIDDevice;
1549
1550    ASSERT(pvHIDInstance != 0);
1551
1552    //
1553    // Create the instance pointer.
1554    //
1555    psHIDDevice = (tUSBDHIDDevice*)pvHIDInstance;
1556
1557    //
1558    // Get our instance data pointer.
1559    //
1560    psInst = &psHIDDevice->sPrivateData;
1561
1562    //
1563    // If we are connected, process our idle timers.
1564    //
1565    if (psInst->bConnected) {
1566        ProcessIdleTimers(psHIDDevice, ui32TimemS);
1567    }
1568
1569    //
1570    // Do we have a deferred receive waiting
1571    //
1572    if (psInst->ui16DeferredOpFlags & (1 << HID_DO_PACKET_RX)) {
1573        //
1574        // Yes - how big is the waiting packet?
1575        //
1576        ui32Size = MAP_USBEndpointDataAvail(USB0_BASE, psInst->ui8OUTEndpoint);
1577
1578        //
1579        // Tell the client that there is a packet waiting for it.
1580        //
1581        psHIDDevice->pfnRxCallback(psHIDDevice->pvRxCBData,
1582                                   USB_EVENT_RX_AVAILABLE, ui32Size, (void*)0);
1583    }
1584
1585    return;
1586}
1587
1588//*****************************************************************************
1589//
1590//! Initializes HID device operation for a given USB controller.
1591//!
1592//! \param ui32Index is the index of the USB controller which is to be
1593//! initialized for HID device operation.
1594//! \param psHIDDevice points to a structure containing parameters customizing
1595//! the operation of the HID device.
1596//!
1597//! An application wishing to offer a USB HID interface to a host system
1598//! must call this function to initialize the USB controller and attach the
1599//! device to the USB bus.  This function performs all required USB
1600//! initialization.
1601//!
1602//! On successful completion, this function will return the \e psHIDDevice
1603//! pointer passed to it.  This must be passed on all future calls from the
1604//! application to the HID device class driver.
1605//!
1606//! The USB HID device class API offers the application a report-based transmit
1607//! interface for Input reports.  Output reports may be received via the
1608//! control endpoint or via a dedicated Interrupt OUT endpoint.  If using the
1609//! dedicated endpoint, report data is delivered to the application packet-by-
1610//! packet.  If the application uses reports longer than \b USBDHID_MAX_PACKET
1611//! bytes and would rather receive full reports, it may use a USB buffer above
1612//! the receive channel to allow full reports to be read.
1613//!
1614//! Transmit Operation:
1615//!
1616//! Calls to USBDHIDReportWrite() pass complete reports to the driver for
1617//! transmission.  These will be transmitted to the host using as many USB
1618//! packets as are necessary to complete the transmission.
1619//!
1620//! Once a full Input report has been acknowledged by the USB host, a
1621//! \b USB_EVENT_TX_COMPLETE event is sent to the application transmit callback
1622//! to inform it that another report may be transmitted.
1623//!
1624//! Receive Operation (when using a dedicated interrupt OUT endpoint):
1625//!
1626//! An incoming USB data packet will result in a call to the application
1627//! callback with event \b USB_EVENT_RX_AVAILABLE.  The application must then
1628//! call USBDHIDPacketRead(), passing a buffer capable of holding the received
1629//! packet.  The size of the packet may be determined by calling function
1630//! USBDHIDRxPacketAvailable() prior to reading the packet.
1631//!
1632//! Receive Operation (when not using a dedicated OUT endpoint):
1633//!
1634//! If no dedicated OUT endpoint is used, Output and Feature reports are sent
1635//! from the host using the control endpoint, endpoint zero.  When such a
1636//! report is received, \b USBD_HID_EVENT_GET_REPORT_BUFFER is sent to the
1637//! application which must respond with a buffer large enough to hold the
1638//! report.  The device class driver will then copy the received report into
1639//! the supplied buffer before sending \b USBD_HID_EVENT_SET_REPORT to indicate
1640//! that the report is now available.
1641//!
1642//! \note The application must not make any calls to the low level USB device
1643//! interface if interacting with USB via the USB HID device class API.  Doing
1644//! so will cause unpredictable (though almost certainly unpleasant) behavior.
1645//!
1646//! \return Returns NULL on failure or the \e psHIDDevice pointer on success.
1647//
1648//*****************************************************************************
1649void* USBDHIDInit(uint32_t ui32Index, tUSBDHIDDevice* psHIDDevice) {
1650    tDeviceDescriptor* pi16DevDesc;
1651
1652    //
1653    // Check parameter validity.
1654    //
1655    ASSERT(ui32Index == 0);
1656    ASSERT(psHIDDevice);
1657    ASSERT(psHIDDevice->ppui8StringDescriptors);
1658    ASSERT(psHIDDevice->pfnRxCallback);
1659    ASSERT(psHIDDevice->pfnTxCallback);
1660    ASSERT(psHIDDevice->ppui8ClassDescriptors);
1661    ASSERT(psHIDDevice->psHIDDescriptor);
1662    ASSERT((psHIDDevice->ui8NumInputReports == 0) || psHIDDevice->psReportIdle);
1663
1664    USBDHIDCompositeInit(ui32Index, psHIDDevice, 0);
1665
1666    //
1667    // Fix up the device descriptor with the client-supplied values.
1668    //
1669    pi16DevDesc = (tDeviceDescriptor*)
1670                      psHIDDevice->sPrivateData.sDevInfo.pui8DeviceDescriptor;
1671    pi16DevDesc->idVendor = psHIDDevice->ui16VID;
1672    pi16DevDesc->idProduct = psHIDDevice->ui16PID;
1673
1674    //
1675    // All is well so now pass the descriptors to the lower layer and put
1676    // the HID device on the bus.
1677    //
1678    USBDCDInit(ui32Index, &psHIDDevice->sPrivateData.sDevInfo,
1679               (void*)psHIDDevice);
1680
1681    //
1682    // Return the pointer to the instance indicating that everything went well.
1683    //
1684    return ((void*)psHIDDevice);
1685}
1686
1687//*****************************************************************************
1688//
1689//! Initializes HID device operation for a given USB controller.
1690//!
1691//! \param ui32Index is the index of the USB controller which is to be
1692//! initialized for HID device operation.
1693//! \param psHIDDevice points to a structure containing parameters customizing
1694//! the operation of the HID device.
1695//! \param psCompEntry is the composite device entry to initialize when
1696//! creating a composite device.
1697//!
1698//! USB HID device classes call this function to initialize the lower level
1699//! HID interface in the USB controller.  If this HID device device is part of
1700//! a composite device, then the \e psCompEntry should point to the composite
1701//! device entry to initialize.  This is part of the array that is passed to
1702//! the USBDCompositeInit() function.
1703//!
1704//! \return Returns zero on failure or a non-zero instance value that should be
1705//! used with the remaining USB HID APIs.
1706//
1707//*****************************************************************************
1708void* USBDHIDCompositeInit(uint32_t ui32Index, tUSBDHIDDevice* psHIDDevice,
1709                           tCompositeEntry* psCompEntry) {
1710    tHIDInstance* psInst;
1711    tEndpointDescriptor* psEndpoint;
1712
1713    //
1714    // Check parameter validity.
1715    //
1716    ASSERT(ui32Index == 0);
1717    ASSERT(psHIDDevice);
1718    ASSERT(psHIDDevice->ppsConfigDescriptor);
1719    ASSERT(psHIDDevice->ppui8StringDescriptors);
1720    ASSERT(psHIDDevice->pfnRxCallback);
1721    ASSERT(psHIDDevice->pfnTxCallback);
1722    ASSERT(psHIDDevice->ppui8ClassDescriptors);
1723    ASSERT(psHIDDevice->psHIDDescriptor);
1724    ASSERT((psHIDDevice->ui8NumInputReports == 0) || psHIDDevice->psReportIdle);
1725
1726    //
1727    // Initialize the workspace in the passed instance structure.
1728    //
1729    psInst = &psHIDDevice->sPrivateData;
1730
1731    //
1732    // Initialize the device information structure.
1733    //
1734    psInst->sDevInfo.psCallbacks = &g_sHIDHandlers;
1735    psInst->sDevInfo.pui8DeviceDescriptor = g_pui8HIDDeviceDescriptor;
1736    psInst->sDevInfo.ppsConfigDescriptors = psHIDDevice->ppsConfigDescriptor;
1737    psInst->sDevInfo.ppui8StringDescriptors =
1738        psHIDDevice->ppui8StringDescriptors;
1739    psInst->sDevInfo.ui32NumStringDescriptors =
1740        psHIDDevice->ui32NumStringDescriptors;
1741
1742    //
1743    // Default the endpoints zero before looking for them in the configuration
1744    // descriptor.
1745    //
1746    psInst->ui8Interface = 0;
1747    psInst->ui8INEndpoint = 0;
1748    psInst->ui8OUTEndpoint = 0;
1749
1750    //
1751    // Get the first endpoint descriptor on interface 0.
1752    //
1753    psEndpoint = USBDCDConfigGetInterfaceEndpoint(
1754        psHIDDevice->ppsConfigDescriptor[0], psInst->ui8Interface, 0, 0);
1755
1756    if (psEndpoint) {
1757        if (psEndpoint->bEndpointAddress & 0x80) {
1758            psInst->ui8INEndpoint = IndexToUSBEP(psEndpoint->bEndpointAddress);
1759        } else {
1760            psInst->ui8OUTEndpoint = IndexToUSBEP(psEndpoint->bEndpointAddress);
1761        }
1762    }
1763
1764    //
1765    // Get the second endpoint descriptor on interface 0.
1766    //
1767    psEndpoint = USBDCDConfigGetInterfaceEndpoint(
1768        psHIDDevice->ppsConfigDescriptor[0], psInst->ui8Interface, 0, 1);
1769    if (psEndpoint) {
1770        if (psEndpoint->bEndpointAddress & 0x80) {
1771            psInst->ui8INEndpoint = IndexToUSBEP(psEndpoint->bEndpointAddress);
1772        } else {
1773            psInst->ui8OUTEndpoint = IndexToUSBEP(psEndpoint->bEndpointAddress);
1774        }
1775    }
1776
1777    //
1778    // Must have at least an IN endpoint.
1779    //
1780    if (psInst->ui8INEndpoint == 0) {
1781        return ((void*)0);
1782    }
1783
1784    //
1785    // Initialize the composite entry that is used by the composite device
1786    // class.
1787    //
1788    if (psCompEntry != 0) {
1789        psCompEntry->psDevInfo = &psInst->sDevInfo;
1790        psCompEntry->pvInstance = (void*)psHIDDevice;
1791    }
1792
1793    psInst->ui32USBBase = USB0_BASE;
1794    psInst->iHIDRxState = eHIDStateUnconfigured;
1795    psInst->iHIDTxState = eHIDStateUnconfigured;
1796    psInst->ui16DeferredOpFlags = 0;
1797    psInst->bConnected = false;
1798    psInst->bGetRequestPending = false;
1799    psInst->bSendInProgress = false;
1800    psInst->ui16InReportIndex = 0;
1801    psInst->ui16InReportSize = 0;
1802    psInst->pui8InReportData = (uint8_t*)0;
1803    psInst->ui16OutReportSize = 0;
1804    psInst->pui8OutReportData = (uint8_t*)0;
1805
1806    //
1807    // Initialize the device info structure for the HID device.
1808    //
1809    USBDCDDeviceInfoInit(0, &psInst->sDevInfo);
1810
1811    //
1812    // Initialize the input report idle timers if any input reports exist.
1813    //
1814    ClearIdleTimers(psHIDDevice);
1815
1816    //
1817    // Initialize the USB tick module, this will prevent it from being
1818    // initialized later in the call to USBDCDInit();
1819    //
1820    InternalUSBTickInit();
1821
1822    //
1823    // Register our tick handler (this must be done after USBDCDInit).
1824    //
1825    InternalUSBRegisterTickHandler(HIDTickHandler, (void*)psHIDDevice);
1826
1827    //
1828    // Return the pointer to the instance indicating that everything went well.
1829    //
1830    return ((void*)psHIDDevice);
1831}
1832
1833//*****************************************************************************
1834//
1835//! Shuts down the HID device.
1836//!
1837//! \param pvHIDInstance is the pointer to the device instance structure as
1838//! returned by USBDHIDInit().
1839//!
1840//! This function terminates HID operation for the instance supplied and
1841//! removes the device from the USB bus.  This function should not be called
1842//! if the HID device is part of a composite device and instead the
1843//! USBDCompositeTerm() function should be called for the full composite
1844//! device.
1845//!
1846//! Following this call, the \e pvHIDInstance instance should not me used in
1847//! any other calls.
1848//!
1849//! \return None.
1850//
1851//*****************************************************************************
1852void USBDHIDTerm(void* pvHIDInstance) {
1853    tHIDInstance* psInst;
1854
1855    ASSERT(pvHIDInstance);
1856
1857    //
1858    // Get a pointer to our instance data.
1859    //
1860    psInst = &((tUSBDHIDDevice*)pvHIDInstance)->sPrivateData;
1861
1862    //
1863    // Terminate the requested instance.
1864    //
1865    USBDCDTerm(USBBaseToIndex(psInst->ui32USBBase));
1866
1867    psInst->ui32USBBase = 0;
1868}
1869
1870//*****************************************************************************
1871//
1872//! Sets the client-specific pointer parameter for the receive channel
1873//! callback.
1874//!
1875//! \param pvHIDInstance is the pointer to the device instance structure as
1876//! returned by USBDHIDInit().
1877//! \param pvCBData is the pointer that client wishes to be provided on each
1878//! event sent to the receive channel callback function.
1879//!
1880//! The client uses this function to change the callback pointer passed in
1881//! the first parameter on all callbacks to the \e pfnRxCallback function
1882//! passed on USBDHIDInit().
1883//!
1884//! If a client wants to make runtime changes in the callback pointer, it must
1885//! ensure that the pvHIDInstance structure passed to USBDHIDInit() resides in
1886//! RAM.  If this structure is in flash, callback data changes will not be
1887//! possible.
1888//!
1889//! \return Returns the previous callback pointer that was being used for
1890//! this instance's receive callback.
1891//
1892//*****************************************************************************
1893void* USBDHIDSetRxCBData(void* pvHIDInstance, void* pvCBData) {
1894    void* pvOldValue;
1895
1896    ASSERT(pvHIDInstance);
1897
1898    //
1899    // Set the callback data for the receive channel after remembering the
1900    // previous value.
1901    //
1902    pvOldValue = ((tUSBDHIDDevice*)pvHIDInstance)->pvRxCBData;
1903    ((tUSBDHIDDevice*)pvHIDInstance)->pvRxCBData = pvCBData;
1904
1905    //
1906    // Return the previous callback data value.
1907    //
1908    return (pvOldValue);
1909}
1910
1911//*****************************************************************************
1912//
1913//! Sets the client-specific data pointer for the transmit callback.
1914//!
1915//! \param pvHIDInstance is the pointer to the device instance structure as
1916//! returned by USBDHIDInit().
1917//! \param pvCBData is the pointer that client wishes to be provided on each
1918//! event sent to the transmit channel callback function.
1919//!
1920//! The client uses this function to change the callback data pointer passed in
1921//! the first parameter on all callbacks to the \e pfnTxCallback function
1922//! passed on USBDHIDInit().
1923//!
1924//! If a client wants to make runtime changes in the callback data, it must
1925//! ensure that the pvHIDInstance structure passed to USBDHIDInit() resides in
1926//! RAM.  If this structure is in flash, callback data changes will not be
1927//! possible.
1928//!
1929//! \return Returns the previous callback data pointer that was being used for
1930//! this instance's transmit callback.
1931//
1932//*****************************************************************************
1933void* USBDHIDSetTxCBData(void* pvHIDInstance, void* pvCBData) {
1934    void* pvOldValue;
1935
1936    ASSERT(pvHIDInstance);
1937
1938    //
1939    // Set the callback data for the transmit channel after remembering the
1940    // previous value.
1941    //
1942    pvOldValue = ((tUSBDHIDDevice*)pvHIDInstance)->pvTxCBData;
1943    ((tUSBDHIDDevice*)pvHIDInstance)->pvTxCBData = pvCBData;
1944
1945    //
1946    // Return the previous callback data value.
1947    //
1948    return (pvOldValue);
1949}
1950
1951//*****************************************************************************
1952//
1953//! Transmits a HID device report to the USB host via the HID interrupt IN
1954//! endpoint.
1955//!
1956//! \param pvHIDInstance is the pointer to the device instance structure as
1957//! returned by USBDHIDInit().
1958//! \param pi8Data points to the first byte of data which is to be transmitted.
1959//! \param ui32Length is the number of bytes of data to transmit.
1960//! \param bLast is ignored in this implementation.  This parameter is required
1961//! to ensure compatibility with other device class drivers and USB buffers.
1962//!
1963//! This function schedules the supplied data for transmission to the USB
1964//! host in a single USB transaction using as many packets as it takes to send
1965//! all the data in the report.  If no transmission is currently ongoing,
1966//! the first packet of data is immediately copied to the relevant USB endpoint
1967//! FIFO for transmission.  Whenever all the report data has been acknowledged
1968//! by the host, a \b USB_EVENT_TX_COMPLETE event will be sent to the
1969//! application transmit callback indicating that another report can now be
1970//! transmitted.
1971//!
1972//! The caller must ensure that the data pointed to by \e pui8Data remains
1973//! accessible and unaltered until the \b USB_EVENT_TX_COMPLETE is received.
1974//!
1975//! \return Returns the number of bytes actually scheduled for transmission.
1976//! At this level, this will either be the number of bytes passed or 0 to
1977//! indicate a failure.
1978//
1979//*****************************************************************************
1980uint32_t USBDHIDReportWrite(void* pvHIDInstance, uint8_t* pi8Data,
1981                            uint32_t ui32Length, bool bLast) {
1982    tHIDInstance* psInst;
1983    int32_t i32Retcode;
1984
1985    ASSERT(pvHIDInstance);
1986
1987    //
1988    // Get our instance data pointer
1989    //
1990    psInst = &((tUSBDHIDDevice*)pvHIDInstance)->sPrivateData;
1991
1992    //
1993    // Set a flag indicating that we are currently in the process of sending
1994    // a packet.
1995    //
1996    psInst->bSendInProgress = true;
1997
1998    //
1999    // Can we send the data provided?
2000    //
2001    if (psInst->iHIDTxState != eHIDStateIdle) {
2002        //
2003        // We are in the middle of sending another report.  Return 0 to
2004        // indicate that we can't send this report until the previous one
2005        // finishes.
2006        //
2007        psInst->bSendInProgress = false;
2008        return (0);
2009    }
2010
2011    //
2012    // Clear the elapsed time since this report was last sent.
2013    //
2014    if (ui32Length) {
2015        ClearReportTimer(pvHIDInstance, *pi8Data);
2016    }
2017
2018    //
2019    // Keep track of the whereabouts of the report so that we can send it in
2020    // multiple packets if necessary.
2021    //
2022    psInst->pui8InReportData = pi8Data;
2023    psInst->ui16InReportIndex = 0;
2024    psInst->ui16InReportSize = ui32Length;
2025
2026    //
2027    // Schedule transmission of the first packet of the report.
2028    //
2029    psInst->iHIDTxState = eHIDStateWaitData;
2030    i32Retcode = ScheduleReportTransmission(psInst);
2031
2032    //
2033    // Clear the flag we use to indicate that we are in the midst of sending
2034    // a packet.
2035    //
2036    psInst->bSendInProgress = false;
2037
2038    //
2039    // Did an error occur while trying to send the data?
2040    //
2041    if (i32Retcode != -1) {
2042        //
2043        // No - tell the caller we sent all the bytes provided.
2044        //
2045        return (ui32Length);
2046    } else {
2047        //
2048        // Yes - tell the caller we could not send the data.
2049        //
2050        return (0);
2051    }
2052}
2053
2054//*****************************************************************************
2055//
2056//! Reads a packet of data received from the USB host via the interrupt OUT
2057//! endpoint (if in use).
2058//!
2059//! \param pvHIDInstance is the pointer to the device instance structure as
2060//! returned by USBDHIDInit().
2061//! \param pi8Data points to a buffer into which the received data will be
2062//! written.
2063//! \param ui32Length is the size of the buffer pointed to by pi8Data.
2064//! \param bLast indicates whether the client will make a further call to
2065//! read additional data from the packet.
2066//!
2067//! This function reads up to \e ui32Length bytes of data received from the USB
2068//! host into the supplied application buffer.  If the driver detects that the
2069//! entire packet has been read, it is acknowledged to the host.
2070//!
2071//! The \e bLast parameter is ignored in this implementation since the end of
2072//! a packet can be determined without relying upon the client to provide
2073//! this information.
2074//!
2075//! \return Returns the number of bytes of data read.
2076//
2077//*****************************************************************************
2078uint32_t USBDHIDPacketRead(void* pvHIDInstance, uint8_t* pi8Data,
2079                           uint32_t ui32Length, bool bLast) {
2080    uint32_t ui32EPStatus, ui32Count, ui32Pkt;
2081    tHIDInstance* psInst;
2082    int32_t i32Retcode;
2083
2084    ASSERT(pvHIDInstance);
2085
2086    //
2087    // Get our instance data pointer
2088    //
2089    psInst = &((tUSBDHIDDevice*)pvHIDInstance)->sPrivateData;
2090
2091    //
2092    // Does the relevant endpoint FIFO have a packet waiting for us?
2093    //
2094    ui32EPStatus =
2095        MAP_USBEndpointStatus(psInst->ui32USBBase, psInst->ui8OUTEndpoint);
2096    if (ui32EPStatus & USB_DEV_RX_PKT_RDY) {
2097        //
2098        // How many bytes are available for us to receive?
2099        //
2100        ui32Pkt = MAP_USBEndpointDataAvail(psInst->ui32USBBase,
2101                                           psInst->ui8OUTEndpoint);
2102
2103        //
2104        // Get as much data as we can.
2105        //
2106        ui32Count = ui32Length;
2107        i32Retcode = MAP_USBEndpointDataGet(
2108            psInst->ui32USBBase, psInst->ui8OUTEndpoint, pi8Data, &ui32Count);
2109
2110        //
2111        // Did we read the last of the packet data?
2112        //
2113        if (ui32Count == ui32Pkt) {
2114            //
2115            // Clear the endpoint status so that we know no packet is
2116            // waiting.
2117            //
2118            MAP_USBDevEndpointStatusClear(psInst->ui32USBBase,
2119                                          psInst->ui8OUTEndpoint, ui32EPStatus);
2120
2121            //
2122            // Acknowledge the data, thus freeing the host to send the
2123            // next packet.
2124            //
2125            MAP_USBDevEndpointDataAck(psInst->ui32USBBase,
2126                                      psInst->ui8OUTEndpoint, true);
2127
2128            //
2129            // Clear the flag we set to indicate that a packet read is
2130            // pending.
2131            //
2132            SetDeferredOpFlag(&psInst->ui16DeferredOpFlags, HID_DO_PACKET_RX,
2133                              false);
2134        }
2135
2136        //
2137        // If all went well, tell the caller how many bytes they got.
2138        //
2139        if (i32Retcode != -1) {
2140            return (ui32Count);
2141        }
2142    }
2143
2144    //
2145    // No packet was available or an error occurred while reading so tell
2146    // the caller no bytes were returned.
2147    //
2148    return (0);
2149}
2150
2151//*****************************************************************************
2152//
2153//! Returns the number of free bytes in the transmit buffer.
2154//!
2155//! \param pvHIDInstance is the pointer to the device instance structure as
2156//! returned by USBDHIDInit().
2157//!
2158//! This function indicates to the caller whether or not it is safe to send a
2159//! new report using a call to USBDHIDReportWrite().  The value returned will
2160//! be the maximum USB packet size (\b USBDHID_MAX_PACKET) if no transmission
2161//! is currently outstanding or 0 if a transmission is in progress.  Since the
2162//! function USBDHIDReportWrite() can accept full reports longer than a single
2163//! USB packet, the caller should be aware that the returned value from this
2164//! class driver, unlike others, does not indicate the maximum size of report
2165//! that can be written but is merely an indication that another report can be
2166//! written.
2167//!
2168//! \return Returns 0 if an outgoing report is still being transmitted or
2169//! \b USBDHID_MAX_PACKET if no transmission is currently in progress.
2170//
2171//*****************************************************************************
2172uint32_t USBDHIDTxPacketAvailable(void* pvHIDInstance) {
2173    tHIDInstance* psInst;
2174
2175    ASSERT(pvHIDInstance);
2176
2177    //
2178    // Get our instance data pointer.
2179    //
2180    psInst = &((tUSBDHIDDevice*)pvHIDInstance)->sPrivateData;
2181
2182    //
2183    // Do we have a packet transmission currently ongoing?
2184    //
2185    if (psInst->iHIDTxState != eHIDStateIdle) {
2186        //
2187        // We are not ready to receive a new packet so return 0.
2188        //
2189        return (0);
2190    } else {
2191        //
2192        // We can receive a packet so return the max packet size for the
2193        // relevant endpoint.
2194        //
2195        return (USBDHID_MAX_PACKET);
2196    }
2197}
2198
2199//*****************************************************************************
2200//
2201//! Determines whether a packet is available and, if so, the size of the
2202//! buffer required to read it.
2203//!
2204//! \param pvHIDInstance is the pointer to the device instance structure as
2205//! returned by USBDHIDInit().
2206//!
2207//! This function may be used to determine if a received packet remains to be
2208//! read and allows the application to determine the buffer size needed to
2209//! read the data.
2210//!
2211//! \return Returns 0 if no received packet remains unprocessed or the
2212//! size of the packet if a packet is waiting to be read.
2213//
2214//*****************************************************************************
2215uint32_t USBDHIDRxPacketAvailable(void* pvHIDInstance) {
2216    uint32_t ui32EPStatus, ui32Size;
2217    tHIDInstance* psInst;
2218
2219    ASSERT(pvHIDInstance);
2220
2221    //
2222    // Get our instance data pointer
2223    //
2224    psInst = &((tUSBDHIDDevice*)pvHIDInstance)->sPrivateData;
2225
2226    //
2227    // Does the relevant endpoint FIFO have a packet waiting for us?
2228    //
2229    ui32EPStatus =
2230        MAP_USBEndpointStatus(psInst->ui32USBBase, psInst->ui8OUTEndpoint);
2231    if (ui32EPStatus & USB_DEV_RX_PKT_RDY) {
2232        //
2233        // Yes - a packet is waiting.  How big is it?
2234        //
2235        ui32Size = MAP_USBEndpointDataAvail(psInst->ui32USBBase,
2236                                            psInst->ui8OUTEndpoint);
2237
2238        return (ui32Size);
2239    } else {
2240        //
2241        // There is no packet waiting to be received.
2242        //
2243        return (0);
2244    }
2245}
2246#ifndef DEPRECATED
2247
2248//*****************************************************************************
2249//
2250//! Reports the device power status (bus- or self-powered) to the USB library.
2251//!
2252//! \param pvHIDInstance is the pointer to the HID device instance structure.
2253//! \param ui8Power indicates the current power status, either
2254//! \b USB_STATUS_SELF_PWR or \b USB_STATUS_BUS_PWR.
2255//!
2256//! Applications which support switching between bus- or self-powered
2257//! operation should call this function whenever the power source changes
2258//! to indicate the current power status to the USB library.  This information
2259//! is required by the USB library to allow correct responses to be provided
2260//! when the host requests status from the device.
2261//!
2262//! \return None.
2263//
2264//*****************************************************************************
2265void USBDHIDPowerStatusSet(void* pvHIDInstance, uint8_t ui8Power) {
2266    ASSERT(pvHIDInstance);
2267
2268    //
2269    // Pass the request through to the lower layer.
2270    //
2271    USBDCDPowerStatusSet(0, ui8Power);
2272}
2273#endif
2274
2275//*****************************************************************************
2276//
2277//! Requests a remote wake up to resume communication when in suspended state.
2278//!
2279//! \param pvHIDInstance is the pointer to the HID device instance structure.
2280//!
2281//! When the bus is suspended, an application which supports remote wake up
2282//! (advertised to the host via the configuration descriptor) may call this
2283//! function to initiate remote wake up signaling to the host.  If the remote
2284//! wake up feature has not been disabled by the host, this will cause the bus
2285//! to resume operation within 20mS.  If the host has disabled remote wake up,
2286//! \b false will be returned to indicate that the wake up request was not
2287//! successful.
2288//!
2289//! \return Returns \b true if the remote wake up is not disabled and the
2290//! signaling was started or \b false if remote wake up is disabled or if
2291//! signaling is currently ongoing following a previous call to this function.
2292//
2293//*****************************************************************************
2294bool USBDHIDRemoteWakeupRequest(void* pvHIDInstance) {
2295    ASSERT(pvHIDInstance);
2296
2297    //
2298    // Pass the request through to the lower layer.
2299    //
2300    return (USBDCDRemoteWakeupRequest(0));
2301}
2302
2303//*****************************************************************************
2304//
2305// Close the Doxygen group.
2306//! @}
2307//
2308//*****************************************************************************