1 /*
2 * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "hci_protocol.h"
17
18 #include <cerrno>
19 #include <cstring>
20
21 #include <unistd.h>
22
23 #include <hdf_log.h>
24 namespace OHOS {
25 namespace HDI {
26 namespace Bluetooth {
27 namespace Hci {
28 const PacketHeader HciProtocol::header_[HCI_PACKET_TYPE_MAX] = {
29 {.headerSize = 0, .dataLengthOffset = 0, .dataLengthSize = 0}, /* HCI_PACKET_TYPE_UNKNOWN */
30 {.headerSize = 3, .dataLengthOffset = 2, .dataLengthSize = 1}, /* HCI_PACKET_TYPE_COMMAND */
31 {.headerSize = 4, .dataLengthOffset = 2, .dataLengthSize = 2}, /* HCI_PACKET_TYPE_ACL_DATA */
32 {.headerSize = 3, .dataLengthOffset = 2, .dataLengthSize = 1}, /* HCI_PACKET_TYPE_SCO_DATA */
33 {.headerSize = 2, .dataLengthOffset = 1, .dataLengthSize = 1}, /* HCI_PACKET_TYPE_EVENT */
34 };
35
GetPacketHeaderInfo(HciPacketType packetType)36 const PacketHeader &HciProtocol::GetPacketHeaderInfo(HciPacketType packetType)
37 {
38 if (packetType >= HCI_PACKET_TYPE_MAX) {
39 return header_[HCI_PACKET_TYPE_UNKNOWN];
40 }
41 return header_[packetType];
42 }
43
Read(int fd,uint8_t * data,size_t length)44 ssize_t HciProtocol::Read(int fd, uint8_t *data, size_t length)
45 {
46 const int bufsize = 256;
47 char buf[bufsize] = {0};
48 ssize_t ret = TEMP_FAILURE_RETRY(read(fd, data, length));
49 if (ret == -1) {
50 strerror_r(errno, buf, sizeof(buf));
51 HDF_LOGE("read failed err:%s", buf);
52 ret = 0;
53 }
54 return ret;
55 }
56
Write(int fd,const uint8_t * data,size_t length)57 ssize_t HciProtocol::Write(int fd, const uint8_t *data, size_t length)
58 {
59 const int bufsize = 256;
60 char buf[bufsize] = {0};
61 ssize_t ret = 0;
62 do {
63 ret = TEMP_FAILURE_RETRY(write(fd, data, length));
64 } while (ret == -1 && errno == EAGAIN);
65
66 if (ret == -1) {
67 strerror_r(errno, buf, sizeof(buf));
68 HDF_LOGE("write failed err:%s", buf);
69 } else if (static_cast<size_t>(ret) != length) {
70 HDF_LOGE("write data %zd less than %zu.", ret, length);
71 }
72 return ret;
73 }
74 } // namespace Hci
75 } // namespace Bluetooth
76 } // namespace HDI
77 } // namespace OHOS