如何写一个简单轻松的OpenHarmony蓝牙应用

654 篇文章 4 订阅
648 篇文章 6 订阅

此文件就是介绍 OpenHarmony 中的蓝牙接口和如何自己开发一个简单的蓝牙应用程序。

OpenHarmony 蓝牙接口简介

接口名称参数返回值作用
enableBluetooth()boolean开启蓝牙
disableBluetooth()boolean关闭蓝牙
getState()BluetoothState:enum获取蓝牙状态
setLocalName(name: string)boolean设置蓝牙名称
getLocalName()string获取蓝牙名称
setBluetoothScanMode(mode: ScanMode, duration: number)boolean设置蓝牙扫描模式
startBluetoothDiscovery()boolean发现蓝牙
pairDevice(deviceId: string)boolean配对设备
on.pinRequired(type: "pinRequired", callback: Callback<PinRequiredParam>)void侦听配对请求事件
disableBluetooth()boolean
  • getState
enum BluetoothState {
   /** Indicates the local Bluetooth is off */
   STATE_OFF = 0,
   /** Indicates the local Bluetooth is turning on */
   STATE_TURNING_ON = 1,
   /** Indicates the local Bluetooth is on, and ready for use */
   STATE_ON = 2,
   /** Indicates the local Bluetooth is turning off */
   STATE_TURNING_OFF = 3,
   /** Indicates the local Bluetooth is turning LE mode on */
   STATE_BLE_TURNING_ON = 4,
   /** Indicates the local Bluetooth is in LE only mode */
   STATE_BLE_ON = 5,
   /** Indicates the local Bluetooth is turning off LE only mode */
   STATE_BLE_TURNING_OFF = 6
  • setBluetoothScanMode
enum ScanMode {
   /** Indicates the scan mode is none */
   SCAN_MODE_NONE = 0,
   /** Indicates the scan mode is connectable */
   SCAN_MODE_CONNECTABLE = 1,
   /** Indicates the scan mode is general discoverable */
   SCAN_MODE_GENERAL_DISCOVERABLE = 2,
   /** Indicates the scan mode is limited discoverable */
   SCAN_MODE_LIMITED_DISCOVERABLE = 3,
   /** Indicates the scan mode is connectable and general discoverable */
   SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE = 4,
   /** Indicates the scan mode is connectable and limited discoverable */
   SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE = 5
}

OpenHarmony 典蓝牙配对流程

开启蓝牙

//开蓝牙
ListItem() {
    TitleComponent({ 
        title: "enableBluetooth",                                                            //显示功能的名称
        bgColor: this.currentClick === 0 ? $r('app.color.font_color_007DFF') :  $r('app.color.white_bg_color')
    });                                                                                     //点击后颜色变化
}
.padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })   
    .onClick(() => {                                                                        //点击事件                
    if (this.btEnable) {                                                                    //判断蓝牙是否已经打开
        this.message = '蓝牙已经使能';                                                  
        return;
    }
    let ret = BluetoothModel.enableBluetooth();                                             //打开蓝牙
    this.btEnable = ret;                                                               //如果启用了蓝牙,则返回true,否则返回false
    AppStorage.SetOrCreate('bluetoothIsOn', this.btEnable);                                 //存储蓝牙打开的结果,方便调用
    AppStorage.SetOrCreate('currentClick', this.currentClick);
    this.message = "蓝牙使能执行结果:" + ret;                                                   //输出结果
})

设置发现模式

