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