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 "js_systemload_listener.h"
17 #include "res_sched_log.h"
18
19 namespace OHOS {
20 namespace ResourceSchedule {
21 using OnSystemloadLevelCb = std::function<void(napi_env, napi_value, int32_t)>;
22 struct CallBackContext {
23 napi_env env = nullptr;
24 std::shared_ptr<NativeReference> callbackRef = nullptr;
25 OnSystemloadLevelCb onSystemloadLevelCb = nullptr;
26 int32_t level = 0;
27 };
28
SystemloadListener(napi_env env,napi_value callbackObj,OnSystemloadLevelCb callback)29 SystemloadListener::SystemloadListener(napi_env env, napi_value callbackObj, OnSystemloadLevelCb callback)
30 : napiEnv_(env), systemloadLevelCb_(callback)
31 {
32 if (napiEnv_ == nullptr || callbackObj == nullptr) {
33 return;
34 }
35 napi_ref tmpRef = nullptr;
36 napi_create_reference(napiEnv_, callbackObj, 1, &tmpRef);
37 callbackRef_.reset(reinterpret_cast<NativeReference*>(tmpRef));
38 napi_value callbackWorkName = nullptr;
39 napi_create_string_utf8(env, "ThreadSafeFunction in SystemloadListener", NAPI_AUTO_LENGTH, &callbackWorkName);
40 napi_create_threadsafe_function(env, nullptr, nullptr, callbackWorkName, 0, 1, nullptr, nullptr, nullptr,
41 ThreadSafeCallBack, &threadSafeFunction_);
42 }
43
ThreadSafeCallBack(napi_env ThreadSafeEnv,napi_value js_cb,void * context,void * data)44 void SystemloadListener::ThreadSafeCallBack(napi_env ThreadSafeEnv, napi_value js_cb, void* context, void* data)
45 {
46 RESSCHED_LOGI("SystemloadListener ThreadSafeCallBack start");
47 CallBackContext* callBackContext = reinterpret_cast<CallBackContext*>(data);
48 callBackContext->onSystemloadLevelCb(callBackContext->env,
49 callBackContext->callbackRef->GetNapiValue(), callBackContext->level);
50 delete callBackContext;
51 }
52
OnSystemloadLevel(int32_t level)53 void SystemloadListener::OnSystemloadLevel(int32_t level)
54 {
55 if (napiEnv_ == nullptr || callbackRef_ == nullptr || systemloadLevelCb_ == nullptr) {
56 return;
57 }
58 CallBackContext* callBackContext = new CallBackContext();
59 callBackContext->env = napiEnv_;
60 callBackContext->callbackRef = callbackRef_;
61 callBackContext->level = level;
62 callBackContext->onSystemloadLevelCb = systemloadLevelCb_;
63 napi_acquire_threadsafe_function(threadSafeFunction_);
64 napi_call_threadsafe_function(threadSafeFunction_, callBackContext, napi_tsfn_blocking);
65 }
66 } // ResourceSchedule
67 } // OHOS