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 "notifier_impl.h"
17
18 #include "logger.h"
19 #include "objectstore_errors.h"
20
21 namespace OHOS::ObjectStore {
GetInstance()22 std::shared_ptr<NotifierImpl> NotifierImpl::GetInstance()
23 {
24 static std::shared_ptr<NotifierImpl> instance;
25 static std::mutex instanceLock;
26 if (instance == nullptr) {
27 std::lock_guard<std::mutex> lockGuard(instanceLock);
28 if (instance == nullptr) {
29 instance = std::make_shared<NotifierImpl>();
30 if (instance == nullptr) {
31 LOG_ERROR("Failed to alloc NotifierImpl!");
32 return nullptr;
33 }
34 uint32_t ret = DistributedObjectStore::GetInstance()->SetStatusNotifier(instance);
35 if (ret != SUCCESS) {
36 LOG_ERROR("SetStatusNotifier %{public}d error", ret);
37 } else {
38 LOG_INFO("SetStatusNotifier success");
39 }
40 }
41 }
42 return instance;
43 }
44
AddWatcher(std::string & sessionId,JSWatcher * watcher)45 void NotifierImpl::AddWatcher(std::string &sessionId, JSWatcher *watcher)
46 {
47 std::lock_guard<std::mutex> lock(mutex_);
48 watchers_.insert_or_assign(sessionId, watcher);
49 }
50
DelWatcher(std::string & sessionId)51 void NotifierImpl::DelWatcher(std::string &sessionId)
52 {
53 std::lock_guard<std::mutex> lock(mutex_);
54 watchers_.erase(sessionId);
55 }
56
OnChanged(const std::string & sessionId,const std::string & networkId,const std::string & onlineStatus)57 void NotifierImpl::OnChanged(
58 const std::string &sessionId, const std::string &networkId, const std::string &onlineStatus)
59 {
60 LOG_INFO(
61 "status changed %{public}s %{public}s %{public}s", sessionId.c_str(), networkId.c_str(), onlineStatus.c_str());
62 std::lock_guard<std::mutex> lock(mutex_);
63 if (watchers_.count(sessionId) != 0) {
64 LOG_INFO(
65 "start emit %{public}s %{public}s %{public}s", sessionId.c_str(), networkId.c_str(), onlineStatus.c_str());
66 watchers_.at(sessionId)->Emit("status", sessionId, networkId, onlineStatus);
67 LOG_INFO(
68 "end emit %{public}s %{public}s %{public}s", sessionId.c_str(), networkId.c_str(), onlineStatus.c_str());
69 }
70 }
~NotifierImpl()71 NotifierImpl::~NotifierImpl()
72 {
73 }
74 } // namespace OHOS::ObjectStore
75