了解更多开源内容请访问:开源基础软件社区https://ost.51cto.com项目介绍书文档为串口实现说明在eTS项目的hap包中访问,通过JS接口开放给上层应用。1、开发环境准备好安装OpenHarmonySDK1。在DevEcoStudio菜单栏中选择Tools->SDKManager2,在OpenHarmonySDK选项中选择API版本进行安装。2.创建一个eTS工程,创建一个支持NativeC++的eTS工程。NAPI库1.添加文件src/main/cpp/types/libserialhelper/serialhelper.d.ts/**Copyright(C)2021-2022HuaweiDeviceCo.,Ltd.*LicensedundertheApacheLicense,Version2.0(the“执照”);*除非遵守许可证,否则您不得使用此文件。*您可以在**http://www.apache.org/licenses/LICENSE-2.0获得许可证副本**除非适用法律要求或书面同意,否则根据许可证分发的软件*分发于“按原样”为基础,*不提供任何明示或暗示的保证或条件。*有关特定语言的管理权限和*许可证下的限制,请参阅许可证。*/import{AsyncCallback,Callback}from"basic";declarenamespaceserialHelper{/***打开串口。*@paramdev表示串口dev。*/函数openSerial(dev:string,callback:AsyncCallback):void;函数openSerial(dev:string):Promise;/***关闭串口。*@paramdev表示串口dev。*/functioncloseSerial(dev:string,callback:AsyncCallback):void;functioncloseSerial(dev:string):Promise;}exportdefaultserialHelper;2.添加文件src/main/cpp/types/libserialhelper/package.json{"name":"libserialhelper.so","types":"./serialhelper.d.ts"}3.生成对应的c++源码根据serialhelper.d.ts文件方法一:手动编写src/main/cpp/serial_helper.cpp结构AsyncCallInfo{napi_envenv=nullptr;napi_refcallbackRef=nullptr;napi_deferreddeferred=nullptr;napi_async_workwork=nullptr;void*data=nullptr;};staticvoidAsyncCallFinish(AsyncCallInfo*asyncCallInfo,int32_tresult,napi_value*asyncResult){if(asyncCallInfo->deferred){if(result==0){napi_resolve_deferred(asyncCallInfo->env,asyncCallInfo->延迟,asyncResult[1]==nullptr?asyncResult[0]:asyncResult[1]);}else{napi_reject_deferred(asyncCallInfo->env,asyncCallInfo->deferred,asyncResult[0]);}}else{napi_valuecallback=nullptr;napi_get_reference_value(asyncCallInfo->env,asyncCallInfo->callbackRef,&callback);napi_call_function(asyncCallInfo->env,nullptr,callback,CALLBACK_ARGV_CNT,asyncResult,nullptr);napi_delete_reference(asyncCallInfo->env,asyncCallInfo->回调参考);}}staticnapi_valueCall_OpenSerial(napi_envenv,napi_callback_infoinfo){size_targc=0;napi_valueargs[DEFAULT_ARG_COUNT]={0};napi_get_cb_info(env,info,&argc,args,nullptr,nullptr);...napi_valueresourceName=nullptr;napi_create_string_utf8(env,"x_napi_tool",NAPI_AUTO_LENGTH,&resourceName);napi_create_async_work(env,nullptr,resourceName,[](napi_envenv,void*data){AsyncCallInfo*asyncCallInfo=(AsyncCallInfo*)data;OpenSerialValue*openValue=(OpenSerialValue*)asyncCallInfo->data;//openValue->out=SerialClient::GetInstance()->OpenSerial(openValue->dev);},[](napi_envenv,napi_statusstatus,void*data){AsyncCallInfo*asyncCallInfo=(AsyncCallInfo*)data;OpenSerialValue*openValue=(OpenSerialValue*)asyncCallInfo->数据;napi_valueasyncResult[CALLBACK_ARGV_CNT]={nullptr,nullptr};napi_create_int32(env,openValue->out,&asyncResult[0]);AsyncCallFinish(asyncCallInfo,openValue->out,asyncResult);napi_delete_async_work(env,asyncCallwork);开放价值;删除asyncCallInfo;},(void*)asyncCallInfo,&asyncCallInfo->work);napi_queue_async_work(env,asyncCallInfo->work);returnretValue;}方法二:使用NAPI框架生成工具生成工具链接(1)将serialhelper.d.ts和basic.d.ts复制到同一个目录下,创建out目录。(2)执行./napi_generator-linux-fserialhelper.d.ts-oout。(3)将生成的源代码文件复制到src/main/cpp。4.make文件:src/main/cpp/CMakeList.txt#CMake的最低版本.cmake_minimum_required(VERSION3.4.1)project(XComponent)set(NATIVERENDER_ROOT_PATH${CMAKE_CURRENT_SOURCE_DIR})include_directories(${NATIVERENDER_ROOT_library}(seraddary})SHAREDserial_helper.cpp)target_link_libraries(serialhelperPUBLIClibace_napi.z.solibc++.a)5.添加项目依赖项/package.json:"devDependencies":{"@types/libserialhelper.so":"file:./src/main/cpp/types/libserialhelper"}entry/package-lock.json:"dependencies":{"@types/libserialhelper.so":{"version":"file:src/main/cpp/types/libserialhelper",“开发”:真}}6。编译生成修改编译项entry/build-profile.json5:"buildOption":{"externalNativeOptions":{"path":"./src/main/cpp/CMakeLists.txt","arguments":"-v-DOHOS_STL=c++_shared","abiFilters":["armeabi-v7a",],"cppFlags":"",}}4.实现串口异步回调,添加串口IPC客户端libserialport_service_api.z.solibrary,并实现具体的异步回调函数复制libserialport_service_api.z.so到entry/libs/armeabi-a7v目录将库的头文件复制到entry/src/main/cpp/include目录下。继承SerialCallbackBase类实现串口数据异步回调SerialAsyncCallback。类SerialAsyncCallback:publicSerialCallbackBase{public:SerialAsyncCallback()=default;~SerialAsyncCallback();//通知回调事件voidOnCallBackEvent()override;//接收串口数据voidOnRecvData(constuint8_t*buffer,uint32_tlength)override;...};修改src/main/cpp/CMakeList.txt文件。#CMake.cmake_minimum_required(VERSION3.4.1)project(XComponent)set(NATIVERENDER_ROOT_PATH${CMAKE_CURRENT_SOURCE_DIR})include_directories(${NATIVERENDER_ROOT_PATH}${NATIVERENDER_ROOT_PATH}/include)link_directories(${NATIVERENDER_ROOT_PATH}/../.最低版本./../libs/${CMAKE_OHOS_ARCH_ABI})add_library(serialhelperSHAREDserial_helper.cppx_napi_tool.cppserial_async_callback.cpp)target_link_libraries(serialhelperPUBLIClibace_napi.z.solibc++.alibhilog_ndk.z.solibuv.solibserialport_service_api.z.so)在napi函数中调用api函数,使用NAPI框架生成工具生成OpenSerial代码,如下:structOpenSerial_value_struct{std::stringin0;int32_tout;};voidOpenSerial_execute(XNapiTool*pxt,void*data){OpenSerial_value_struct*vio=(OpenSerial_value_struct*)data;vio->out=get_serial_client()->OpenSerial(vio->in0);}voidOpenSerial_complete(XNapiTool*pxt,void*data){OpenSerial_value_struct*vio=(OpenSerial_value_struct*)数据;napi_value结果=nullptr;结果=NUM??BER_C_2_JS(pxt,Int32,vio->out);{napi_valueargs[XNapiTool::ARGV_CNT]={result,nullptr};pxt->FinishAsync(vio->out,args);}deletevio;}napi_valueOpenSerial_middle(napi_envenv,napi_callback_infoinfo){XNapiTool*pxt=std::make_unique(env,info).release();如果(pxt->IsFailed()){napi_valueerr=pxt->GetError();删除pxt;返回错误;}结构OpenSerial_value_struct*vio=newOpenSerial_value_struct();pxt->SwapJs2CUtf8(pxt->GetArgv(0),vio->in0);napi_valueresult=pxt->StartAsync(OpenSerial_execute,vio,OpenSerial_complete,pxt->GetArgc()==2?pxt->GetArgv(1):nullptr);如果(pxt->IsFailed()){结果=pxt->GetError();}returnresult;}模板注册staticnapi_valueinit(napi_envenv,napi_valueexports){std::shared_ptrpxt=std::make_shared(env,exports);//js函数与C++函数投影pxt->DefineFunction("setOptions",OHOS::SerialPort::SetOptions_middle);pxt->DefineFunction("openSerial",OHOS::SerialPort::OpenSerial_middle);pxt->DefineFunction("closeSerial",OHOS::SerialPort::CloseSerial_middle);pxt->DefineFunction("clearBuffer",OHOS::SerialPort::ClearBuffer_middle);pxt->DefineFunction("sendData",OHOS::SerialPort::SendData_middle);pxt->DefineFunction("recvData",OHOS::SerialPort::RecvData_middle);pxt->DefineFunction("传输",OHOS::SerialPort::Transmit_middle);pxt->DefineFunction("on",OHOS::SerialPort::on_middle);pxt->DefineFunction("off",OHOS::SerialPort::off_middle);pxt->DefineFunction("setGPIODirection",OHOS::SerialPort::setGPIODirection_middle);pxt->DefineFunction("setGPIOValue",OHOS::SerialPort::setGPIOValue_middle);pxt->DefineFunction("getGPIOValue",OHOS::SerialPort::getGPIOValue_middle);返回出口;}staticnapi_moduleg_serialHelper_Module={.nm_version=1,.nm_flags=0,.nm_filename=nullptr,.nm_register_func=init,.nm_modname="serialhelper",.nm_priv=((void*)0),.reserved={(void*)0},};extern"C"__attribute__((constructor))voidRegister_serialHelper_Module(void){napi_module_register(&g_serialHelper_Module);}eTS调试接口验证importserialHelperfrom"libserialhelper.so"...//打开串口this.tty/dev/ttyXRUSB0serialHelper.openSerial(this.tty).then(()=>{HiLog.i(TAG,"serialopenSerial"+this.tty+"success")this.status='open'}).catch((error)=>{HiLog.i(TAG,"openSerial"+this.tty+"failed:"+error)});...//设置为异步serialHelper.on("/dev/ttyXRUSB0",(data)=>{vardataString="";for(vari=0;i