blob: 2df2b3b914fb79138636c0a8f4310a525759ba8a [file] [log] [blame]
Zach Johnson917efb12017-02-26 23:46:05 -08001//
2// Copyright 2017 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
17#include "h4_protocol.h"
18
19#define LOG_TAG "android.hardware.bluetooth-hci-h4"
20#include <android-base/logging.h>
Peng Qi1d3d5a92017-06-19 18:01:07 +080021#include <errno.h>
Zach Johnson917efb12017-02-26 23:46:05 -080022#include <fcntl.h>
Peng Qi1d3d5a92017-06-19 18:01:07 +080023#include <log/log.h>
24#include <sys/uio.h>
Zach Johnson917efb12017-02-26 23:46:05 -080025
26namespace android {
27namespace hardware {
28namespace bluetooth {
29namespace hci {
30
31size_t H4Protocol::Send(uint8_t type, const uint8_t* data, size_t length) {
Peng Qi1d3d5a92017-06-19 18:01:07 +080032 struct iovec iov[] = {{&type, sizeof(type)},
33 {const_cast<uint8_t*>(data), length}};
34 ssize_t ret = 0;
35 do {
36 ret = TEMP_FAILURE_RETRY(writev(uart_fd_, iov, sizeof(iov) / sizeof(iov[0])));
37 } while (-1 == ret && EAGAIN == errno);
38
39 if (ret == -1) {
40 ALOGE("%s error writing to UART (%s)", __func__, strerror(errno));
41 } else if (ret == 0) {
42 // Nothing written :(
43 ALOGE("%s zero bytes written - something went wrong...", __func__);
Zach Johnson917efb12017-02-26 23:46:05 -080044 }
Peng Qi1d3d5a92017-06-19 18:01:07 +080045 return ret;
Zach Johnson917efb12017-02-26 23:46:05 -080046}
47
48void H4Protocol::OnPacketReady() {
49 switch (hci_packet_type_) {
50 case HCI_PACKET_TYPE_EVENT:
51 event_cb_(hci_packetizer_.GetPacket());
52 break;
53 case HCI_PACKET_TYPE_ACL_DATA:
54 acl_cb_(hci_packetizer_.GetPacket());
55 break;
56 case HCI_PACKET_TYPE_SCO_DATA:
57 sco_cb_(hci_packetizer_.GetPacket());
58 break;
59 default: {
60 bool bad_packet_type = true;
61 CHECK(!bad_packet_type);
62 }
63 }
64 // Get ready for the next type byte.
65 hci_packet_type_ = HCI_PACKET_TYPE_UNKNOWN;
66}
67
68void H4Protocol::OnDataReady(int fd) {
69 if (hci_packet_type_ == HCI_PACKET_TYPE_UNKNOWN) {
70 uint8_t buffer[1] = {0};
71 size_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, 1));
72 CHECK(bytes_read == 1);
73 hci_packet_type_ = static_cast<HciPacketType>(buffer[0]);
74 } else {
75 hci_packetizer_.OnDataReady(fd, hci_packet_type_);
76 }
77}
78
79} // namespace hci
80} // namespace bluetooth
81} // namespace hardware
82} // namespace android