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 #ifndef LOG_TAG
16 #define LOG_TAG "bt_napi_timer"
17 #endif
18
19 #include "napi_timer.h"
20
21 #include "bluetooth_log.h"
22 #include "bluetooth_errorcode.h"
23 #include "common_timer_errors.h"
24
25 namespace OHOS {
26 namespace Bluetooth {
27
GetInstance(void)28 NapiTimer *NapiTimer::GetInstance(void)
29 {
30 static NapiTimer instance;
31 return &instance;
32 }
33
NapiTimer()34 NapiTimer::NapiTimer() : timer_(std::make_unique<OHOS::Utils::Timer>("NapiBtTimer"))
35 {
36 timer_->Setup();
37 }
38
~NapiTimer()39 NapiTimer::~NapiTimer()
40 {
41 if (timer_) {
42 timer_->Shutdown();
43 }
44 }
45
Register(const TimerCallback & callback,uint32_t & outTimerId,uint32_t interval)46 int NapiTimer::Register(const TimerCallback& callback, uint32_t &outTimerId, uint32_t interval)
47 {
48 if (timer_ == nullptr) {
49 HILOGE("timer_ is nulptr");
50 return BT_ERR_INTERNAL_ERROR;
51 }
52
53 uint32_t ret = timer_->Register(callback, interval, true); // only support once timer now
54 if (ret == OHOS::Utils::TIMER_ERR_DEAL_FAILED) {
55 HILOGE("Register timer failed");
56 return BT_ERR_INTERNAL_ERROR;
57 }
58
59 outTimerId = ret;
60 HILOGI("timerId: %{public}u", outTimerId);
61 return BT_NO_ERROR;
62 }
63
Unregister(uint32_t timerId)64 void NapiTimer::Unregister(uint32_t timerId)
65 {
66 if (timerId == 0) {
67 HILOGE("timerId is 0, no registered timer");
68 return;
69 }
70
71 HILOGI("timerId: %{public}d", timerId);
72 if (timer_ == nullptr) {
73 HILOGE("timer_ is nulptr");
74 return;
75 }
76
77 timer_->Unregister(timerId);
78 }
79
80 } // namespace Bluetooth
81 } // namespace OHOS