1 /* 2 * Copyright (C) 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 #ifndef NAPI_BLUETOOTH_EVENT_H_ 16 #define NAPI_BLUETOOTH_EVENT_H_ 17 18 #include <string> 19 #include <map> 20 #include <napi_bluetooth_utils.h> 21 22 namespace OHOS { 23 namespace Bluetooth { 24 25 class AsyncEventData : public BluetoothCallbackInfo { 26 public: 27 std::function<napi_value ()> packResult; 28 AsyncEventData(const std::shared_ptr<BluetoothCallbackInfo> & cb,std::function<napi_value ()> p)29 explicit AsyncEventData(const std::shared_ptr<BluetoothCallbackInfo> &cb, std::function<napi_value ()> p) 30 { 31 this->env_ = cb->env_; 32 this->callback_ = cb->callback_; 33 this->state_ = cb->state_; 34 this->deviceId_ = cb->deviceId_; 35 this->info_ = cb->info_; 36 packResult = p; 37 } 38 39 AsyncEventData() = delete; 40 ~AsyncEventData()41 virtual ~AsyncEventData() { 42 } 43 }; 44 45 void UpdateCallbackInfo(std::map<std::string, std::shared_ptr<BluetoothCallbackInfo>> callbackInfos, 46 const std::string &type); 47 48 class NapiEvent { 49 public: 50 static napi_value CreateResult(const std::shared_ptr<BluetoothCallbackInfo> &cb, int value); 51 static napi_value CreateResult(const std::shared_ptr<BluetoothCallbackInfo> &cb, 52 BluetoothOppTransferInformation &information); 53 static napi_value OnEvent(napi_env env, napi_callback_info cbinfo, 54 std::map<std::string, std::shared_ptr<BluetoothCallbackInfo>> &callbackInfos); 55 static napi_value OffEvent(napi_env env, napi_callback_info cbinfo, 56 std::map<std::string, std::shared_ptr<BluetoothCallbackInfo>> &callbackInfos); 57 static void EventNotify(AsyncEventData *asyncEvent); 58 59 template<typename T> CheckAndNotify(const std::shared_ptr<BluetoothCallbackInfo> & cb,const T & obj)60 static void CheckAndNotify(const std::shared_ptr<BluetoothCallbackInfo> &cb, const T& obj) 61 { 62 if (cb == nullptr) { 63 HILOGI("checkAndNotify event cb is nullptr!"); 64 return; 65 } 66 auto func = std::bind( 67 [](const std::shared_ptr<BluetoothCallbackInfo> &cb, T& obj) -> napi_value { 68 return NapiEvent::CreateResult(cb, obj); 69 }, 70 cb, obj); 71 AsyncEventData *asyncEvent = new (std::nothrow)AsyncEventData(cb, func); 72 if (asyncEvent == nullptr) { 73 HILOGI("asyncEvent is nullptr!"); 74 return; 75 } 76 EventNotify(asyncEvent); 77 } 78 }; 79 80 } // namespace Bluetooth 81 } // namespace OHOS 82 #endif /* NAPI_BLUETOOTH_EVENT_H_ */