• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 "sensor_js.h"
16 
17 #include <algorithm>
18 #include <cinttypes>
19 #include <cstdlib>
20 #include <cmath>
21 #include <string>
22 #include <unistd.h>
23 
24 #include "refbase.h"
25 #include "securec.h"
26 
27 #include "geomagnetic_field.h"
28 #include "sensor_algorithm.h"
29 #include "sensor_napi_error.h"
30 #include "sensor_napi_utils.h"
31 #include "sensor_system_js.h"
32 
33 namespace OHOS {
34 namespace Sensors {
35 namespace {
36 constexpr int32_t QUATERNION_LENGTH = 4;
37 constexpr int32_t ROTATION_VECTOR_LENGTH = 3;
38 constexpr int32_t REPORTING_INTERVAL = 200000000;
39 constexpr int32_t INVALID_SENSOR_TYPE = -1;
40 constexpr int32_t DEFAULT_DEVICE_ID = -1;
41 constexpr int32_t DEFAULT_SENSOR_ID = 0;
42 constexpr int32_t IS_LOCAL_DEVICE = 1;
43 constexpr int32_t NON_LOCAL_DEVICE = 0;
44 constexpr int32_t INVALID_SUBSCRIBE_SIZE = -1;
45 constexpr int32_t DEFAULT_SUBSCRIBE_SIZE = 0;
46 constexpr int32_t SENSOR_SUBSCRIBE_FAILURE = 1001;
47 constexpr int32_t INPUT_ERROR = 202;
48 constexpr float BODY_STATE_EXCEPT = 1.0f;
49 constexpr float THRESHOLD = 0.000001f;
50 constexpr uint32_t COMPATIBILITY_CHANGE_VERSION_API12 = 12;
51 constexpr int32_t ARGC_NUM_TWO = 2;
52 constexpr int32_t ARGC_NUM_THREE = 3;
53 constexpr int32_t ARGS_NUM_TWO = 2;
54 } // namespace
55 static std::map<std::string, int64_t> g_samplingPeriod = {
56     {"normal", 200000000},
57     {"ui", 60000000},
58     {"game", 20000000},
59 };
60 static std::mutex g_mutex;
61 static std::mutex g_bodyMutex;
62 static float g_bodyState = -1.0f;
63 static std::map<SensorDescription, std::vector<sptr<AsyncCallbackInfo>>> g_subscribeCallbacks;
64 static std::mutex g_onMutex;
65 static std::mutex g_onceMutex;
66 static std::mutex g_plugMutex;
67 static std::map<SensorDescription, std::vector<sptr<AsyncCallbackInfo>>> g_onceCallbackInfos;
68 static std::map<SensorDescription, std::vector<sptr<AsyncCallbackInfo>>> g_onCallbackInfos;
69 static std::vector<sptr<AsyncCallbackInfo>> g_plugCallbackInfo;
70 
CheckSubscribe(SensorDescription sensorDesc)71 static bool CheckSubscribe(SensorDescription sensorDesc)
72 {
73     std::lock_guard<std::mutex> onCallbackLock(g_onMutex);
74     auto iter = g_onCallbackInfos.find(sensorDesc);
75     return iter != g_onCallbackInfos.end();
76 }
77 
CopySensorData(SensorEvent * event,std::shared_ptr<CallbackSensorData> cb)78 static bool CopySensorData(SensorEvent *event, std::shared_ptr<CallbackSensorData> cb)
79 {
80     CHKPF(event);
81     CHKPF(cb);
82     int32_t sensorTypeId = event->sensorTypeId;
83     cb->sensorTypeId = sensorTypeId;
84     cb->dataLength = event->dataLen;
85     cb->timestamp = event->timestamp;
86     cb->sensorAccuracy = event->option;
87     CHKPF(event->data);
88     if (event->dataLen < sizeof(float)) {
89         SEN_HILOGE("Event dataLen less than float size");
90         return false;
91     }
92     if (sizeof(cb->data) < event->dataLen) {
93         SEN_HILOGE("cb space is insufficient");
94         return false;
95     }
96     auto data = reinterpret_cast<float *>(event->data);
97     if (memcpy_s(cb->data, sizeof(cb->data),
98         data, event->dataLen) != EOK) {
99         SEN_HILOGE("Copy data failed");
100         return false;
101     }
102     return true;
103 }
104 
CheckSystemSubscribe(SensorDescription sensorDesc)105 static bool CheckSystemSubscribe(SensorDescription sensorDesc)
106 {
107     std::lock_guard<std::mutex> subscribeLock(g_mutex);
108     auto iter = g_subscribeCallbacks.find(sensorDesc);
109     return iter != g_subscribeCallbacks.end();
110 }
111 
EmitSubscribeCallback(SensorEvent * event)112 static void EmitSubscribeCallback(SensorEvent *event)
113 {
114     CHKPV(event);
115     if (!CheckSystemSubscribe({event->deviceId, event->sensorTypeId, event->sensorId, event->location})) {
116         return;
117     }
118     std::lock_guard<std::mutex> subscribeLock(g_mutex);
119     std::shared_ptr<CallbackSensorData> cb = std::make_shared<CallbackSensorData>();
120     if (!CopySensorData(event, cb)) {
121         SEN_HILOGE("Copy sensor data failed");
122         return;
123     }
124     auto data = reinterpret_cast<float *>(event->data);
125     auto callbacks = g_subscribeCallbacks[{event->deviceId, event->sensorTypeId, event->sensorId, event->location}];
126     for (auto &callback : callbacks) {
127         if (event->sensorTypeId == SENSOR_TYPE_ID_WEAR_DETECTION && callback->type == SUBSCRIBE_CALLBACK) {
128             std::lock_guard<std::mutex> onBodyLock(g_bodyMutex);
129             g_bodyState = *data;
130             cb->data[0] = (fabs(g_bodyState - BODY_STATE_EXCEPT) < THRESHOLD) ? true : false;
131         }
132         EmitUvEventLoop(callback, cb);
133     }
134 }
135 
EmitOnCallback(SensorEvent * event)136 static void EmitOnCallback(SensorEvent *event)
137 {
138     CHKPV(event);
139     if (!CheckSubscribe({event->deviceId, event->sensorTypeId, event->sensorId, event->location})) {
140         return;
141     }
142     std::lock_guard<std::mutex> onCallbackLock(g_onMutex);
143     std::shared_ptr<CallbackSensorData> cb = std::make_shared<CallbackSensorData>();
144     if (!CopySensorData(event, cb)) {
145         SEN_HILOGE("Copy sensor data failed");
146         return;
147     }
148     auto onCallbackInfos = g_onCallbackInfos[{event->deviceId, event->sensorTypeId, event->sensorId, event->location}];
149     for (auto &onCallbackInfo : onCallbackInfos) {
150         EmitUvEventLoop(onCallbackInfo, cb);
151     }
152 }
153 
EmitOnceCallback(SensorEvent * event)154 static void EmitOnceCallback(SensorEvent *event)
155 {
156     CHKPV(event);
157     std::lock_guard<std::mutex> onceCallbackLock(g_onceMutex);
158     auto iter = g_onceCallbackInfos.find({event->deviceId, event->sensorTypeId, event->sensorId, event->location});
159     if (iter == g_onceCallbackInfos.end()) {
160         return;
161     }
162     std::shared_ptr<CallbackSensorData> cb = std::make_shared<CallbackSensorData>();
163     if (!CopySensorData(event, cb)) {
164         SEN_HILOGE("Copy sensor data failed");
165         return;
166     }
167     auto &onceCallbackInfos = iter->second;
168     while (!onceCallbackInfos.empty()) {
169         auto onceCallbackInfo = onceCallbackInfos.front();
170         auto beginIter = onceCallbackInfos.begin();
171         onceCallbackInfos.erase(beginIter);
172         EmitUvEventLoop(std::move(onceCallbackInfo), cb);
173     }
174     g_onceCallbackInfos.erase({event->deviceId, event->sensorTypeId, event->sensorId, event->location});
175 
176     CHKCV((!CheckSubscribe({event->deviceId, event->sensorTypeId, event->sensorId, event->location})),
177         "Has client subscribe, not need cancel subscribe");
178     CHKCV((!CheckSystemSubscribe({event->deviceId, event->sensorTypeId, event->sensorId, event->location})),
179         "Has client subscribe system api, not need cancel subscribe");
180     UnsubscribeSensor({event->deviceId, event->sensorTypeId, event->sensorId, event->location});
181 }
182 
DataCallbackImpl(SensorEvent * event)183 void DataCallbackImpl(SensorEvent *event)
184 {
185     CHKPV(event);
186     EmitOnCallback(event);
187     EmitSubscribeCallback(event);
188     EmitOnceCallback(event);
189 }
190 
UpdatePlugInfo(SensorStatusEvent * plugEvent,sptr<AsyncCallbackInfo> & asyncCallbackInfo)191 static void UpdatePlugInfo(SensorStatusEvent *plugEvent, sptr<AsyncCallbackInfo> &asyncCallbackInfo)
192 {
193     CALL_LOG_ENTER;
194     CHKPV(plugEvent);
195     asyncCallbackInfo->sensorStatusEvent = *plugEvent;
196     SEN_HILOGD("asyncCallbackInfo->sensorStatus : [ deviceId = %{public}d, isSensorOnline = %{public}d]",
197         asyncCallbackInfo->sensorStatusEvent.deviceId, asyncCallbackInfo->sensorStatusEvent.isSensorOnline);
198     return;
199 }
200 
PlugDataCallbackImpl(SensorStatusEvent * plugEvent)201 void PlugDataCallbackImpl(SensorStatusEvent *plugEvent)
202 {
203     CALL_LOG_ENTER;
204     CHKPV(plugEvent);
205     std::lock_guard<std::mutex> plugCallbackLock(g_plugMutex);
206     std::shared_ptr<CallbackSensorData> cb = std::make_shared<CallbackSensorData>();
207     for (auto& callback : g_plugCallbackInfo) {
208         UpdatePlugInfo(plugEvent, callback);
209         EmitUvEventLoop(callback, cb);
210     }
211 }
212 
213 const SensorUser user = {
214     .callback = DataCallbackImpl,
215     .plugCallback = PlugDataCallbackImpl
216 };
217 
UnsubscribeSensor(const SensorDescription & sensorDesc)218 int32_t UnsubscribeSensor(const SensorDescription &sensorDesc)
219 {
220     CALL_LOG_ENTER;
221     int32_t ret = DeactivateSensorEnhanced({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId,
222         sensorDesc.location}, &user);
223     if (ret != ERR_OK) {
224         SEN_HILOGE("DeactivateSensor failed");
225         return ret;
226     }
227     return UnsubscribeSensorEnhanced({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId,
228         sensorDesc.location}, &user);
229 }
230 
SubscribeSensor(const SensorDescription & sensorDesc,int64_t interval,RecordSensorCallback callback)231 int32_t SubscribeSensor(const SensorDescription &sensorDesc, int64_t interval, RecordSensorCallback callback)
232 {
233     CALL_LOG_ENTER;
234     int32_t ret = SubscribeSensorEnhanced({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId,
235         sensorDesc.location}, &user);
236     if (ret != ERR_OK) {
237         SEN_HILOGE("SubscribeSensor failed");
238         return ret;
239     }
240     ret = SetBatchEnhanced({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId,
241         sensorDesc.location}, &user, interval, 0);
242     if (ret != ERR_OK) {
243         SEN_HILOGE("SetBatch failed");
244         return ret;
245     }
246     return ActivateSensorEnhanced({sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId,
247         sensorDesc.location}, &user);
248 }
249 
CleanCallbackInfo(napi_env env,std::map<SensorDescription,std::vector<sptr<AsyncCallbackInfo>>> & callbackInfo)250 void CleanCallbackInfo(napi_env env, std::map<SensorDescription, std::vector<sptr<AsyncCallbackInfo>>> &callbackInfo)
251 {
252     for (auto &event : callbackInfo) {
253         auto &vecCallbackInfo = event.second;
254         // Automatically call the destructor of the AsyncCallbackInfo
255         vecCallbackInfo.erase(std::remove_if(vecCallbackInfo.begin(), vecCallbackInfo.end(),
256             [&env](const sptr<AsyncCallbackInfo> &myCallbackInfo) {
257                 return env == myCallbackInfo->env;
258             }), vecCallbackInfo.end());
259     }
260 }
261 
CleanOnCallbackInfo(napi_env env)262 void CleanOnCallbackInfo(napi_env env)
263 {
264     std::lock_guard<std::mutex> onCallbackLock(g_onMutex);
265     CleanCallbackInfo(env, g_onCallbackInfos);
266 }
267 
CleanOnceCallbackInfo(napi_env env)268 void CleanOnceCallbackInfo(napi_env env)
269 {
270     std::lock_guard<std::mutex> onceCallbackLock(g_onceMutex);
271     CleanCallbackInfo(env, g_onceCallbackInfos);
272 }
273 
CleanSubscribeCallbackInfo(napi_env env)274 void CleanSubscribeCallbackInfo(napi_env env)
275 {
276     std::lock_guard<std::mutex> subscribeLock(g_mutex);
277     CleanCallbackInfo(env, g_subscribeCallbacks);
278 }
279 
CleanUp(void * data)280 void CleanUp(void *data)
281 {
282     auto env = *(reinterpret_cast<napi_env*>(data));
283     CleanOnCallbackInfo(env);
284     CleanOnceCallbackInfo(env);
285     CleanSubscribeCallbackInfo(env);
286     delete reinterpret_cast<napi_env*>(data);
287     data = nullptr;
288 }
289 
IsOnceSubscribed(napi_env env,SensorDescription sensorDesc,napi_value callback)290 static bool IsOnceSubscribed(napi_env env, SensorDescription sensorDesc, napi_value callback)
291 {
292     CALL_LOG_ENTER;
293     auto iter = g_onceCallbackInfos.find(sensorDesc);
294     if (iter == g_onceCallbackInfos.end()) {
295         SEN_HILOGW("Already subscribed, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d",
296             sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId);
297         return false;
298     }
299     std::vector<sptr<AsyncCallbackInfo>> callbackInfos = g_onceCallbackInfos[sensorDesc];
300     for (auto callbackInfo : callbackInfos) {
301         CHKPC(callbackInfo);
302         if (callbackInfo->env != env) {
303             continue;
304         }
305         napi_value sensorCallback = nullptr;
306         CHKNRF(env, napi_get_reference_value(env, callbackInfo->callback[0], &sensorCallback),
307             "napi_get_reference_value");
308         if (IsSameValue(env, callback, sensorCallback)) {
309             return true;
310         }
311     }
312     return false;
313 }
314 
UpdateOnceCallback(napi_env env,SensorDescription sensorDesc,napi_value callback)315 static void UpdateOnceCallback(napi_env env, SensorDescription sensorDesc, napi_value callback)
316 {
317     CALL_LOG_ENTER;
318     std::lock_guard<std::mutex> onceCallbackLock(g_onceMutex);
319     CHKCV((!IsOnceSubscribed(env, sensorDesc, callback)), "The callback has been subscribed");
320     sptr<AsyncCallbackInfo> asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, ONCE_CALLBACK);
321     CHKPV(asyncCallbackInfo);
322     napi_status status = napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]);
323     if (status != napi_ok) {
324         ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail");
325         return;
326     }
327     std::vector<sptr<AsyncCallbackInfo>> callbackInfos = g_onceCallbackInfos[sensorDesc];
328     callbackInfos.push_back(asyncCallbackInfo);
329     g_onceCallbackInfos[sensorDesc] = callbackInfos;
330 }
331 
GetDeviceId(napi_env env,napi_value value,int32_t & deviceId)332 static bool GetDeviceId(napi_env env, napi_value value, int32_t &deviceId)
333 {
334     napi_value napi_deviceId = GetNamedProperty(env, value, "deviceId");
335     if (!IsMatchType(env, napi_deviceId, napi_number)) {
336         SEN_HILOGE("deviceId failed");
337         return false;
338     }
339     if (!GetNativeInt32(env, napi_deviceId, deviceId)) {
340         SEN_HILOGE("GetNativeInt32 failed");
341         return false;
342     }
343     return true;
344 }
345 
GetSensorId(napi_env env,napi_value value,int32_t & sensorId)346 static bool GetSensorId(napi_env env, napi_value value, int32_t &sensorId)
347 {
348     napi_value napi_sensorId = GetNamedProperty(env, value, "sensorIndex");
349     if (!IsMatchType(env, napi_sensorId, napi_number)) {
350         SEN_HILOGE("sensorIndex failed");
351         return false;
352     }
353     if (!GetNativeInt32(env, napi_sensorId, sensorId)) {
354         SEN_HILOGE("GetNativeInt32 failed");
355         return false;
356     }
357     return true;
358 }
359 
GetLocationDeviceId(int32_t & deviceId)360 static bool GetLocationDeviceId(int32_t &deviceId)
361 {
362     SensorInfo *sensorInfos = nullptr;
363     int32_t count = 0;
364     int32_t ret = GetAllSensors(&sensorInfos, &count);
365     if (ret != OHOS::ERR_OK) {
366         SEN_HILOGE("GetAllSensors failed");
367         return false;
368     }
369     for (int32_t i = 0; i < count; ++i) {
370         if (sensorInfos[i].location == IS_LOCAL_DEVICE) {
371             SEN_HILOGD("The location deviceId is %{public}d", sensorInfos[i].deviceId);
372             deviceId = sensorInfos[i].deviceId;
373             return true;
374         }
375     }
376     return false;
377 }
378 
Once(napi_env env,napi_callback_info info)379 static napi_value Once(napi_env env, napi_callback_info info)
380 {
381     CALL_LOG_ENTER;
382     size_t argc = 3;
383     napi_value args[3] = { 0 };
384     napi_value thisVar = nullptr;
385     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
386     if (status != napi_ok || argc < 2) {
387         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
388         return nullptr;
389     }
390     if ((!IsMatchType(env, args[0], napi_number)) || (!IsMatchType(env, args[1], napi_function))) {
391         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type");
392         return nullptr;
393     }
394     int32_t sensorType = INVALID_SENSOR_TYPE;
395     if (!GetNativeInt32(env, args[0], sensorType)) {
396         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail");
397         return nullptr;
398     }
399     if (!CheckSubscribe({DEFAULT_DEVICE_ID, sensorType, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE})) {
400         SEN_HILOGD("No subscription to change sensor data, registration is required");
401         int32_t ret = SubscribeSensor({DEFAULT_DEVICE_ID, sensorType, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE},
402             REPORTING_INTERVAL, DataCallbackImpl);
403         if (ret != ERR_OK) {
404             ThrowErr(env, ret, "SubscribeSensor fail");
405             return nullptr;
406         }
407     }
408     UpdateOnceCallback(env, {DEFAULT_DEVICE_ID, sensorType, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}, args[1]);
409     return nullptr;
410 }
411 
IsSubscribed(napi_env env,SensorDescription sensorDesc,napi_value callback)412 static bool IsSubscribed(napi_env env, SensorDescription sensorDesc, napi_value callback)
413 {
414     CALL_LOG_ENTER;
415     auto iter = g_onCallbackInfos.find(sensorDesc);
416     if (iter == g_onCallbackInfos.end()) {
417         SEN_HILOGW("No client subscribe, deviceIndex:%{public}d, sensortypeId:%{public}d, sensorId:%{public}d",
418             sensorDesc.deviceId, sensorDesc.sensorType, sensorDesc.sensorId);
419         return false;
420     }
421     std::vector<sptr<AsyncCallbackInfo>> callbackInfos = g_onCallbackInfos[sensorDesc];
422     for (auto callbackInfo : callbackInfos) {
423         CHKPC(callbackInfo);
424         if (callbackInfo->env != env) {
425             continue;
426         }
427         napi_value sensorCallback = nullptr;
428         CHKNRF(env, napi_get_reference_value(env, callbackInfo->callback[0], &sensorCallback),
429             "napi_get_reference_value");
430         if (IsSameValue(env, callback, sensorCallback)) {
431             return true;
432         }
433     }
434     return false;
435 }
436 
UpdateCallbackInfos(napi_env env,SensorDescription sensorDesc,napi_value callback)437 static void UpdateCallbackInfos(napi_env env, SensorDescription sensorDesc, napi_value callback)
438 {
439     CALL_LOG_ENTER;
440     std::lock_guard<std::mutex> onCallbackLock(g_onMutex);
441     CHKCV((!IsSubscribed(env, sensorDesc, callback)), "The callback has been subscribed");
442     sptr<AsyncCallbackInfo> asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, ON_CALLBACK);
443     CHKPV(asyncCallbackInfo);
444     napi_status status = napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]);
445     if (status != napi_ok) {
446         ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail");
447         return;
448     }
449     std::vector<sptr<AsyncCallbackInfo>> callbackInfos = g_onCallbackInfos[sensorDesc];
450     callbackInfos.push_back(asyncCallbackInfo);
451     g_onCallbackInfos[sensorDesc] = callbackInfos;
452 }
453 
GetInterval(napi_env env,napi_value value,int64_t & interval)454 static bool GetInterval(napi_env env, napi_value value, int64_t &interval)
455 {
456     napi_value napiInterval = GetNamedProperty(env, value, "interval");
457     if (IsMatchType(env, napiInterval, napi_number)) {
458         if (!GetNativeInt64(env, napiInterval, interval)) {
459             SEN_HILOGE("GetNativeInt64 failed");
460             return false;
461         }
462     } else if (IsMatchType(env, napiInterval, napi_string)) {
463         std::string mode;
464         if (!GetStringValue(env, napiInterval, mode)) {
465             SEN_HILOGE("GetStringValue failed");
466             return false;
467         }
468         auto iter = g_samplingPeriod.find(mode);
469         if (iter == g_samplingPeriod.end()) {
470             SEN_HILOGE("Find interval mode failed");
471             return false;
472         }
473         interval = iter->second;
474         SEN_HILOGI("%{public}s", mode.c_str());
475     } else {
476         SEN_HILOGE("Interval failed");
477         return false;
478     }
479     return true;
480 }
481 
IsPlugSubscribed(napi_env env,napi_value callback)482 static bool IsPlugSubscribed(napi_env env, napi_value callback)
483 {
484     CALL_LOG_ENTER;
485     for (auto callbackInfo : g_plugCallbackInfo) {
486         CHKPC(callbackInfo);
487         if (callbackInfo->env != env) {
488             continue;
489         }
490         napi_value plugCallback = nullptr;
491         CHKNRF(env, napi_get_reference_value(env, callbackInfo->callback[0], &plugCallback),
492             "napi_get_reference_value");
493         if (IsSameValue(env, callback, plugCallback)) {
494             return true;
495         }
496     }
497     return false;
498 }
499 
UpdatePlugCallbackInfos(const napi_env & env,napi_value callback)500 static void UpdatePlugCallbackInfos(const napi_env& env, napi_value callback)
501 {
502     CALL_LOG_ENTER;
503     std::lock_guard<std::mutex> plugCallbackLock(g_plugMutex);
504     CHKCV((!IsPlugSubscribed(env, callback)), "The plugCallback has been subscribed");
505     sptr<AsyncCallbackInfo> asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, SENSOR_STATE_CHANGE);
506     CHKPV(asyncCallbackInfo);
507     napi_status status = napi_create_reference(env, callback, 1, &asyncCallbackInfo->callback[0]);
508     if (status != napi_ok) {
509         ThrowErr(env, PARAMETER_ERROR, "napi_create_reference fail");
510         return;
511     }
512     g_plugCallbackInfo.push_back(asyncCallbackInfo);
513 }
514 
SubscribeSensorPlug(SensorPlugCallback callback)515 int32_t SubscribeSensorPlug(SensorPlugCallback callback)
516 {
517     CALL_LOG_ENTER;
518     int32_t ret = SubscribeSensorPlug(&user);
519     if (ret != ERR_OK) {
520         SEN_HILOGE("SubscribeSensorPlug failed");
521     }
522     return ret;
523 }
524 
OnPlugSensor(napi_env env,const napi_value type,const napi_value callback)525 static napi_value OnPlugSensor(napi_env env, const napi_value type, const napi_value callback)
526 {
527     CALL_LOG_ENTER;
528     std::string plugType;
529     CHKCP(GetStringValue(env, type, plugType), "get plugType fail");
530     if (plugType != "sensorStatusChange") {
531         ThrowErr(env, PARAMETER_ERROR, "Wrong sensorStatusChange type");
532         return nullptr;
533     }
534     int32_t ret = SubscribeSensorPlug(PlugDataCallbackImpl);
535     if (ret != ERR_OK) {
536         ThrowErr(env, ret, "SubscribeSensorPlug fail");
537         return nullptr;
538     }
539     UpdatePlugCallbackInfos(env, callback);
540     return nullptr;
541 }
542 
GetDeviceIdBySensorInfoParam(napi_env env,napi_value value,int32_t & deviceId)543 static bool GetDeviceIdBySensorInfoParam(napi_env env, napi_value value, int32_t &deviceId)
544 {
545     napi_value napiSensorInfoParam = GetNamedProperty(env, value, "sensorInfoParam");
546     if (!IsMatchType(env, napiSensorInfoParam, napi_object)) {
547         SEN_HILOGW("sensorInfoParam failed");
548         return false;
549     }
550     if (!GetDeviceId(env, napiSensorInfoParam, deviceId)) {
551         return false;
552     }
553     return true;
554 }
555 
GetSensorIdBySensorInfoParam(napi_env env,napi_value value,int32_t & sensorId)556 static bool GetSensorIdBySensorInfoParam(napi_env env, napi_value value, int32_t &sensorId)
557 {
558     napi_value napiSensorInfoParam = GetNamedProperty(env, value, "sensorInfoParam");
559     if (!IsMatchType(env, napiSensorInfoParam, napi_object)) {
560         SEN_HILOGW("sensorInfoParam failed");
561         return false;
562     }
563     if (!GetSensorId(env, napiSensorInfoParam, sensorId)) {
564         return false;
565     }
566     return true;
567 }
568 
GetOptionalParameter(napi_env env,size_t argc,napi_value args,int64_t & interval,SensorDescription & sensorDesc)569 static bool GetOptionalParameter(napi_env env, size_t argc, napi_value args, int64_t &interval,
570     SensorDescription &sensorDesc)
571 {
572     int32_t localDeviceId = DEFAULT_DEVICE_ID;
573     if (!GetLocationDeviceId(localDeviceId)) {
574         SEN_HILOGW("Cant fand local deviceId, default loacl deviceId :%{public}d", localDeviceId);
575     }
576     sensorDesc.deviceId = localDeviceId;
577     sensorDesc.sensorId = DEFAULT_SENSOR_ID;
578     sensorDesc.location = IS_LOCAL_DEVICE;
579     if (argc >= ARGC_NUM_THREE && IsMatchType(env, args, napi_object)) {
580         if (!GetInterval(env, args, interval)) {
581             SEN_HILOGW("Get interval failed");
582         }
583         if (!GetDeviceIdBySensorInfoParam(env, args, sensorDesc.deviceId)) {
584             SEN_HILOGW("No deviceId, This device is selected by default");
585             sensorDesc.deviceId = localDeviceId;
586         }
587         if (!GetSensorIdBySensorInfoParam(env, args, sensorDesc.sensorId)) {
588             sensorDesc.sensorId = DEFAULT_SENSOR_ID;
589             SEN_HILOGW("No sensorId, The first sensor of the type is selected by default");
590         }
591     }
592     if (sensorDesc.deviceId != localDeviceId) {
593         sensorDesc.location = NON_LOCAL_DEVICE;
594     }
595     SEN_HILOGD("Interval is %{public}" PRId64, interval);
596     return true;
597 }
598 
On(napi_env env,napi_callback_info info)599 static napi_value On(napi_env env, napi_callback_info info)
600 {
601     CALL_LOG_ENTER;
602     size_t argc = 3;
603     napi_value args[3] = { 0 };
604     napi_value thisVar = nullptr;
605     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
606     if (status != napi_ok || argc < 2) {
607         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
608         return nullptr;
609     }
610     if (IsMatchType(env, args[0], napi_string) && IsMatchType(env, args[1], napi_function)) {
611         return OnPlugSensor(env, args[0], args[1]);
612     }
613     if ((!IsMatchType(env, args[0], napi_number)) || (!IsMatchType(env, args[1], napi_function))) {
614         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type");
615         return nullptr;
616     }
617     SensorDescription sensorDesc;
618     sensorDesc.sensorType = INVALID_SENSOR_TYPE;
619     if (!GetNativeInt32(env, args[0], sensorDesc.sensorType)) {
620         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail");
621         return nullptr;
622     }
623     int64_t interval = REPORTING_INTERVAL;
624     if (!GetOptionalParameter(env, argc, args[ARGS_NUM_TWO], interval, sensorDesc)) {
625         SEN_HILOGE("location deviceId fail");
626         return nullptr;
627     }
628     int32_t ret = SubscribeSensor(sensorDesc, interval, DataCallbackImpl);
629     if (ret != ERR_OK) {
630         ThrowErr(env, ret, "SubscribeSensor fail");
631         return nullptr;
632     }
633     UpdateCallbackInfos(env, sensorDesc, args[1]);
634     return nullptr;
635 }
636 
RemoveAllPlugCallback(napi_env env)637 static int32_t RemoveAllPlugCallback(napi_env env)
638 {
639     CALL_LOG_ENTER;
640     std::lock_guard<std::mutex> plugCallbackLock(g_plugMutex);
641     for (auto iter = g_plugCallbackInfo.begin(); iter != g_plugCallbackInfo.end();) {
642         CHKPC(*iter);
643         if ((*iter)->env != env) {
644             ++iter;
645             continue;
646         }
647         iter = g_plugCallbackInfo.erase(iter);
648     }
649     if (g_plugCallbackInfo.empty()) {
650         SEN_HILOGD("No subscription to change sensor data");
651         return DEFAULT_SUBSCRIBE_SIZE;
652     }
653     return g_plugCallbackInfo.size();
654 }
655 
RemovePlugCallback(napi_env env,napi_value callback)656 static int32_t RemovePlugCallback(napi_env env, napi_value callback)
657 {
658     CALL_LOG_ENTER;
659     std::lock_guard<std::mutex> plugCallbackLock(g_plugMutex);
660     for (auto iter = g_plugCallbackInfo.begin(); iter != g_plugCallbackInfo.end();) {
661         CHKPC(*iter);
662         if ((*iter)->env != env) {
663             continue;
664         }
665         napi_value sensorCallback = nullptr;
666         if (napi_get_reference_value(env, (*iter)->callback[0], &sensorCallback) != napi_ok) {
667             SEN_HILOGE("napi_get_reference_value fail");
668             continue;
669         }
670         if (IsSameValue(env, callback, sensorCallback)) {
671             iter = g_plugCallbackInfo.erase(iter);
672             SEN_HILOGD("Remove callback success");
673             break;
674         } else {
675             ++iter;
676         }
677     }
678     if (g_plugCallbackInfo.empty()) {
679         SEN_HILOGD("No subscription to change sensor data");
680         return DEFAULT_SUBSCRIBE_SIZE;
681     }
682     return g_plugCallbackInfo.size();
683 }
684 
OffPlugSensor(napi_env env,size_t argc,const napi_value type,const napi_value callback)685 static napi_value OffPlugSensor(napi_env env, size_t argc, const napi_value type, const napi_value callback)
686 {
687     CALL_LOG_ENTER;
688     std::string plugType;
689     CHKCP(GetStringValue(env, type, plugType), "get plugType fail");
690     if (plugType != "sensorStatusChange") {
691         ThrowErr(env, PARAMETER_ERROR, "Wrong sensorStatusChange type");
692         return nullptr;
693     }
694     int32_t subscribeSize = INVALID_SUBSCRIBE_SIZE;
695     if (argc == 1) {
696         subscribeSize = RemoveAllPlugCallback(env);
697     } else if (IsMatchType(env, callback, napi_undefined) || IsMatchType(env, callback, napi_null)) {
698         subscribeSize = RemoveAllPlugCallback(env);
699     } else if (IsMatchType(env, callback, napi_function)) {
700         subscribeSize = RemovePlugCallback(env, callback);
701     } else {
702         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, args[1] should is napi_function");
703         return nullptr;
704     }
705     if (subscribeSize > DEFAULT_SUBSCRIBE_SIZE) {
706         SEN_HILOGW("There are other client subscribe system js api as well, not need unsubscribe");
707         return nullptr;
708     }
709     int32_t ret = UnsubscribeSensorPlug(&user);
710     if (ret != ERR_OK) {
711         ThrowErr(env, ret, "UnSubscribeSensorPlug fail");
712         return nullptr;
713     }
714     return nullptr;
715 }
716 
RemoveAllCallback(napi_env env,SensorDescription sensorDesc)717 static int32_t RemoveAllCallback(napi_env env, SensorDescription sensorDesc)
718 {
719     CALL_LOG_ENTER;
720     std::lock_guard<std::mutex> onCallbackLock(g_onMutex);
721     std::vector<sptr<AsyncCallbackInfo>> callbackInfos = g_onCallbackInfos[sensorDesc];
722     for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) {
723         CHKPC(*iter);
724         if ((*iter)->env != env) {
725             ++iter;
726             continue;
727         }
728         iter = callbackInfos.erase(iter);
729     }
730     if (callbackInfos.empty()) {
731         SEN_HILOGD("No subscription to change sensor data");
732         g_onCallbackInfos.erase(sensorDesc);
733         return DEFAULT_SUBSCRIBE_SIZE;
734     }
735     g_onCallbackInfos[sensorDesc] = callbackInfos;
736     return callbackInfos.size();
737 }
738 
RemoveCallback(napi_env env,SensorDescription sensorDesc,napi_value callback)739 static int32_t RemoveCallback(napi_env env, SensorDescription sensorDesc, napi_value callback)
740 {
741     CALL_LOG_ENTER;
742     std::lock_guard<std::mutex> onCallbackLock(g_onMutex);
743     std::vector<sptr<AsyncCallbackInfo>> callbackInfos = g_onCallbackInfos[sensorDesc];
744     for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) {
745         CHKPC(*iter);
746         if ((*iter)->env != env) {
747             continue;
748         }
749         napi_value sensorCallback = nullptr;
750         if (napi_get_reference_value(env, (*iter)->callback[0], &sensorCallback) != napi_ok) {
751             SEN_HILOGE("napi_get_reference_value fail");
752             continue;
753         }
754         if (IsSameValue(env, callback, sensorCallback)) {
755             iter = callbackInfos.erase(iter);
756             SEN_HILOGD("Remove callback success");
757             break;
758         } else {
759             ++iter;
760         }
761     }
762     if (callbackInfos.empty()) {
763         SEN_HILOGD("No subscription to change sensor data");
764         g_onCallbackInfos.erase(sensorDesc);
765         return DEFAULT_SUBSCRIBE_SIZE;
766     }
767     g_onCallbackInfos[sensorDesc] = callbackInfos;
768     return callbackInfos.size();
769 }
770 
GetSensorInfoParameter(napi_env env,size_t argc,napi_value args,SensorDescription & sensorDesc)771 static bool GetSensorInfoParameter(napi_env env, size_t argc, napi_value args, SensorDescription &sensorDesc)
772 {
773     int32_t localDeviceId = DEFAULT_DEVICE_ID;
774     if (!GetLocationDeviceId(localDeviceId)) {
775         SEN_HILOGW("Cant fand local deviceId, default loacl deviceId :%{public}d", localDeviceId);
776     }
777     sensorDesc.deviceId = localDeviceId;
778     sensorDesc.sensorId = DEFAULT_SENSOR_ID;
779     sensorDesc.location = IS_LOCAL_DEVICE;
780     if (argc >= ARGC_NUM_TWO && IsMatchType(env, args, napi_object)) {
781         if (!GetDeviceId(env, args, sensorDesc.deviceId)) {
782             SEN_HILOGW("No deviceId, This device is selected by default");
783             sensorDesc.deviceId = localDeviceId;
784         }
785         if (!GetSensorId(env, args, sensorDesc.sensorId)) {
786             sensorDesc.sensorId = DEFAULT_SENSOR_ID;
787             SEN_HILOGW("No sensorId, The first sensor of the type is selected by default");
788         }
789     } else if ((argc == 1) || IsMatchType(env, args, napi_undefined) ||
790         IsMatchType(env, args, napi_null)) {
791             SEN_HILOGW("no deviceId, sensorIndex, Select the default deviceId and sensorIndex.");
792     } else {
793         return false;
794     }
795     if (sensorDesc.deviceId != localDeviceId) {
796         sensorDesc.location = NON_LOCAL_DEVICE;
797     }
798     return true;
799 }
800 
GetSensorType(napi_env env,napi_value args,SensorDescription & sensorDesc)801 static bool GetSensorType(napi_env env, napi_value args, SensorDescription &sensorDesc)
802 {
803     sensorDesc.sensorType = INVALID_SENSOR_TYPE;
804     if ((!IsMatchType(env, args, napi_number)) || (!GetNativeInt32(env, args, sensorDesc.sensorType))) {
805         return false;
806     }
807     int32_t localDeviceId = DEFAULT_DEVICE_ID;
808     if (!GetLocationDeviceId(localDeviceId)) {
809         SEN_HILOGW("Cant fand local deviceId, default loacl deviceId :%{public}d", localDeviceId);
810     }
811     sensorDesc.deviceId = localDeviceId;
812     sensorDesc.sensorId = DEFAULT_SENSOR_ID;
813     sensorDesc.location = IS_LOCAL_DEVICE;
814     return true;
815 }
816 
Off(napi_env env,napi_callback_info info)817 static napi_value Off(napi_env env, napi_callback_info info)
818 {
819     CALL_LOG_ENTER;
820     size_t argc = 3;
821     napi_value args[3] = { 0 };
822     napi_value thisVar = nullptr;
823     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
824     if (status != napi_ok || argc < 1) {
825         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
826         return nullptr;
827     }
828     if (IsMatchType(env, args[0], napi_string)) {
829         return OffPlugSensor(env, argc, args[0], args[1]);
830     }
831     SensorDescription sensorDesc;
832     if (!GetSensorType(env, args[0], sensorDesc)) {
833         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type or get number fail");
834         return nullptr;
835     }
836     napi_value args_tmp = args[1];
837     if (!IsMatchType(env, args_tmp, napi_function)) {
838         args_tmp = args[ARGS_NUM_TWO];
839         if (!GetSensorInfoParameter(env, argc, args[1], sensorDesc)) {
840             ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, args[1] should is napi_object");
841             return nullptr;
842         }
843     }
844     int32_t subscribeSize = INVALID_SUBSCRIBE_SIZE;
845     if (argc == 1) {
846         subscribeSize = RemoveAllCallback(env, sensorDesc);
847     } else if (IsMatchType(env, args_tmp, napi_undefined) ||
848         IsMatchType(env, args_tmp, napi_null)) {
849         subscribeSize = RemoveAllCallback(env, sensorDesc);
850     } else if (IsMatchType(env, args_tmp, napi_function)) {
851         subscribeSize = RemoveCallback(env, sensorDesc, args_tmp);
852     } else {
853         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, args[2] should is napi_function");
854         return nullptr;
855     }
856     if (CheckSystemSubscribe(sensorDesc) || (subscribeSize > DEFAULT_SUBSCRIBE_SIZE)) {
857         SEN_HILOGW("There are other client subscribe system js api as well, not need unsubscribe");
858         return nullptr;
859     }
860     int32_t ret = UnsubscribeSensor(sensorDesc);
861     if (ret == PARAMETER_ERROR || ret == PERMISSION_DENIED) {
862         ThrowErr(env, ret, "UnsubscribeSensor fail");
863     }
864     return nullptr;
865 }
866 
EmitAsyncWork(napi_value param,sptr<AsyncCallbackInfo> info)867 static napi_value EmitAsyncWork(napi_value param, sptr<AsyncCallbackInfo> info)
868 {
869     CHKPP(info);
870     napi_status status = napi_generic_failure;
871     if (param != nullptr) {
872         status = napi_create_reference(info->env, param, 1, &info->callback[0]);
873         if (status != napi_ok) {
874             SEN_HILOGE("napi_create_reference fail");
875             return nullptr;
876         }
877         EmitAsyncCallbackWork(info);
878         return nullptr;
879     }
880     napi_value promise = nullptr;
881     status = napi_create_promise(info->env, &info->deferred, &promise);
882     if (status != napi_ok) {
883         SEN_HILOGE("napi_create_promise fail");
884         return nullptr;
885     }
886     EmitPromiseWork(info);
887     return promise;
888 }
889 
GetGeomagneticField(napi_env env,napi_callback_info info)890 static napi_value GetGeomagneticField(napi_env env, napi_callback_info info)
891 {
892     CALL_LOG_ENTER;
893     size_t argc = 3;
894     napi_value args[3] = { 0 };
895     napi_value thisVar = nullptr;
896     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
897     if (status != napi_ok || argc < 2) {
898         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
899         return nullptr;
900     }
901     if ((!IsMatchType(env, args[0], napi_object)) || (!IsMatchType(env, args[1], napi_number))) {
902         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type");
903         return nullptr;
904     }
905     napi_value napiLatitude = GetNamedProperty(env, args[0], "latitude");
906     if (napiLatitude == nullptr) {
907         ThrowErr(env, PARAMETER_ERROR, "napiLatitude is null");
908         return nullptr;
909     }
910     double latitude = 0;
911     if (!GetNativeDouble(env, napiLatitude, latitude)) {
912         ThrowErr(env, PARAMETER_ERROR, "Get latitude fail");
913         return nullptr;
914     }
915     napi_value napiLongitude = GetNamedProperty(env, args[0], "longitude");
916     if (napiLongitude == nullptr) {
917         ThrowErr(env, PARAMETER_ERROR, "napiLongitude is null");
918         return nullptr;
919     }
920     double longitude = 0;
921     if (!GetNativeDouble(env, napiLongitude, longitude)) {
922         ThrowErr(env, PARAMETER_ERROR, "Get longitude fail");
923         return nullptr;
924     }
925     napi_value napiAltitude = GetNamedProperty(env, args[0], "altitude");
926     if (napiAltitude == nullptr) {
927         ThrowErr(env, PARAMETER_ERROR, "napiAltitude is null");
928         return nullptr;
929     }
930     double altitude = 0;
931     if (!GetNativeDouble(env, napiAltitude, altitude)) {
932         ThrowErr(env, PARAMETER_ERROR, "Get altitude fail");
933         return nullptr;
934     }
935     int64_t timeMillis = 0;
936     if (!GetNativeInt64(env, args[1], timeMillis)) {
937         ThrowErr(env, PARAMETER_ERROR, "Get timeMillis fail");
938         return nullptr;
939     }
940     GeomagneticField geomagneticField(latitude, longitude, altitude, timeMillis);
941     sptr<AsyncCallbackInfo> asyncCallbackInfo =
942         new (std::nothrow) AsyncCallbackInfo(env, GET_GEOMAGNETIC_FIELD);
943     CHKPP(asyncCallbackInfo);
944     asyncCallbackInfo->data.geomagneticData = {
945         .x = geomagneticField.ObtainX(),
946         .y = geomagneticField.ObtainY(),
947         .z = geomagneticField.ObtainZ(),
948         .geomagneticDip = geomagneticField.ObtainGeomagneticDip(),
949         .deflectionAngle = geomagneticField.ObtainDeflectionAngle(),
950         .levelIntensity = geomagneticField.ObtainLevelIntensity(),
951         .totalIntensity = geomagneticField.ObtainTotalIntensity(),
952     };
953     if (argc >= 3 && IsMatchType(env, args[2], napi_function)) {
954         return EmitAsyncWork(args[2], asyncCallbackInfo);
955     }
956     return EmitAsyncWork(nullptr, asyncCallbackInfo);
957 }
958 
GetAxisX(napi_env env,napi_value value)959 static napi_value GetAxisX(napi_env env, napi_value value)
960 {
961     return GetNamedProperty(env, value, "x");
962 }
963 
GetAxisY(napi_env env,napi_value value)964 static napi_value GetAxisY(napi_env env, napi_value value)
965 {
966     return GetNamedProperty(env, value, "y");
967 }
968 
TransformCoordinateSystem(napi_env env,napi_callback_info info)969 static napi_value TransformCoordinateSystem(napi_env env, napi_callback_info info)
970 {
971     CALL_LOG_ENTER;
972     size_t argc = 3;
973     napi_value args[3]  = { 0 };
974     napi_value thisVar = nullptr;
975     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
976     if (status != napi_ok || argc < 2) {
977         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
978         return nullptr;
979     }
980     if ((!IsMatchArrayType(env, args[0])) || (!IsMatchType(env, args[1], napi_object))) {
981         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type");
982         return nullptr;
983     }
984     std::vector<float> inRotationVector;
985     if (!GetFloatArray(env, args[0], inRotationVector)) {
986         ThrowErr(env, PARAMETER_ERROR, "Get inRotationVector fail");
987         return nullptr;
988     }
989     size_t length = inRotationVector.size();
990     if ((length != DATA_LENGTH) && (length != THREE_DIMENSIONAL_MATRIX_LENGTH)) {
991         ThrowErr(env, PARAMETER_ERROR, "Wrong inRotationVector length");
992         return nullptr;
993     }
994     napi_value napiAxisX = GetAxisX(env, args[1]);
995     if (napiAxisX == nullptr) {
996         ThrowErr(env, PARAMETER_ERROR, "napiAxisX is null");
997         return nullptr;
998     }
999     int32_t axisX = 0;
1000     if (!GetNativeInt32(env, napiAxisX, axisX)) {
1001         ThrowErr(env, PARAMETER_ERROR, "Get axisY fail");
1002         return nullptr;
1003     }
1004     napi_value napiAxisY = GetAxisY(env, args[1]);
1005     if (napiAxisY == nullptr) {
1006         ThrowErr(env, PARAMETER_ERROR, "napiAxisY is null");
1007         return nullptr;
1008     }
1009     int32_t axisY = 0;
1010     if (!GetNativeInt32(env, napiAxisY, axisY)) {
1011         ThrowErr(env, PARAMETER_ERROR, "Get axisY fail");
1012         return nullptr;
1013     }
1014     sptr<AsyncCallbackInfo> asyncCallbackInfo =
1015         new (std::nothrow) AsyncCallbackInfo(env, TRANSFORM_COORDINATE_SYSTEM);
1016     CHKPP(asyncCallbackInfo);
1017     std::vector<float> outRotationVector(length);
1018     SensorAlgorithm sensorAlgorithm;
1019     int32_t ret = sensorAlgorithm.TransformCoordinateSystem(inRotationVector, axisX, axisY, outRotationVector);
1020     if (ret != OHOS::ERR_OK) {
1021         ThrowErr(env, ret, "Transform coordinate system fail");
1022         return nullptr;
1023     } else {
1024         for (size_t i = 0; i < length; ++i) {
1025             asyncCallbackInfo->data.reserveData.reserve[i] = outRotationVector[i];
1026         }
1027         asyncCallbackInfo->data.reserveData.length = static_cast<int32_t>(length);
1028     }
1029     if (argc >= 3 && IsMatchType(env, args[2], napi_function)) {
1030         return EmitAsyncWork(args[2], asyncCallbackInfo);
1031     }
1032     return EmitAsyncWork(nullptr, asyncCallbackInfo);
1033 }
1034 
GetAngleModify(napi_env env,napi_callback_info info)1035 static napi_value GetAngleModify(napi_env env, napi_callback_info info)
1036 {
1037     CALL_LOG_ENTER;
1038     size_t argc = 3;
1039     napi_value args[3] = { 0 };
1040     napi_value thisVar = nullptr;
1041     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1042     if (status != napi_ok || argc < 2) {
1043         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
1044         return nullptr;
1045     }
1046     if (!IsMatchArrayType(env, args[0])) {
1047         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array");
1048         return nullptr;
1049     }
1050     if (!IsMatchArrayType(env, args[1])) {
1051         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array");
1052         return nullptr;
1053     }
1054     sptr<AsyncCallbackInfo> asyncCallbackInfo =
1055         new (std::nothrow) AsyncCallbackInfo(env, GET_ANGLE_MODIFY);
1056     CHKPP(asyncCallbackInfo);
1057     std::vector<float> curRotationVector;
1058     if (!GetFloatArray(env, args[0], curRotationVector)) {
1059         ThrowErr(env, PARAMETER_ERROR, "Get curRotationVector fail");
1060         return nullptr;
1061     }
1062     std::vector<float> preRotationVector;
1063     if (!GetFloatArray(env, args[1], preRotationVector)) {
1064         ThrowErr(env, PARAMETER_ERROR, "Get preRotationVector fail");
1065         return nullptr;
1066     }
1067     std::vector<float> angleChange(ROTATION_VECTOR_LENGTH);
1068     SensorAlgorithm sensorAlgorithm;
1069     int32_t ret = sensorAlgorithm.GetAngleModify(curRotationVector, preRotationVector, angleChange);
1070     if (ret != OHOS::ERR_OK) {
1071         ThrowErr(env, ret, "Get angle modify fail");
1072         return nullptr;
1073     } else {
1074         asyncCallbackInfo->data.reserveData.length = ROTATION_VECTOR_LENGTH;
1075         for (int32_t i = 0; i < ROTATION_VECTOR_LENGTH; ++i) {
1076             asyncCallbackInfo->data.reserveData.reserve[i] = angleChange[i];
1077         }
1078     }
1079     if (argc >= 3 && IsMatchType(env, args[2], napi_function)) {
1080         return EmitAsyncWork(args[2], asyncCallbackInfo);
1081     }
1082     return EmitAsyncWork(nullptr, asyncCallbackInfo);
1083 }
1084 
GetDirection(napi_env env,napi_callback_info info)1085 static napi_value GetDirection(napi_env env, napi_callback_info info)
1086 {
1087     CALL_LOG_ENTER;
1088     size_t argc = 3;
1089     napi_value args[3] = { 0 };
1090     napi_value thisVar = nullptr;
1091     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1092     if (status != napi_ok || argc < 1) {
1093         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
1094         return nullptr;
1095     }
1096     if (!IsMatchArrayType(env, args[0])) {
1097         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array");
1098         return nullptr;
1099     }
1100     sptr<AsyncCallbackInfo> asyncCallbackInfo =
1101         new (std::nothrow) AsyncCallbackInfo(env, GET_DIRECTION);
1102     CHKPP(asyncCallbackInfo);
1103     std::vector<float> rotationMatrix;
1104     if (!GetFloatArray(env, args[0], rotationMatrix)) {
1105         ThrowErr(env, PARAMETER_ERROR, "Get rotationMatrix fail");
1106         return nullptr;
1107     }
1108     std::vector<float> rotationAngle(ROTATION_VECTOR_LENGTH);
1109     SensorAlgorithm sensorAlgorithm;
1110     int32_t ret = sensorAlgorithm.GetDirection(rotationMatrix, rotationAngle);
1111     if (ret != OHOS::ERR_OK) {
1112         ThrowErr(env, ret, "Get direction fail");
1113         return nullptr;
1114     } else {
1115         asyncCallbackInfo->data.reserveData.length = ROTATION_VECTOR_LENGTH;
1116         for (int32_t i = 0; i < ROTATION_VECTOR_LENGTH; ++i) {
1117             asyncCallbackInfo->data.reserveData.reserve[i] = rotationAngle[i];
1118         }
1119     }
1120     if (argc >= 2 && IsMatchType(env, args[1], napi_function)) {
1121         return EmitAsyncWork(args[1], asyncCallbackInfo);
1122     }
1123     return EmitAsyncWork(nullptr, asyncCallbackInfo);
1124 }
1125 
CreateQuaternion(napi_env env,napi_callback_info info)1126 static napi_value CreateQuaternion(napi_env env, napi_callback_info info)
1127 {
1128     CALL_LOG_ENTER;
1129     size_t argc = 2;
1130     napi_value args[2] = { 0 };
1131     napi_value thisVar = nullptr;
1132     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1133     if (status != napi_ok || argc < 1) {
1134         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info failed or number of parameter invalid");
1135         return nullptr;
1136     }
1137     if (!IsMatchArrayType(env, args[0])) {
1138         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array");
1139         return nullptr;
1140     }
1141     sptr<AsyncCallbackInfo> asyncCallbackInfo =
1142         new (std::nothrow) AsyncCallbackInfo(env, CREATE_QUATERNION);
1143     CHKPP(asyncCallbackInfo);
1144     std::vector<float> rotationVector;
1145     if (!GetFloatArray(env, args[0], rotationVector)) {
1146         ThrowErr(env, PARAMETER_ERROR, "Get rotationVector failed");
1147         return nullptr;
1148     }
1149     std::vector<float> quaternion(QUATERNION_LENGTH);
1150     SensorAlgorithm sensorAlgorithm;
1151     int32_t ret = sensorAlgorithm.CreateQuaternion(rotationVector, quaternion);
1152     if (ret != OHOS::ERR_OK) {
1153         ThrowErr(env, ret, "CreateQuaternion fail");
1154         return nullptr;
1155     } else {
1156         asyncCallbackInfo->data.reserveData.length = QUATERNION_LENGTH;
1157         for (int32_t i = 0; i < QUATERNION_LENGTH; ++i) {
1158             asyncCallbackInfo->data.reserveData.reserve[i] = quaternion[i];
1159         }
1160     }
1161     if (argc >= 2 && IsMatchType(env, args[1], napi_function)) {
1162         return EmitAsyncWork(args[1], asyncCallbackInfo);
1163     }
1164     return EmitAsyncWork(nullptr, asyncCallbackInfo);
1165 }
1166 
GetAltitude(napi_env env,napi_callback_info info)1167 static napi_value GetAltitude(napi_env env, napi_callback_info info)
1168 {
1169     CALL_LOG_ENTER;
1170     size_t argc = 3;
1171     napi_value args[3] = { 0 };
1172     napi_value thisVar = nullptr;
1173     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1174     if (status != napi_ok || argc < 2) {
1175         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
1176         return nullptr;
1177     }
1178     if ((!IsMatchType(env, args[0], napi_number)) || (!IsMatchType(env, args[1], napi_number))) {
1179         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type");
1180         return nullptr;
1181     }
1182     sptr<AsyncCallbackInfo> asyncCallbackInfo =
1183         new (std::nothrow) AsyncCallbackInfo(env, GET_ALTITUDE);
1184     CHKPP(asyncCallbackInfo);
1185     float seaPressure = 0;
1186     if (!GetNativeFloat(env, args[0], seaPressure)) {
1187         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get seaPressure fail");
1188         return nullptr;
1189     }
1190     float currentPressure = 0;
1191     if (!GetNativeFloat(env, args[1], currentPressure)) {
1192         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get currentPressure fail");
1193         return nullptr;
1194     }
1195     float altitude = 0;
1196     SensorAlgorithm sensorAlgorithm;
1197     int32_t ret = sensorAlgorithm.GetAltitude(seaPressure, currentPressure, &altitude);
1198     if (ret != OHOS::ERR_OK) {
1199         ThrowErr(env, ret, "Get altitude fail");
1200         return nullptr;
1201     } else {
1202         asyncCallbackInfo->data.reserveData.reserve[0] = altitude;
1203     }
1204     if (argc >= 3 && IsMatchType(env, args[2], napi_function)) {
1205         return EmitAsyncWork(args[2], asyncCallbackInfo);
1206     }
1207     return EmitAsyncWork(nullptr, asyncCallbackInfo);
1208 }
1209 
GetGeomagneticDip(napi_env env,napi_callback_info info)1210 static napi_value GetGeomagneticDip(napi_env env, napi_callback_info info)
1211 {
1212     CALL_LOG_ENTER;
1213     size_t argc = 2;
1214     napi_value args[2] = { 0 };
1215     napi_value thisVar = nullptr;
1216     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1217     if (status != napi_ok || argc < 1) {
1218         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
1219         return nullptr;
1220     }
1221     if (!IsMatchArrayType(env, args[0])) {
1222         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array");
1223         return nullptr;
1224     }
1225     sptr<AsyncCallbackInfo> asyncCallbackInfo =
1226         new (std::nothrow) AsyncCallbackInfo(env, GET_GEOMAGNETIC_DIP);
1227     CHKPP(asyncCallbackInfo);
1228     std::vector<float> inclinationMatrix;
1229     if (!GetFloatArray(env, args[0], inclinationMatrix)) {
1230         ThrowErr(env, PARAMETER_ERROR, "Get inclinationMatrix fail");
1231         return nullptr;
1232     }
1233     float geomagneticDip = 0;
1234     SensorAlgorithm sensorAlgorithm;
1235     int32_t ret = sensorAlgorithm.GetGeomagneticDip(inclinationMatrix, &geomagneticDip);
1236     if (ret != OHOS::ERR_OK) {
1237         ThrowErr(env, ret, "Get geomagnetic dip fail");
1238         return nullptr;
1239     } else {
1240         asyncCallbackInfo->data.reserveData.reserve[0] = geomagneticDip;
1241     }
1242     if (argc >= 2 && IsMatchType(env, args[1], napi_function)) {
1243         return EmitAsyncWork(args[1], asyncCallbackInfo);
1244     }
1245     return EmitAsyncWork(nullptr, asyncCallbackInfo);
1246 }
1247 
CreateRotationAndInclination(const napi_env & env,napi_value args[],size_t argc)1248 static napi_value CreateRotationAndInclination(const napi_env &env, napi_value args[], size_t argc)
1249 {
1250     CALL_LOG_ENTER;
1251     if (argc < 2) {
1252         ThrowErr(env, PARAMETER_ERROR, "The number of parameters is not valid");
1253         return nullptr;
1254     }
1255     std::vector<float> gravity;
1256     if (!GetFloatArray(env, args[0], gravity)) {
1257         ThrowErr(env, PARAMETER_ERROR, "Get gravity fail");
1258         return nullptr;
1259     }
1260     std::vector<float> geomagnetic;
1261     if (!GetFloatArray(env, args[1], geomagnetic)) {
1262         ThrowErr(env, PARAMETER_ERROR, "Get geomagnetic fail");
1263         return nullptr;
1264     }
1265     std::vector<float> rotation(THREE_DIMENSIONAL_MATRIX_LENGTH);
1266     std::vector<float> inclination(THREE_DIMENSIONAL_MATRIX_LENGTH);
1267     sptr<AsyncCallbackInfo> asyncCallbackInfo =
1268         new (std::nothrow) AsyncCallbackInfo(env, ROTATION_INCLINATION_MATRIX);
1269     CHKPP(asyncCallbackInfo);
1270     SensorAlgorithm sensorAlgorithm;
1271     int32_t ret = sensorAlgorithm.CreateRotationAndInclination(gravity, geomagnetic, rotation, inclination);
1272     if (ret != OHOS::ERR_OK) {
1273         ThrowErr(env, ret, "Create rotation and inclination matrix fail");
1274         return nullptr;
1275     } else {
1276         asyncCallbackInfo->data.reserveData.length = THREE_DIMENSIONAL_MATRIX_LENGTH;
1277         for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; ++i) {
1278             asyncCallbackInfo->data.rationMatrixData.rotationMatrix[i] = rotation[i];
1279         }
1280         for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; ++i) {
1281             asyncCallbackInfo->data.rationMatrixData.inclinationMatrix[i] = inclination[i];
1282         }
1283     }
1284     if (argc >= 3 && IsMatchType(env, args[2], napi_function)) {
1285         return EmitAsyncWork(args[2], asyncCallbackInfo);
1286     }
1287     return EmitAsyncWork(nullptr, asyncCallbackInfo);
1288 }
1289 
GetRotationMatrix(const napi_env & env,napi_value args[],size_t argc)1290 static napi_value GetRotationMatrix(const napi_env &env, napi_value args[], size_t argc)
1291 {
1292     CALL_LOG_ENTER;
1293     if (argc < 1) {
1294         ThrowErr(env, PARAMETER_ERROR, "The number of parameters is not valid");
1295         return nullptr;
1296     }
1297     std::vector<float> rotationVector;
1298     if (!GetFloatArray(env, args[0], rotationVector)) {
1299         ThrowErr(env, PARAMETER_ERROR, "Get rotationVector fail");
1300         return nullptr;
1301     }
1302     sptr<AsyncCallbackInfo> asyncCallbackInfo =
1303         new (std::nothrow) AsyncCallbackInfo(env, CREATE_ROTATION_MATRIX);
1304     CHKPP(asyncCallbackInfo);
1305     std::vector<float> rotationMatrix(THREE_DIMENSIONAL_MATRIX_LENGTH);
1306     SensorAlgorithm sensorAlgorithm;
1307     int32_t ret = sensorAlgorithm.CreateRotationMatrix(rotationVector, rotationMatrix);
1308     if (ret != OHOS::ERR_OK) {
1309         ThrowErr(env, ret, "Create rotation matrix fail");
1310         return nullptr;
1311     } else {
1312         asyncCallbackInfo->data.reserveData.length = THREE_DIMENSIONAL_MATRIX_LENGTH;
1313         for (int32_t i = 0; i < THREE_DIMENSIONAL_MATRIX_LENGTH; ++i) {
1314             asyncCallbackInfo->data.reserveData.reserve[i] = rotationMatrix[i];
1315         }
1316     }
1317     if (argc >= 2 && IsMatchType(env, args[1], napi_function)) {
1318         return EmitAsyncWork(args[1], asyncCallbackInfo);
1319     }
1320     return EmitAsyncWork(nullptr, asyncCallbackInfo);
1321 }
1322 
CreateRotationMatrix(napi_env env,napi_callback_info info)1323 static napi_value CreateRotationMatrix(napi_env env, napi_callback_info info)
1324 {
1325     CALL_LOG_ENTER;
1326     size_t argc = 3;
1327     napi_value args[3] = { 0 };
1328     napi_value thisVar = nullptr;
1329     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1330     if (status != napi_ok || argc < 1) {
1331         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
1332         return nullptr;
1333     }
1334     if (!IsMatchArrayType(env, args[0])) {
1335         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be array");
1336         return nullptr;
1337     }
1338     if (argc >= 2 && IsMatchArrayType(env, args[1])) {
1339         return CreateRotationAndInclination(env, args, argc);
1340     } else {
1341         return GetRotationMatrix(env, args, argc);
1342     }
1343 }
1344 
GetSensorList(napi_env env,napi_callback_info info)1345 static napi_value GetSensorList(napi_env env, napi_callback_info info)
1346 {
1347     CALL_LOG_ENTER;
1348     size_t argc = 1;
1349     napi_value args[1] = { 0 };
1350     napi_value thisVar = nullptr;
1351     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1352     if (status != napi_ok) {
1353         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail");
1354         return nullptr;
1355     }
1356     sptr<AsyncCallbackInfo> asyncCallbackInfo =
1357         new (std::nothrow) AsyncCallbackInfo(env, GET_SENSOR_LIST);
1358     CHKPP(asyncCallbackInfo);
1359     SensorInfo *sensorInfos = nullptr;
1360     int32_t count = 0;
1361     int32_t ret = GetAllSensors(&sensorInfos, &count);
1362     if (ret != OHOS::ERR_OK) {
1363         SEN_HILOGE("Get sensor list fail");
1364         asyncCallbackInfo->type = FAIL;
1365         asyncCallbackInfo->error.code = ret;
1366     } else {
1367         for (int32_t i = 0; i < count; ++i) {
1368             if ((sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT1) ||
1369                 (sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_PROXIMITY1) ||
1370                 (sensorInfos[i].sensorTypeId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) {
1371                 SEN_HILOGD("This sensor is secondary ambient light");
1372                 continue;
1373             }
1374             asyncCallbackInfo->sensorInfos.push_back(*(sensorInfos + i));
1375         }
1376     }
1377     if (argc >= 1 && IsMatchType(env, args[0], napi_function)) {
1378         return EmitAsyncWork(args[0], asyncCallbackInfo);
1379     }
1380     return EmitAsyncWork(nullptr, asyncCallbackInfo);
1381 }
1382 
GetSensorListSync(napi_env env,napi_callback_info info)1383 static napi_value GetSensorListSync(napi_env env, napi_callback_info info)
1384 {
1385     CALL_LOG_ENTER;
1386     size_t argc = 0;
1387     napi_value result = nullptr;
1388     napi_get_undefined(env, &result);
1389     napi_value thisVar = nullptr;
1390     napi_status status = napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr);
1391     if (status != napi_ok) {
1392         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail");
1393         return result;
1394     }
1395     SensorInfo *sensorInfos = nullptr;
1396     int32_t count = 0;
1397     int32_t ret = GetAllSensors(&sensorInfos, &count);
1398     if (ret != OHOS::ERR_OK) {
1399         ThrowErr(env, ret, "Get sensor list fail");
1400         return result;
1401     }
1402     vector<SensorInfo> sensorInfoVec;
1403     for (int32_t i = 0; i < count; ++i) {
1404         if ((sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT1) ||
1405             (sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_PROXIMITY1) ||
1406             (sensorInfos[i].sensorTypeId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) {
1407             SEN_HILOGD("This sensor is secondary ambient light");
1408             continue;
1409         }
1410         sensorInfoVec.push_back(*(sensorInfos + i));
1411     }
1412     if (napi_create_array(env, &result) != napi_ok) {
1413         ThrowErr(env, PARAMETER_ERROR, "napi_create_array fail");
1414         return result;
1415     }
1416     for (uint32_t i = 0; i < sensorInfoVec.size(); ++i) {
1417         napi_value value = nullptr;
1418         if (!ConvertToSensorInfo(env, sensorInfoVec[i], value)) {
1419             ThrowErr(env, PARAMETER_ERROR, "Convert sensor info fail");
1420             return result;
1421         }
1422         if (napi_set_element(env, result, i, value) != napi_ok) {
1423             ThrowErr(env, PARAMETER_ERROR, "napi_set_element fail");
1424         }
1425     }
1426     return result;
1427 }
1428 
GetSingleSensor(napi_env env,napi_callback_info info)1429 static napi_value GetSingleSensor(napi_env env, napi_callback_info info)
1430 {
1431     CALL_LOG_ENTER;
1432     size_t argc = 2;
1433     napi_value args[2] = { 0 };
1434     napi_value thisVar = nullptr;
1435     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1436     if (status != napi_ok || argc < 1) {
1437         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
1438         return nullptr;
1439     }
1440     int32_t sensorTypeId = INVALID_SENSOR_TYPE;
1441     if (!GetNativeInt32(env, args[0], sensorTypeId)) {
1442         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail");
1443         return nullptr;
1444     }
1445     int32_t deviceId = DEFAULT_DEVICE_ID;
1446     if (!GetLocationDeviceId(deviceId)) {
1447         SEN_HILOGW("Cant fand local deviceId, default deviceId :%{public}d", deviceId);
1448     }
1449     sptr<AsyncCallbackInfo> asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, GET_SINGLE_SENSOR);
1450     CHKPP(asyncCallbackInfo);
1451     SensorInfo *sensorInfos = nullptr;
1452     int32_t count = 0;
1453     int32_t ret = GetAllSensors(&sensorInfos, &count);
1454     if (ret != OHOS::ERR_OK) {
1455         SEN_HILOGE("Get sensor list fail");
1456         asyncCallbackInfo->type = FAIL;
1457         asyncCallbackInfo->error.code = ret;
1458     } else {
1459         for (int32_t i = 0; i < count; ++i) {
1460             if ((sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT1) ||
1461                 (sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_PROXIMITY1) ||
1462                 (sensorInfos[i].sensorTypeId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) {
1463                 SEN_HILOGD("This sensor is secondary ambient light");
1464                 continue;
1465             }
1466             if (sensorInfos[i].deviceId == deviceId && sensorInfos[i].sensorTypeId == sensorTypeId) {
1467                 asyncCallbackInfo->sensorInfos.push_back(*(sensorInfos + i));
1468                 break;
1469             }
1470         }
1471         if (asyncCallbackInfo->sensorInfos.empty()) {
1472             uint32_t targetVersion = 0;
1473             if (GetSelfTargetVersion(targetVersion) && (targetVersion < COMPATIBILITY_CHANGE_VERSION_API12)) {
1474                 ThrowErr(env, PARAMETER_ERROR, "The sensor is not supported by the device");
1475                 return nullptr;
1476             }
1477             ThrowErr(env, SENSOR_NO_SUPPORT, "The sensor is not supported by the device");
1478             return nullptr;
1479         }
1480     }
1481     if (argc >= 2 && IsMatchType(env, args[1], napi_function)) {
1482         return EmitAsyncWork(args[1], asyncCallbackInfo);
1483     }
1484     return EmitAsyncWork(nullptr, asyncCallbackInfo);
1485 }
1486 
GetSingleSensorSync(napi_env env,napi_callback_info info)1487 static napi_value GetSingleSensorSync(napi_env env, napi_callback_info info)
1488 {
1489     CALL_LOG_ENTER;
1490     size_t argc = 1;
1491     napi_value args[1] = { 0 };
1492     napi_value result = nullptr;
1493     napi_get_undefined(env, &result);
1494     napi_value thisVar = nullptr;
1495     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1496     if (status != napi_ok || argc == 0) {
1497         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
1498         return result;
1499     }
1500     int32_t sensorTypeId = INVALID_SENSOR_TYPE;
1501     if (!GetNativeInt32(env, args[0], sensorTypeId)) {
1502         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, get number fail");
1503         return result;
1504     }
1505     int32_t deviceId = DEFAULT_DEVICE_ID;
1506     if (!GetLocationDeviceId(deviceId)) {
1507         SEN_HILOGW("Cant fand local deviceId, default deviceId :%{public}d", deviceId);
1508     }
1509     SensorInfo *sensorInfos = nullptr;
1510     int32_t count = 0;
1511     int32_t ret = GetAllSensors(&sensorInfos, &count);
1512     if (ret != OHOS::ERR_OK) {
1513         ThrowErr(env, ret, "Get sensor list fail");
1514         return result;
1515     }
1516     vector<SensorInfo> sensorInfoVec;
1517     for (int32_t i = 0; i < count; ++i) {
1518         if ((sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT1) ||
1519             (sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_PROXIMITY1) ||
1520             (sensorInfos[i].sensorTypeId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) {
1521             SEN_HILOGD("This sensor is secondary ambient light");
1522             continue;
1523         }
1524         if (sensorInfos[i].deviceId == deviceId && sensorInfos[i].sensorTypeId == sensorTypeId) {
1525             sensorInfoVec.push_back(*(sensorInfos + i));
1526             break;
1527         }
1528     }
1529     if (sensorInfoVec.empty()) {
1530         ThrowErr(env, SENSOR_NO_SUPPORT, "The sensor is not supported by the device");
1531         return result;
1532     }
1533     if (!ConvertToSensorInfo(env, sensorInfoVec[0], result)) {
1534         ThrowErr(env, PARAMETER_ERROR, "Convert sensor info fail");
1535     }
1536     return result;
1537 }
1538 
FilteringSensorList(SensorInfo * sensorInfos,vector<SensorInfo> & callbackSensorInfo,int32_t count)1539 static void FilteringSensorList(SensorInfo *sensorInfos, vector<SensorInfo> &callbackSensorInfo, int32_t count)
1540 {
1541     for (int32_t i = 0; i < count; ++i) {
1542         if ((sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT1) ||
1543             (sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_PROXIMITY1) ||
1544             (sensorInfos[i].sensorTypeId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) {
1545             SEN_HILOGD("This sensor is secondary ambient light");
1546             continue;
1547         }
1548         callbackSensorInfo.push_back(*(sensorInfos + i));
1549     }
1550     return;
1551 }
1552 
GetSensorListByDeviceSync(napi_env env,napi_callback_info info)1553 static napi_value GetSensorListByDeviceSync(napi_env env, napi_callback_info info)
1554 {
1555     CALL_LOG_ENTER;
1556     size_t argc = 1;
1557     napi_value args[1] = { 0 };
1558     napi_value result = nullptr;
1559     napi_get_undefined(env, &result);
1560     if (napi_create_array(env, &result) != napi_ok) {
1561         SEN_HILOGE("napi_create_array fail");
1562         return result;
1563     }
1564     napi_value thisVar = nullptr;
1565     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1566     if (status != napi_ok) {
1567         SEN_HILOGE("napi_get_cb_info fail or number of parameter invalid");
1568         return result;
1569     }
1570     int32_t deviceId = DEFAULT_DEVICE_ID;
1571     if (!GetNativeInt32(env, args[0], deviceId)) {
1572         SEN_HILOGW("Get deviceId failed");
1573         if (!GetLocationDeviceId(deviceId)) {
1574             SEN_HILOGW("Cant fand local deviceId, default deviceId :%{public}d", deviceId);
1575         }
1576     }
1577     SensorInfo *sensorInfos = nullptr;
1578     int32_t count = 0;
1579     int32_t ret = GetDeviceSensors(deviceId, &sensorInfos, &count);
1580     if (ret != OHOS::ERR_OK) {
1581         SEN_HILOGE("Get deviceSensorList failed, ret:%{public}d", deviceId);
1582         return result;
1583     }
1584     vector<SensorInfo> sensorInfoVec;
1585     FilteringSensorList(sensorInfos, sensorInfoVec, count);
1586     for (uint32_t i = 0; i < sensorInfoVec.size(); ++i) {
1587         napi_value value = nullptr;
1588         if (!ConvertToSensorInfo(env, sensorInfoVec[i], value)) {
1589             SEN_HILOGE("Convert sensor info fail");
1590             return result;
1591         }
1592         if (napi_set_element(env, result, i, value) != napi_ok) {
1593             SEN_HILOGE("napi_set_element fail");
1594         }
1595     }
1596     return result;
1597 }
1598 
FilteringSingleSensorList(SensorInfo * sensorInfos,vector<SensorInfo> & callbackSensorInfo,int32_t count,int32_t sensorTypeId)1599 static void FilteringSingleSensorList(SensorInfo *sensorInfos, vector<SensorInfo> &callbackSensorInfo, int32_t count,
1600     int32_t sensorTypeId)
1601 {
1602     for (int32_t i = 0; i < count; ++i) {
1603         if ((sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_AMBIENT_LIGHT1) ||
1604             (sensorInfos[i].sensorTypeId == SENSOR_TYPE_ID_PROXIMITY1) ||
1605             (sensorInfos[i].sensorTypeId > GL_SENSOR_TYPE_PRIVATE_MIN_VALUE)) {
1606             SEN_HILOGD("This sensor is secondary ambient light");
1607             continue;
1608         }
1609         if (sensorInfos[i].sensorTypeId == sensorTypeId) {
1610             callbackSensorInfo.push_back(*(sensorInfos + i));
1611         }
1612     }
1613     return;
1614 }
1615 
GetSingleSensorByDeviceSync(napi_env env,napi_callback_info info)1616 static napi_value GetSingleSensorByDeviceSync(napi_env env, napi_callback_info info)
1617 {
1618     CALL_LOG_ENTER;
1619     size_t argc = 2;
1620     napi_value args[2] = { 0 };
1621     napi_value result = nullptr;
1622     napi_get_undefined(env, &result);
1623     if (napi_create_array(env, &result) != napi_ok) {
1624         SEN_HILOGE("napi_create_array fail");
1625         return result;
1626     }
1627     napi_value thisVar = nullptr;
1628     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1629     if (status != napi_ok || argc < 1) {
1630         SEN_HILOGE("napi_get_cb_info fail or number of parameter invalid");
1631         return result;
1632     }
1633     int32_t sensorTypeId = INVALID_SENSOR_TYPE;
1634     if (!GetNativeInt32(env, args[0], sensorTypeId)) {
1635         SEN_HILOGE("Wrong argument type, get number fail");
1636         return result;
1637     }
1638     int32_t deviceId = DEFAULT_DEVICE_ID;
1639     if (!GetNativeInt32(env, args[1], deviceId)) {
1640         SEN_HILOGW("Get deviceId failed");
1641         if (!GetLocationDeviceId(deviceId)) {
1642             SEN_HILOGW("Cant fand local deviceId, default deviceId :%{public}d", deviceId);
1643         }
1644     }
1645     SensorInfo *sensorInfos = nullptr;
1646     int32_t count = 0;
1647     int32_t ret = GetDeviceSensors(deviceId, &sensorInfos, &count);
1648     if (ret != OHOS::ERR_OK) {
1649         SEN_HILOGE("Get sensor list fail");
1650         return result;
1651     }
1652     vector<SensorInfo> sensorInfoVec;
1653     FilteringSingleSensorList(sensorInfos, sensorInfoVec, count, sensorTypeId);
1654     for (uint32_t i = 0; i < sensorInfoVec.size(); ++i) {
1655         napi_value value = nullptr;
1656         if (!ConvertToSensorInfo(env, sensorInfoVec[i], value)) {
1657             SEN_HILOGE("Convert sensor info fail");
1658             return result;
1659         }
1660         if (napi_set_element(env, result, i, value) != napi_ok) {
1661             SEN_HILOGE("napi_set_element fail");
1662         }
1663     }
1664     return result;
1665 }
1666 
RegisterSubscribeCallback(napi_env env,napi_value args,sptr<AsyncCallbackInfo> & asyncCallbackInfo,napi_value & napiFail,string interval)1667 bool RegisterSubscribeCallback(napi_env env, napi_value args, sptr<AsyncCallbackInfo> &asyncCallbackInfo,
1668     napi_value &napiFail, string interval)
1669 {
1670     napi_value napiSuccess = GetNamedProperty(env, args, "success");
1671     if (!IsMatchType(env, napiSuccess, napi_function)) {
1672         SEN_HILOGE("get napiSuccess fail");
1673         return false;
1674     }
1675     if (!RegisterNapiCallback(env, napiSuccess, asyncCallbackInfo->callback[0])) {
1676         SEN_HILOGE("register success callback fail");
1677         return false;
1678     }
1679     napiFail = GetNamedProperty(env, args, "fail");
1680     if (IsMatchType(env, napiFail, napi_function)) {
1681         SEN_HILOGD("Has fail callback");
1682         if (!RegisterNapiCallback(env, napiFail, asyncCallbackInfo->callback[1])) {
1683             SEN_HILOGE("register fail callback fail");
1684             return false;
1685         }
1686     }
1687     if (auto iter = g_samplingPeriod.find(interval); iter == g_samplingPeriod.end()) {
1688         if (!IsMatchType(env, napiFail, napi_function)) {
1689             SEN_HILOGE("input error, interval is invalid");
1690             return false;
1691         }
1692         CreateFailMessage(SUBSCRIBE_FAIL, INPUT_ERROR, "input error", asyncCallbackInfo);
1693         EmitAsyncCallbackWork(asyncCallbackInfo);
1694         return false;
1695     }
1696     return true;
1697 }
1698 
Subscribe(napi_env env,napi_callback_info info,int32_t sensorTypeId,CallbackDataType type)1699 napi_value Subscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId, CallbackDataType type)
1700 {
1701     CALL_LOG_ENTER;
1702     size_t argc = 1;
1703     napi_value args[1] = { 0 };
1704     napi_value thisVar = nullptr;
1705     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1706     if (status != napi_ok || argc < 1) {
1707         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
1708         return nullptr;
1709     }
1710     if (!IsMatchType(env, args[0], napi_object)) {
1711         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be object");
1712         return nullptr;
1713     }
1714     string interval = "normal";
1715     if ((sensorTypeId == SENSOR_TYPE_ID_ACCELEROMETER) ||
1716         ((sensorTypeId == SENSOR_TYPE_ID_ORIENTATION) && (type != SUBSCRIBE_COMPASS))
1717         || (sensorTypeId == SENSOR_TYPE_ID_GYROSCOPE)) {
1718         napi_value napiInterval = GetNamedProperty(env, args[0], "interval");
1719         CHKCP(GetStringValue(env, napiInterval, interval), "get interval fail");
1720     }
1721     sptr<AsyncCallbackInfo> asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, type);
1722     CHKPP(asyncCallbackInfo);
1723     napi_value napiFail;
1724     CHKCP(RegisterSubscribeCallback(env, args[0], asyncCallbackInfo, napiFail, interval), "register callback failed");
1725     int32_t deviceId = DEFAULT_DEVICE_ID;
1726     if (!GetLocationDeviceId(deviceId)) {
1727         SEN_HILOGW("Cant fand local deviceId, default deviceId :%{public}d", deviceId);
1728     }
1729     int32_t ret = SubscribeSensor({deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE},
1730         g_samplingPeriod[interval], DataCallbackImpl);
1731     if (ret != OHOS::ERR_OK) {
1732         CHKCP(IsMatchType(env, napiFail, napi_function), "subscribe fail");
1733         CreateFailMessage(SUBSCRIBE_FAIL, SENSOR_SUBSCRIBE_FAILURE, "subscribe fail", asyncCallbackInfo);
1734         EmitAsyncCallbackWork(asyncCallbackInfo);
1735         return nullptr;
1736     }
1737     std::lock_guard<std::mutex> subscribeLock(g_mutex);
1738     std::vector<sptr<AsyncCallbackInfo>> callbackInfos = g_subscribeCallbacks[{deviceId, sensorTypeId,
1739         DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}];
1740     callbackInfos.push_back(asyncCallbackInfo);
1741     g_subscribeCallbacks[{deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}] = callbackInfos;
1742     return nullptr;
1743 }
1744 
RemoveSubscribeCallback(napi_env env,SensorDescription sensorDesc)1745 static bool RemoveSubscribeCallback(napi_env env, SensorDescription sensorDesc)
1746 {
1747     CALL_LOG_ENTER;
1748     std::lock_guard<std::mutex> subscribeCallbackLock(g_mutex);
1749     std::vector<sptr<AsyncCallbackInfo>> callbackInfos = g_subscribeCallbacks[sensorDesc];
1750     for (auto iter = callbackInfos.begin(); iter != callbackInfos.end();) {
1751         CHKPC(*iter);
1752         if ((*iter)->env != env) {
1753             ++iter;
1754             continue;
1755         }
1756         iter = callbackInfos.erase(iter);
1757     }
1758     if (callbackInfos.empty()) {
1759         g_subscribeCallbacks.erase(sensorDesc);
1760         return true;
1761     }
1762     return false;
1763 }
1764 
Unsubscribe(napi_env env,napi_callback_info info,int32_t sensorTypeId)1765 napi_value Unsubscribe(napi_env env, napi_callback_info info, int32_t sensorTypeId)
1766 {
1767     CALL_LOG_ENTER;
1768     size_t argc = 1;
1769     napi_value args[1] = { 0 };
1770     napi_value thisVar = nullptr;
1771     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1772     if (status != napi_ok) {
1773         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail");
1774         return nullptr;
1775     }
1776     int32_t deviceId = DEFAULT_DEVICE_ID;
1777     if (!GetLocationDeviceId(deviceId)) {
1778         SEN_HILOGW("Cant fand local deviceId, default deviceId :%{public}d", deviceId);
1779     }
1780     if (!RemoveSubscribeCallback(env, {deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}) ||
1781         CheckSubscribe({deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE})) {
1782         SEN_HILOGW("There are other client subscribe as well, not need unsubscribe");
1783         return nullptr;
1784     }
1785     if (UnsubscribeSensor({deviceId, sensorTypeId, DEFAULT_SENSOR_ID, IS_LOCAL_DEVICE}) != OHOS::ERR_OK) {
1786         SEN_HILOGW("UnsubscribeSensor failed");
1787         return nullptr;
1788     }
1789     return nullptr;
1790 }
1791 
GetBodyState(napi_env env,napi_callback_info info)1792 napi_value GetBodyState(napi_env env, napi_callback_info info)
1793 {
1794     CALL_LOG_ENTER;
1795     size_t argc = 1;
1796     napi_value args[1] = { 0 };
1797     napi_value thisVar = nullptr;
1798     napi_status status = napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr);
1799     if (status != napi_ok || argc < 1) {
1800         ThrowErr(env, PARAMETER_ERROR, "napi_get_cb_info fail or number of parameter invalid");
1801         return nullptr;
1802     }
1803     if (!IsMatchType(env, args[0], napi_object)) {
1804         ThrowErr(env, PARAMETER_ERROR, "Wrong argument type, should be object");
1805         return nullptr;
1806     }
1807     sptr<AsyncCallbackInfo> asyncCallbackInfo = new (std::nothrow) AsyncCallbackInfo(env, GET_BODY_STATE);
1808     CHKPP(asyncCallbackInfo);
1809     napi_value napiSuccess = GetNamedProperty(env, args[0], "success");
1810     CHKCP(IsMatchType(env, napiSuccess, napi_function), "get napiSuccess fail");
1811     CHKCP(RegisterNapiCallback(env, napiSuccess, asyncCallbackInfo->callback[0]),
1812         "register success callback fail");
1813     std::lock_guard<std::mutex> onBodyLock(g_bodyMutex);
1814     asyncCallbackInfo->data.sensorData.data[0] =
1815         (fabs(g_bodyState - BODY_STATE_EXCEPT) < THRESHOLD) ? true : false;
1816     std::shared_ptr<CallbackSensorData> cb = std::make_shared<CallbackSensorData>();
1817     EmitUvEventLoop(asyncCallbackInfo, cb);
1818     return nullptr;
1819 }
1820 
EnumClassConstructor(napi_env env,napi_callback_info info)1821 static napi_value EnumClassConstructor(napi_env env, napi_callback_info info)
1822 {
1823     size_t argc = 0;
1824     napi_value args[1] = {0};
1825     napi_value ret = nullptr;
1826     void *data = nullptr;
1827     CHKNRP(env, napi_get_cb_info(env, info, &argc, args, &ret, &data), "napi_get_cb_info");
1828     return ret;
1829 }
1830 
CreateEnumSensorType(napi_env env,napi_value exports)1831 static napi_value CreateEnumSensorType(napi_env env, napi_value exports)
1832 {
1833     napi_property_descriptor desc[] = {
1834         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ACCELEROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_ACCELEROMETER)),
1835         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GYROSCOPE", GetNapiInt32(env, SENSOR_TYPE_ID_GYROSCOPE)),
1836         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_AMBIENT_LIGHT", GetNapiInt32(env, SENSOR_TYPE_ID_AMBIENT_LIGHT)),
1837         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_MAGNETIC_FIELD", GetNapiInt32(env, SENSOR_TYPE_ID_MAGNETIC_FIELD)),
1838         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_BAROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_BAROMETER)),
1839         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HALL", GetNapiInt32(env, SENSOR_TYPE_ID_HALL)),
1840         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_TEMPERATURE", GetNapiInt32(env, SENSOR_TYPE_ID_TEMPERATURE)),
1841         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PROXIMITY", GetNapiInt32(env, SENSOR_TYPE_ID_PROXIMITY)),
1842         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HUMIDITY", GetNapiInt32(env, SENSOR_TYPE_ID_HUMIDITY)),
1843         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_COLOR", GetNapiInt32(env, SENSOR_TYPE_ID_COLOR)),
1844         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_SAR", GetNapiInt32(env, SENSOR_TYPE_ID_SAR)),
1845         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ORIENTATION", GetNapiInt32(env, SENSOR_TYPE_ID_ORIENTATION)),
1846         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GRAVITY", GetNapiInt32(env, SENSOR_TYPE_ID_GRAVITY)),
1847         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_LINEAR_ACCELERATION",
1848             GetNapiInt32(env, SENSOR_TYPE_ID_LINEAR_ACCELERATION)),
1849         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ROTATION_VECTOR",
1850             GetNapiInt32(env, SENSOR_TYPE_ID_ROTATION_VECTOR)),
1851         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_AMBIENT_TEMPERATURE",
1852             GetNapiInt32(env, SENSOR_TYPE_ID_AMBIENT_TEMPERATURE)),
1853         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED",
1854             GetNapiInt32(env, SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED)),
1855         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED",
1856             GetNapiInt32(env, SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED)),
1857         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_SIGNIFICANT_MOTION",
1858             GetNapiInt32(env, SENSOR_TYPE_ID_SIGNIFICANT_MOTION)),
1859         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PEDOMETER_DETECTION",
1860             GetNapiInt32(env, SENSOR_TYPE_ID_PEDOMETER_DETECTION)),
1861         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_PEDOMETER", GetNapiInt32(env, SENSOR_TYPE_ID_PEDOMETER)),
1862         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_HEART_RATE", GetNapiInt32(env, SENSOR_TYPE_ID_HEART_RATE)),
1863         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_WEAR_DETECTION", GetNapiInt32(env, SENSOR_TYPE_ID_WEAR_DETECTION)),
1864         DECLARE_NAPI_STATIC_PROPERTY("SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED",
1865             GetNapiInt32(env, SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED)),
1866     };
1867     napi_value result = nullptr;
1868     CHKNRP(env, napi_define_class(env, "SensorType", NAPI_AUTO_LENGTH, EnumClassConstructor, nullptr,
1869         sizeof(desc) / sizeof(*desc), desc, &result), "napi_define_class");
1870     CHKNRP(env, napi_set_named_property(env, exports, "SensorType", result), "napi_set_named_property fail");
1871     return exports;
1872 }
1873 
CreateEnumSensorId(napi_env env,napi_value exports)1874 static napi_value CreateEnumSensorId(napi_env env, napi_value exports)
1875 {
1876     napi_property_descriptor desc[] = {
1877         DECLARE_NAPI_STATIC_PROPERTY("ACCELEROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_ACCELEROMETER)),
1878         DECLARE_NAPI_STATIC_PROPERTY("GYROSCOPE", GetNapiInt32(env, SENSOR_TYPE_ID_GYROSCOPE)),
1879         DECLARE_NAPI_STATIC_PROPERTY("AMBIENT_LIGHT", GetNapiInt32(env, SENSOR_TYPE_ID_AMBIENT_LIGHT)),
1880         DECLARE_NAPI_STATIC_PROPERTY("MAGNETIC_FIELD", GetNapiInt32(env, SENSOR_TYPE_ID_MAGNETIC_FIELD)),
1881         DECLARE_NAPI_STATIC_PROPERTY("BAROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_BAROMETER)),
1882         DECLARE_NAPI_STATIC_PROPERTY("HALL", GetNapiInt32(env, SENSOR_TYPE_ID_HALL)),
1883         DECLARE_NAPI_STATIC_PROPERTY("TEMPERATURE", GetNapiInt32(env, SENSOR_TYPE_ID_TEMPERATURE)),
1884         DECLARE_NAPI_STATIC_PROPERTY("PROXIMITY", GetNapiInt32(env, SENSOR_TYPE_ID_PROXIMITY)),
1885         DECLARE_NAPI_STATIC_PROPERTY("HUMIDITY", GetNapiInt32(env, SENSOR_TYPE_ID_HUMIDITY)),
1886         DECLARE_NAPI_STATIC_PROPERTY("COLOR", GetNapiInt32(env, SENSOR_TYPE_ID_COLOR)),
1887         DECLARE_NAPI_STATIC_PROPERTY("SAR", GetNapiInt32(env, SENSOR_TYPE_ID_SAR)),
1888         DECLARE_NAPI_STATIC_PROPERTY("ORIENTATION", GetNapiInt32(env, SENSOR_TYPE_ID_ORIENTATION)),
1889         DECLARE_NAPI_STATIC_PROPERTY("GRAVITY", GetNapiInt32(env, SENSOR_TYPE_ID_GRAVITY)),
1890         DECLARE_NAPI_STATIC_PROPERTY("LINEAR_ACCELEROMETER", GetNapiInt32(env, SENSOR_TYPE_ID_LINEAR_ACCELERATION)),
1891         DECLARE_NAPI_STATIC_PROPERTY("ROTATION_VECTOR", GetNapiInt32(env, SENSOR_TYPE_ID_ROTATION_VECTOR)),
1892         DECLARE_NAPI_STATIC_PROPERTY("AMBIENT_TEMPERATURE", GetNapiInt32(env, SENSOR_TYPE_ID_AMBIENT_TEMPERATURE)),
1893         DECLARE_NAPI_STATIC_PROPERTY("MAGNETIC_FIELD_UNCALIBRATED",
1894             GetNapiInt32(env, SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED)),
1895         DECLARE_NAPI_STATIC_PROPERTY("GYROSCOPE_UNCALIBRATED",
1896             GetNapiInt32(env, SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED)),
1897         DECLARE_NAPI_STATIC_PROPERTY("SIGNIFICANT_MOTION", GetNapiInt32(env, SENSOR_TYPE_ID_SIGNIFICANT_MOTION)),
1898         DECLARE_NAPI_STATIC_PROPERTY("PEDOMETER_DETECTION", GetNapiInt32(env, SENSOR_TYPE_ID_PEDOMETER_DETECTION)),
1899         DECLARE_NAPI_STATIC_PROPERTY("PEDOMETER", GetNapiInt32(env, SENSOR_TYPE_ID_PEDOMETER)),
1900         DECLARE_NAPI_STATIC_PROPERTY("HEART_RATE", GetNapiInt32(env, SENSOR_TYPE_ID_HEART_RATE)),
1901         DECLARE_NAPI_STATIC_PROPERTY("WEAR_DETECTION", GetNapiInt32(env, SENSOR_TYPE_ID_WEAR_DETECTION)),
1902         DECLARE_NAPI_STATIC_PROPERTY("ACCELEROMETER_UNCALIBRATED",
1903             GetNapiInt32(env, SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED)),
1904     };
1905     napi_value result = nullptr;
1906     CHKNRP(env, napi_define_class(env, "SensorId", NAPI_AUTO_LENGTH, EnumClassConstructor, nullptr,
1907         sizeof(desc) / sizeof(*desc), desc, &result), "napi_define_class");
1908     CHKNRP(env, napi_set_named_property(env, exports, "SensorId", result), "napi_set_named_property fail");
1909     return exports;
1910 }
1911 
CreateEnumSensorAccuracy(napi_env env,napi_value exports)1912 static napi_value CreateEnumSensorAccuracy(napi_env env, napi_value exports)
1913 {
1914     napi_property_descriptor desc[] = {
1915         DECLARE_NAPI_STATIC_PROPERTY("ACCURACY_UNRELIABLE", GetNapiInt32(env, ACCURACY_UNRELIABLE)),
1916         DECLARE_NAPI_STATIC_PROPERTY("ACCURACY_LOW", GetNapiInt32(env, ACCURACY_LOW)),
1917         DECLARE_NAPI_STATIC_PROPERTY("ACCURACY_MEDIUM", GetNapiInt32(env, ACCURACY_MEDIUM)),
1918         DECLARE_NAPI_STATIC_PROPERTY("ACCURACY_HIGH", GetNapiInt32(env, ACCURACY_HIGH)),
1919     };
1920     napi_value result = nullptr;
1921     CHKNRP(env, napi_define_class(env, "SensorAccuracy", NAPI_AUTO_LENGTH, EnumClassConstructor, nullptr,
1922         sizeof(desc) / sizeof(*desc), desc, &result), "napi_define_class");
1923     CHKNRP(env, napi_set_named_property(env, exports, "SensorAccuracy", result), "napi_set_named_property fail");
1924     return exports;
1925 }
1926 
Init(napi_env env,napi_value exports)1927 static napi_value Init(napi_env env, napi_value exports)
1928 {
1929     napi_property_descriptor desc[] = {
1930         DECLARE_NAPI_FUNCTION("on", On),
1931         DECLARE_NAPI_FUNCTION("once", Once),
1932         DECLARE_NAPI_FUNCTION("off", Off),
1933         DECLARE_NAPI_FUNCTION("getGeomagneticField", GetGeomagneticField),
1934         DECLARE_NAPI_FUNCTION("getGeomagneticInfo", GetGeomagneticField),
1935         DECLARE_NAPI_FUNCTION("transformCoordinateSystem", TransformCoordinateSystem),
1936         DECLARE_NAPI_FUNCTION("transformRotationMatrix", TransformCoordinateSystem),
1937         DECLARE_NAPI_FUNCTION("getAngleModify", GetAngleModify),
1938         DECLARE_NAPI_FUNCTION("getAngleVariation", GetAngleModify),
1939         DECLARE_NAPI_FUNCTION("getDirection", GetDirection),
1940         DECLARE_NAPI_FUNCTION("getOrientation", GetDirection),
1941         DECLARE_NAPI_FUNCTION("createQuaternion", CreateQuaternion),
1942         DECLARE_NAPI_FUNCTION("getQuaternion", CreateQuaternion),
1943         DECLARE_NAPI_FUNCTION("getAltitude", GetAltitude),
1944         DECLARE_NAPI_FUNCTION("getDeviceAltitude", GetAltitude),
1945         DECLARE_NAPI_FUNCTION("getGeomagneticDip", GetGeomagneticDip),
1946         DECLARE_NAPI_FUNCTION("getInclination", GetGeomagneticDip),
1947         DECLARE_NAPI_FUNCTION("createRotationMatrix", CreateRotationMatrix),
1948         DECLARE_NAPI_FUNCTION("getRotationMatrix", CreateRotationMatrix),
1949         DECLARE_NAPI_FUNCTION("getSensorList", GetSensorList),
1950         DECLARE_NAPI_FUNCTION("getSensorListSync", GetSensorListSync),
1951         DECLARE_NAPI_FUNCTION("getSingleSensor", GetSingleSensor),
1952         DECLARE_NAPI_FUNCTION("getSingleSensorSync", GetSingleSensorSync),
1953         DECLARE_NAPI_FUNCTION("getSensorListByDeviceSync", GetSensorListByDeviceSync),
1954         DECLARE_NAPI_FUNCTION("getSingleSensorByDeviceSync", GetSingleSensorByDeviceSync),
1955         DECLARE_NAPI_FUNCTION("subscribeAccelerometer", SubscribeAccelerometer),
1956         DECLARE_NAPI_FUNCTION("unsubscribeAccelerometer", UnsubscribeAccelerometer),
1957         DECLARE_NAPI_FUNCTION("subscribeCompass", SubscribeCompass),
1958         DECLARE_NAPI_FUNCTION("unsubscribeCompass", UnsubscribeCompass),
1959         DECLARE_NAPI_FUNCTION("subscribeProximity", SubscribeProximity),
1960         DECLARE_NAPI_FUNCTION("unsubscribeProximity", UnsubscribeProximity),
1961         DECLARE_NAPI_FUNCTION("subscribeLight", SubscribeLight),
1962         DECLARE_NAPI_FUNCTION("unsubscribeLight", UnsubscribeLight),
1963         DECLARE_NAPI_FUNCTION("subscribeStepCounter", SubscribeStepCounter),
1964         DECLARE_NAPI_FUNCTION("unsubscribeStepCounter", UnsubscribeStepCounter),
1965         DECLARE_NAPI_FUNCTION("subscribeBarometer", SubscribeBarometer),
1966         DECLARE_NAPI_FUNCTION("unsubscribeBarometer", UnsubscribeBarometer),
1967         DECLARE_NAPI_FUNCTION("subscribeHeartRate", SubscribeHeartRate),
1968         DECLARE_NAPI_FUNCTION("unsubscribeHeartRate", UnsubscribeHeartRate),
1969         DECLARE_NAPI_FUNCTION("subscribeOnBodyState", SubscribeOnBodyState),
1970         DECLARE_NAPI_FUNCTION("unsubscribeOnBodyState", UnsubscribeOnBodyState),
1971         DECLARE_NAPI_FUNCTION("getOnBodyState", GetOnBodyState),
1972         DECLARE_NAPI_FUNCTION("subscribeDeviceOrientation", SubscribeDeviceOrientation),
1973         DECLARE_NAPI_FUNCTION("unsubscribeDeviceOrientation", UnsubscribeDeviceOrientation),
1974         DECLARE_NAPI_FUNCTION("subscribeGyroscope", SubscribeGyroscope),
1975         DECLARE_NAPI_FUNCTION("unsubscribeGyroscope", UnsubscribeGyroscope),
1976         DECLARE_NAPI_FUNCTION("subscribeGravity", SubscribeGravity),
1977         DECLARE_NAPI_FUNCTION("unsubscribeGravity", UnsubscribeGravity),
1978         DECLARE_NAPI_FUNCTION("subscribeMagnetic", SubscribeMagnetic),
1979         DECLARE_NAPI_FUNCTION("unsubscribeMagnetic", UnsubscribeMagnetic),
1980         DECLARE_NAPI_FUNCTION("subscribeHall", SubscribeHall),
1981         DECLARE_NAPI_FUNCTION("unsubscribeHall", UnsubscribeHall),
1982     };
1983     CHKNRP(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc),
1984         "napi_define_properties");
1985     CHKCP(CreateEnumSensorType(env, exports), "Create enum sensor type fail");
1986     CHKCP(CreateEnumSensorId(env, exports), "Create enum sensor id fail");
1987     CHKCP(CreateEnumSensorAccuracy(env, exports), "Create enum sensor accuracy fail");
1988     // 注册env清理钩子函数
1989     napi_env *pEnv = new (std::nothrow) napi_env;
1990     if (pEnv == nullptr) {
1991         SEN_HILOGE("Init, pEnv is nullptr");
1992         return exports;
1993     }
1994     *pEnv = env;
1995     auto ret = napi_add_env_cleanup_hook(env, CleanUp, reinterpret_cast<void*>(pEnv));
1996     if (ret != napi_status::napi_ok) {
1997         SEN_HILOGE("Init, napi_add_env_cleanup_hook failed");
1998     }
1999 
2000     return exports;
2001 }
2002 
2003 static napi_module _module = {
2004     .nm_version = 1,
2005     .nm_flags = 0,
2006     .nm_filename = nullptr,
2007     .nm_register_func = Init,
2008     .nm_modname = "sensor",
2009     .nm_priv = ((void *)0),
2010     .reserved = {0}
2011 };
2012 
RegisterModule(void)2013 extern "C" __attribute__((constructor)) void RegisterModule(void)
2014 {
2015     napi_module_register(&_module);
2016 }
2017 } // namespace Sensors
2018 } // namespace OHOS