更新记录

1.0.0(2023-06-09) 下载此版本

初始化


平台兼容性

Vue2 Vue3
×
App 快应用 微信小程序 支付宝小程序 百度小程序 字节小程序 QQ小程序
× × × × × × ×
钉钉小程序 快手小程序 飞书小程序 京东小程序
× × × ×
H5-Safari Android Browser 微信浏览器(Android) QQ浏览器(Android) Chrome IE Edge Firefox PC-Safari
× × × × × × × × ×

经典蓝牙sdk

本插件只支持在安卓中使用

APP模块配置

manifest =》app模块配置 =》勾选Bluetooth(低功耗蓝牙) manifest =》app模块配置 =》勾选Geolocation(定位)

APP权限配置

勾选以下三个蓝牙权限

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="androidpermission.BLUETOOTH ADMIN"/>
<uses-permission android:name="android,permission.BLUETOOTH PRIVILEGED"/>

添加完成所有权限之后,打包自定义调试基座进行调试

初始化蓝牙sdk

<script>
    //引入sdk
    import bluetoothTool from '@/static/libs/BluetoothTool.js'

    export default {
        mounted() {
            let that = this;
            //#ifdef APP-PLUS
                // 蓝牙
                bluetoothTool.init({
                    listenBTStatusCallback: (state)=> { 
                        //蓝牙状态发生变化回调
                    },
                    discoveryDeviceCallback: (newDevice) => {
                         //查询蓝牙列表回调
                    },
                    discoveryFinishedCallback: function() { 
                        //搜索完成回调
                        that.msg = "搜索完成";
                    },
                    readDataCallback: function(dataByteArr) { 
                        //监听消息回调
                        // 结果里有个value值,该值为 ArrayBuffer 类型,所以在控制台无法用肉眼观察到,必须将该值转换为16进制
                        let resHex = that.ab2hex(dataByteArr)
                        // 最后将16进制转换为ascii码,就能看到对应的结果
                        let result = that.hexCharCodeToStr(resHex)
                        console.log(result)
                    },
                    connExceptionCallback: function(e) { 
                        //连接失败回调
                        console.log(e);
                        that.msg = "设备连接失败";
                    }
                });

            //#endif
        },
        methods: {
            // 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进制的内容转成我们看得懂的字符串内容
            hexCharCodeToStr(hexCharCodeStr) {
                var trimedStr = hexCharCodeStr.trim();
                var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
                var len = rawStr.length;
                if (len % 2 !== 0) {
                        alert("存在非法字符!");
                        return "";
                }
                var curCharCode;
                var resultStr = [];
                for (var i = 0; i < len; i = i + 2) {
                        curCharCode = parseInt(rawStr.substr(i, 2), 16);
                        resultStr.push(String.fromCharCode(curCharCode));
                }
                return resultStr.join("");
            },
        }
    }
</script>

搜索蓝牙

//注意,想要搜索蓝牙必须调起定位授权,让用户同意授权之后才可以执行;
 //调用之后会在init中的discoveryDeviceCallback进行监听
// 使用openBluetoothAdapter 接口,免去主动申请权限的麻烦
uni.openBluetoothAdapter({
    success(res) {
        that.devices = []
        console.log("打开 蓝牙模块,开始搜索模式...")
        console.log(res)
        bluetoothTool.discoveryNewDevice();                     
    }
})

停止搜索

uni.stopBluetoothDevicesDiscovery({
    success(res) {
        console.log(res)
    }
})

连接蓝牙

onConn(item) {
    console.log("连接蓝牙---------------" + item.address)
    bluetoothTool.connDevice(item.address,(result)=>{
        if(result) {
            uni.setStorageSync('lastBleAddress', item.address)
        }

        console.log('连接结果:',result)
    });
},

断开蓝牙

onClose() {
    bluetoothTool.disConnDevice()
},

获取已配对的蓝牙列表

onClose() {
    bluetoothTool.getPairedDevices()
},

发送数据

onClose() {
    bluetoothTool.sendData(dataStr)
},

全部代码

<template>
    <view>
        <button @click="searchBle">搜索蓝牙</button>
        <button @click="stopFindBule">停止搜索</button>
        <button @click="onClose">断开蓝牙</button>
        <view style="margin-top: 30upx;" :key="index" v-for="(item,index) in devices">
            <button style="width: 400upx; color: #0081FF;" @click="onConn(item)">{{item.name}}</button>
        </view>
    </view>

</template>

