uniapp 中藍牙連接、下發(fā)數(shù)據(jù)、監(jiān)聽接收數(shù)據(jù)

創(chuàng)建一個新頁面,直接把代碼全部復制、粘貼

<template>
    <view style="height: 100%;">
        <view class="content" v-if="Loading">
            <view class="content_t">
                <u-loading mode="flower" size="120" :show="true"></u-loading>
                <view class="txt">{{status_txt}}</view>
            </view>
            <view class="content_b" />
        </view>
        <view style="height: 100%;" v-else>
            <view class="content" v-if="bluetoothList.length>0">
                <view @click="goConnectBle(item,index)" class="bluetooth_item" v-for="(item, index) in bluetoothList"
                    :key="index">
                    <text>{{item.name}}</text>
                    <text>{{item.deviceId}}</text>
                </view>

                <u-button @click="writeTest">
                    寫入測試
                </u-button>
                
                <view class="">
                    藍牙返回的數(shù)據(jù)為:{{bleData}}
                </view>
            </view>

            <view class="content" v-else>
                <view class="content_t">
                    <view class="common_txt">
                        未發(fā)現(xiàn)附近的藍牙設備
                    </view>
                    <view class="default_txt" style="line-height: 100rpx;">
                        請確認設備已接通電源并盡量接近手機
                    </view>
                    <u-button style="margin-bottom: 50rpx;" size="default" shape="circle" :hairLine="true"
                        class="common_txt" @click="ReSearchBle()">
                        重新掃描
                    </u-button>
                </view>
                <view class="content_b" />
            </view>
        </view>

    </view>
</template>

