1 /*
2 * Copyright (c) 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 #include "p2p_broadcast_receiver.h"
16
17 #include "conn_log.h"
18 #include "softbus_error_code.h"
19
20 namespace OHOS::SoftBus {
GetInstance()21 P2pBroadcast *P2pBroadcast::GetInstance()
22 {
23 static P2pBroadcast instance;
24 return &instance;
25 }
26
RegisterBroadcastListener(const BroadcastReceiverAction * actions,size_t size,const std::string & name,ListenerPriority priority,BroadcastListener listener)27 int P2pBroadcast::RegisterBroadcastListener(const BroadcastReceiverAction *actions, size_t size,
28 const std::string &name, ListenerPriority priority, BroadcastListener listener)
29 {
30 CONN_CHECK_AND_RETURN_RET_LOGE(actions, SOFTBUS_INVALID_PARAM, CONN_WIFI_DIRECT, "action is null");
31 CONN_CHECK_AND_RETURN_RET_LOGE(listener, SOFTBUS_INVALID_PARAM, CONN_WIFI_DIRECT, "listener is null");
32
33 for (size_t i = 0; i < size; i++) {
34 BroadcastReceiverAction action = actions[i];
35 ActionListener actionListener {};
36 actionListener.priority = priority;
37 actionListener.listener = listener;
38 actionListener.name = name;
39 listenerMap_[action].push_back(actionListener);
40 }
41 return SOFTBUS_OK;
42 }
43
DispatchWorkHandler(BroadcastReceiverAction action,const BroadcastParam & param)44 void P2pBroadcast::DispatchWorkHandler(BroadcastReceiverAction action, const BroadcastParam ¶m)
45 {
46 auto it = listenerMap_.find(action);
47 if (it == listenerMap_.end()) {
48 CONN_LOGE(CONN_WIFI_DIRECT, "listener not find, action=%{public}d", static_cast<int>(action));
49 return;
50 }
51
52 std::vector<ActionListener> listeners = it->second;
53 for (auto priority = static_cast<int32_t>(ListenerPriority::LISTENER_PRIORITY_HIGH);
54 priority >= static_cast<int32_t>(ListenerPriority::LISTENER_PRIORITY_LOW); priority--) {
55 for (auto &listener : listeners) {
56 if (static_cast<int32_t>(listener.priority) == priority && listener.listener) {
57 listener.listener(action, param);
58 }
59 }
60 }
61 }
62
63 } // namespace OHOS::SoftBus
64