1/******************************************************************************
2 *
3 *  Copyright (C) 2009-2012 Broadcom Corporation
4 *
5 *  Licensed under the Apache License, Version 2.0 (the "License");
6 *  you may not use this file except in compliance with the License.
7 *  You may obtain a copy of the License at:
8 *
9 *  http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 *
17 ******************************************************************************/
18
19//#if (defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE))
20
21#include <ctype.h>
22#include <fcntl.h>
23#include <sys/poll.h>
24#include <pthread.h>
25#include <stdio.h>
26#include <string.h>
27#include <stdint.h>
28#include <errno.h>
29#include <unistd.h>
30#include <linux/uhid.h>
31#include <unistd.h>
32#include "btif_hh.h"
33#include "bta_api.h"
34#include "bta_hh_api.h"
35#include "btif_util.h"
36#include "bta_hh_co.h"
37
38const char *dev_path = "/dev/uhid";
39
40#if (BLE_INCLUDED == TRUE && BTA_HH_LE_INCLUDED == TRUE)
41#include "btif_config.h"
42#define BTA_HH_NV_LOAD_MAX       16
43static tBTA_HH_RPT_CACHE_ENTRY sReportCache[BTA_HH_NV_LOAD_MAX];
44#endif
45
46/*Internal function to perform UHID write and error checking*/
47static int uhid_write(int fd, const struct uhid_event *ev)
48{
49    ssize_t ret;
50    ret = write(fd, ev, sizeof(*ev));
51    if (ret < 0){
52        int rtn = -errno;
53        APPL_TRACE_ERROR("%s: Cannot write to uhid:%s",
54                         __FUNCTION__, strerror(errno));
55        return rtn;
56    } else if (ret != (ssize_t)sizeof(*ev)) {
57        APPL_TRACE_ERROR("%s: Wrong size written to uhid: %zd != %zu",
58                         __FUNCTION__, ret, sizeof(*ev));
59        return -EFAULT;
60    } else {
61        return 0;
62    }
63}
64
65/* Internal function to parse the events received from UHID driver*/
66static int uhid_event(btif_hh_device_t *p_dev)
67{
68    struct uhid_event ev;
69    ssize_t ret;
70    memset(&ev, 0, sizeof(ev));
71    if(!p_dev)
72    {
73        APPL_TRACE_ERROR("%s: Device not found",__FUNCTION__)
74        return -1;
75    }
76    ret = read(p_dev->fd, &ev, sizeof(ev));
77    if (ret == 0) {
78        APPL_TRACE_ERROR("%s: Read HUP on uhid-cdev %s", __FUNCTION__,
79                                                 strerror(errno));
80        return -EFAULT;
81    } else if (ret < 0) {
82        APPL_TRACE_ERROR("%s: Cannot read uhid-cdev: %s", __FUNCTION__,
83                                                strerror(errno));
84        return -errno;
85    } else if (ret < (ssize_t)sizeof(ev.type)) {
86        APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu",
87                         __FUNCTION__, ret, sizeof(ev.type));
88        return -EFAULT;
89    }
90
91    switch (ev.type) {
92    case UHID_START:
93        APPL_TRACE_DEBUG("UHID_START from uhid-dev\n");
94        break;
95    case UHID_STOP:
96        APPL_TRACE_DEBUG("UHID_STOP from uhid-dev\n");
97        break;
98    case UHID_OPEN:
99        APPL_TRACE_DEBUG("UHID_OPEN from uhid-dev\n");
100        break;
101    case UHID_CLOSE:
102        APPL_TRACE_DEBUG("UHID_CLOSE from uhid-dev\n");
103        break;
104    case UHID_OUTPUT:
105        if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output))) {
106            APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu",
107                             __FUNCTION__, ret,
108                             sizeof(ev.type) + sizeof(ev.u.output));
109            return -EFAULT;
110        }
111
112        APPL_TRACE_DEBUG("UHID_OUTPUT: Report type = %d, report_size = %d"
113                            ,ev.u.output.rtype, ev.u.output.size);
114        //Send SET_REPORT with feature report if the report type in output event is FEATURE
115        if(ev.u.output.rtype == UHID_FEATURE_REPORT)
116            btif_hh_setreport(p_dev, BTHH_FEATURE_REPORT,
117                              ev.u.output.size, ev.u.output.data);
118        else if(ev.u.output.rtype == UHID_OUTPUT_REPORT)
119            btif_hh_setreport(p_dev, BTHH_OUTPUT_REPORT,
120                              ev.u.output.size, ev.u.output.data);
121        else
122            btif_hh_setreport(p_dev, BTHH_INPUT_REPORT,
123                              ev.u.output.size, ev.u.output.data);
124           break;
125    case UHID_OUTPUT_EV:
126        APPL_TRACE_DEBUG("UHID_OUTPUT_EV from uhid-dev\n");
127        break;
128    case UHID_FEATURE:
129        APPL_TRACE_DEBUG("UHID_FEATURE from uhid-dev\n");
130        break;
131    case UHID_FEATURE_ANSWER:
132        APPL_TRACE_DEBUG("UHID_FEATURE_ANSWER from uhid-dev\n");
133        break;
134
135    default:
136        APPL_TRACE_DEBUG("Invalid event from uhid-dev: %u\n", ev.type);
137    }
138
139    return 0;
140}
141
142/*******************************************************************************
143**
144** Function create_thread
145**
146** Description creat a select loop
147**
148** Returns pthread_t
149**
150*******************************************************************************/
151static inline pthread_t create_thread(void *(*start_routine)(void *), void * arg){
152    APPL_TRACE_DEBUG("create_thread: entered");
153    pthread_attr_t thread_attr;
154
155    pthread_attr_init(&thread_attr);
156    pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
157    pthread_t thread_id = -1;
158    if ( pthread_create(&thread_id, &thread_attr, start_routine, arg)!=0 )
159    {
160        APPL_TRACE_ERROR("pthread_create : %s", strerror(errno));
161        return -1;
162    }
163    APPL_TRACE_DEBUG("create_thread: thread created successfully");
164    return thread_id;
165}
166
167/*******************************************************************************
168**
169** Function btif_hh_poll_event_thread
170**
171** Description the polling thread which polls for event from UHID driver
172**
173** Returns void
174**
175*******************************************************************************/
176static void *btif_hh_poll_event_thread(void *arg)
177{
178
179    btif_hh_device_t *p_dev = arg;
180    APPL_TRACE_DEBUG("%s: Thread created fd = %d", __FUNCTION__, p_dev->fd);
181    struct pollfd pfds[1];
182    int ret;
183    pfds[0].fd = p_dev->fd;
184    pfds[0].events = POLLIN;
185
186    while(p_dev->hh_keep_polling){
187        ret = poll(pfds, 1, 50);
188        if (ret < 0) {
189            APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __FUNCTION__, strerror(errno));
190            break;
191        }
192        if (pfds[0].revents & POLLIN) {
193            APPL_TRACE_DEBUG("btif_hh_poll_event_thread: POLLIN");
194            ret = uhid_event(p_dev);
195            if (ret){
196                break;
197            }
198        }
199    }
200
201    p_dev->hh_poll_thread_id = -1;
202    return 0;
203}
204
205static inline void btif_hh_close_poll_thread(btif_hh_device_t *p_dev)
206{
207    APPL_TRACE_DEBUG("%s", __FUNCTION__);
208    p_dev->hh_keep_polling = 0;
209    if(p_dev->hh_poll_thread_id > 0)
210        pthread_join(p_dev->hh_poll_thread_id,NULL);
211
212    return;
213}
214
215void bta_hh_co_destroy(int fd)
216{
217    struct uhid_event ev;
218    memset(&ev, 0, sizeof(ev));
219    ev.type = UHID_DESTROY;
220    uhid_write(fd, &ev);
221    APPL_TRACE_DEBUG("%s: Closing fd=%d", __func__, fd);
222    close(fd);
223}
224
225int bta_hh_co_write(int fd, UINT8* rpt, UINT16 len)
226{
227    APPL_TRACE_DEBUG("bta_hh_co_data: UHID write");
228    struct uhid_event ev;
229    memset(&ev, 0, sizeof(ev));
230    ev.type = UHID_INPUT;
231    ev.u.input.size = len;
232    if(len > sizeof(ev.u.input.data)){
233        APPL_TRACE_WARNING("%s: Report size greater than allowed size",
234                           __FUNCTION__);
235        return -1;
236    }
237    memcpy(ev.u.input.data, rpt, len);
238    return uhid_write(fd, &ev);
239
240}
241
242
243/*******************************************************************************
244**
245** Function      bta_hh_co_open
246**
247** Description   When connection is opened, this call-out function is executed
248**               by HH to do platform specific initialization.
249**
250** Returns       void.
251*******************************************************************************/
252void bta_hh_co_open(UINT8 dev_handle, UINT8 sub_class, tBTA_HH_ATTR_MASK attr_mask,
253                    UINT8 app_id)
254{
255    UINT32 i;
256    btif_hh_device_t *p_dev = NULL;
257
258    if (dev_handle == BTA_HH_INVALID_HANDLE) {
259        APPL_TRACE_WARNING("%s: Oops, dev_handle (%d) is invalid...",
260                           __FUNCTION__, dev_handle);
261        return;
262    }
263
264    for (i = 0; i < BTIF_HH_MAX_HID; i++) {
265        p_dev = &btif_hh_cb.devices[i];
266        if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN &&
267            p_dev->dev_handle == dev_handle) {
268            // We found a device with the same handle. Must be a device reconnected.
269            APPL_TRACE_WARNING("%s: Found an existing device with the same handle "
270                                                                "dev_status = %d",__FUNCTION__,
271                                                                p_dev->dev_status);
272            APPL_TRACE_WARNING("%s:     bd_addr = [%02X:%02X:%02X:%02X:%02X:]", __FUNCTION__,
273                 p_dev->bd_addr.address[0], p_dev->bd_addr.address[1], p_dev->bd_addr.address[2],
274                 p_dev->bd_addr.address[3], p_dev->bd_addr.address[4]);
275                 APPL_TRACE_WARNING("%s:     attr_mask = 0x%04x, sub_class = 0x%02x, app_id = %d",
276                                  __FUNCTION__, p_dev->attr_mask, p_dev->sub_class, p_dev->app_id);
277
278            if(p_dev->fd<0) {
279                p_dev->fd = open(dev_path, O_RDWR | O_CLOEXEC);
280                if (p_dev->fd < 0){
281                    APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s",
282                                                                    __FUNCTION__,strerror(errno));
283                }else
284                    APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
285            }
286            p_dev->hh_keep_polling = 1;
287            p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev);
288            break;
289        }
290        p_dev = NULL;
291    }
292
293    if (p_dev == NULL) {
294        // Did not find a device reconnection case. Find an empty slot now.
295        for (i = 0; i < BTIF_HH_MAX_HID; i++) {
296            if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_UNKNOWN) {
297                p_dev = &btif_hh_cb.devices[i];
298                p_dev->dev_handle = dev_handle;
299                p_dev->attr_mask  = attr_mask;
300                p_dev->sub_class  = sub_class;
301                p_dev->app_id     = app_id;
302                p_dev->local_vup  = FALSE;
303
304                btif_hh_cb.device_num++;
305                // This is a new device,open the uhid driver now.
306                p_dev->fd = open(dev_path, O_RDWR | O_CLOEXEC);
307                if (p_dev->fd < 0){
308                    APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s",
309                                                                    __FUNCTION__,strerror(errno));
310                }else{
311                    APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd);
312                    p_dev->hh_keep_polling = 1;
313                    p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev);
314                }
315
316
317                break;
318            }
319        }
320    }
321
322    if (p_dev == NULL) {
323        APPL_TRACE_ERROR("%s: Error: too many HID devices are connected", __FUNCTION__);
324        return;
325    }
326
327    p_dev->dev_status = BTHH_CONN_STATE_CONNECTED;
328    APPL_TRACE_DEBUG("%s: Return device status %d", __FUNCTION__, p_dev->dev_status);
329}
330
331
332/*******************************************************************************
333**
334** Function      bta_hh_co_close
335**
336** Description   When connection is closed, this call-out function is executed
337**               by HH to do platform specific finalization.
338**
339** Parameters    dev_handle  - device handle
340**                  app_id      - application id
341**
342** Returns          void.
343*******************************************************************************/
344void bta_hh_co_close(UINT8 dev_handle, UINT8 app_id)
345{
346    UINT32 i;
347    btif_hh_device_t *p_dev = NULL;
348
349    APPL_TRACE_WARNING("%s: dev_handle = %d, app_id = %d", __FUNCTION__, dev_handle, app_id);
350    if (dev_handle == BTA_HH_INVALID_HANDLE) {
351        APPL_TRACE_WARNING("%s: Oops, dev_handle (%d) is invalid...", __FUNCTION__, dev_handle);
352        return;
353    }
354
355    for (i = 0; i < BTIF_HH_MAX_HID; i++) {
356        p_dev = &btif_hh_cb.devices[i];
357        if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN && p_dev->dev_handle == dev_handle) {
358            APPL_TRACE_WARNING("%s: Found an existing device with the same handle "
359                                                        "dev_status = %d, dev_handle =%d"
360                                                        ,__FUNCTION__,p_dev->dev_status
361                                                        ,p_dev->dev_handle);
362            btif_hh_close_poll_thread(p_dev);
363            break;
364        }
365     }
366}
367
368
369/*******************************************************************************
370**
371** Function         bta_hh_co_data
372**
373** Description      This function is executed by BTA when HID host receive a data
374**                  report.
375**
376** Parameters       dev_handle  - device handle
377**                  *p_rpt      - pointer to the report data
378**                  len         - length of report data
379**                  mode        - Hid host Protocol Mode
380**                  sub_clas    - Device Subclass
381**                  app_id      - application id
382**
383** Returns          void
384*******************************************************************************/
385void bta_hh_co_data(UINT8 dev_handle, UINT8 *p_rpt, UINT16 len, tBTA_HH_PROTO_MODE mode,
386                    UINT8 sub_class, UINT8 ctry_code, BD_ADDR peer_addr, UINT8 app_id)
387{
388    btif_hh_device_t *p_dev;
389    UNUSED(peer_addr);
390
391    APPL_TRACE_DEBUG("%s: dev_handle = %d, subclass = 0x%02X, mode = %d, "
392         "ctry_code = %d, app_id = %d",
393         __FUNCTION__, dev_handle, sub_class, mode, ctry_code, app_id);
394
395    p_dev = btif_hh_find_connected_dev_by_handle(dev_handle);
396    if (p_dev == NULL) {
397        APPL_TRACE_WARNING("%s: Error: unknown HID device handle %d", __FUNCTION__, dev_handle);
398        return;
399    }
400    // Send the HID report to the kernel.
401    if (p_dev->fd >= 0) {
402        bta_hh_co_write(p_dev->fd, p_rpt, len);
403    }else {
404        APPL_TRACE_WARNING("%s: Error: fd = %d, len = %d", __FUNCTION__, p_dev->fd, len);
405    }
406}
407
408
409/*******************************************************************************
410**
411** Function         bta_hh_co_send_hid_info
412**
413** Description      This function is called in btif_hh.c to process DSCP received.
414**
415** Parameters       dev_handle  - device handle
416**                  dscp_len    - report descriptor length
417**                  *p_dscp     - report descriptor
418**
419** Returns          void
420*******************************************************************************/
421void bta_hh_co_send_hid_info(btif_hh_device_t *p_dev, char *dev_name, UINT16 vendor_id,
422                             UINT16 product_id, UINT16 version, UINT8 ctry_code,
423                             int dscp_len, UINT8 *p_dscp)
424{
425    int result;
426    struct uhid_event ev;
427
428    if (p_dev->fd < 0) {
429        APPL_TRACE_WARNING("%s: Error: fd = %d, dscp_len = %d", __FUNCTION__, p_dev->fd, dscp_len);
430        return;
431    }
432
433    APPL_TRACE_WARNING("%s: fd = %d, name = [%s], dscp_len = %d", __FUNCTION__,
434                                                                    p_dev->fd, dev_name, dscp_len);
435    APPL_TRACE_WARNING("%s: vendor_id = 0x%04x, product_id = 0x%04x, version= 0x%04x,"
436                                                                    "ctry_code=0x%02x",__FUNCTION__,
437                                                                    vendor_id, product_id,
438                                                                    version, ctry_code);
439
440//Create and send hid descriptor to kernel
441    memset(&ev, 0, sizeof(ev));
442    ev.type = UHID_CREATE;
443    strncpy((char*)ev.u.create.name, dev_name, sizeof(ev.u.create.name) - 1);
444    snprintf((char*)ev.u.create.uniq, sizeof(ev.u.create.uniq),
445             "%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X",
446             p_dev->bd_addr.address[5], p_dev->bd_addr.address[4],
447             p_dev->bd_addr.address[3], p_dev->bd_addr.address[2],
448             p_dev->bd_addr.address[1], p_dev->bd_addr.address[0]);
449    ev.u.create.rd_size = dscp_len;
450    ev.u.create.rd_data = p_dscp;
451    ev.u.create.bus = BUS_BLUETOOTH;
452    ev.u.create.vendor = vendor_id;
453    ev.u.create.product = product_id;
454    ev.u.create.version = version;
455    ev.u.create.country = ctry_code;
456    result = uhid_write(p_dev->fd, &ev);
457
458    APPL_TRACE_WARNING("%s: fd = %d, dscp_len = %d, result = %d", __FUNCTION__,
459                                                                    p_dev->fd, dscp_len, result);
460
461    if (result) {
462        APPL_TRACE_WARNING("%s: Error: failed to send DSCP, result = %d", __FUNCTION__, result);
463
464        /* The HID report descriptor is corrupted. Close the driver. */
465        close(p_dev->fd);
466        p_dev->fd = -1;
467    }
468}
469
470#if (BLE_INCLUDED == TRUE && BTA_HH_LE_INCLUDED == TRUE)
471/*******************************************************************************
472**
473** Function         bta_hh_le_co_rpt_info
474**
475** Description      This callout function is to convey the report information on
476**                  a HOGP device to the application. Application can save this
477**                  information in NV if device is bonded and load it back when
478**                  stack reboot.
479**
480** Parameters       remote_bda  - remote device address
481**                  p_entry     - report entry pointer
482**                  app_id      - application id
483**
484** Returns          void.
485**
486*******************************************************************************/
487void bta_hh_le_co_rpt_info(BD_ADDR remote_bda, tBTA_HH_RPT_CACHE_ENTRY *p_entry, UINT8 app_id)
488{
489    UNUSED(app_id);
490
491    unsigned idx = 0;
492
493    bdstr_t bdstr;
494    sprintf(bdstr, "%02x:%02x:%02x:%02x:%02x:%02x",
495        remote_bda[0], remote_bda[1], remote_bda[2],
496        remote_bda[3], remote_bda[4], remote_bda[5]);
497
498    size_t len = btif_config_get_bin_length(bdstr, "HidReport");
499    if (len >= sizeof(tBTA_HH_RPT_CACHE_ENTRY) && len <= sizeof(sReportCache))
500    {
501        btif_config_get_bin(bdstr, "HidReport", (uint8_t *)sReportCache, &len);
502        idx = len / sizeof(tBTA_HH_RPT_CACHE_ENTRY);
503    }
504
505    if (idx < BTA_HH_NV_LOAD_MAX)
506    {
507        memcpy(&sReportCache[idx++], p_entry, sizeof(tBTA_HH_RPT_CACHE_ENTRY));
508        btif_config_set_bin(bdstr, "HidReport", (const uint8_t *)sReportCache,
509            idx * sizeof(tBTA_HH_RPT_CACHE_ENTRY));
510        BTIF_TRACE_DEBUG("%s() - Saving report; dev=%s, idx=%d", __FUNCTION__, bdstr, idx);
511    }
512}
513
514
515/*******************************************************************************
516**
517** Function         bta_hh_le_co_cache_load
518**
519** Description      This callout function is to request the application to load the
520**                  cached HOGP report if there is any. When cache reading is completed,
521**                  bta_hh_le_ci_cache_load() is called by the application.
522**
523** Parameters       remote_bda  - remote device address
524**                  p_num_rpt: number of cached report
525**                  app_id      - application id
526**
527** Returns          the acched report array
528**
529*******************************************************************************/
530tBTA_HH_RPT_CACHE_ENTRY * bta_hh_le_co_cache_load (BD_ADDR remote_bda,
531                                                   UINT8 *p_num_rpt, UINT8 app_id)
532{
533    UNUSED(app_id);
534
535    unsigned idx = 0;
536
537    bdstr_t bdstr;
538    sprintf(bdstr, "%02x:%02x:%02x:%02x:%02x:%02x",
539        remote_bda[0], remote_bda[1], remote_bda[2],
540        remote_bda[3], remote_bda[4], remote_bda[5]);
541
542    size_t len = btif_config_get_bin_length(bdstr, "HidReport");
543    if (!p_num_rpt && len < sizeof(tBTA_HH_RPT_CACHE_ENTRY))
544        return NULL;
545
546    if (len > sizeof(sReportCache))
547        len = sizeof(sReportCache);
548    btif_config_get_bin(bdstr, "HidReport", (uint8_t *)sReportCache, &len);
549    *p_num_rpt = len / sizeof(tBTA_HH_RPT_CACHE_ENTRY);
550
551    BTIF_TRACE_DEBUG("%s() - Loaded %d reports; dev=%s", __FUNCTION__, *p_num_rpt, bdstr);
552
553    return sReportCache;
554}
555
556/*******************************************************************************
557**
558** Function         bta_hh_le_co_reset_rpt_cache
559**
560** Description      This callout function is to reset the HOGP device cache.
561**
562** Parameters       remote_bda  - remote device address
563**
564** Returns          none
565**
566*******************************************************************************/
567void bta_hh_le_co_reset_rpt_cache (BD_ADDR remote_bda, UINT8 app_id)
568{
569    UNUSED(app_id);
570
571    bdstr_t bdstr;
572    sprintf(bdstr, "%02x:%02x:%02x:%02x:%02x:%02x",
573        remote_bda[0], remote_bda[1], remote_bda[2],
574        remote_bda[3], remote_bda[4], remote_bda[5]);
575    btif_config_remove(bdstr, "HidReport");
576
577    BTIF_TRACE_DEBUG("%s() - Reset cache for bda %s", __FUNCTION__, bdstr);
578}
579#endif /* #if (BLE_INCLUDED == TRUE && BTA_HH_LE_INCLUDED == TRUE) */
580
581