<script>
    export default {
        data() {
            return {
                Loading: false,
                bluetoothList: [],
                status_txt:'正在識別附近的設備',
                bleData:''
            };
        },

        onLoad() {
            this.InitBle()
        },
        onUnload() {
            if (this.timer1) {
                clearTimeout(this.timer1);
                this.timer1 = null;
            }
            if (this.timer2) {
                clearTimeout(this.timer2);
                this.timer2 = null;
            }

        },
        
        methods: {
            // 點擊連接藍牙
            goConnectBle(e, index) {
                console.log('開始連接藍牙', e, index)

                this.Loading = true
                this.status_txt = '正在連接中...'
                this.ConnectBle(e.deviceId)
            },


            writeTest() {
                this.BleWrite('5500000003010C303DAA') 
            },

            /* ===========藍牙模塊開始================ */

            // 初始化藍牙
            InitBle() {
                let _this = this
                uni.openBluetoothAdapter({ //初始化藍牙模塊
                    success(res) {
                        console.log('初始化藍牙', res);
                        uni.showToast({
                            title: '初始化成功',
                            icon: 'success',
                            duration: 800
                        })
                        _this.SearchBle(); //2.0
                    },
                    fail(err) {
                        uni.showToast({
                            title: '請檢查是否已開啟藍牙',
                            icon: 'none',
                            duration: 1500
                        })
                    }
                })
            },

            // 搜索藍牙
            SearchBle() {
                let _this = this
                uni.startBluetoothDevicesDiscovery({
                    success(res) {
                        console.log('藍牙開啟搜索', res)
                        _this.Loading = true
                        _this.timer1 = setTimeout(() => { //加個延遲、目的是為了設備搜索完畢再獲取列表,不然獲取為空列表
                            _this.GetBleList() //3.0
                        }, 3000)
                    },
                    fail(res) {
                        console.log("查找設備失敗!");
                        uni.showToast({
                            icon: "none",
                            title: "查找設備失??!",
                            duration: 3000
                        })
                    }
                })
            },


            // 搜索到的藍牙列表
            GetBleList() {
                var _this = this;
                uni.getBluetoothDevices({
                    success: function(res) {
                        // console.log('藍牙設備列表==1', JSON.stringify(res.devices))
                        var bluetoothArr = res.devices.filter(function(obj) {
                            return obj.name != "未知設備" && obj.name == 'mycar_ble';  //這里過濾自己想要的設備
                            // return obj.name != "未知設備" && obj.name == 'CXL';
                        })
                        console.log('藍牙設備列表==2過濾后==', bluetoothArr)
                        _this.bluetoothList = bluetoothArr
                        // _this.bluetoothList = []
                    },
                    fail: function() {
                        console.log("搜索藍牙設備失敗");
                        uni.showToast({
                            title: '搜索藍牙設備失敗或附件暫無開啟的藍牙設備',
                            icon: 'none',
                            duration: 2000
                        })
                    },
                    complete: function() {
                        console.log('搜索完成')
                        _this.Loading = false
                        _this.StopSearchBle()
                    }
                })
            },



            // 藍牙連接  根據(jù)某一id連接設備,4.0
            ConnectBle(deviceId) {
                var _this = this;
                uni.createBLEConnection({
                    deviceId: deviceId, //設備id
                    success: (res) => {
                        console.log('連接藍牙成功==', res)
                        // _this.postDeviceInfo()   //提交藍牙信息到后臺
                        _this.deviceId = deviceId

                        // 設置藍牙最大傳輸單元。
                        // uni.setBLEMTU(22,512)
                        _this.NoticeConnection(); //連接成功后,開始監(jiān)聽異常
                        _this.timer2 = setTimeout(() => { //加個延遲、目的是為了確保連接成功后,再獲取服務列表--可以顯示正在連接效果
                            _this.Loading = false
                            _this.GetServiceId(deviceId); //5.0
                            uni.showToast({
                                title: '連接成功',
                                icon: 'success',
                                duration: 800
                            })
                        }, 3000)
                    },
                    fail: function(err) {
                        console.log('藍牙連接失敗err===', err)
                        if(err.errMsg == 'createBLEConnection:fail already connect'){
                            _this.Loading = false
                            _this.status_txt = '已有藍牙連接'
                        }else{
                            _this.status_txt = err.errMsg
                        }
                    },
                    complete: function() {
                        console.log('藍牙連接完成')
                    }
                })
            },


            //獲取藍牙設備的服務uuid,5.0    //服務uuid可能有多個
            GetServiceId(deviceId) {
                console.log('連接的藍牙設備deviceId====', deviceId)
                var _this = this
                uni.getBLEDeviceServices({
                    deviceId,
                    success(res) {
                        console.log('獲取藍牙四個服務==', res)
                        _this.serviceid_list = res.services //藍牙服務列表放在data里面只是備用
                        _this.serviceId = res.services[1].uuid //這是用來監(jiān)聽藍牙下發(fā)和接收的服務uuid
                        _this.GetCharacteIdNotify(_this.serviceId,
                            deviceId) //6.0  獲取第2個服務uuid的特征值 (關于獲取第幾個uuid服務,看藍牙方面提供的協(xié)議
                    }
                })
            },

            // 根據(jù)服務uuid獲取藍牙特征值,開始監(jiān)聽寫入和接收
            GetCharacteIdNotify(serviceId, deviceId) {
                let _this = this
                uni.getBLEDeviceCharacteristics({
                    deviceId,
                    serviceId,
                    success(res) {
                        console.log('獲取藍牙特征值', res.characteristics)
                        _this.writeId = res.characteristics[0].uuid //寫入id
                        _this.notifyId = res.characteristics[1].uuid //接收id
                        _this.startNoticeBle(_this.notifyId) //7.0,開始偵聽數(shù)據(jù)
                    }
                })
            },

            // 開啟藍牙數(shù)據(jù)監(jiān)聽
            startNoticeBle(notifyId) {
                let _this = this
                uni.notifyBLECharacteristicValueChange({
                    state: true, // 啟用 notify 功能
                    deviceId: _this.deviceId,
                    serviceId: _this.serviceId,
                    characteristicId: notifyId,
                    success(res) {
                        console.log("監(jiān)聽成功===", res.errMsg, 'deviceId===', _this.deviceId)
                        _this.GetDataFromBle();
                    },
                    fail: function(err) {
                        console.log('開啟監(jiān)聽失敗', err)
                    }
                })
            },

            // 設備返回的數(shù)據(jù)接收
            GetDataFromBle() {
                var _this = this;
                uni.onBLECharacteristicValueChange((res) => {
                    // 此時可以拿到藍牙設備返回來的數(shù)據(jù)是一個ArrayBuffer類型數(shù)據(jù),所以需要通過一個方法轉換成字符串
                    console.log('返回的十六進制', _this.ab2hex(res.value))
                    _this.bleData = _this.ab2hex(res.value)
                    // let data = that.ab2hex(res.value)
                    // let head = data.slice(0,2);
                })
            },

            // 向藍牙寫入數(shù)據(jù)
            BleWrite(instruction) {
                // 向藍牙設備發(fā)送一個0x00的16進制數(shù)據(jù)
                let _this = this
                let serviceId = _this.serviceId
                let characteristicId = _this.writeId
                let deviceId = _this.deviceId
                const buffer = _this.hexStringToArrayBuffer(instruction);
                // const dataView = new DataView(buffer)
                // dataView.setUint8(0, 0)
                uni.writeBLECharacteristicValue({
                    deviceId, // 藍牙設備 deviceId
                    serviceId, // 藍牙服務uuid,即第二個uuid
                    characteristicId, // 藍牙特征值的 (即 writeId)
                    value: buffer, // 這里的value是ArrayBuffer類型
                    success(res) {
                        console.log('指令下發(fā)成功==', res.errMsg,res)
                    },
                    fail(err) {
                        console.log('寫入數(shù)據(jù)失敗', err)
                        uni.showToast({
                            icon: "none",
                            title: "請確保您的手機已連接設備",
                            duration: 3000
                        })
                    }
                })
            },

            // 停止搜索藍牙
            StopSearchBle() {
                uni.stopBluetoothDevicesDiscovery({
                    success(res) {
                        console.log('停止搜索藍牙', res)
                    }
                })
            },

            // 重新搜索藍牙
            ReSearchBle() {
                console.log('重新掃描')
                this.SearchBle()
            },

            // 關閉藍牙模塊
                
                  CloseBle(macId) {
                      uni.closeBLEConnection({
                          deviceId: macId,
                          success(res) {
                              uni.closeBluetoothAdapter({
                                  success: function(res) {
                                    console.log("斷開藍牙")
                                    },
                                  fail: function(err) {}
                                  })
                              },
                        fail(err) {}
                      })
                    },

            // 監(jiān)聽藍牙連接狀態(tài)
            NoticeConnection() {
                var _this = this;
                uni.onBLEConnectionStateChange((res) => {
                    console.log('開始監(jiān)聽藍牙狀態(tài)', res)
                    if (!res.connected) {
                        console.log('連接已斷開');
                        uni.showModal({
                            title: '提示',
                            content: '藍牙已斷開,請重新搜索重連!',
                            success(res) {}
                        })
                        // clearInterval(_this.data.timer)
                    }
                })
            },



            /* ===========藍牙模塊結束================ */


            // 工具函數(shù)
            // ArrayBuffer轉16進度字符串示例
            ab2hex(buffer) {
                const hexArr = Array.prototype.map.call(
                    new Uint8Array(buffer),
                    function(bit) {
                        return ('00' + bit.toString(16)).slice(-2)
                    }
                )
                return hexArr.join('')
            },

            hexStringToArrayBuffer(str) {
                if (!str) {
                    return new ArrayBuffer(0);
                }
                var buffer = new ArrayBuffer(str.length);
                let dataView = new DataView(buffer)
                let ind = 0;
                for (var i = 0, len = str.length; i < len; i += 2) {
                    let code = parseInt(str.substr(i, 2), 16)
                    dataView.setUint8(ind, code)
                    ind++
                }
                return buffer;
            },


        },
    }
