1 /* 2 * Copyright (C) 2025 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 #ifndef BLUETOOTH_SPP_CLIENT_IMPL_H 16 #define BLUETOOTH_SPP_CLIENT_IMPL_H 17 18 #include <map> 19 #include <queue> 20 #include <thread> 21 22 #include "bluetooth_socket.h" 23 #include "bluetooth_spp_utils.h" 24 #include "cj_common_ffi.h" 25 #include "napi_bluetooth_utils.h" 26 27 namespace OHOS { 28 namespace Bluetooth { 29 struct CjBluetoothCallbackInfo { 30 int64_t callback_ = 0; 31 std::string deviceId_; 32 }; 33 34 struct SppCallbackBuffer { 35 ssize_t len_; 36 char data_[1024]; 37 }; 38 39 struct BufferCallbackInfo : public CjBluetoothCallbackInfo { PushDataBufferCallbackInfo40 void PushData(const std::shared_ptr<SppCallbackBuffer>& data) 41 { 42 std::lock_guard<std::mutex> lock(bufferLock_); 43 buffer_.push(data); 44 } 45 PopDataBufferCallbackInfo46 std::shared_ptr<SppCallbackBuffer> PopData() 47 { 48 std::lock_guard<std::mutex> lock(bufferLock_); 49 if (buffer_.empty()) { 50 return nullptr; 51 } 52 std::shared_ptr<SppCallbackBuffer> ret = buffer_.front(); 53 buffer_.pop(); 54 return ret; 55 } 56 57 private: 58 std::mutex bufferLock_; 59 std::queue<std::shared_ptr<SppCallbackBuffer>> buffer_; 60 }; 61 62 constexpr const char* REGISTER_SPP_READ_TYPE = "sppRead"; 63 64 struct SppClientImpl { 65 static int32_t SppConnect(std::string deviceId, SppOption sppOption, int32_t* errCode); 66 static int32_t SppCloseClientSocket(int32_t socket); 67 static int32_t SppWrite(int32_t clientSocket, CArrUI8 data); 68 static int32_t On(std::string type, int32_t clientSocket, int64_t cbId); 69 static int32_t Off(std::string type, int32_t clientSocket, int64_t cbId); 70 static void SppRead(int id); 71 static std::string GetDeviceId(int32_t clientSocket, int32_t* errCode); 72 73 static int count; 74 static std::map<int, std::shared_ptr<SppClientImpl>> clientMap; 75 76 int id_ = -1; 77 bool sppReadFlag = false; 78 std::map<std::string, std::shared_ptr<CjBluetoothCallbackInfo>> callbackInfos_ = {}; 79 80 std::shared_ptr<ClientSocket> client_ = nullptr; 81 std::shared_ptr<BluetoothRemoteDevice> device_ = nullptr; 82 std::shared_ptr<std::thread> thread_; 83 }; 84 } // namespace Bluetooth 85 } // namespace OHOS 86 #endif /* BLUETOOTH_SPP_CLIENT_IMPL_H */