ListItem() {
    TitleComponent({
        title: "setBluetoothScanMode",                                                       //显示功能的名称
        bgColor: this.currentClick === 6 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
    });                                                                                      //点击后颜色变化
}
.padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
    .onClick(() => {                                                                         //点击事件   
    this.currentClick = 6;
    if (this.btEnable) {                                                                     //判断蓝牙是否已经打开 
        retObj = {mod: 0, duration: -1}                                  //mode表示要设置的蓝牙扫描模式{@link ScanMode}。                                                                                  //*@param duration指示主机可发现的持续时间(秒)。
        setLocalNameRet = BluetoothModel.setBluetoothScanMode(mode, dur);
        if (setLocalNameRet) {
            AppStorage.SetOrCreate('setScanModeRet', setLocalNameRet);
            retObj.mod = mode;
            retObj.duration = dur; 
        } else {                                                          //如果设置了蓝牙扫描模式,返回true,否则返回false。
            console.info("BluetoothModel.setBluetoothScanMode failed!")
            onsole.info("BluetoothModel.setBluetoothScanMode success!", retObj)             
            this.message = "setBluetoothScanMode执行" + this.setLocalNameRet ? '成功' : '失败';
        } 
    }else {
        this.message = "蓝牙未使能";
    }
})

注册 pinRequest

ListItem() {
    TitleComponent({
        title: "btPinRequired"                                                                //显示功能的名称
        bgColor: this.currentClick === 18 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
    });                                                                                       //点击后颜色变化
}
.padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
    .onClick(() => {                                                                            //点击事件
    if (!this.btEnable) {                                                                   //判断蓝牙是否已经打开 
        this.message = "蓝牙未使能"; 
        return;
    }
    if (this.isPinRequiredClick) {                                                //判断监听是否开启,即为一个“开关”,并存储数据
        bluetooth.off('pinRequired', () => {                                   
        })
        this.message = 'on:pinRequired监听已关闭,再次点击将开启监听';
        this.isPinRequiredClick = false;
        AppStorage.SetOrCreate('on_pinRequired', this.btPinRequired);
        return;
    }
    this.isPinRequiredClick = true;
    AppStorage.SetOrCreate('on_pinRequired', this.btPinRequired);                //type要侦听的配对请求事件的类型为:pinRequired
    this.pinMessage = 'PIN: ';
    bluetooth.on('pinRequired', (data) => {                                           //callback回调用于侦听配对请求事件。
        this.pinMessage = 'PIN: ';
        this.pinMessage += data.pinCode;
    })
    this.message = 'on:pinRequired监听已启动,再次点击将关闭监听。';
})

配对设备

ListItem() {
    TitleComponent({ 
        title: "pairDevice",                                                                   //显示功能的名称  
        bgColor: this.currentClick === 10 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
    });                                                                                        //点击后颜色变化
} 
.padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
    .onClick(() => {                                                                         //点击事件
    if (!this.btEnable) {                                                                   //判断蓝牙是否已经打开 
        this.message = '蓝牙未使能';
        return;
    }
    if (this.deviceId == '') {                                                      //deviceId为要配对的远程设备的地址
        this.message = "请输入目标设备的MAC";                                          //若为空,请输入目标MAC
        return;
    } else {
        this.pairDevice(this.deviceId);                                          //如果配对过程已启动,则返回true,否则返回false
    }
})

OpenHarmony 经典蓝牙设备发现流程

  1. 开启蓝牙(同上)
  2. 设置发现模式(同上)
  3. 开始蓝牙发现
ListItem() {
    TitleComponent({
        title: "startBluetoothDiscovery",                                                              //显示功能的名称  
        bgColor: this.currentClick === 8 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
    });                                                                                                //点击后颜色变化
}
.padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
    .onClick(() => {//点击事件
    LogUtil.info(this.TAG_PAGE + 'startBluetoothDiscovery 111');
    if (!this.btEnable) {                                                                   //判断蓝牙是否已经打开 
        this.message = '蓝牙未使能';
        return;
    }
    Router.push({ uri: PAGE_URI_DEVICE_FOUND_MODE });                                      //搜索发现蓝牙的分界面
})

搜索发现蓝牙的分界面

Scroll() {
    Column() {
        if (this.isOn) {
            PairedDeviceComponent({                                                      //显示已配对的设备
                controller: this.deviceController
            })
            AvailableDeviceComponent({                                                   //显示可被配对的设备                      
                controller: this.deviceController 
            })
        }
    }
    .width(ConfigData.WH_100_100)
}


//PairedDeviceComponent

