1 /*
2  * Copyright (c) 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 "power_mgr_async_reply.h"
17 #include "power_common.h"
18 
19 namespace OHOS {
20 namespace PowerMgr {
OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)21 int PowerMgrStubAsync::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
22 {
23     POWER_HILOGI(COMP_FWK, "code=%{public}u, flags=%{public}d", code, option.GetFlags());
24     std::u16string descriptor = PowerMgrStubAsync::GetDescriptor();
25     std::u16string remoteDescriptor = data.ReadInterfaceToken();
26     if (descriptor != remoteDescriptor) {
27         POWER_HILOGE(COMP_FWK, "Descriptor is not matched");
28         return E_GET_POWER_SERVICE_FAILED;
29     }
30     int result = ERR_OK;
31     switch (code) {
32         case SEND_ASYNC_REPLY: {
33             int32_t replyData = data.ReadInt32();
34             SendAsyncReply(replyData);
35             break;
36         }
37         default:
38             result = IPCObjectStub::OnRemoteRequest(code, data, reply, option);
39             break;
40     }
41 
42     return result;
43 }
44 
SendAsyncReply(int replyValue)45 void PowerMgrStubAsync::SendAsyncReply(int replyValue)
46 {
47     std::unique_lock<std::mutex> lck(mutex_);
48     asyncReply_ = replyValue;
49     notified = true;
50     lck.unlock();
51     cv_.notify_all();
52 }
53 
WaitForAsyncReply(int timeout)54 int PowerMgrStubAsync::WaitForAsyncReply(int timeout)
55 {
56     std::unique_lock<std::mutex> lck(mutex_);
57     cv_.wait_for(lck, std::chrono::milliseconds(timeout), [this]() {
58         return notified;
59     });
60     return asyncReply_;
61 }
62 
SendAsyncReply(int replyValue)63 void PowerMgrProxyAsync::SendAsyncReply(int replyValue)
64 {
65     sptr<IRemoteObject> remote = Remote();
66     RETURN_IF(remote == nullptr);
67     MessageParcel data;
68     MessageParcel reply;
69     MessageOption option = { MessageOption::TF_ASYNC };
70     if (!data.WriteInterfaceToken(PowerMgrProxyAsync::GetDescriptor())) {
71         POWER_HILOGE(COMP_FWK, "Write descriptor failed");
72         return;
73     }
74     data.WriteInt32(replyValue);
75     remote->SendRequest(SEND_ASYNC_REPLY, data, reply, option);
76 }
77 } // namespace PowerMgr
78 } // namespace OHOS