• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 "distributed_device_profile_client.h"
17 
18 #include <algorithm>
19 #include <bitset>
20 #include <chrono>
21 #include <functional>
22 #include <new>
23 #include <nlohmann/json.hpp>
24 #include <string>
25 #include <thread>
26 #include <type_traits>
27 #include <unistd.h>
28 #include <utility>
29 
30 #include "device_profile_errors.h"
31 #include "device_profile_log.h"
32 #include "event_handler.h"
33 #include "event_runner.h"
34 #include "idistributed_device_profile.h"
35 #include "if_system_ability_manager.h"
36 #include "ipc_skeleton.h"
37 #include "iremote_broker.h"
38 #include "iservice_registry.h"
39 #include "profile_event_notifier_stub.h"
40 #include "service_characteristic_profile.h"
41 #include "system_ability_definition.h"
42 
43 namespace OHOS {
44 namespace DeviceProfile {
45 using namespace std::chrono_literals;
46 
47 namespace {
48 const std::string TAG = "DistributedDeviceProfileClient";
49 const std::string JSON_NULL = "null";
50 constexpr int32_t RETRY_TIMES_GET_SERVICE = 5;
51 }
52 
53 IMPLEMENT_SINGLE_INSTANCE(DistributedDeviceProfileClient);
54 
PutDeviceProfile(const ServiceCharacteristicProfile & profile)55 int32_t DistributedDeviceProfileClient::PutDeviceProfile(const ServiceCharacteristicProfile& profile)
56 {
57     if (CheckProfileInvalidity(profile)) {
58         return ERR_DP_INVALID_PARAMS;
59     }
60 
61     auto dps = GetDeviceProfileService();
62     if (dps == nullptr) {
63         return ERR_DP_GET_SERVICE_FAILED;
64     }
65     return dps->PutDeviceProfile(profile);
66 }
67 
GetDeviceProfile(const std::string & udid,const std::string & serviceId,ServiceCharacteristicProfile & profile)68 int32_t DistributedDeviceProfileClient::GetDeviceProfile(const std::string& udid, const std::string& serviceId,
69     ServiceCharacteristicProfile& profile)
70 {
71     auto dps = GetDeviceProfileService();
72     if (dps == nullptr) {
73         return ERR_DP_GET_SERVICE_FAILED;
74     }
75     return dps->GetDeviceProfile(udid, serviceId, profile);
76 }
77 
DeleteDeviceProfile(const std::string & serviceId)78 int32_t DistributedDeviceProfileClient::DeleteDeviceProfile(const std::string& serviceId)
79 {
80     if (serviceId.empty()) {
81         return ERR_DP_INVALID_PARAMS;
82     }
83 
84     auto dps = GetDeviceProfileService();
85     if (dps == nullptr) {
86         return ERR_DP_GET_SERVICE_FAILED;
87     }
88     return dps->DeleteDeviceProfile(serviceId);
89 }
90 
SubscribeProfileEvent(const SubscribeInfo & subscribeInfo,const std::shared_ptr<IProfileEventCallback> & eventCb)91 int32_t DistributedDeviceProfileClient::SubscribeProfileEvent(const SubscribeInfo& subscribeInfo,
92     const std::shared_ptr<IProfileEventCallback>& eventCb)
93 {
94     std::list<SubscribeInfo> subscribeInfos;
95     subscribeInfos.emplace_back(subscribeInfo);
96     std::list<ProfileEvent> failedEvents;
97     return SubscribeProfileEvents(subscribeInfos, eventCb, failedEvents);
98 }
99 
SubscribeProfileEvents(const std::list<SubscribeInfo> & subscribeInfos,const std::shared_ptr<IProfileEventCallback> & eventCb,std::list<ProfileEvent> & failedEvents)100 int32_t DistributedDeviceProfileClient::SubscribeProfileEvents(const std::list<SubscribeInfo>& subscribeInfos,
101     const std::shared_ptr<IProfileEventCallback>& eventCb,
102     std::list<ProfileEvent>& failedEvents)
103 {
104     if (subscribeInfos.empty() || eventCb == nullptr) {
105         return ERR_DP_INVALID_PARAMS;
106     }
107 
108     ProfileEvents subProfileEvents;
109     for (auto& subscribeInfo : subscribeInfos) {
110         subProfileEvents.set(static_cast<uint32_t>(subscribeInfo.profileEvent));
111     }
112     // duplicated profile event is disallowed
113     if (subProfileEvents.count() != subscribeInfos.size()) {
114         return ERR_DP_INVALID_PARAMS;
115     }
116 
117     std::unique_lock<std::mutex> autoLock(subscribeLock_);
118     sptr<IRemoteObject> notifier;
119     auto iter = subscribeRecords_.find(eventCb);
120     if (iter != subscribeRecords_.end()) {
121         notifier = iter->second.notifier;
122     } else {
123         notifier = sptr<ProfileEventNotifierStub>(
124             new ProfileEventNotifierStub(eventCb));
125     }
126     autoLock.unlock();
127 
128     auto dps = GetDeviceProfileService();
129     if (dps == nullptr) {
130         return ERR_DP_GET_SERVICE_FAILED;
131     }
132 
133     failedEvents.clear();
134     int32_t errCode = dps->SubscribeProfileEvents(subscribeInfos, notifier, failedEvents);
135     for (auto failedEvent : failedEvents) {
136         subProfileEvents.reset(static_cast<uint32_t>(failedEvent));
137     }
138 
139     autoLock.lock();
140     iter = subscribeRecords_.find(eventCb);
141     if (iter != subscribeRecords_.end()) {
142         MergeSubscribeInfoLocked(iter->second.subscribeInfos, subscribeInfos);
143         iter->second.profileEvents |= subProfileEvents;
144     } else {
145         SubscribeRecord record {subscribeInfos, notifier, subProfileEvents};
146         subscribeRecords_.emplace(eventCb, std::move(record));
147     }
148     return errCode;
149 }
150 
UnsubscribeProfileEvent(ProfileEvent profileEvent,const std::shared_ptr<IProfileEventCallback> & eventCb)151 int32_t DistributedDeviceProfileClient::UnsubscribeProfileEvent(ProfileEvent profileEvent,
152     const std::shared_ptr<IProfileEventCallback>& eventCb)
153 {
154     std::list<ProfileEvent> profileEvents;
155     profileEvents.emplace_back(profileEvent);
156     std::list<ProfileEvent> failedEvents;
157     return UnsubscribeProfileEvents(profileEvents, eventCb, failedEvents);
158 }
159 
UnsubscribeProfileEvents(const std::list<ProfileEvent> & profileEvents,const std::shared_ptr<IProfileEventCallback> & eventCb,std::list<ProfileEvent> & failedEvents)160 int32_t DistributedDeviceProfileClient::UnsubscribeProfileEvents(const std::list<ProfileEvent>& profileEvents,
161     const std::shared_ptr<IProfileEventCallback>& eventCb,
162     std::list<ProfileEvent>& failedEvents)
163 {
164     if (profileEvents.empty() || eventCb == nullptr) {
165         return ERR_DP_INVALID_PARAMS;
166     }
167 
168     std::unique_lock<std::mutex> autoLock(subscribeLock_);
169     ProfileEvents unsubProfileEvents;
170     for (auto profileEvent : profileEvents) {
171         unsubProfileEvents.set(static_cast<uint32_t>(profileEvent));
172     }
173     auto iter = subscribeRecords_.find(eventCb);
174     if (iter == subscribeRecords_.end()) {
175         return ERR_DP_NOT_SUBSCRIBED;
176     }
177     sptr<IRemoteObject> notifier = iter->second.notifier;
178     autoLock.unlock();
179 
180     auto dps = GetDeviceProfileService();
181     if (dps == nullptr) {
182         return ERR_DP_GET_SERVICE_FAILED;
183     }
184 
185     failedEvents.clear();
186     int32_t errCode = dps->UnsubscribeProfileEvents(profileEvents, notifier, failedEvents);
187     autoLock.lock();
188     iter = subscribeRecords_.find(eventCb);
189     if (iter != subscribeRecords_.end()) {
190         for (auto failedEvent : failedEvents) {
191             unsubProfileEvents.reset(static_cast<uint32_t>(failedEvent));
192         }
193         auto& subProfileEvents = iter->second.profileEvents;
194         subProfileEvents &= ~unsubProfileEvents;
195         if (subProfileEvents.none()) {
196             subscribeRecords_.erase(iter);
197         }
198     }
199     return errCode;
200 }
201 
SyncDeviceProfile(const SyncOptions & syncOptions,const std::shared_ptr<IProfileEventCallback> & syncCb)202 int32_t DistributedDeviceProfileClient::SyncDeviceProfile(const SyncOptions& syncOptions,
203     const std::shared_ptr<IProfileEventCallback>& syncCb)
204 {
205     auto dps = GetDeviceProfileService();
206     if (dps == nullptr) {
207         return ERR_DP_GET_SERVICE_FAILED;
208     }
209 
210     sptr<IRemoteObject> notifier =
211         sptr<ProfileEventNotifierStub>(new ProfileEventNotifierStub(syncCb));
212     return dps->SyncDeviceProfile(syncOptions, notifier);
213 }
214 
GetDeviceProfileService()215 sptr<IDistributedDeviceProfile> DistributedDeviceProfileClient::GetDeviceProfileService()
216 {
217     std::lock_guard<std::mutex> lock(serviceLock_);
218     if (dpProxy_ != nullptr) {
219         return dpProxy_;
220     }
221 
222     auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
223     if (samgrProxy == nullptr) {
224         HILOGE("get samgr failed");
225         return nullptr;
226     }
227     auto object = samgrProxy->GetSystemAbility(DISTRIBUTED_DEVICE_PROFILE_SA_ID);
228     if (object == nullptr) {
229         HILOGE("get service failed");
230         return nullptr;
231     }
232     HILOGI("get service succeeded");
233     if (dpDeathRecipient_ == nullptr) {
234         dpDeathRecipient_ = sptr<IRemoteObject::DeathRecipient>(
235             new DeviceProfileDeathRecipient);
236     }
237     object->AddDeathRecipient(dpDeathRecipient_);
238     dpProxy_ = iface_cast<IDistributedDeviceProfile>(object);
239     return dpProxy_;
240 }
241 
CheckProfileInvalidity(const ServiceCharacteristicProfile & profile)242 bool DistributedDeviceProfileClient::CheckProfileInvalidity(const ServiceCharacteristicProfile& profile)
243 {
244     return profile.GetServiceId().empty() ||
245            profile.GetServiceType().empty() ||
246            profile.GetCharacteristicProfileJson().empty() ||
247            profile.GetCharacteristicProfileJson() == JSON_NULL;
248 }
249 
MergeSubscribeInfoLocked(std::list<SubscribeInfo> & subscribeInfos,const std::list<SubscribeInfo> & newSubscribeInfos)250 void DistributedDeviceProfileClient::MergeSubscribeInfoLocked(std::list<SubscribeInfo>& subscribeInfos,
251     const std::list<SubscribeInfo>& newSubscribeInfos)
252 {
253     for (const auto& newSubscribeInfo : newSubscribeInfos) {
254         auto iter = std::find_if(subscribeInfos.begin(), subscribeInfos.end(),
255             [&newSubscribeInfo](const auto& subscribeInfo) {
256             return subscribeInfo.profileEvent == newSubscribeInfo.profileEvent;
257         });
258         if (iter == subscribeInfos.end()) {
259             subscribeInfos.emplace_back(newSubscribeInfo);
260             continue;
261         }
262         // override with the new subscribe info for same profile event
263         *iter = newSubscribeInfo;
264     }
265 }
266 
OnServiceDied(const sptr<IRemoteObject> & remote)267 void DistributedDeviceProfileClient::OnServiceDied(const sptr<IRemoteObject>& remote)
268 {
269     HILOGI("called");
270     {
271         std::lock_guard<std::mutex> lock(serviceLock_);
272         dpProxy_ = nullptr;
273     }
274 
275     std::lock_guard<std::mutex> lock(subscribeLock_);
276     if (dpClientHandler_ == nullptr) {
277         auto runner = AppExecFwk::EventRunner::Create("dpclient" + std::to_string(getpid()));
278         dpClientHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
279     }
280 
281     // try resubscribe when device profile service died
282     auto resubscribe = [this]() {
283         int32_t retryTimes = 0;
284         sptr<IDistributedDeviceProfile> dps;
285         do {
286             std::this_thread::sleep_for(500ms);
287             dps = GetDeviceProfileService();
288             if (dps != nullptr) {
289                 HILOGI("get service succeeded");
290                 break;
291             }
292             if (retryTimes++ == RETRY_TIMES_GET_SERVICE) {
293                 HILOGE("get service timeout");
294                 return;
295             }
296         } while (true);
297 
298         std::list<ProfileEvent> failedEvents;
299         std::lock_guard<std::mutex> lock(subscribeLock_);
300         for (const auto& [_, subscribeRecord] : subscribeRecords_) {
301             int32_t errCode = dps->SubscribeProfileEvents(subscribeRecord.subscribeInfos,
302                 subscribeRecord.notifier, failedEvents);
303             HILOGI("resubscribe result = %{public}d", errCode);
304         }
305     };
306     if (dpClientHandler_ != nullptr && !dpClientHandler_->PostTask(resubscribe)) {
307         HILOGE("post task failed");
308     }
309 }
310 
OnRemoteDied(const wptr<IRemoteObject> & remote)311 void DistributedDeviceProfileClient::DeviceProfileDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
312 {
313     DistributedDeviceProfileClient::GetInstance().OnServiceDied(remote.promote());
314 }
315 } // namespace DeviceProfile
316 } // namespace OHOS
317