1 /* 2 * Copyright (c) 2022-2023 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 #ifndef DEVICESTATUS_EVENT_H 17 #define DEVICESTATUS_EVENT_H 18 19 #include <list> 20 #include <map> 21 #include <memory> 22 #include <mutex> 23 #include <string> 24 25 #include "napi/native_api.h" 26 27 namespace OHOS { 28 namespace Msdp { 29 namespace DeviceStatus { 30 struct DeviceStatusEventListener { 31 napi_ref onHandlerRef { nullptr }; 32 }; 33 34 class DeviceStatusEvent { 35 public: 36 DeviceStatusEvent(napi_env env); 37 DeviceStatusEvent() = default; 38 virtual ~DeviceStatusEvent(); 39 40 virtual bool On(int32_t eventType, napi_value handler, bool isOnce); 41 virtual bool Off(int32_t eventType, napi_value handler); 42 43 protected: 44 virtual bool OffOnce(int32_t eventType, napi_value handler); 45 virtual void OnEvent(int32_t eventType, size_t argc, int32_t value, bool isOnce); 46 void CheckRet(int32_t eventType, size_t argc, int32_t value, 47 std::shared_ptr<DeviceStatusEventListener> &typeHandler); 48 void SendRet(int32_t eventType, int32_t value, napi_value &result); 49 void ClearEventMap(); 50 bool RemoveAllCallback(int32_t eventType); 51 bool SaveCallbackByEvent(int32_t eventType, napi_value handler, bool isOnce, 52 std::map<int32_t, std::list<std::shared_ptr<DeviceStatusEventListener>>> events); 53 bool IsNoExistCallback(std::list<std::shared_ptr<DeviceStatusEventListener>>, 54 napi_value handler, int32_t eventType); 55 void SaveCallback(int32_t eventType, napi_ref onHandlerRef, bool isOnce); 56 57 napi_env env_ { nullptr }; 58 napi_ref thisVarRef_ { nullptr }; 59 std::mutex mutex_; 60 std::map<int32_t, std::list<std::shared_ptr<DeviceStatusEventListener>>> events_; 61 std::map<int32_t, std::list<std::shared_ptr<DeviceStatusEventListener>>> eventOnces_; 62 }; 63 } // namespace DeviceStatus 64 } // namespace Msdp 65 } // namespace OHOS 66 #endif // DEVICESTATUS_EVENT_H 67