</script>

<style lang="scss" scoped>
    .content {
        display: flex;
        flex: 1;
        height: 100%;
        flex-direction: column;

        .bluetooth_item {
            border-bottom: 1rpx solid #ccc;
            line-height: 100rpx;
            padding: 0 50rpx;
            display: flex;
            justify-content: space-between;
        }
    }

    .content_t {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        align-items: center;

        .txt {
            color: $bg-color;
            margin: 40rpx 0rpx 120rpx;
            font-size: 34rpx;
        }

    }

    .content_b {
        flex: 1;
    }

    .common_txt {
        color: $bg-color;
        font-size: 34rpx;
    }

    .default_txt {
        color: #999;
        font-size: 24rpx;
    }
</style>

暫時封裝 bluetooth.js

const app = getApp()
module.exports = {
    /* ===========藍牙模塊開始================ */

    //  一、 初始化藍牙
    // InitBle(bleListCallback, errCallback, statusCallback) {
    InitBle() {
        let _this = this
        uni.openBluetoothAdapter({ //初始化藍牙模塊
            success(res) {
                console.log('init ble success==', res);
                uni.showToast({
                    title: '初始化成功',
                    icon: 'success',
                    duration: 800
                })
                _this.SearchBle(bleListCallback, errCallback, statusCallback); //2.0 關于初始化是否需要獲取列表根據(jù)需求來做,有可能你只需要初始化,那么把這個注釋掉即可
            },
            fail(err) {
                uni.showToast({
                    title: '請檢查是否已開啟藍牙',
                    icon: 'none',
                    duration: 1500
                })
            }
        })
    },

    // 搜索藍牙
    SearchBle(bleListCallback, errCallback, statusCallback) {
        let _this = this
        uni.startBluetoothDevicesDiscovery({
            success(res) {
                console.log('start search ble==', res)
                let Loading = true
                statusCallback(Loading)
                _this.timer1 = setTimeout(() => { //加個延遲、目的是為了設備搜索完畢再獲取列表,不然獲取為空列表
                    _this.GetBleList(bleListCallback, errCallback, statusCallback) //3.0
                    if (this.timer1) {
                        clearTimeout(this.timer1);
                        this.timer1 = null;
                    }
                }, 5000)
            },
            fail(err) {
                console.log("search ble fail==", err);
                errCallback(err)
                uni.showToast({
                    icon: "none",
                    title: "查找設備失??!",
                    duration: 3000
                })
            }
        })
    },


    // 搜索到的藍牙列表
    GetBleList(bleListCallback, errCallback, statusCallback) {
        var _this = this;
        uni.getBluetoothDevices({
            success(res) {
                // console.log('藍牙設備列表==1', JSON.stringify(res.devices))
                var bluetoothArr = res.devices.filter(function(obj) {
                    return obj.name != "未知設備" && obj.name == 'mycar_ble'; //這里過濾自己想要的設備
                    // return obj.name != "未知設備" && obj.name == 'CXL';
                })
                console.log('get ble fliter list===', bluetoothArr)
                bleListCallback(bluetoothArr)
                _this.bluetoothList = bluetoothArr
                // _this.bluetoothList = []
            },
            fail(err) {
                console.log("get ble fliter fail==", err);
                errCallback(err)
                uni.showToast({
                    title: '搜索藍牙設備失敗或附件暫無開啟的藍牙設備',
                    icon: 'none',
                    duration: 2000
                })
            },
            complete() {
                console.log('searh ble complete==')
                let Loading = false
                statusCallback(Loading)
                _this.StopSearchBle()
            }
        })
    },


    //  二、 藍牙連接  根據(jù)某一id連接設備,4.0
    ConnectBle(deviceId, successCallback, errorCallback) {
        var _this = this;
        uni.createBLEConnection({
            deviceId: deviceId, //設備id
            success(res) {
                console.log('connect success==', res)
                _this.deviceId = deviceId
                // 設置藍牙最大傳輸單元。
                // uni.setBLEMTU(22,512)
                _this.NoticeConnection(deviceId); //連接成功后,開始監(jiān)聽異常
                _this.timer2 = setTimeout(() => { //加個延遲、目的是為了確保連接成功后,再獲取服務列表--可以顯示正在連接效果
                    _this.GetServiceId(deviceId, successCallback, errorCallback); //5.0
                    uni.showToast({
                        title: '連接成功',
                        icon: 'success',
                        duration: 800
                    })
                    if (this.timer2) {
                        clearTimeout(this.timer2);
                        this.timer2 = null;
                    }
                }, 3000)
            },
            fail(err) {
                console.log('connect err===', err)
                errorCallback(err)
                if (err.errMsg == 'createBLEConnection:fail already connect') {
                    uni.showToast({
                        icon: "none",
                        title: "藍牙設備已連接",
                        duration: 3000
                    })
                } else {
                    uni.showToast({
                        icon: "none",
                        title: err.errMsg,
                        duration: 3000
                    })
                }
            },
            complete: function() {
                console.log('connect finish==')
            }
        })
    },

    //獲取藍牙設備的服務uuid,5.0    //服務uuid可能有多個
    GetServiceId(deviceId, successCallback, errorCallback) {
        var _this = this
        uni.getBLEDeviceServices({
            deviceId,
            success(res) {
                console.log('get servicesIds==', res)
                _this.serviceid_list = res.services //藍牙服務列表放在data里面只是備用
                _this.serviceId = res.services[1].uuid //這是用來監(jiān)聽藍牙下發(fā)和接收的服務uuid,關于獲取第幾個uuid服務,看藍牙方面提供的協(xié)議
                _this.GetCharacteIdNotify(_this.serviceId, deviceId,
                    successCallback) //6.0  獲取第2個服務uuid的特征值 (關于獲取第幾個uuid服務,看藍牙方面提供的協(xié)議
            },
            fail(err) {
                errorCallback(err)
            }
        })
    },

    // 根據(jù)服務uuid獲取藍牙特征值,開始監(jiān)聽寫入和接收
    GetCharacteIdNotify(serviceId, deviceId, successCallback) {
        let _this = this
        uni.getBLEDeviceCharacteristics({
            deviceId,
            serviceId,
            success(res) {
                console.log('get characterIds==', res.characteristics)
                _this.writeId = res.characteristics[0].uuid //寫入id
                _this.notifyId = res.characteristics[1].uuid //接收id
                _this.startNoticeBle(successCallback) //7.0,開始偵聽數(shù)據(jù)
            }
        })
    },

    // 開啟藍牙監(jiān)聽功能
    startNoticeBle(successCallback) {
        let _this = this
        uni.notifyBLECharacteristicValueChange({
            state: true, // 啟用 notify 功能
            deviceId: _this.deviceId,
            serviceId: _this.serviceId,
            characteristicId: _this.notifyId,
            success(res) {
                console.log("watch and notice success===", res.errMsg, 'deviceId===', _this.deviceId)
                successCallback(res)
                // _this.GetDataFromBle();
            },
            fail: function(err) {
                console.log('watch and notice fail==', err)
            }
        })
    },



    //  三、 設備返回的數(shù)據(jù)接收
    GetDataFromBle(successCallback, errorCallback) {
        var _this = this;
        uni.onBLECharacteristicValueChange((res) => {
            // 此時可以拿到藍牙設備返回來的數(shù)據(jù)是一個ArrayBuffer類型數(shù)據(jù),所以需要通過一個方法轉換成字符串
            // console.log('返回的十六進制', _this.ab2hex(res.value))
            _this.bleData = _this.ab2hex(res.value)
            successCallback(_this.bleData)
        })
    },

    // 向藍牙寫入數(shù)據(jù)
    BleWrite(instruction, successCallback, errorCallback) {
        // 向藍牙設備發(fā)送一個0x00的16進制數(shù)據(jù)
        let _this = this
        let serviceId = _this.serviceId
        let characteristicId = _this.writeId
        let deviceId = _this.deviceId
        const buffer = _this.hexStringToArrayBuffer(instruction);
        // const dataView = new DataView(buffer)
        // dataView.setUint8(0, 0)
        uni.writeBLECharacteristicValue({
            deviceId, // 藍牙設備 deviceId
            serviceId, // 藍牙服務uuid,即第二個uuid
            characteristicId, // 藍牙特征值的 (即 writeId)
            value: buffer, // 這里的value是ArrayBuffer類型
            success(res) {
                console.log('指令下發(fā)成功==', instruction, res, )
                _this.GetDataFromBle(successCallback, errorCallback);
            },
            fail(err) {
                console.log('寫入數(shù)據(jù)失敗', err)
                errorCallback(err)
                // uni.showToast({
                //  icon: "none",
                //  title: "請確保您的手機已開啟藍牙并已連接設備",
                //  duration: 3000
                // })
            }
        })
    },

    // 停止搜索藍牙
    StopSearchBle() {
        uni.stopBluetoothDevicesDiscovery({
            success(res) {
                console.log('stop search ble===', res)
            }
        })
    },

    // 重新搜索藍牙
    ReSearchBle(bleListCallback, errCallback, statusCallback) {
        console.log('重新掃描')
        this.SearchBle(bleListCallback, errCallback, statusCallback)
    },

    // 關閉藍牙
    CloseBle(macId) {
        uni.closeBLEConnection({
            deviceId: macId,
            success(res) {
                uni.closeBluetoothAdapter({
                    success: function(res) {
                        console.log("斷開藍牙")
                    },
                    fail: function(err) {}
                })
            },
            fail(err) {}
        })

    },


    // 監(jiān)聽藍牙連接狀態(tài)
    NoticeConnection() {
        var _this = this;
        uni.onBLEConnectionStateChange((res) => {
            console.log('開始監(jiān)聽藍牙狀態(tài)', res)
            if (!res.connected) {
                console.log('連接已斷開');
                app.globalData.isConnect = false;
                uni.showModal({
                    title: '提示',
                    content: '藍牙已斷開,請重新搜索重連!',
                    success(res) {}
                })
                // clearInterval(_this.data.timer)
            }
        })
    },



    /* ===========藍牙模塊結束================ */


    // 工具函數(shù)


    // 指令生成
    order(instruction, data) { //傳入指令和內(nèi)容
        // let instruction = '02',data = '00'
        let length = (instruction + data).length / 2
        let hexLength = this.ten2Hex(length) //十六進制長度
        // console.log('lenth==',length,hexLength)

        let str = instruction + data //命令字與數(shù)據(jù)包字節(jié)
        let id = 0
        let sum = 0
        for (let i = 0; i < str.length / 2; i++) {
            id += 2
            let hexstr = str.slice(id - 2, id) //將數(shù)據(jù)拆分,將其轉成10進制累加
            let intstr = this.hex2int(hexstr) //十進制
            sum += intstr
        }

        let checkstr = String(sum)
        let check = checkstr.slice(checkstr.length - 2, checkstr.length) //取得累加和后兩位數(shù)后,轉成16進制校驗碼
        let hexcheck = this.ten2Hex(check)


        // console.log('最終和為==',sum,check,hexcheck)             
        let order = '550000' + '00' + hexLength + instruction + data + hexcheck +
            'AA' //     '00' 與 hexLength 共兩個字節(jié), hexLength 最大為ff,即長度暫時不要超過255,若是需要長度超過255的需要判斷16進制的數(shù)據(jù)是否需要自動進位,本項目不需要再多做處理
        return order
    },



    //字符轉換成16進制發(fā)送到服務器
    Char2Hex(str) {
        if (str === "") {
            return "";
        } else {
            var hexCharCode = '';
            for (var i = 0; i < str.length; i++) {
                hexCharCode += (str.charCodeAt(i)).toString(16);
            }
            return hexCharCode //  tuh:  747568
        }
    },

    //字符轉換成16進制發(fā)送到服務器[轉換放到新數(shù)組]
    Char2Hex2(str) {
        if (str === "") {
            return "";
        } else {
            var hexCharCode = [];
            for (var i = 0; i < str.length; i++) {
                hexCharCode.push('0x' + (str.charCodeAt(i)).toString(16));
            }
            hexCharCode.join(",");
            return hexCharCode //tuh:  ["0x74", "0x75", "0x68"]
        }
    },



    // ArrayBuffer轉16進度字符串示例
    ab2hex(buffer) {
        const hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function(bit) {
                return ('00' + bit.toString(16)).slice(-2)
            }
        )
        return hexArr.join('')
    },

    // 16進制轉buffer
    hexStringToArrayBuffer(str) {
        if (!str) {
            return new ArrayBuffer(0);
        }
        var buffer = new ArrayBuffer(str.length);
        let dataView = new DataView(buffer)
        let ind = 0;
        for (var i = 0, len = str.length; i < len; i += 2) {
            let code = parseInt(str.substr(i, 2), 16)
            dataView.setUint8(ind, code)
            ind++
        }
        return buffer;
    },

    // 10進制轉16進制
    ten2Hex(number) {
        return Number(number) < 16 ? '0' + Number(number).toString(16) : Number(number).toString(16)
    },

    // 16進制轉10進制整數(shù)
    hex2int(hex) {
        var len = hex.length,
            a = new Array(len),
            code;
        for (var i = 0; i < len; i++) {
            code = hex.charCodeAt(i);
            if (48 <= code && code < 58) {
                code -= 48;
            } else {
                code = (code & 0xdf) - 65 + 10;
            }
            a[i] = code;
        }

        return a.reduce(function(acc, c) {
            acc = 16 * acc + c;
            return acc;
        }, 0);
    },

    //16進制轉10進制浮點數(shù)
    hex2Float(t) {

        t = t.replace(/\s+/g, "");
        if (t == "") {
            return "";
        }
        if (t == "00000000") {
            return "0";
        }
        if ((t.length > 8) || (isNaN(parseInt(t, 16)))) {
            return "Error";
        }
        if (t.length < 8) {
            t = this.FillString(t, "0", 8, true);
        }
        t = parseInt(t, 16).toString(2);
        t = this.FillString(t, "0", 32, true);
        var s = t.substring(0, 1);
        var e = t.substring(1, 9);
        var m = t.substring(9);
        e = parseInt(e, 2) - 127;
        m = "1" + m;
        if (e >= 0) {
            m = m.substr(0, e + 1) + "." + m.substring(e + 1)
        } else {
            m = "0." + this.FillString(m, "0", m.length - e - 1, true)
        }
        if (m.indexOf(".") == -1) {
            m = m + ".0";
        }
        var a = m.split(".");
        var mi = parseInt(a[0], 2);
        var mf = 0;
        for (var i = 0; i < a[1].length; i++) {
            mf += parseFloat(a[1].charAt(i)) * Math.pow(2, -(i + 1));
        }
        m = parseInt(mi) + parseFloat(mf);
        if (s == 1) {
            m = 0 - m;
        }
        return m;
    },

    //浮點數(shù)轉16進制
    float2Hex(t) {
        if (t == "") {
            return "";
        }
        t = parseFloat(t);
        if (isNaN(t) == true) {
            return "Error";
        }
        if (t == 0) {
            return "00000000";
        }
        var s,
            e,
            m;
        if (t > 0) {
            s = 0;
        } else {
            s = 1;
            t = 0 - t;
        }
        m = t.toString(2);
        if (m >= 1) {
            if (m.indexOf(".") == -1) {
                m = m + ".0";
            }
            e = m.indexOf(".") - 1;
        } else {
            e = 1 - m.indexOf("1");
        }
        if (e >= 0) {
            m = m.replace(".", "");
        } else {
            m = m.substring(m.indexOf("1"));
        }
        if (m.length > 24) {
            m = m.substr(0, 24);
        } else {
            m = this.FillString(m, "0", 24, false)
        }
        m = m.substring(1);
        e = (e + 127).toString(2);
        e = this.FillString(e, "0", 8, true);
        var r = parseInt(s + e + m, 2).toString(16);
        r = this.FillString(r, "0", 8, true);
        return this.InsertString(r, " ", 2).toUpperCase();
    },

    //需要用到的函數(shù)
    InsertString(t, c, n) {
        var r = new Array();
        for (var i = 0; i * 2 < t.length; i++) {
            r.push(t.substr(i * 2, n));
        }
        return r.join(c);
    },
    //需要用到的函數(shù)
    FillString(t, c, n, b) {
        if ((t == "") || (c.length != 1) || (n <= t.length)) {
            return t;
        }
        var l = t.length;
        for (var i = 0; i < n - l; i++) {
            if (b == true) {
                t = c + t;
            } else {
                t += c;
            }
        }
        return t;
    },

}