<script>
    import bluetoothTool from '@/static/libs/BluetoothTool.js'

    export default {
        data() {
            return {
                devices: [],
                connId: '',
                msg: ''
            }
        },
        watch:{
            msg(){
                uni.showToast({
                    title: this.msg
                })
            }
        },
        mounted() {
            let that = this;
            //#ifdef APP-PLUS
                // 蓝牙
                bluetoothTool.init({
                    listenBTStatusCallback: (state)=> { //蓝牙状态发生变化回调
                        console.log('state', state)
                        if(state == 'STATE_ON') {
                            let lastBleAddress = uni.getStorageSync('lastBleAddress')
                            if(lastBleAddress) {
                                uni.showLoading({
                                    title: '正在连接...'
                                })
                                console.log(lastBleAddress)
                                bluetoothTool.connDevice(lastBleAddress,(result)=>{
                                    uni.hideLoading()
                                    uni.showToast({
                                        title: result?'连接成功!':'连接失败...'
                                    });
                                })
                            }
                        }
                    },
                    discoveryDeviceCallback: this.onDevice, //查询蓝牙列表回调
                    discoveryFinishedCallback: function() { //搜索完成回调
                        that.msg = "搜索完成";
                    },
                    readDataCallback: function(dataByteArr) { //监听消息回调
                        // 结果里有个value值,该值为 ArrayBuffer 类型,所以在控制台无法用肉眼观察到,必须将该值转换为16进制
                        let resHex = that.ab2hex(dataByteArr)
                        // 最后将16进制转换为ascii码,就能看到对应的结果
                        let result = that.hexCharCodeToStr(resHex)
                        console.log(result)
                    },
                    connExceptionCallback: function(e) { //连接失败回调
                        console.log(e);
                        that.msg = "设备连接失败";
                    }
                });

            //#endif
        },
        methods: {
            destroyed: function() {
                console.log("destroyed----------")
                if (this.connId != '') {
                    uni.closeBLEConnection({
                        deviceId: this.connId,
                        success(res) {
                            console.log(res)
                        }
                    })
                }

            },
            searchBle() {
                var that = this
                console.log("initBule")
                if(uni.getAppAuthorizeSetting().locationAuthorized != 'authorized') {
                    uni.showToast({title: '请打开定位权限', icon: 'none'})
                    let timer = setTimeout(() => {
                        uni.openAppAuthorizeSetting()
                    }, 1000)
                } else {
                    // 使用openBluetoothAdapter 接口,免去主动申请权限的麻烦
                    uni.openBluetoothAdapter({
                        success(res) {
                            that.devices = []
                            console.log("打开 蓝牙模块,开始搜索模式...")
                            console.log(res)
                            bluetoothTool.discoveryNewDevice();
                            // that.onDevice()
                        }
                    })
                }

            },
            onDevice(newDevice){
                console.log("监听寻找到新设备的事件---------------")
                console.log(newDevice)
                if(newDevice.name && newDevice.name != 'null') {
                    this.devices.push({
                        name: newDevice.name,
                        address: newDevice.address
                    })
                }
            },
            stopFindBule() {
                console.log("停止搜寻附近的蓝牙外围设备---------------")
                uni.stopBluetoothDevicesDiscovery({
                    success(res) {
                        console.log(res)
                    }
                })
            },
            onConn(item) {
                console.log(item)
                console.log("连接蓝牙---------------" + item.address)

                bluetoothTool.connDevice(item.address,(result)=>{
                    if(result) {
                        uni.setStorageSync('lastBleAddress', item.address)
                    }

                    console.log('连接结果:',result)
                });
            },
            // 断开电子秤
            onClose() {
                bluetoothTool.disConnDevice()
                console.log(this.msgList)
            },

            // 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进制的内容转成我们看得懂的字符串内容
            hexCharCodeToStr(hexCharCodeStr) {
                var trimedStr = hexCharCodeStr.trim();
                var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
                var len = rawStr.length;
                if (len % 2 !== 0) {
                        alert("存在非法字符!");
                        return "";
                }
                var curCharCode;
                var resultStr = [];
                for (var i = 0; i < len; i = i + 2) {
                        curCharCode = parseInt(rawStr.substr(i, 2), 16);
                        resultStr.push(String.fromCharCode(curCharCode));
                }
                return resultStr.join("");
            },
        }
    }
</script>

<style>

</style>

隐私、权限声明

1. 本插件需要申请的系统权限列表:

蓝牙权限 定位权限 <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="androidpermission.BLUETOOTH ADMIN"/> <uses-permission android:name="android,permission.BLUETOOTH PRIVILEGED"/>

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

许可协议

MIT协议

使用中有什么不明白的地方,就向插件作者提问吧~ 我要提问