OpenHarmony开发者论坛
标题:
Openharmony liteOS 串口通信
[打印本页]
作者:
liubo-688
时间:
2024-12-31 17:40
标题:
OpenHarmony liteOS 串口通信
[md]一、代码程序说明
由于 liteOS 资源较低,为了有更好的性能,并跨越框架层直接对系统层进行操作,故上层应用的代码应全部用 c++语言编写,整合为系统组件,在系统编译时编译成 hap 包即可。
**二、代码开发**
1. ```
| |
```
| -- |
| | ![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image003.gif) |
代码结构
cert :放 hap 签名证书文件 p7b include : 头文件
resources : 应用资源文件src : cpp 代码文件BUILD.gn : 编译构建config.json : 应用配置文件
2. ```
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image004.gif)config.json 示例
```
{
"app": {
"bundleName": "com.example.mytest",
"vendor": "ohos",
"version": {
"code": 1,
"name": "1.0"
},
"apiVersion": {
"compatible": 3,
"target": 4
}
},
"deviceConfig": {
"default": {
"keepAlive": false
}
},
"module": {
"package": "com.example.mytest",
"name": ".MainAbility",
"deviceType": [
"phone",
"tv",
"tablet",
"pc",
"car",
"smartWatch",
"sportsWatch",
"smartVision"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "mytest",
"moduleType": "entry"
},
"abilities": [
{
"name": "MainAbility",
"icon": "assets/mytest/resources/drawable/icon.png",
"label": "串口 Demo",
"launchType": "standard",
"type": "page",
"visible": true,
"srcLanguage":"c++"
}
![文本框: ]
}
}
](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image005.gif)
## 3. BUILD.gn 构建配置示例
import("//build/lite/config/hap\_pack.gni") shared\_library("mytest") { #生成 so 库文件
sources = [ "src/main\_ability.cpp", "src/main\_ability\_slice.cpp",
]
include\_dirs = [#头文件路径"include",
"\${aafwk\_lite\_path}/interfaces/kits/ability\_lite", "\${appexecfwk\_lite\_path}/interfaces/kits/bundle\_lite", "\${aafwk\_lite\_path}/interfaces/kits/want\_lite", "//base/startup/syspara\_lite/interfaces/kits",
]
deps = [#依赖关系"\${aafwk\_lite\_path}/frameworks/ability\_lite:aafwk\_abilitykit\_lite", "\${appexecfwk\_lite\_path}/frameworks/bundle\_lite:bundle", "//foundation/distributedschedule/samgr\_lite/samgr:samgr", "//foundation/graphic/surface",
"//foundation/graphic/ui:lite\_ui", "//foundation/graphic/utils:lite\_graphic\_utils", "//utils/native/lite/kv\_store:kv\_store",
]
#clang 编译项
ldflags = [ "-shared" ] ldflags += [ "-lstdc++" ] ldflags += [ "-lpthread" ]
ldflags += [ "-L\$ohos\_root\_path/sysroot/usr/lib" ]
ldflags += [ "-Wl,-rpath-link=\$ohos\_root\_path/sysroot/usr/lib" ] ldflags += [
"-lui",
"-lsurface",
"-lability",
]
defines = [ "ENABLE\_WINDOW=1", "ABILITY\_WINDOW\_SUPPORT",
]
}
#编译为 hap 包
hap\_pack("mytest\_hap") { deps = [ ":mytest" ] mode = "hap"
json\_path = "config.json"
ability\_so\_path = "\$root\_out\_dir/libmytest.so" force = "true"
cert\_profile = "cert/mytest.p7b" resources\_path = "resources" hap\_name = "mytest"
privatekey = "HOS Application Provision Release"
}
4. ```
src/main\_ability.cpp 代码示例
```
| |
| - |
| |
namespace OHOS { REGISTER_AA(MainAbility)
void MainAbility::OnStart(const Want& want)
{
SetMainRoute("MainAbilitySlice"); Ability::OnStart(want);
}
void MainAbility::OnInactive()
{
Ability::OnInactive();
}
void MainAbility::OnActive(const Want& want)
{
Ability::OnActive(want);
}
void MainAbility::OnBackground()
{
Ability::OnBackground();
}
void MainAbility::OnStop()
{
Ability::OnStop();
}
} // namespace OHOS
](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image006.gif) |
5. ```
src/main\_ability\_slice.cpp 示例
```
| |
| - |
| |
#include <common/screen.h>
](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image007.gif) |
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image008.gif)#include <components/ui\_label.h>
#include <components/ui\_label\_button.h>
#include "main\_ability\_slice.h"
#include "ability\_loader.h"
#include "event\_listener.h"
//#include "btn\_onclick\_listener.h"
#include <components/ui\_view.h>
#include <events/click\_event.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#include <malloc.h>
#include <time.h>
#include <thread>
namespace OHOS {
REGISTER\_AS(MainAbilitySlice)
//全局配置 uart 设备参数
#define BUFF\_LEN 256
#define DEVICE "/dev/ttyS0" //串口号,如:ttyS1,ttyS3,ttyS4 ... #define BAUDRATE "9600" //波特率
#define COMMAND "43 61 6C 63 54 0D 0A" //向串口发的指令,该指令为 ASCII 指令,如要发送 hex byte 指令,则需要进行转换处理
class BtnOnclickListener : public UIView::OnClickListener {
protected:
/\*
//设置操作的 uart 设备
void setDevice(const char \*device\_name){
deviceName = device\_name;
}\*/
//返回 2 进制 bundrate
speed\_t getBaudRate(int baudrate){
switch(baudrate) {
case 0: return B0;
case 50: return B50;
case 75: return B75;
case 110: return B110;
case 134: return B134;
case 150: return B150;
case 200: return B200;
case 300: return B300;
case 600: return B600;
case 1200: return B1200;
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image010.gif)case 1800: return B1800;
case 2400: return B2400;
case 4800: return B4800;
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
case 460800: return B460800;
case 500000: return B500000;
case 576000: return B576000;
case 921600: return B921600;
case 1000000: return B1000000;
case 1152000: return B1152000;
case 1500000: return B1500000;
case 2000000: return B2000000;
case 2500000: return B2500000;
case 3000000: return B3000000;
case 3500000: return B3500000;
case 4000000: return B4000000;
default: return B9600;
}
}
//初始化串口
int uartInit(const char \*baudRate\_d){
speed\_t baudRate\_t = getBaudRate(atoi(baudRate\_d));
int fd;
fd = open(DEVICE, O\_RDWR | O\_NOCTTY);
if(fd == -1) {
printf("\\n Error! in Opening device : %s " , DEVICE);
return -1;
}
struct termios SerialPortSettings;
if (tcgetattr(fd, &SerialPortSettings) != 0)
{
printf("\\n tcgetattr ERROR !");
return -1;
}else{
printf("\\n tcgetattr Successfully !");
}
if(cfsetispeed(&SerialPortSettings, baudRate\_t) != 0){
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image011.gif)printf("\\n cfsetispeed ERROR !");
return -1;
}else{
printf("\\n cfsetispeed Successfully !");
}
if (cfsetospeed(&SerialPortSettings, baudRate\_t) != 0)
{
printf("\\n cfsetospeed ERROR !");
return -1;
}else{
printf("\\n cfsetospeed Successfully !");
}
SerialPortSettings.c\_cflag &= \~PARENB;
SerialPortSettings.c\_cflag &= \~CSTOPB;
//SerialPortSettings.c\_cflag &= \~CSIZE;
SerialPortSettings.c\_cflag |= CS8;
SerialPortSettings.c\_cflag &= \~CRTSCTS;
SerialPortSettings.c\_cflag |= CREAD | CLOCAL;
SerialPortSettings.c\_iflag &= \~(IXON | IXOFF | IXANY);
SerialPortSettings.c\_lflag &= \~(ICANON | ECHO | ECHOE | ISIG | ECHONL);
SerialPortSettings.c\_iflag &= \~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl
SerialPortSettings.c\_iflag &= \~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received
bytes
SerialPortSettings.c\_oflag &= \~OPOST;
SerialPortSettings.c\_oflag &= \~ONLCR; // Prevent conversion of newline to carriage return/line feed
SerialPortSettings.c\_cc[VMIN] = 1;
SerialPortSettings.c\_cc[VTIME] = 3;
if(tcsetattr(fd, TCSANOW, &SerialPortSettings) != 0) {
printf("\\n ERROR ! in Setting attributes");
return -1;
}else{
printf("\\n BaudRate = %d \\n StopBits = 1 \\n Parity = none",baudRate\_d);
}
if (tcflush(fd, TCIFLUSH) != 0)
{
printf("\\n tcflush ERROR!");
return -1;
}else{
printf("\\n tcflush Successfully!");
close(fd);
}
return 0;
}
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image012.gif)//hex 转为 byte 指令
int hexstringtobyte(char \*in, unsigned char \*out) {
int len = (int)strlen(in);
char \*str = (char \*)malloc(len);
memset(str, 0, len);
memcpy(str, in, len);
for (int i = 0; i < len; i+=2) {
//小写转大写
if(str
>= 'a' && str
<= 'f') str
= str
& \~0x20;
if(str[i+1] >= 'a' && str
<= 'f') str[i+1] = str[i+1] & \~0x20;
//处理第前 4 位
if(str
>= 'A' && str
<= 'F')
out[i/2] = (str
-'A'+10)<<4;
else
out[i/2] = (str
& \~0x30)<<4;
//处理后 4 位, 并组合起来
if(str[i+1] >= 'A' && str[i+1] <= 'F')
out[i/2] |= (str[i+1]-'A'+10);
else
out[i/2] |= (str[i+1] & \~0x30);
}
free(str);
return 0;
}
//发指令后接收返回数据,如:返回测温模块所测的温度值
char\* sendCmdReceive(const char \*cmd){
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image014.gif)![文本框: char *_cmd;](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image015.gif)
strcpy(\_cmd,cmd);
unsigned char hexCmd[16] = {0};
hexstringtobyte(\_cmd,hexCmd);
int fd = open(DEVICE, O\_RDWR | O\_NOCTTY | O\_NONBLOCK);
if(fd == -1){
printf("\\n Error! in Opening device ");
return NULL;
}else{
printf("\\n device Opened Successfully , device:%s ", DEVICE);
write(fd,hexCmd,sizeof(hexCmd)/sizeof(hexCmd[0]));
printf("\\n device write Successfully ");
int bytes\_read = 0;
unsigned char read\_buffer[16] = {0};
usleep(1000 \* 100);
bytes\_read = read(fd, read\_buffer, sizeof(read\_buffer));
printf("\\n\\n Open cmd by Bytes Rxed %d\\n", bytes\_read);
char \*tp = (char \*)malloc(5);
sprintf(tp,"%.1f",(float)(read\_buffer[2] + (read\_buffer[3] / 100.0)) + 0.05);//四舍五入
//printf("temp:%s",temp);
/\*
if(bytes\_read > 0) {
for(int i = 0; i < bytes\_read; i++) {
printf("%02X ", read\_buffer
);
}
}\*/
close(fd);
return tp;
}
}
//监听返回数据
static void\* readDataHandle(UILabel \*lb){
int fd = open(DEVICE, O\_RDONLY | O\_NOCTTY );
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image016.gif)if(fd == -1){
printf("\\n Error! in Opening device ");
}else{
int bytes\_read = 0;
char read\_buffer[BUFF\_LEN] = {0};
while (1)
{
bytes\_read = read(fd, read\_buffer, sizeof(read\_buffer));
printf("\\n\\n Open cmd by Bytes len: %d , read\_buffer : %s\\n\\n", bytes\_read,read\_buffer);
if (bytes\_read > 0) {
lb->SetText(read\_buffer);
memset(read\_buffer,0,BUFF\_LEN);
}
}
}
close(fd);
}
//只发指令
void sendCmd(const char \*cmd) {
int fd = open(DEVICE, O\_RDWR | O\_NOCTTY | O\_NONBLOCK);
if(fd == -1){
printf("\\n Error! in Opening device ");
}else{
printf("\\n device Opened Successfully , device:%s, cmd=%s ", DEVICE,cmd);
write(fd,cmd,strlen(cmd));
}
close(fd);
}
//16 进制转 10 进制
int hextod(char \*str)
{
char \*s = str + 2;//跳过 0X
int num = strlen(s) - 1;//获取当前的长度后减 1
int sum = 0;
int dxh = 0;
for(int i = num; i >= 0; i--)
{
switch(s[num - i])//从高位获取它的值
{
case '0': sum = 0;break;
case '1': sum = 1;break;
case '2': sum = 2;break;
case '3': sum = 3;break;
case '4': sum = 4;break;
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image017.gif)case '5': sum = 5;break;
case '6': sum = 6;break;
case '7': sum = 7;break;
case '8': sum = 8;break;
case '9': sum = 9;break;
case 'a': sum = 10;break;
case 'b': sum = 11;break;
case 'c': sum = 12;break;
case 'd': sum = 13;break;
case 'e': sum = 14;break;
case 'f': sum = 15;break;
case 'A': sum = 10;break;
case 'B': sum = 11;break;
case 'C': sum = 12;break;
case 'D': sum = 13;break;
case 'E': sum = 14;break;
case 'F': sum = 15;break;
}
for(int j = 1; j < i+1; j++)//根据位数转化为 10 进制
{
sum \*= 16;//高一位等于低一位的 16
}
dxh += sum;//每一位的十进制相加
}
return dxh;//返回最终结果
}
public:
BtnOnclickListener(UILabel \*lb){
uartInit(BAUDRATE);
//子线程监听接收数据
std::thread t(readDataHandle,lb);
t.detach();
}
bool OnClick(UIView &view,const ClickEvent& event) override{
/\*
time\_t t = time(0);
char tmp[32]= {0};
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&t));
\*/
sendCmd(COMMAND);
return true;
}
};
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image018.gif)MainAbilitySlice::\~MainAbilitySlice()
{
ReleaseView();
}
void MainAbilitySlice::ReleaseView()
{
if (headImageView\_)
{
delete headImageView\_;
headImageView\_ = nullptr;
}
if (headView\_)
{
delete headView\_;
headView\_ = nullptr;
}
if (headLablelFont\_)
{
delete headLablelFont\_;
headLablelFont\_ = nullptr;
}
if (inputView\_)
{
delete inputView\_;
inputView\_ = nullptr;
}
if (lableDevTag\_)
{
delete lableDevTag\_;
lableDevTag\_ = nullptr;
}
if (lableBundTag\_)
{
delete lableBundTag\_;
lableBundTag\_ = nullptr;
}
if (lableBundRate\_)
{
delete lableBundRate\_;
lableBundRate\_ = nullptr;
}
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image019.gif)if (lableCmdTag\_)
{
delete lableCmdTag\_;
lableCmdTag\_ = nullptr;
}
if (lableCmd\_)
{
delete lableCmd\_;
lableCmd\_ = nullptr;
}
if (lableRecTag\_)
{
delete lableRecTag\_;
lableRecTag\_ = nullptr;
}
if (lableRecData\_)
{
delete lableRecData\_;
lableRecData\_ = nullptr;
}
if (enterView\_)
{
delete enterView\_;
enterView\_ = nullptr;
}
if (lableTail\_) {
delete lableTail\_;
lableTail\_ = nullptr;
}
if (btnImageView\_)
{
delete btnImageView\_;
btnImageView\_ = nullptr;
}
}
void MainAbilitySlice::SetHead()
{
UIViewGroup \*headView\_ = new UIViewGroup();
rootview\_->Add(headView\_);
headView\_->SetPosition(0, 0, Screen::GetInstance().GetWidth(), 70);
headView\_->SetStyle(STYLE\_BACKGROUND\_COLOR, Color::Gray().full);
headView\_->SetStyle(STYLE\_BACKGROUND\_OPA, 255);
headView\_->SetTouchable(true);
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image020.gif)auto onClick = [this](UIView& view, const Event& event) -> bool {
Terminate();
return true;
};
headView\_->SetOnClickListener(new EventListener(onClick, nullptr));
headImageView\_ = new UIImageView();
headView\_->Add(headImageView\_);
headImageView\_->SetPosition(39, 16, 30, 30);
headImageView\_->SetSrc(DE\_IMAGE\_BACK);
headLablelFont\_ = new UILabel();
headLablelFont\_->SetPosition(100, 15, 180, 60);
headLablelFont\_->SetText("back");
headLablelFont\_->SetFont(FOND\_PATH, FOND\_SIZE);
headLablelFont\_->SetStyle(STYLE\_TEXT\_COLOR, Color::ColorTo32(Color::White()));
headView\_->Add(headLablelFont\_);
}
void MainAbilitySlice::setInput(){
inputView\_ = new UIViewGroup();
inputView\_->SetPosition(36, 108, 700, 500);
inputView\_->SetStyle(STYLE\_BACKGROUND\_COLOR, Color::Gray().full);
inputView\_->SetStyle(STYLE\_BACKGROUND\_OPA, 0);
//inputView\_->SetStyle(STYLE\_BORDER\_RADIUS, 16);
rootview\_->Add(inputView\_);
lableDevTag\_ = new UILabel();
lableDevTag\_->SetPosition(36, 10,100,50);
lableDevTag\_->SetStyle(STYLE\_TEXT\_COLOR, Color::Black().full);
lableDevTag\_->SetFont(FOND\_PATH, FOND\_SIZE); lableDevTag\_->SetText("设备");
inputView\_->Add(lableDevTag\_);
lableTail\_ = new UILabel();
lableTail\_->SetPosition(120, 2, 220, 70);
lableTail\_->SetStyle(STYLE\_BACKGROUND\_COLOR, Color::Gray().full);
lableTail\_->SetStyle(STYLE\_BACKGROUND\_OPA, 255);
lableTail\_->SetStyle(STYLE\_BORDER\_RADIUS, 16);
lableTail\_->SetStyle(STYLE\_PADDING\_LEFT, 5);
lableTail\_->SetAlign(TEXT\_ALIGNMENT\_LEFT,TEXT\_ALIGNMENT\_CENTER);
lableTail\_->SetFont(FOND\_PATH, FOND\_SIZE);
lableTail\_->SetText(DEVICE);
inputView\_->Add(lableTail\_);
lableBundTag\_ = new UILabel();
lableBundTag\_->SetPosition(36, 110,100,50);
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image021.gif)lableBundTag\_->SetStyle(STYLE\_TEXT\_COLOR, Color::Black().full);
lableBundTag\_->SetFont(FOND\_PATH, FOND\_SIZE); lableBundTag\_->SetText("波特");
inputView\_->Add(lableBundTag\_);
lableBundRate\_ = new UILabel();
lableBundRate\_->SetPosition(120, 100, 220, 70);
lableBundRate\_->SetStyle(STYLE\_BACKGROUND\_COLOR, Color::Gray().full);
lableBundRate\_->SetStyle(STYLE\_BACKGROUND\_OPA, 255);
lableBundRate\_->SetStyle(STYLE\_BORDER\_RADIUS, 16);
lableBundRate\_->SetStyle(STYLE\_PADDING\_LEFT, 5);
lableBundRate\_->SetAlign(TEXT\_ALIGNMENT\_LEFT,TEXT\_ALIGNMENT\_CENTER);
lableBundRate\_->SetFont(FOND\_PATH, FOND\_SIZE);
lableBundRate\_->SetText(BAUDRATE);
inputView\_->Add(lableBundRate\_);
lableCmdTag\_ = new UILabel();
lableCmdTag\_->SetPosition(36, 210,100,50);
lableCmdTag\_->SetStyle(STYLE\_TEXT\_COLOR, Color::Black().full);
lableCmdTag\_->SetFont(FOND\_PATH, FOND\_SIZE); lableCmdTag\_->SetText("指令");
inputView\_->Add(lableCmdTag\_);
lableCmd\_ = new UILabel();
lableCmd\_->SetPosition(120, 200, 400, 70);
lableCmd\_->SetStyle(STYLE\_BACKGROUND\_COLOR, Color::Gray().full);
lableCmd\_->SetStyle(STYLE\_BACKGROUND\_OPA, 255);
lableCmd\_->SetStyle(STYLE\_BORDER\_RADIUS, 16);
lableCmd\_->SetStyle(STYLE\_PADDING\_LEFT, 5);
lableCmd\_->SetAlign(TEXT\_ALIGNMENT\_LEFT,TEXT\_ALIGNMENT\_CENTER);
lableCmd\_->SetFont(FOND\_PATH, FOND\_SIZE);
lableCmd\_->SetText(COMMAND);
inputView\_->Add(lableCmd\_);
lableRecTag\_ = new UILabel();
lableRecTag\_->SetPosition(36, 310,100,50);
lableRecTag\_->SetStyle(STYLE\_TEXT\_COLOR, Color::Black().full);
lableRecTag\_->SetFont(FOND\_PATH, FOND\_SIZE); lableRecTag\_->SetText("接收");
inputView\_->Add(lableRecTag\_);
lableRecData\_ = new UILabel();
lableRecData\_->SetPosition(120, 300, 400, 70);
lableRecData\_->SetStyle(STYLE\_BACKGROUND\_COLOR, Color::Gray().full);
lableRecData\_->SetStyle(STYLE\_BACKGROUND\_OPA, 255);
lableRecData\_->SetStyle(STYLE\_BORDER\_RADIUS, 16);
lableRecData\_->SetStyle(STYLE\_PADDING\_LEFT, 5);
lableRecData\_->SetAlign(TEXT\_ALIGNMENT\_LEFT,TEXT\_ALIGNMENT\_CENTER);
lableRecData\_->SetFont(FOND\_PATH, FOND\_SIZE);
inputView\_->Add(lableRecData\_);
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image022.gif)//光标输入状态
/\*
UILabel \*lablelCursorText\_ = new UILabel();
lablelCursorText\_->SetPosition(24, 3, 2, 70);
lablelCursorText\_->SetStyle(STYLE\_BACKGROUND\_COLOR, Color::ColorTo32(Color::GetColorFromRGB(0x0D, 0x9F, 0xF8)));
lablelCursorText\_->SetStyle(STYLE\_BACKGROUND\_OPA, 255);
inputView\_->Add(lablelCursorText\_);
\*/
BtnOnclickListener \*clickListener = new BtnOnclickListener(lableRecData\_);
enterView\_ = new UIViewGroup();
enterView\_->SetPosition(120, 400, 150, 70);
enterView\_->SetStyle(STYLE\_BACKGROUND\_COLOR, Color::ColorTo32(Color::GetColorFromRGB(0x0D, 0x9F, 0xF8)));
enterView\_->SetStyle(STYLE\_BACKGROUND\_OPA, 255);
enterView\_->SetStyle(STYLE\_BORDER\_RADIUS, 16);
enterView\_->SetTouchable(true);
enterView\_->SetOnClickListener(clickListener);
inputView\_->Add(enterView\_);
btnImageView\_ = new UIImageView();
btnImageView\_->SetPosition(10, 20);
btnImageView\_->SetSrc(DE\_IMAGE\_ENTER);
enterView\_->Add(btnImageView\_);
btnImageView\_->SetTouchable(true);
btnImageView\_->SetOnClickListener(clickListener);
}
void MainAbilitySlice::OnStart(const Want& want)
{
AbilitySlice::OnStart(want);
rootview\_ = RootView::GetWindowRootView();
rootview\_->SetPosition(0, 0);
rootview\_->Resize(Screen::GetInstance().GetWidth(), Screen::GetInstance().GetHeight());
rootview\_->SetStyle(STYLE\_BACKGROUND\_OPA, UN\_OPACITY);
rootview\_->SetStyle(STYLE\_BACKGROUND\_COLOR, Color::White().full);//Color::Blue().full
SetHead();
setInput();
SetUIContent(rootview\_);
rootview\_->Invalidate();
}
void MainAbilitySlice::OnInactive()
{
AbilitySlice::OnInactive();
}
![文本框: void MainAbilitySlice::OnActive(const Want& want)
{
AbilitySlice::OnActive(want);
//子线程监听接收数据
//std::thread t(readUartDataThreadHandle,lableRecData_);
//t.detach();
}
void MainAbilitySlice::OnBackground()
{
AbilitySlice::OnBackground();
}
void MainAbilitySlice::OnStop()
{
AbilitySlice::OnStop();
}
} // namespace OHOS
](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image023.gif)
## 6. include/event\_listener.h 示例
| |
| - |
| |
#include <functional> #include <utility>
#include "components/ui_view.h"
namespace OHOS {
using OnEventFunc = std::function<bool(UIView &view, const Event &event)>;
class EventListener : public UIView::OnClickListener, public UIView::OnLongPressListener { public:
EventListener() = delete;
~EventListener() override = default;
EventListener(OnEventFunc onClick, OnEventFunc onLongPress)
{
onClick_ = std::move(onClick); onLongPress_ = std::move(onLongPress);
}
bool OnClick(UIView& view, const ClickEvent &event) override
{
if (!onClick_) { return false;
}
UIView *currentView = &view;
](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image024.gif) |
![文本框: if (currentView == nullptr) { return false;
}
return onClick_(*currentView, event);
}
bool OnLongPress(UIView& view, const LongPressEvent &event) override
{
if (!onLongPress_) { return false;
}
UIView *currentView = &view; if (currentView == nullptr) {
return false;
}
return onLongPress_(*currentView, event);
}
private:
OnEventFunc onClick_ {}; OnEventFunc onLongPress_ {};
};
} // namespace OHOS #endif
](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image025.gif)
7. ```
include/ui\_config.h 示例
```
| |
| - |
| |
![文本框: static constexpr int16_t TITLE_LABLE_OPACITY = 255; // translucent static constexpr int16_t GROUP_VIEW_RADIUS = 20; // view radius
#ifndef TMP_BUF_SIZE #define TMP_BUF_SIZE 128 #endif
#define DE_IMAGE_ENTER "/storage/app/run/com.example.mytest/mytest/assets/mytest/resources/drawable/enter.png" #define DE_IMAGE_BACK "/storage/app/run/com.example.mytest/mytest/assets/mytest/resources/drawable/back.png" #define FOND_PATH "SourceHanSansSC-Regular.otf"
#define FOND_SIZE 40
#ifndef LAUNCHER_SUCCESS #define LAUNCHER_SUCCESS 0
#endif
#ifndef LAUNCHER_PARAMERROR #define LAUNCHER_PARAMERROR (-1)
#endif
#ifndef WEEK_DAY_MAX #define WEEK_DAY_MAX 7 #endif
} // namespace OHOS
#endif
](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image027.gif)
其它头文件不做示例,可从 cpp 中推荐创建
**三、集成说明**
8. ```
将上述应用代码放置于 applications/sample/camera 路径下
```
9. ```
修改 build/lite/components/applications.json,在其中添加组件配置
```
| |
| - |
| |
10. 若要修要 app 应用的 bundleName 与 package 名,请修改
applications/sample/camera/mytest/config.json (修改 bundleName 与 package 名需要替换 cert 下
p7b 签 名文件)
![](file:///C:/Users/zhang/AppData/Local/Temp/msohtmlclip1/01/clip_image031.jpg)
11. 执行编译命 令 : hb build
若编译失败,试着执行重新编译
rm -rf out hb build -f
12. ```
编译成功后在 out 目录下查找 mytest.hap ,如果找到则说明集成成功,最后重烧开发板,重新启动即可看到“串口 DEMO”应用已被安装
```
**四、串口配置**
用 c++语言编辑器打开上述 src/main\_ability\_slice.cpp,将开头的常量替换为开发板实际参数即可
![image.png](
https://forums-obs.openharmony.c ... fefbz572nncknhy.png
"image.png")
串口初始化后,自动在子线程中进行来数据监听,当收到数据后,会通过 UIView 的 Label 控件展示在应用界面上,如下图:
|
![image.png](
https://forums-obs.openharmony.c ... l9sxc19122n2m5f.png
"image.png")
| |
| - |
| |
[/md]
欢迎光临 OpenHarmony开发者论坛 (https://forums.openharmony.cn/)
Powered by Discuz! X3.5