build() {
    Column() {
        if (this.pairedDevices && this.pairedDevices.length > 0) {
            // paired devices title
            Row() {
                Text($r('app.string.bluetooth_paired_devices'))                          //已配对的设备
                    .fontSize($r('app.float.font_14'))
                    .fontColor($r('app.color.font_color_182431'))
            }
            .width(ConfigData.WH_100_100)
                .padding({
                left: $r('app.float.distance_24'),
                top: $r('app.float.distance_19_5'),
                bottom: $r('app.float.distance_9_5')
            })
            List() {
                // paired devices list
                ForEach(this.pairedDevices, (item: BluetoothDevice, index: number) => {
                    ListItem() {
                        Row() {
                            PairedItem({
                                name: item.deviceName,
                                type: item.deviceType,
                                state: item.connectionState.toString(),
                                mac: item.deviceId
                            })
                        }
                        .width(ConfigData.WH_100_100)
                            .borderRadius($r("app.float.radius_24"))
                            .padding($r('app.float.distance_4'))
                            .backgroundColor($r("app.color.white_bg_color"))
                            .onClick(() => {
                            this.itemClicked(item);
                        })
                    }
                }, item => JSON.stringify(item));
            }
            .height(200)
                .divider({
                strokeWidth: 1,
                color: $r('app.color.color_E3E3E3_grey'),
                startMargin: $r('app.float.wh_value_52'),
                endMargin: $r('app.float.wh_value_12')
            })
                .backgroundColor($r("app.color.white_bg_color"))
                .borderRadius($r("app.float.radius_24"))
        }
    }
}

//AvailableDeviceComponent

build() {
    Column() {
        Row() {
            // available devices title
            Text($r('app.string.bluetooth_available_devices'))                            //可用设备
                .fontSize($r('app.float.font_14'))
                .fontColor($r('app.color.font_color_182431'))
                .width(ConfigData.WH_100_100)
                .padding({
                left: $r('app.float.distance_24'),
                top: $r('app.float.distance_19_5'),
                bottom: $r('app.float.distance_9_5')
            })
            Blank()

            // bluetooth discovering
            if (this.isDeviceDiscovering) {
                DiscoveringAnimatorComponent()
            }
        }
        .width(ConfigData.WH_100_100)

        if (this.availableDevices && this.availableDevices.length >= 1) {
            Scroll() {
                List() {
                    // paired devices list
                    ForEach(this.availableDevices, (item: BluetoothDevice) => {
                        ListItem() {
                            Row() {
                                AvailableItem({
                                    name: item.deviceName,
                                    type: item.deviceType,
                                    state: item.connectionState.toString(),
                                    mac: item.deviceId
                                })
                            }
                            .width(ConfigData.WH_100_100)
                                .borderRadius($r("app.float.radius_24"))
                                .padding($r('app.float.distance_4'))
                                .backgroundColor($r("app.color.white_bg_color"))
                                .onClick(() => {
                                LogUtil.info(this.TAG_PAGE + 'item on click : ' + JSON.stringify(item));
                                AppStorage.SetOrCreate('pairedMac', item.deviceId);
                                //                AppStorage.SetOrCreate('pairedName', item.deviceName);
                                this.pairDevice(item)
                            })
                        }
                    }, item => JSON.stringify(item));
                }
                .backgroundColor($r("app.color.white_bg_color"))
                    .borderRadius($r("app.float.radius_24"))
                    .height("80%")
                    .divider({
                    strokeWidth: 1,
                    color: $r('app.color.color_E3E3E3_grey'),
                    startMargin: $r('app.float.wh_value_52'),
                    endMargin: $r('app.float.wh_value_12')
                })
            }
            .scrollBar(BarState.Auto)
                .scrollBarWidth(20)
        } else {
            Row() {
                // Scanning...
                Text($r('app.string.scanning'))
                    .fontSize($r('app.float.font_20'))
                    .textCase(TextCase.UpperCase);
            }
        }
    }
}

整体代码

