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