使用

<template>
    <view style="height: 100%;">
        <view class="content" v-if="Loading">
            <view class="content_t">
                <u-loading mode="flower" size="120" :show="true"></u-loading>
                <view class="txt">{{status_txt}}</view>
            </view>
            <view class="content_b" />
        </view>
        <view style="height: 100%;" v-else>
            <view class="content" v-if="bluetoothList.length>0">
                <view @click="goConnectBle(item,index)" class="bluetooth_item" v-for="(item, index) in bluetoothList"
                    :key="index">
                    <text>{{item.name}}</text>
                    <text>{{item.deviceId}}</text>
                    <u-icon name="arrow-right" :size="30" style="color:#666"></u-icon>
                </view>

<!--                <u-button @click="writeTest">
                    寫入測試
                </u-button>
                
                <view class="">
                    藍牙返回的數(shù)據(jù)為:{{bleData}}
                </view> -->
            </view>

            <view class="content" v-else>
                <view class="content_t">
                    <view class="common_txt">
                        未發(fā)現(xiàn)附近的藍牙設備
                    </view>
                    <view class="default_txt" style="line-height: 100rpx;">
                        請確認設備已接通電源并盡量接近手機
                    </view>
                    <u-button style="margin-bottom: 50rpx;" size="default" shape="circle" :hairLine="true"
                        class="common_txt" @click="ReSearchBle()">
                        重新掃描
                    </u-button>
                </view>
                <view class="content_b"/>
            </view>
        </view>

    </view>