├─Component
│   │  └─controller
│   ├─pageTitle.ets
│   ├─headComponent.ets
│   └─titleComponent.ets
├─MainAbility
│  ├─controller
│  ├─model
│      ├─BluetoothDevice.ts
│      └─BluetoothModel.ts
│  └─pages
│      ├─homePage.ets
│      └─deviceFound.ets
└─Utils

page

//homePage
build() {
    Column() {
        GridContainer({
            columns: 12,
            sizeType: SizeType.Auto,
            gutter: vp2px(1) === 2 ? '12vp' : '0vp',
            margin: vp2px(1) === 2 ? '24vp' : '0vp'
        }) {
            Row({}) {
                Column() {
                }
                .width(ConfigData.WH_100_100)
                    .height(ConfigData.WH_100_100)
                    .useSizeType({
                    xs: { span: 0, offset: 0 }, sm: { span: 0, offset: 0 },
                    md: { span: 0, offset: 0 }, lg: { span: 2, offset: 0 }
                });
                Column() {
                    Text(this.message)
                        .fontSize($r("app.float.font_30"))
                        .lineHeight($r("app.float.lineHeight_41"))
                        .fontWeight(FontWeight.Bold)
                        .fontFamily('HarmonyHeiTi')
                        .textAlign(TextAlign.Start)
                        .width(ConfigData.WH_100_100)
                        .padding({
                        left: $r('app.float.distance_26'),
                        top: $r('app.float.distance_12'),
                        bottom: $r('app.float.distance_17')
                    })
                    Column() {
                        HeadComponent({ headName: $r('app.string.test1'), isActive: true })
                        Scroll() {
                            Column({ space: '12vp' }) {
                                List() {
                                    //开蓝牙
                                    ListItem() {
                                        TitleComponent({
                                            title: "enableBluetooth",
                                            bgColor: this.currentClick === 0 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 0;
                                        if (this.btEnable) {
                                            this.message = '蓝牙已经使能';
                                            return;
                                        }
                                        let ret = BluetoothModel.enableBluetooth();
                                        this.btEnable = ret;
                                        AppStorage.SetOrCreate('bluetoothIsOn', this.btEnable);
                                        AppStorage.SetOrCreate('currentClick', this.currentClick);
                                        this.message = "蓝牙使能执行结果:" + ret;
                                    })
                                    //设置状态
                                    ListItem() {
                                        TitleComponent({
                                            title: "getState",
                                            bgColor: this.currentClick === 2 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 2;
                                        let ret = BluetoothModel.getState();
                                        switch (ret) {
                                            case 0:
                                                this.stateBT = 'STATE_OFF';
                                                break;
                                            case 1:
                                                this.stateBT = 'STATE_TURNING_ON';
                                                break;
                                            case 2:
                                                this.stateBT = 'STATE_ON';
                                                break;
                                            case 3:
                                                this.stateBT = 'STATE_TURNING_OFF';
                                                break;
                                            case 4:
                                                this.stateBT = 'STATE_BLE_TURNING_ON';
                                                break;
                                            case 5:
                                                this.stateBT = 'STATE_BLE_ON';
                                                break;
                                            case 6:
                                                this.stateBT = 'STATE_BLE_TURNING_OFF';
                                                break;
                                            default:
                                                this.stateBT = '未知状态';
                                                break;
                                        }
                                        this.message = "当前蓝牙的状态是:" + this.stateBT;
                                    })
                                    //设置本地名称  
                                    ListItem() {
                                        TitleComponent({
                                            title: "setLocalName",
                                            bgColor: this.currentClick === 4 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 4;
                                        if (this.btEnable) {
                                            Router.push({ uri: PAGE_URI_DEVICE_NAME });
                                            this.message = "设置SCAN MODE " + this.setScanModeRet ? '成功' : '失败';
                                        } else {
                                            this.message = "蓝牙未使能";
                                        }
                                    })
                                    //设置扫描模式   
                                    ListItem() {
                                        TitleComponent({
                                            title: "setBluetoothScanMode",
                                            bgColor: this.currentClick === 6 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 6;
                                        if (!this.btEnable) {
                                            Router.push({ uri: PAGE_URI_SET_SCAN_MODE });
                                            this.message = "setBluetoothScanMode执行" + this.setLocalNameRet ? '成功' : '失败';
                                        } else {
                                            this.message = "蓝牙未使能";
                                        }
                                    })
                                    // 开始蓝牙发现
                                    ListItem() {
                                        TitleComponent({
                                            title: "startBluetoothDiscovery",
                                            bgColor: this.currentClick === 8 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        LogUtil.info(this.TAG_PAGE + 'startBluetoothDiscovery 111');
                                        if (this.btEnable) {
                                            this.message = '蓝牙未使能';
                                            return;
                                        }
                                        this.currentClick = 8;
                                        Router.push({ uri: PAGE_URI_DEVICE_FOUND_MODE });
                                    })
                                    //监听PinRequired
                                    ListItem() {
                                        TitleComponent({
                                            title: this.btPinRequired,
                                            pinRequiredFlag: true,
                                            bgColor: this.currentClick === 18 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        if (!this.btEnable) {
                                            this.message = "蓝牙未使能";
                                            return;
                                        }
                                        if (this.isPinRequiredClick) {
                                            bluetooth.off('pinRequired', () => {

                                            })
                                            this.message = 'on:pinRequired监听已关闭,再次点击将开启监听';
                                            this.isPinRequiredClick = false;
                                            this.btPinRequired = 'on:pinRequired';
                                            AppStorage.SetOrCreate('on_pinRequired', this.btPinRequired);
                                            return;
                                        }
                                        this.isPinRequiredClick = true;
                                        this.currentClick = 18;
                                        this.btPinRequired = 'off:pinRequired';
                                        AppStorage.SetOrCreate('on_pinRequired', this.btPinRequired);
                                        this.pinMessage = 'PIN: ';
                                        bluetooth.on('pinRequired', (data) => {
                                            this.pinMessage = 'PIN: ';
                                            this.pinMessage += data.pinCode;
                                        })
                                        this.message = 'on:pinRequired监听已启动,再次点击将关闭监听。';
                                    })
                                    //配对设备
                                    ListItem() {
                                        TitleComponent({
                                            title: "pairDevice",
                                            bgColor: this.currentClick === 10 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 10;
                                        if (!this.btEnable) {
                                            this.message = '蓝牙未使能';
                                            return;
                                        }
                                        if (this.deviceId == '') {
                                            this.message = "请输入目标设备的MAC";
                                            return;
                                        } else {
                                            this.pairDevice(this.deviceId);
                                        }
                                    })
                                    //关蓝牙
                                    ListItem() {
                                        TitleComponent({
                                            title: "disableBluetooth",
                                            bgColor: this.currentClick === 1 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 1;
                                        if (!this.btEnable) {
                                            this.message = '蓝牙还未使能';
                                            return;
                                        }
                                        let ret = BluetoothModel.disableBluetooth();
                                        this.btEnable = false;
                                        AppStorage.SetOrCreate('bluetoothIsOn', this.btEnable);
                                        this.message = "蓝牙去使能执行结果:" + ret;
                                    })
                                }
                            }
                            .width(ConfigData.WH_100_100)
                                .height(600)
                        }
                        .scrollable(ScrollDirection.Vertical).scrollBar(BarState.On)
                        .scrollBarColor(Color.Gray).scrollBarWidth(30)
                    }
                    .padding({ left: $r('app.float.distance_2'), right: $r('app.float.distance_2') })
                    .width(ConfigData.WH_100_100)
                    .height(ConfigData.WH_100_100)
                    .useSizeType({
                    xs: { span: 12, offset: 0 }, sm: { span: 12, offset: 0 },
                    md: { span: 12, offset: 0 }, lg: { span: 8, offset: 2 }
                    });
                }
                .padding({ left: $r('app.float.distance_2'), right: $r('app.float.distance_2') })
                .width(ConfigData.WH_100_100)
                .height(ConfigData.WH_100_100)
                .useSizeType({
                xs: { span: 12, offset: 0 }, sm: { span: 12, offset: 0 },
                md: { span: 12, offset: 0 }, lg: { span: 8, offset: 2 }
                });
            }
            .width(ConfigData.WH_100_100)
            .height(ConfigData.WH_100_100);
        }
        .backgroundColor($r("sys.color.ohos_id_color_sub_background"))
        .width(ConfigData.WH_100_100)
        .height(ConfigData.WH_100_100);
    }
}

component:

// titlecomoponent

import ConfigData from '../Utils/ConfigData';
@Component
export struct TitleComponent{
    private title:string | Resource;
    private fontSize:string ='35vp';
    private stateChangeFlag: boolean = false;
    private pinRequiredFlag: boolean = false;
    private bondStateChangeFlag: boolean = false;
    @State isTouched:boolean = false;
    @State bgColor: Resource = $r('app.color.font_color_007DFF');
    @StorageLink('on_stateChange') state: string = 'on:stateChange';
    @StorageLink('on_pinRequired') pin: string = 'on:pinRequired';
    @StorageLink('on_bondStateChange') bondState: string = 'on:bondStateChange';
    build(){
        Column(){
            Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems:ItemAlign.Center }) {
                Text(this.stateChangeFlag ? this.state : (this.pinRequiredFlag ? this.pin : (this.bondStateChangeFlag ? this.bondState : this.title)))
                    .textAlign(TextAlign.Center)
                    .width("100%")
                    .height(100)
                    .fontSize(this.fontSize)
                    .fontColor($r('app.color.font_color_182431'))
                    .fontWeight(FontWeight.Medium)
            }
            .height(ConfigData.WH_100_100)
                .width(ConfigData.WH_100_100)
                .backgroundColor(this.bgColor)
                .linearGradient(this.isTouched ? {
                angle: 90,
                direction: GradientDirection.Right,
                colors: [[$r("app.color.DCEAF9"), 0.0], [$r("app.color.FAFAFA"), 1.0]]
            } : {
                angle: 90, direction: GradientDirection.Right,
                colors: [[$r("sys.color.ohos_id_color_foreground_contrary"), 1], [$r("sys.color.ohos_id_color_foreground_contrary"), 1]]})
                .onTouch((event: TouchEvent) => {
                if (event.type === TouchType.Down) {
                    this.isTouched = true;
                }
                if (event.type === TouchType.Up) {
                    this.isTouched = false;
                }
            })
        }
        .padding($r('app.float.distance_4'))
        .height("100vp")
        .borderRadius($r('app.float.radius_12'))
    }
}

model:

import { DeviceState } from './BluetoothModel'
export class Profile {
    profileId: number = -1;
    profileConnectionState: number = -1
    constructor() {
    }
}
/**
 * Bluetooth device class
 */
export default class BluetoothDevice {
    deviceId: string = '';
    deviceName: string = '';
    deviceType: string = '';
    connectionState: number = 0;
    profiles: Map<number, Profile> = new Map();
    constructor() {
    }
    setProfiles(data: Array<{
    	profileId: number;
    	profileConnectionState: number;
    }>): void{
        	data.forEach((item: {
        	profileId: number;
        	profileConnectionState: number;
    	}) => {
        	this.setProfile({
            	profileId: item.profileId,
            	deviceId: this.deviceId,
            	profileConnectionState: item.profileConnectionState
        	})
    	})
	}
	setProfile(data: {
		profileId: number;
        deviceId: string;
        profileConnectionState: number;
    }): void{
    	if (this.deviceId !== data.deviceId) {
        	return;
    	}
    	this.profiles.set(data.profileId, data)
    	let countStateDisconnect = 0;
		let countStateConnecting = 0;
		let countStateConnected = 0;
		let countStateDisconnecting = 0;
		this.profiles.forEach((profile, key) => {
    		if (profile.profileConnectionState == 0) {
        		// 0:the current profile is disconnected
        		countStateDisconnect++;
    		} else if (profile.profileConnectionState == 1) {
        		// 1:the current profile is being connected
       		 countStateConnecting++;
    		} else if (profile.profileConnectionState == 2) {
        		// 2:the current profile is connected
        	countStateConnected++;
    		} else if (profile.profileConnectionState == 3) {
        		// 3:the current profile is being disconnected
        		countStateDisconnecting++;
    		}
		});
		if (countStateConnected > 0 || countStateDisconnecting > 0) {
    		this.connectionState = DeviceState.STATE_CONNECTED;
		} else if (countStateConnecting > 0) {
    		this.connectionState = DeviceState.STATE_CONNECTING;
		} else {
    		this.connectionState = DeviceState.STATE_DISCONNECTED;
		}
	}
}

预览图

                                                   

拥抱鸿蒙,拥抱未来,选择远方,风雨兼程。

最后

如果你想成为一名鸿蒙开发者,以下这些资料将是十分优质且有价值,让你的鸿蒙开发之路事半功倍!相对于网上那些碎片化的知识内容,这份学习资料的知识点更加系统化,更容易理解和记忆。

鸿蒙Next全套VIP学习资料←点击领取!(安全链接,放心点击

包含了:【OpenHarmony多媒体技术、Stage模型、ArkUI多端部署、分布式应用开发、音频、视频、WebGL、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战】等技术知识点。

1.鸿蒙(HarmonyOS NEXT)最新学习路线

有了路线图,怎么能没有学习资料呢,小编也准备了一份联合鸿蒙官方发布笔记整理收纳的一套系统性的鸿蒙(OpenHarmony )学习手册(共计1236页)与鸿蒙(OpenHarmony )开发入门教学视频,内容包含:ArkTS、ArkUI、Web开发、应用模型、资源分类…等知识点。

获取以上完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习资料

2.大厂面试必问面试题

3.鸿蒙南向开发技术

 4.鸿蒙APP开发必备

 5.HarmonyOS Next 最新全套视频教程

 6.鸿蒙生态应用开发白皮书V2.0PDF

获取以上完整鸿蒙HarmonyOS学习资料,请点击→纯血版全套鸿蒙HarmonyOS学习资料

总结
总的来说,华为鸿蒙不再兼容安卓,对中年程序员来说是一个挑战,也是一个机会。只有积极应对变化,不断学习和提升自己,他们才能在这个变革的时代中立于不败之地。 

  • 12
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenHarmony一个开源的操作系统,主要目标是为全场景智能终端提供统一的解决方案。在开发过程中,覆盖率是一个重要的指标,用于衡量测试用例对代码的覆盖程度。在 OpenHarmony 中,可以通过以下方式来查看本地覆盖率。 首先,确保项目中已经集成了覆盖率工具。OpenHarmony 使用的是 gcov 工具,该工具可以在编译时插入代码,生成覆盖率统计信息。 接下来,在项目代码中插入覆盖率测试代码。可以设置特定的宏来标识需要进行覆盖率统计的代码块,在测试用例中触发这些代码块,从而生成覆盖率信息。 然后,重新编译项目并执行测试用例。在测试用例执行完毕后,覆盖率工具会生成覆盖率统计数据。 最后,查看覆盖率统计报告。OpenHarmony 提供了一个覆盖率分析工具 lcov,可以用来生成 HTML 格式的覆盖率统计报告。通过运行 lcov 命令,可以将覆盖率统计数据转换为人类可读的报告。 在覆盖率报告中,可以看到各个代码文件的覆盖率信息,包括覆盖率百分比、被测试覆盖的代码行和未被测试覆盖的代码行等。通过分析报告,可以了解到代码中哪些地方覆盖不足,从而优化测试用例,提高代码覆盖率。 总而言之,通过在 OpenHarmony 项目中集成覆盖率工具,插入覆盖率测试代码,并使用 lcov 工具生成覆盖率统计报告,可以方便地查看本地覆盖率信息,并做出针对性的优化措施。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值