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 <unistd.h> 17#include <cerrno> 18#include <cinttypes> 19#include "bluetooth_socket_outputstream.h" 20#include "bluetooth_log.h" 21#include "sys/socket.h" 22 23namespace OHOS { 24namespace Bluetooth { 25 26static constexpr int32_t SOCKET_SEND_TIME_THRESHOLD = 1000; // 1000ms 27static int64_t GetNowTimestamp(void) 28{ 29 struct timeval tv; 30 gettimeofday(&tv, nullptr); 31 int64_t timestamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; 32 return timestamp; 33} 34 35OutputStream::OutputStream(int socketFd) : socketFd_(socketFd) 36{} 37 38OutputStream::~OutputStream() 39{} 40 41int OutputStream::Write(const uint8_t *buf, size_t length) 42{ 43 if (socketFd_ == -1) { 44 HILOGE("socket closed."); 45 return -1; 46 } 47 48 int64_t beginTimestamp = GetNowTimestamp(); 49 auto ret = send(socketFd_, buf, length, MSG_NOSIGNAL); 50 int64_t endTimestamp = GetNowTimestamp(); 51 if (endTimestamp - beginTimestamp > SOCKET_SEND_TIME_THRESHOLD) { 52 HILOGE("socket send time %{public}" PRId64, endTimestamp - beginTimestamp); 53 } 54 55 HILOGD("ret: %{public}zu", ret); 56 57 if (ret == -1) { 58 HILOGE("Error."); 59 return -1; 60 } 61 return ret; 62} 63} // namespace Bluetooth 64} // namespace OHOS