</template>

<script>
    import bluetooth from './bluetooth.js'
    export default {
        data() {
            return {
                Loading: false,
                bluetoothList: [],
                status_txt:'正在識別附近的設備',
                bleData:''
            };
        },

        onLoad() {
            bluetooth.InitBle((data)=>{
                console.log('搜索頁面藍牙初始化成功===返回藍牙列表=====',data)
                this.bluetoothList = data
            },(err)=>{
                console.log('搜索頁面藍牙初始化失敗=========',err)
            },(status)=>{
                console.log('搜索頁面藍牙初始化狀態(tài)=========Loding',status)
                this.Loading = status
            })      
        },
        
        methods: {
            // 點擊連接藍牙
            goConnectBle(e, index) {
                // console.log('開始連接藍牙', e, index)
                this.Loading = true
                this.status_txt = '正在連接中...'
                bluetooth.ConnectBle(e.deviceId,(data)=>{
                    console.log('頁面連接藍牙成功', data)
                    this.Loading = false
                    uni.switchTab({
                        url:'../index/index'
                    })
                },(err)=>{
                    console.log('頁面連接藍牙失敗', err)
                    this.Loading = false
                })
            },

            // writeTest() {
            //  bluetooth.BleWrite('5500000003010C303DAA',(data)=>{
            //      console.log('頁面返回數(shù)據(jù)==',data)
            //  },(err)=>{
                    
            //  }) 
            // },

            /* ===========藍牙模塊開始================ */
            
            ReSearchBle() {
                bluetooth.ReSearchBle((data)=>{
                    this.bluetoothList = data
                },(err)=>{
                    console.log('重新搜索失敗=========',err)
                },(status)=>{
                    console.log('重新搜索狀態(tài)=========Loding',status)
                    this.Loading = status
                })
            },

        },
    }
</script>

<style lang="scss" scoped>
    .content {
        display: flex;
        flex: 1;
        height: 100%;
        flex-direction: column;

        .bluetooth_item {
            border-bottom: 1rpx solid #ccc;
            line-height: 100rpx;
            padding: 0 50rpx;
            display: flex;
            justify-content: space-between;
        }
    }

    .content_t {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        align-items: center;

        .txt {
            color: $bg-color;
            margin: 40rpx 0rpx 120rpx;
            font-size: 34rpx;
        }

    }

    .content_b {
        flex: 1;
    }

    .common_txt {
        color: $bg-color;
        font-size: 34rpx;
    }

    .default_txt {
        color: #999;
        font-size: 24rpx;
    }
</style>
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容