1 /*
2  * Copyright (c) 2023-2024 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 #include "sys_dispatcher.h"
17 #include <cstdio>
18 #include <memory>
19 
20 #include "event.h"
21 #include "hiview_logger.h"
22 #include "plugin_factory.h"
23 #include "sys_event_service_adapter.h"
24 #include "sys_event.h"
25 
26 namespace OHOS {
27 namespace HiviewDFX {
28 REGISTER(SysEventDispatcher);
29 DEFINE_LOG_TAG("SysEventDispatcher");
30 
OnLoad()31 void SysEventDispatcher::OnLoad()
32 {
33     HIVIEW_LOGI("OnLoad.");
34 }
35 
OnUnload()36 void SysEventDispatcher::OnUnload()
37 {
38     HIVIEW_LOGI("OnUnload.");
39 }
40 
DispatchEvent(std::shared_ptr<SysEvent> & sysEvent)41 void SysEventDispatcher::DispatchEvent(std::shared_ptr<SysEvent>& sysEvent)
42 {
43     auto dispatchList = GetHiviewContext()->GetDisPatcherInfo(sysEvent->eventType_, sysEvent->eventName_,
44         sysEvent->GetTag(), sysEvent->domain_);
45     for (auto& dispatcher : dispatchList) {
46         auto ptr = dispatcher.lock();
47         if (ptr != nullptr) {
48             ptr->OnEventListeningCallback(*sysEvent);
49         }
50     }
51 }
52 
Convert2SysEvent(std::shared_ptr<Event> & event)53 std::shared_ptr<SysEvent> SysEventDispatcher::Convert2SysEvent(std::shared_ptr<Event>& event)
54 {
55     if (event == nullptr) {
56         HIVIEW_LOGE("event is null");
57         return nullptr;
58     }
59     if (event->messageType_ != Event::MessageType::SYS_EVENT) {
60         HIVIEW_LOGE("receive out of sys event type");
61         return nullptr;
62     }
63     std::shared_ptr<SysEvent> sysEvent = Event::DownCastTo<SysEvent>(event);
64     if (sysEvent == nullptr) {
65         HIVIEW_LOGE("sysevent is null");
66     }
67     return sysEvent;
68 }
69 
OnEvent(std::shared_ptr<Event> & event)70 bool SysEventDispatcher::OnEvent(std::shared_ptr<Event> &event)
71 {
72     auto sysEvent = Convert2SysEvent(event);
73     if (sysEvent == nullptr) {
74         return false;
75     }
76     DispatchEvent(sysEvent);
77     SysEventServiceAdapter::OnSysEvent(sysEvent);
78     return true;
79 }
80 } // namespace HiviewDFX
81 } // namespace OHOS
82