1 /*
2 * Copyright (c) 2023 Unionman Technology 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 <napi/native_api.h>
16 #include <napi/native_node_api.h>
17 #include "i2c/i2c_ctl.h"
18
19 constexpr uint8_t address = 0x44;
20 constexpr uint16_t i2cNumber = 5;
21
22 static I2c::I2cCtl i2c(i2cNumber, address);
23
24 struct asyncPromiseData {
25 napi_async_work asyncWork;
26 napi_deferred deferred;
27 I2c::HumTem data;
28 };
29
getDataAsync(napi_env env,napi_callback_info cb)30 static napi_value getDataAsync(napi_env env, napi_callback_info cb)
31 {
32 asyncPromiseData* pd = new asyncPromiseData;
33 napi_value promise;
34 napi_create_promise(env, &pd->deferred, &promise);
35 napi_value resourceName;
36 napi_create_string_utf8(env, "getDataAsync", NAPI_AUTO_LENGTH, &resourceName);
37 napi_create_async_work(env, nullptr, resourceName,
38 [](napi_env env, void* data) {
39 asyncPromiseData* pd = reinterpret_cast<asyncPromiseData*>(data);
40 pd->data = i2c.readData();
41 },
42 [](napi_env env, napi_status status, void* data) {
43 asyncPromiseData* pd = reinterpret_cast<asyncPromiseData*>(data);
44 napi_value obj, temc, temf, hum;
45 napi_create_object(env, &obj);
46
47 napi_create_double(env, pd->data.temperatureC, &temc);
48 napi_set_named_property(env, obj, "temperatureC", temc);
49 napi_create_double(env, pd->data.temperatureF, &temf);
50 napi_set_named_property(env, obj, "temperatureF", temf);
51 napi_create_double(env, pd->data.humidity, &hum);
52 napi_set_named_property(env, obj, "humidity", hum);
53
54 napi_resolve_deferred(env, pd->deferred, obj);
55 napi_delete_async_work(env, pd->asyncWork);
56 delete pd;
57 }, pd, &pd->asyncWork);
58 napi_queue_async_work(env, pd->asyncWork);
59 return promise;
60 }
61
registerI2cCtl_Apis(napi_env env,napi_value exports)62 static napi_value registerI2cCtl_Apis(napi_env env, napi_value exports)
63 {
64 i2c.restart();
65 i2c.setMode(I2c::mode::highFrequency4Hz);
66 napi_property_descriptor desc[] = {
67 DECLARE_NAPI_FUNCTION("getDataAsync", getDataAsync),
68 };
69 NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
70 return exports;
71 }
72
73 NAPI_MODULE(i2c_ctl, registerI2cCtl_Apis)