1 /*
2 * Copyright (c) 2023 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 #include "ohos_loop_handler.h"
16
17 namespace OHOS {
18 namespace AbilityRuntime {
19
OnReadable(int32_t)20 void OHOSLoopHandler::OnReadable(int32_t)
21 {
22 HILOG_DEBUG("OHOSLoopHandler::OnReadable is triggered");
23 OnTriggered();
24 }
25
OnWritable(int32_t)26 void OHOSLoopHandler::OnWritable(int32_t)
27 {
28 HILOG_DEBUG("OHOSLoopHandler::OnWritable is triggered");
29 OnTriggered();
30 }
31
OnTriggered()32 void OHOSLoopHandler::OnTriggered()
33 {
34 HILOG_DEBUG("OHOSLoopHandler::OnTriggered is triggered");
35
36 auto fd = uv_backend_fd(uvLoop_);
37 struct epoll_event ev;
38 do {
39 uv_run(uvLoop_, UV_RUN_NOWAIT);
40 } while (epoll_wait(fd, &ev, 1, 0) > 0);
41
42 auto eventHandler = GetOwner();
43 if (!eventHandler) {
44 return;
45 }
46
47 int32_t timeout = uv_backend_timeout(uvLoop_);
48 if (timeout < 0) {
49 if (haveTimerTask_) {
50 eventHandler->RemoveTask(TIMER_TASK);
51 }
52 return;
53 }
54
55 int64_t timeStamp = static_cast<int64_t>(uv_now(uvLoop_)) + timeout;
56 if (timeStamp == lastTimeStamp_) {
57 return;
58 }
59
60 if (haveTimerTask_) {
61 eventHandler->RemoveTask(TIMER_TASK);
62 }
63
64 auto callback = [wp = weak_from_this()] {
65 auto sp = wp.lock();
66 if (sp) {
67 // Timer task is triggered, so there is no timer task now.
68 sp->haveTimerTask_ = false;
69 sp->OnTriggered();
70 }
71 };
72 eventHandler->PostTask(callback, TIMER_TASK, timeout);
73 lastTimeStamp_ = timeStamp;
74 haveTimerTask_ = true;
75 }
76 } // namespace AbilityRuntime
77 } // namespace OHOS