1 /*
2  * Copyright (c) 2022-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 "publisher_item.h"
17 
18 #include "constants.h"
19 #include "dh_utils_tool.h"
20 #include "distributed_hardware_log.h"
21 
22 namespace OHOS {
23 namespace DistributedHardware {
PublisherItem()24 PublisherItem::PublisherItem() : topic_(DHTopic::TOPIC_MIN)
25 {
26 }
27 
PublisherItem(DHTopic topic)28 PublisherItem::PublisherItem(DHTopic topic) : topic_(topic)
29 {
30     DHLOGE("Ctor PublisherItem, topic: %{public}d", topic);
31 }
32 
~PublisherItem()33 PublisherItem::~PublisherItem()
34 {
35     DHLOGE("Dtor PublisherItem, topic: %{public}d", topic_);
36     std::lock_guard<std::mutex> lock(mutex_);
37     listeners_.clear();
38 }
39 
AddListener(const sptr<IPublisherListener> listener)40 void PublisherItem::AddListener(const sptr<IPublisherListener> listener)
41 {
42     if (listener == nullptr) {
43         DHLOGE("Add null publisher listener");
44         return;
45     }
46 
47     std::lock_guard<std::mutex> lock(mutex_);
48     listeners_.insert(listener);
49 }
50 
RemoveListener(const sptr<IPublisherListener> listener)51 void PublisherItem::RemoveListener(const sptr<IPublisherListener> listener)
52 {
53     if (listener == nullptr) {
54         DHLOGE("Remove null publisher listener");
55         return;
56     }
57 
58     std::lock_guard<std::mutex> lock(mutex_);
59     for (const auto &lis : listeners_) {
60         if (lis->AsObject().GetRefPtr() == listener->AsObject().GetRefPtr()) {
61             listeners_.erase(lis);
62             break;
63         }
64     }
65 }
66 
PublishMessage(const std::string & message)67 void PublisherItem::PublishMessage(const std::string &message)
68 {
69     if (!IsMessageLengthValid(message)) {
70         return;
71     }
72     std::lock_guard<std::mutex> lock(mutex_);
73     for (const auto &listener : listeners_) {
74         listener->OnMessage(topic_, message);
75     }
76 }
77 } // DistributedHardware
78 } // OHOS