OpenHarmony的NAPI功能为开发者提供了JS与C/C++不同语言模块之间的相互访问,交互的能力,使得开发者使用C或者C++语言实现应用的关键功能。如操作开发板中某个GPIO节点的状态(OpenHarmony并没有提供直接操作GPIO口状态的API),点亮一个LED灯。
本篇基于前3篇NAPI的讲解总结,做一个控制开发板上LED灯状态的应用作为完结篇。
一、环境准备
设备:rk3568开发板
开发环境:DevEco Studio4.0.0.600
二、NAPI函数编写
1、基于NAPI的GPIO节点控制函数
OpenHarmony并没有提供直接操作GPIO口状态的API。若需要控制开发板上LED灯的亮灭, 需要通过NAPI的方式,写一个可以查询GPIO口状态、一个可以对节点写1和一个可以对节点写0的函数。
(1)main目录如下:
(2)bq_function.cpp
#include "napi/native_api.h"
#include "napi/native_api.h"
#include <cstring>
#include <js_native_api.h>
#include <sys/un.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//对指定节点写1
static napi_value Bq_GPIO_On(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value args[1] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
napi_valuetype valuetype0;
napi_typeof(env, args[0], &valuetype0);
char *ledPath = new char[150]{};
size_t buffSize = 100;
size_t realSize = 0;
napi_get_value_string_utf8(env, args[0], ledPath, buffSize, &realSize);
int fd;
char *ret = new char[50]{};
fd = open(ledPath, O_RDWR | O_TRUNC | O_NOCTTY);
if (fd < 0) {
strcpy(ret, "fail to open file");
} else {
strcpy(ret, "1");
write(fd, "1", 1);
close(fd);
}
napi_value returnValue = nullptr;
napi_create_string_utf8(env, ret, strlen(ret), &returnValue);
return return