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 25#ifdef LOG_DOMAIN 26#undef LOG_DOMAIN 27#endif 28#define LOG_DOMAIN 0xD000105 29 30namespace OHOS { 31namespace HDI { 32namespace Bluetooth { 33namespace Hci { 34const PacketHeader HciProtocol::header_[HCI_PACKET_TYPE_MAX] = { 35 {.headerSize = 0, .dataLengthOffset = 0, .dataLengthSize = 0}, /* HCI_PACKET_TYPE_UNKNOWN */ 36 {.headerSize = 3, .dataLengthOffset = 2, .dataLengthSize = 1}, /* HCI_PACKET_TYPE_COMMAND */ 37 {.headerSize = 4, .dataLengthOffset = 2, .dataLengthSize = 2}, /* HCI_PACKET_TYPE_ACL_DATA */ 38 {.headerSize = 3, .dataLengthOffset = 2, .dataLengthSize = 1}, /* HCI_PACKET_TYPE_SCO_DATA */ 39 {.headerSize = 2, .dataLengthOffset = 1, .dataLengthSize = 1}, /* HCI_PACKET_TYPE_EVENT */ 40}; 41 42const PacketHeader &HciProtocol::GetPacketHeaderInfo(HciPacketType packetType) 43{ 44 if (packetType >= HCI_PACKET_TYPE_MAX) { 45 return header_[HCI_PACKET_TYPE_UNKNOWN]; 46 } 47 return header_[packetType]; 48} 49 50ssize_t HciProtocol::Read(int fd, uint8_t *data, size_t length) 51{ 52 const int bufsize = 256; 53 char buf[bufsize] = {0}; 54 ssize_t ret = TEMP_FAILURE_RETRY(read(fd, data, length)); 55 if (ret == -1) { 56 strerror_r(errno, buf, sizeof(buf)); 57 HDF_LOGE("read failed err:%s", buf); 58 ret = 0; 59 } 60 return ret; 61} 62 63ssize_t HciProtocol::Write(int fd, const uint8_t *data, size_t length) 64{ 65 const int bufsize = 256; 66 char buf[bufsize] = {0}; 67 ssize_t ret = 0; 68 do { 69 ret = TEMP_FAILURE_RETRY(write(fd, data, length)); 70 } while (ret == -1 && errno == EAGAIN); 71 72 if (ret == -1) { 73 strerror_r(errno, buf, sizeof(buf)); 74 HDF_LOGE("write failed err:%s", buf); 75 } else if (static_cast<size_t>(ret) != length) { 76 HDF_LOGE("write data %zd less than %zu.", ret, length); 77 } 78 return ret; 79} 80} // namespace Hci 81} // namespace Bluetooth 82} // namespace HDI 83} // namespace OHOS