1 /*
2  * Copyright (c) 2006-2023, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author       Notes
8  * 2012-01-03     Yi Qiu      first version
9  */
10 
11 #include <rtthread.h>
12 #include <drivers/usb_host.h>
13 #include "hid.h"
14 
15 #if defined(RT_USBH_HID) && defined(RT_USBH_HID_KEYBOARD)
16 
17 #define DBG_TAG    "usbhost.ukbd"
18 #define DBG_LVL           DBG_INFO
19 #include <rtdbg.h>
20 
21 static struct uprotocal kbd_protocal;
22 
rt_usbh_hid_kbd_callback(void * arg)23 static rt_err_t rt_usbh_hid_kbd_callback(void* arg)
24 {
25     int int1, int2;
26     struct uhid* hid;
27 
28     hid = (struct uhid*)arg;
29 
30     int1 = *(rt_uint32_t*)hid->buffer;
31     int2 = *(rt_uint32_t*)(&hid->buffer[4]);
32 
33     if(int1 != 0 || int2 != 0)
34     {
35         LOG_D("key down 0x%x, 0x%x", int1, int2);
36     }
37 
38     return RT_EOK;
39 }
40 
41 static rt_thread_t kbd_thread;
kbd_task(void * param)42 static void kbd_task(void* param)
43 {
44     struct uhintf* intf = (struct uhintf*)param;
45     while (1)
46     {
47         if (rt_usb_hcd_pipe_xfer(intf->device->hcd, ((struct uhid*)intf->user_data)->pipe_in,
48             ((struct uhid*)intf->user_data)->buffer, ((struct uhid*)intf->user_data)->pipe_in->ep.wMaxPacketSize,
49             USB_TIMEOUT_BASIC) == 0)
50         {
51             break;
52         }
53 
54         rt_usbh_hid_kbd_callback(intf->user_data);
55     }
56 }
57 
58 
rt_usbh_hid_kbd_init(void * arg)59 static rt_err_t rt_usbh_hid_kbd_init(void* arg)
60 {
61     struct uhintf* intf = (struct uhintf*)arg;
62 
63     RT_ASSERT(intf != RT_NULL);
64 
65     rt_usbh_hid_set_protocal(intf, 0);
66 
67     rt_usbh_hid_set_idle(intf, 10, 0);
68 
69     LOG_D("start usb keyboard");
70 
71     kbd_thread = rt_thread_create("kbd0", kbd_task, intf, 1024, 8, 100);
72     rt_thread_startup(kbd_thread);
73 
74     return RT_EOK;
75 }
76 
77 /**
78  * This function will define the hid keyboard protocal, it will be register to the protocal list.
79  *
80  * @return the keyboard protocal structure.
81  */
rt_usbh_hid_protocal_kbd(void)82 uprotocal_t rt_usbh_hid_protocal_kbd(void)
83 {
84     kbd_protocal.pro_id = USB_HID_KEYBOARD;
85 
86     kbd_protocal.init = rt_usbh_hid_kbd_init;
87     kbd_protocal.callback = rt_usbh_hid_kbd_callback;
88 
89     return &kbd_protocal;
90 }
91 
92 #endif
93 
94