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