1 /* 2 * Copyright (C) 2021 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 NAPI_BLUETOOTH_SPP_CLIENT_H_ 16 #define NAPI_BLUETOOTH_SPP_CLIENT_H_ 17 18 #include <thread> 19 #include <map> 20 #include <queue> 21 #include "bluetooth_socket.h" 22 #include "napi_bluetooth_utils.h" 23 24 namespace OHOS { 25 namespace Bluetooth { 26 struct SppConnectCallbackInfo : public AsyncCallbackInfo { 27 std::shared_ptr<ClientSocket> client_ = nullptr; 28 std::string deviceId_ = ""; 29 std::shared_ptr<BluetoothRemoteDevice> device_ = nullptr; 30 std::shared_ptr<SppOption> sppOption_ = nullptr; 31 }; 32 33 struct SppCallbackBuffer { 34 ssize_t len_; 35 char data_[1024]; 36 }; 37 38 struct BufferCallbackInfo : public BluetoothCallbackInfo { PushDataBufferCallbackInfo39 void PushData(const std::shared_ptr<SppCallbackBuffer> &data) 40 { 41 std::lock_guard<std::mutex> lock(bufferLock_); 42 buffer_.push(data); 43 } 44 PopDataBufferCallbackInfo45 std::shared_ptr<SppCallbackBuffer> PopData() 46 { 47 std::lock_guard<std::mutex> lock(bufferLock_); 48 if (buffer_.empty()) { 49 return nullptr; 50 } 51 std::shared_ptr<SppCallbackBuffer> ret = buffer_.front(); 52 buffer_.pop(); 53 return ret; 54 } 55 private: 56 std::mutex bufferLock_; 57 std::queue<std::shared_ptr<SppCallbackBuffer>> buffer_; 58 }; 59 60 const std::string REGISTER_SPP_READ_TYPE = "sppRead"; 61 std::shared_ptr<SppOption> GetSppOptionFromJS(napi_env env, napi_value object); 62 63 struct NapiSppClient { 64 static napi_value SppConnect(napi_env env, napi_callback_info info); 65 static napi_value SppCloseClientSocket(napi_env env, napi_callback_info info); 66 static napi_value SppWrite(napi_env env, napi_callback_info info); 67 static napi_value On(napi_env env, napi_callback_info info); 68 static napi_value Off(napi_env env, napi_callback_info info); 69 static void SppRead(int id); 70 71 static int count; 72 static std::map<int, std::shared_ptr<NapiSppClient>> clientMap; 73 74 int id_ = -1; 75 bool sppReadFlag = false; 76 std::map<std::string, std::shared_ptr<BluetoothCallbackInfo>> callbackInfos_ = {}; 77 78 std::shared_ptr<ClientSocket> client_ = nullptr; 79 std::shared_ptr<BluetoothRemoteDevice> device_ = nullptr; 80 std::shared_ptr<std::thread> thread_; 81 napi_threadsafe_function sppReadThreadSafeFunc_ = nullptr; 82 }; 83 } // namespace Bluetooth 84 } // namespace OHOS 85 #endif /* NAPI_BLUETOOTH_SPP_CLIENT_H_ */