1# Subscribing to Task Execution Timeout Events (C/C++) 2 3## Overview 4 5This topic describes how to use the C/C++ APIs provided by HiAppEvent to subscribe to task execution timeout events. For details (such as parameter restrictions and value ranges), see [hiappevent.h](../reference/apis-performance-analysis-kit/capi-hiappevent-h.md). 6 7## Available APIs 8 9| API| Description| 10| -------- | -------- | 11| int OH_HiAppEvent_AddWatcher(HiAppEvent_Watcher \*watcher) | Adds a watcher to listen for application events.| 12| int OH_HiAppEvent_RemoveWatcher(HiAppEvent_Watcher \*watcher) | Removes a watcher for the specified application events.| 13 14## How to Develop 15 16### Adding an Event Watcher 17 18The following describes how to subscribe to the freeze event triggered by a button click. 19 201. Obtain the **jsoncpp.cpp**, **json.h**, and **json-forwards.h** files by referring to **Using JsonCpp in your project** in [the third-party open-source library JsonCpp](https://github.com/open-source-parsers/jsoncpp). 21 222. Create a native C++ project and import the preceding files to the project. The directory structure is as follows: 23 24 ```yml 25 entry: 26 src: 27 main: 28 cpp: 29 json: 30 - json.h 31 - json-forwards.h 32 types: 33 libentry: 34 - index.d.ts 35 - CMakeLists.txt 36 - jsoncpp.cpp 37 - napi_init.cpp 38 ets: 39 entryability: 40 - EntryAbility.ets 41 pages: 42 - Index.ets 43 ``` 44 453. In the **CMakeLists.txt** file, add the source file and dynamic libraries. 46 47 ```cmake 48 # Add the jsoncpp.cpp file, which is used to parse the JSON strings in the subscription events. 49 add_library(entry SHARED napi_init.cpp jsoncpp.cpp) 50 # Add **libhiappevent_ndk.z.so**, **libhilog_ndk.z.so** (log output), and **libohhicollie.so** (HiCollie detection). 51 target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libohhicollie.so libhiappevent_ndk.z.so) 52 ``` 53 544. Import the dependencies to the **napi_init.cpp** file, and define **LOG_TAG**. 55 56 ```c++ 57 #include "napi/native_api.h" 58 #include "json/json.h" 59 #include "hilog/log.h" 60 #include "hiappevent/hiappevent.h" 61 #include <thread> 62 #include <unistd.h> 63 64 #undef LOG_TAG 65 #define LOG_TAG "testTag" 66 ``` 67 685. Subscribe to system events. 69 70 - Watcher of the **onReceive** type. 71 72 In the **napi_init.cpp** file, define the functions related to the watcher of the **onReceive** type. 73 74 ```c++ 75 // Define a variable to cache the pointer to the created watcher. 76 static HiAppEvent_Watcher *systemEventWatcher; 77 78 static void OnReceive(const char *domain, const struct HiAppEvent_AppEventGroup *appEventGroups, uint32_t groupLen) { 79 for (int i = 0; i < groupLen; ++i) { 80 for (int j = 0; j < appEventGroups[i].infoLen; ++j) { 81 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", appEventGroups[i].appEventInfos[j].domain); 82 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", appEventGroups[i].appEventInfos[j].name); 83 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", appEventGroups[i].appEventInfos[j].type); 84 if (strcmp(appEventGroups[i].appEventInfos[j].domain, DOMAIN_OS) == 0 && 85 strcmp(appEventGroups[i].appEventInfos[j].name, EVENT_APP_HICOLLIE) == 0) { 86 Json::Value params; 87 Json::Reader reader(Json::Features::strictMode()); 88 Json::FastWriter writer; 89 if (reader.parse(appEventGroups[i].appEventInfos[j].params, params)) { 90 auto time = params["time"].asInt64(); 91 auto foreground = params["foreground"].asBool(); 92 auto bundleVersion = params["bundle_version"].asString(); 93 auto processName = params["process_name"].asString(); 94 auto pid = params["pid"].asInt(); 95 auto uid = params["uid"].asInt(); 96 auto uuid = params["uuid"].asString(); 97 auto exception = writer.write(params["exception"]); 98 auto hilogSize = params["hilog"].size(); 99 auto peerBindSize = params["peer_binder"].size(); 100 auto memory = writer.write(params["memory"]); 101 auto externalLog = writer.write(params["external_log"]); 102 auto logOverLimit = params["log_over_limit"].asBool(); 103 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time); 104 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.foreground=%{public}d", foreground); 105 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str()); 106 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.process_name=%{public}s", processName.c_str()); 107 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid); 108 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid); 109 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uuid=%{public}s", uuid.c_str()); 110 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.exception=%{public}s", exception.c_str()); 111 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.hilog.size=%{public}d", hilogSize); 112 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.peer_binder.size=%{public}d", peerBindSize); 113 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str()); 114 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str()); 115 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit); 116 } 117 } 118 } 119 } 120 } 121 122 static napi_value RegisterWatcher(napi_env env, napi_callback_info info) { 123 // Set the watcher name. The system identifies different watchers based on their names. 124 systemEventWatcher = OH_HiAppEvent_CreateWatcher("onReceiverWatcher"); 125 // Set the event to watch to EVENT_APP_HICOLLIE. 126 const char *names[] = {EVENT_APP_HICOLLIE}; 127 // Add the events to watch, for example, system events. 128 OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1); 129 // Set the implemented callback. After receiving the event, the watcher immediately triggers the OnReceive callback. 130 OH_HiAppEvent_SetWatcherOnReceive(systemEventWatcher, OnReceive); 131 // Add a watcher to listen for the specified event. 132 OH_HiAppEvent_AddWatcher(systemEventWatcher); 133 return {}; 134 } 135 ``` 136 137 - Watcher of the **onTrigger** type: 138 139 In the **napi_init.cpp** file, define the functions related to the watcher of the **OnTrigger** type. 140 141 ```c++ 142 // Define a variable to cache the pointer to the created watcher. 143 static HiAppEvent_Watcher *systemEventWatcher; 144 145 // Implement the callback function used to return the listened events. The content pointed to by the events pointer is valid only in this function. 146 static void OnTake(const char *const *events, uint32_t eventLen) { 147 Json::Reader reader(Json::Features::strictMode()); 148 Json::FastWriter writer; 149 for (int i = 0; i < eventLen; ++i) { 150 Json::Value eventInfo; 151 if (reader.parse(events[i], eventInfo)) { 152 auto domain = eventInfo["domain_"].asString(); 153 auto name = eventInfo["name_"].asString(); 154 auto type = eventInfo["type_"].asInt(); 155 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", domain.c_str()); 156 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", name.c_str()); 157 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", type); 158 if (domain == DOMAIN_OS && name == EVENT_APP_HICOLLIE) { 159 auto time = eventInfo["time"].asInt64(); 160 auto foreground = eventInfo["foreground"].asBool(); 161 auto bundleVersion = eventInfo["bundle_version"].asString(); 162 auto processName = eventInfo["process_name"].asString(); 163 auto pid = eventInfo["pid"].asInt(); 164 auto uid = eventInfo["uid"].asInt(); 165 auto uuid = eventInfo["uuid"].asString(); 166 auto exception = writer.write(eventInfo["exception"]); 167 auto hilogSize = eventInfo["hilog"].size(); 168 auto peerBindSize = eventInfo["peer_binder"].size(); 169 auto memory = writer.write(eventInfo["memory"]); 170 auto externalLog = writer.write(eventInfo["external_log"]); 171 auto logOverLimit = eventInfo["log_over_limit"].asBool(); 172 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time); 173 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.foreground=%{public}d", foreground); 174 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str()); 175 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.process_name=%{public}s", processName.c_str()); 176 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid); 177 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid); 178 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uuid=%{public}s", uuid.c_str()); 179 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.exception=%{public}s", exception.c_str()); 180 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.hilog.size=%{public}d", hilogSize); 181 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.peer_binder.size=%{public}d", peerBindSize); 182 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str()); 183 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str()); 184 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit); 185 } 186 } 187 } 188 } 189 190 // Implement the subscription callback function to apply custom processing to the obtained event logging data. 191 static void OnTrigger(int row, int size) { 192 // After the callback is received, obtain the specified number of received events. 193 OH_HiAppEvent_TakeWatcherData(systemEventWatcher, row, OnTake); 194 } 195 196 static napi_value RegisterWatcher(napi_env env, napi_callback_info info) { 197 // Set the watcher name. The system identifies different watchers based on their names. 198 systemEventWatcher = OH_HiAppEvent_CreateWatcher("onTriggerWatcher"); 199 // Set the event to watch to EVENT_APP_HICOLLIE. 200 const char *names[] = {EVENT_APP_HICOLLIE}; 201 // Add the events to watch, for example, system events. 202 OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1); 203 // Set the implemented callback function. The callback function will be triggered when the conditions set by OH_HiAppEvent_SetTriggerCondition are met. 204 OH_HiAppEvent_SetWatcherOnTrigger(systemEventWatcher, OnTrigger); 205 // Set the conditions for triggering the subscription callback. For example, trigger this onTrigger callback when the number of new event logs is 1. 206 OH_HiAppEvent_SetTriggerCondition(systemEventWatcher, 1, 0, 0); 207 // Add a watcher to listen for the specified event. 208 OH_HiAppEvent_AddWatcher(systemEventWatcher); 209 return {}; 210 } 211 ``` 212 2136. Add the **TestHiCollieTimerNdk** function. 214 215 In the **napi_init.cpp** file, add the **TestHiCollieTimerNdk** function to construct a task execution timeout event. 216 217 ```c++ 218 // Import the hicollie.h file. 219 #include "hicollie/hicollie.h" 220 static napi_value TestHiCollieTimerNdk(napi_env env, napi_callback_info exports) 221 { 222 // Define the task execution timeout ID. 223 int id; 224 // Define the task timeout detection parameters. When a task times out for 1s, logs are generated. 225 HiCollie_SetTimerParam param = {"testTimer", 1, nullptr, nullptr, HiCollie_Flag::HICOLLIE_FLAG_LOG}; 226 // Set the detection. 227 HiCollie_ErrorCode errorCode = OH_HiCollie_SetTimer(param, &id); 228 if (errorCode == HICOLLIE_SUCCESS) { 229 OH_LOG_INFO(LogType::LOG_APP, "Timer Id is %{public}d", id); 230 // Construct a timeout interval of 2s. 231 sleep(2); 232 OH_HiCollie_CancelTimer(id); 233 } 234 return nullptr; 235 } 236 ``` 237 2387. In the **napi_init.cpp** file, register **RegisterWatcher** and **TestHiCollieTimerNdk** as ArkTS APIs. 239 240 241 242 ```c++ 243 EXTERN_C_START 244 static napi_value Init(napi_env env, napi_value exports) 245 { 246 napi_property_descriptor desc[] = { 247 { "RegisterWatcher", nullptr, RegisterWatcher, nullptr, nullptr, nullptr, napi_default, nullptr }, 248 { "TestHiCollieTimerNdk", nullptr, TestHiCollieTimerNdk, nullptr, nullptr, nullptr, napi_default, nullptr }, 249 }; 250 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 251 return exports; 252 } 253 EXTERN_C_END 254 static napi_module demoModule = { 255 .nm_version = 1, 256 .nm_flags = 0, 257 .nm_filename = nullptr, 258 .nm_register_func = Init, 259 .nm_modname = "entry", 260 .nm_priv = ((void*)0), 261 .reserved = { 0 }, 262 }; 263 extern "C" __attribute__((constructor)) void RegisterEntryModule(void) 264 { 265 napi_module_register(&demoModule); 266 } 267 ``` 268 269 In the **index.d.ts** file, define the ArkTS API. 270 271 ```typescript 272 export const RegisterWatcher: () => void; 273 export const TestHiCollieTimerNdk: () => void; 274 ``` 275 2768. In the **EntryAbility.ets** file, add the following API to **onCreate()**. 277 278 ```typescript 279 // Import the dependent module. 280 import testNapi from 'libentry.so' 281 282 // Add the API to onCreate(). 283 // Register the system event watcher at startup. 284 testNapi.RegisterWatcher(); 285 ``` 286 2879. In the **Index.ets** file, add a button to trigger the task execution timeout event. 288 289 ```typescript 290 import testNapi from 'libentry.so'; 291 @Entry 292 @Component 293 struct Index { 294 @State message: string = 'Hello World'; 295 296 build() { 297 Row() { 298 Column() { 299 Button("TestHiCollieTimerNdk") 300 .fontSize(50) 301 .fontWeight(FontWeight.Bold) 302 .onClick(testNapi.TestHiCollieTimerNdk); // Add a click event to trigger the TestHiCollieTimerNdk method. 303 } 304 .width('100%') 305 } 306 .height('100%') 307 } 308 } 309 ``` 310 31110. In DevEco Studio, click the **Run** button to run the project. Then, click the **testHiCollieTimerNdk** button to trigger a task execution timeout event. 312 313### Verifying the Subscription 314 3151. The application crashes. After restarting the application, you can view the following event information in the **Log** window. 316 317 ```text 318 HiAppEvent eventInfo.domain=OS 319 HiAppEvent eventInfo.name=APP_HICOLLIE 320 HiAppEvent eventInfo.eventType=1 321 HiAppEvent eventInfo.params.time=1740993639620 322 HiAppEvent eventInfo.params.foreground=1 323 HiAppEvent eventInfo.params.bundle_version=1.0.0 324 HiAppEvent eventInfo.params.process_name=com.example.myapplication 325 HiAppEvent eventInfo.params.pid=26251 326 HiAppEvent eventInfo.params.uid=20020172 327 HiAppEvent eventInfo.params.uuid=4e5d7d0e18f5d6d84cf4f0c9e80d66d0b646c1cc2343d3595f07abb0d3547feb 328 HiAppEvent eventInfo.params.exception={"message":"","name":"APP_HICOLLIE"} 329 HiAppEvent eventInfo.params.hilog.size=77 330 HiAppEvent eventInfo.params.peer_binder.size=18 331 HiAppEvent eventInfo.params.threads.size=28 332 HiAppEvent eventInfo.params.memory={"pss":0,"rss":124668,"sys_avail_mem":2220032,"sys_free_mem":526680,"sys_total_mem":11692576,"vss":4238700} 333 HiAppEvent eventInfo.params.external_log=["/data/storage/el2/log/hiappevent/APP_HICOLLIE_1740993644458_26215.log"] 334 HiAppEvent eventInfo.params.log_over_limit=0 335 ``` 336 337### Removing and Destroying an Event Watcher 338 3391. Remove the event watcher. 340 341 ```c++ 342 static napi_value RemoveWatcher(napi_env env, napi_callback_info info) { 343 // Remove the watcher. 344 OH_HiAppEvent_RemoveWatcher(systemEventWatcher); 345 return {}; 346 } 347 ``` 348 3492. Destroy the event watcher. 350 351 ```c++ 352 static napi_value DestroyWatcher(napi_env env, napi_callback_info info) { 353 // Destroy the created watcher and set systemEventWatcher to nullptr. 354 OH_HiAppEvent_DestroyWatcher(systemEventWatcher); 355 systemEventWatcher = nullptr; 356 return {}; 357 } 358 ``` 359