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 MSG_HANDLER_H 17 #define MSG_HANDLER_H 18 19 #include <functional> 20 #include <map> 21 #include <string> 22 23 #include "proto.h" 24 25 namespace OHOS { 26 namespace Msdp { 27 namespace DeviceStatus { 28 template<typename K, typename V> 29 class MsgHandler { 30 public: 31 struct MsgCallback { 32 K id; 33 V fun; 34 }; 35 36 public: Clear()37 void Clear() 38 { 39 callbacks_.clear(); 40 } CheckKey(K id)41 bool CheckKey(K id) 42 { 43 return (GetMsgCallback(id) != nullptr); 44 } 45 GetDebugInfo()46 const std::string& GetDebugInfo() const 47 { 48 std::string str; 49 for (auto &iter : callbacks_) { 50 str += std::to_string(iter.first); 51 str += ','; 52 } 53 if (!str.empty()) { 54 str.resize(str.size() - 1); 55 } 56 57 return std::move(str); 58 } 59 RegisterEvent(MsgCallback & msg)60 bool RegisterEvent(MsgCallback& msg) 61 { 62 auto it = callbacks_.find(msg.id); 63 if (it != callbacks_.end()) { 64 return false; 65 } 66 callbacks_[msg.id] = msg.fun; 67 return true; 68 } 69 70 protected: 71 virtual ~MsgHandler() = default; GetMsgCallback(K id)72 V *GetMsgCallback(K id) 73 { 74 auto iter = callbacks_.find(id); 75 if (iter == callbacks_.end()) { 76 return nullptr; 77 } 78 return &iter->second; 79 } 80 81 protected: 82 std::map<K, V> callbacks_; 83 }; 84 } // namespace DeviceStatus 85 } // namespace Msdp 86 } // namespace OHOS 87 #endif // MSG_HANDLER_H 88