徐州老铁
徐州老铁
  • 发布:2024-07-04 08:52
  • 更新:2025-01-02 18:02
  • 阅读:2870

uni-app使用经典蓝牙串口通信方案

分类:uni-app


    data() {  
            return {  
                bluetooth: 1, //1:打开蓝牙  2:关闭蓝牙  
                turnOnBluetooth: "打开蓝牙", //打开蓝牙  
                turnOffBluetooth: "关闭蓝牙", //关闭蓝牙  
                backgroundColor: "#cecece", //搜索蓝牙按钮背景颜色  

                title: 'Hello',  
                searchLoadingTxt: '',  
                isBlueOk: false,  
                bluetimestoper: null,  
                startchecktimer: null,  
                timeoutOfBlueScanFailure30s: 300000,  
                baseList: [],  
                bluetoothIndex: [],  
                targetDeviceName: '',  
                _deviceId: '', //蓝牙deviceId  
                pairedList: [], //已配对蓝牙  
                pairedLists: [], //已配对蓝牙集合  
                pairedHeight: 0, //已配对蓝牙显示高度  
                unpairedList: [], //未配对蓝牙  
                unpairedHeight: 0, //未配对蓝牙显示高度  
                bluetoothSocket: {},  
            }  
        }  

            //删除已配对设备  
            removePaire(index) {  
                var that = this;  
                uni.showModal({  
                    title: "提示",  
                    content: "是否删除设备",  
                    showCancel: true,  
                    cancelText: "取消",  
                    confirmText: "确定",  
                    success(res) {  
                        // 确定删除设备  
                        if (res.confirm) {  
                            var address = uni.getStorageSync("printerSelected").address;  
                            console.log("已选中蓝牙地址:" + address + " 删除蓝牙地址:" + that.pairedList[index].address);  
                            if (that.pairedList[index].address == address) {  
                                // that.pairedList[0].isSelected=1;  
                                uni.setStorageSync("printerSelected", "");  
                            }  
                            for (var i = 0; i < that.pairedLists.length; i++) {  
                                if (that.pairedLists[i].getAddress() == that.pairedList[index].address) {  
                                    that.pairedLists[i].removeBond();  
                                }  
                            }  
                            that.pairedList.splice(index, 1);  
                            //存储打印机  
                            // uni.setStorageSync("pairedList",that.pairedList);  
                        } else {  
                            console.log("取消删除设备");  
                        }  
                    }  
                })  
                return false;  
            },  

            //设置已选中蓝牙  
            setSelectedPaired(paired) {  
                console.log('paired', paired)  
                var that = this;  
                for (var i = 0; i < that.pairedList.length; i++) {  
                    if (that.pairedList[i].address == paired.address) {  
                        that.pairedList[i].isSelected = 1;  
                    } else {  
                        that.pairedList[i].isSelected = 0;  
                    }  
                }  
                uni.showLoading({  
                    title:'正在建立连接'  
                })  
                uni.navigateTo({  
                    url:`detail?name=${paired.name}&address=${paired.address}`  
                })  

                paired.isSelected = 1;  
                //存储已选择打印机  
                uni.setStorageSync("printerSelected", paired);  
                //存储打印机  
                // uni.setStorageSync("pairedList",that.pairedList);  
            },  

            //判断蓝牙打开状态  
            bluetoothStatus() {  
                var that = this;  
                const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类  
                const blueadapter = BluetoothAdapter.getDefaultAdapter(); //拿到默认蓝牙适配器方法  
                if (blueadapter) {  
                    // 判断蓝牙是否开启  
                    if (blueadapter.isEnabled()) {  
                        // 开启  
                        that.bluetooth = 0;  
                        that.backgroundColor = "red";  

                        var yilianjie = uni.getStorageSync("printerSelected");  
                        var selectAddress = "";  
                        if (yilianjie) {  
                            selectAddress = yilianjie.address;  
                        }  
                        // console.log("已选中地址:"+selectAddress);  

                        //获取手机已配对蓝牙  
                        var lists = blueadapter.getBondedDevices();  
                        plus.android.importClass(lists);  
                        var iterator = lists.iterator();  
                        plus.android.importClass(iterator);  
                        while (iterator.hasNext()) {  
                            var device = iterator.next();  
                            that.pairedLists.push(device);  

                            plus.android.importClass(device);  
                            that.pairedList.push({  
                                name: device.getName(),  
                                address: device.getAddress(),  
                                isSelected: selectAddress == device.getAddress() ? '1' : '0'  
                            })  
                            // console.log(device.getName()+" ###########  "+ device.getAddress());  
                        }  

                        //显示存储的已配对蓝牙  
                        // this.pairedList = uni.getStorageSync("pairedList");  
                    } else {  
                        // 关闭  
                        this.bluetooth = 1;  
                        this.backgroundColor = "#cecece";  
                        this.pairedList = [];  
                    }  
                    this.unpairedList = [];  
                }  
            },  

            //打开蓝牙  
            openBluetooth() {  
                var that = this;  
                // 弹出提示框  
                uni.showModal({  
                    title: "提示",  
                    content: "蓝牙尚未打开,是否打开蓝牙",  
                    showCancel: true,  
                    cancelText: "取消",  
                    confirmText: "确定",  
                    success(res) {  
                        // 点击确定后通过系统打开蓝牙  
                        if (res.confirm) {  
                            const BluetoothAdapter = plus.android.importClass(  
                            'android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类  
                            const blueadapter = BluetoothAdapter.getDefaultAdapter();  
                            if (blueadapter != null) {  
                                that.bluetooth = 0;  
                                that.backgroundColor = "#8A2BCF";  
                                //显示存储的已配对蓝牙  
                                // that.pairedList = uni.getStorageSync("pairedList");  
                                blueadapter.enable();  

                                setTimeout(function() {  
                                    that.bluetoothStatus();  
                                }, 2000)  
                            }  
                        } else {  
                            // 点击取消什么也不做  
                            console.log("取消打开蓝牙");  
                        }  
                    }  
                })  
            },  

            //关闭蓝牙  
            closeBluetooth() {  
                var that = this;  
                // 弹出提示框  
                uni.showModal({  
                    title: "提示",  
                    content: "蓝牙已打开,是否关闭蓝牙",  
                    showCancel: true,  
                    cancelText: "取消",  
                    confirmText: "确定",  
                    success(res) {  
                        // 点击确定后通过系统打开蓝牙  
                        if (res.confirm) {  
                            const BluetoothAdapter = plus.android.importClass(  
                            'android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类  
                            const blueadapter = BluetoothAdapter.getDefaultAdapter();  
                            if (blueadapter != null) {  
                                that.bluetooth = 1;  
                                that.backgroundColor = "#cecece";  
                                that.pairedList = [];  
                                that.unpairedList = [];  
                                uni.setStorageSync("printerSelected", "");  
                                return blueadapter.disable();  
                            }  
                        } else {  
                            // 点击取消什么也不做  
                            console.log("取消关闭蓝牙");  
                        }  
                    }  
                })  
            },  

            //点击打开/关闭蓝牙按钮  
            blueTooth() {  
                if (this.bluetooth == 1) {  
                    console.log("打开蓝牙");  
                    this.openBluetooth();  
                } else {  
                    console.log("关闭蓝牙");  
                    this.closeBluetooth();  
                }  
            },  

            //初始化蓝牙模块  
            openBluetoothAdapter() {  
                //未打开蓝牙点击搜索蓝牙提示弹窗  
                if (this.bluetooth == 1) {  
                    uni.showToast({  
                        title: "请先打开蓝牙",  
                        icon: "error"  
                    })  
                    return;  
                }  
                let system = uni.getSystemInfoSync(); // 获取系统信息  
                if (system.platform === 'android') { // 判断平台  
                    var that = this;  
                    var context = plus.android.importClass("android.content.Context");  
                    var locationManager = plus.android.importClass("android.location.LocationManager");  
                    var main = plus.android.runtimeMainActivity();  
                    var mainSvr = main.getSystemService(context.LOCATION_SERVICE);  
                    // 定位检测  
                    if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {  
                        uni.showModal({  
                            title: "提示",  
                            content: "请打开定位服务功能",  
                            showCancel: false, // 不显示取消按钮  
                            success() {  
                                if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {  
                                    var Intent = plus.android.importClass('android.content.Intent');  
                                    var Settings = plus.android.importClass('android.provider.Settings');  
                                    var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
                                    main.startActivity(intent); // 打开系统设置GPS服务页面  
                                } else {  
                                    console.log('GPS功能已开启');  
                                }  
                            }  
                        });  
                        return false  
                    } else {  
                        console.log('GPS功能已开启');  
                        that.searchDevices()  
                        return true  
                    }  
                }  
            },  

            //搜索蓝牙  
            searchDevices() {  
                var that = this;  
                that.unpairedList = []; //未配对  
                // that.pairedList = [];    //已配对  

                //取内存里面已配对的蓝牙  
                // that.pairedList = uni.getStorageSync("pairedList");  

                //打开蓝牙模块  
                uni.openBluetoothAdapter({  
                    success(res) {  
                        console.log("蓝牙模块:", res);  
                        //获取本机蓝牙适配器状态  
                        uni.getBluetoothAdapterState({  
                            success: function(res) {  
                                console.log("蓝牙适配器状态:", res);  
                                if (res.available) {  
                                    //开始搜寻附近的蓝牙外围设备  
                                    uni.startBluetoothDevicesDiscovery({  
                                        success(res) {  
                                            var main = plus.android.runtimeMainActivity();  
                                            var IntentFilter = plus.android.importClass(  
                                                'android.content.IntentFilter');  
                                            var BluetoothAdapter = plus.android.importClass(  
                                                "android.bluetooth.BluetoothAdapter");  
                                            var BluetoothDevice = plus.android.importClass(  
                                                "android.bluetooth.BluetoothDevice");  
                                            var BAdapter = BluetoothAdapter  
                                        .getDefaultAdapter();  

                                            if (BAdapter != null && !BAdapter.isEnabled()) {  
                                                let _intent = plus.android.importClass(  
                                                    'android.content.Intent');  
                                                let intent = new _intent(blue_client  
                                                    .ACTION_REQUEST_ENABLE);  
                                                main.startActivityForResult(intent, 200);  
                                            }  

                                            uni.showLoading({  
                                                title: "开始搜索设备",  
                                            })  

                                            //获取本机蓝牙信息  
                                            // var name = BAdapter.getName();  
                                            // var address = BAdapter.getAddress();  
                                            // console.log("本机蓝牙名称:"+name+" 本机蓝牙地址:"+address);  

                                            var filter = new IntentFilter();  
                                            var bdevice = new BluetoothDevice();  
                                            BAdapter.startDiscovery(); //开启搜索    
                                            var receiver;  
                                            receiver = plus.android.implements(  
                                                'io.dcloud.android.content.BroadcastReceiver', {  
                                                    onReceive: function(context,  
                                                    intent) { //实现onReceiver回调函数    
                                                        plus.android.importClass(  
                                                            intent); //通过intent实例引入intent类,方便以后的‘.’操作  
                                                        if (intent.getAction() ==  
                                                            "android.bluetooth.adapter.action.DISCOVERY_FINISHED"  
                                                            ) {  
                                                            main.unregisterReceiver(  
                                                                receiver); //取消监听  

                                                            console.log("搜索结束");  
                                                            console.log(that  
                                                                .unpairedList);  
                                                            // console.log(that.pairedList);  
                                                            //把已配对的蓝牙存内存  
                                                            // uni.setStorageSync("pairedList",that.pairedList);  
                                                            uni.hideLoading();  
                                                        } else {  
                                                            if (intent  
                                                                .getParcelableExtra(  
                                                                    BluetoothDevice  
                                                                    .EXTRA_DEVICE)  
                                                                .getBondState() === 10  
                                                                ) {  
                                                                var y = 0;  
                                                                for (let x = 0; x <  
                                                                    that.unpairedList  
                                                                    .length; x++) {  
                                                                    if (that  
                                                                        .unpairedList[  
                                                                            x]  
                                                                        .address ==  
                                                                        intent  
                                                                        .getParcelableExtra(  
                                                                            BluetoothDevice  
                                                                            .EXTRA_DEVICE  
                                                                            )  
                                                                        .getAddress()  
                                                                        ) {  
                                                                        y++;  
                                                                    }  
                                                                }  
                                                                if (y > 0) {  
                                                                    y = 0;  
                                                                } else {  
                                                                    that.unpairedList  
                                                                        .push({  
                                                                            name: intent  
                                                                                .getParcelableExtra(  
                                                                                    BluetoothDevice  
                                                                                    .EXTRA_DEVICE  
                                                                                    )  
                                                                                .getName(),  
                                                                            address: intent  
                                                                                .getParcelableExtra(  
                                                                                    BluetoothDevice  
                                                                                    .EXTRA_DEVICE  
                                                                                    )  
                                                                                .getAddress()  
                                                                        })  
                                                                }  
                                                            }  

                                                        }  
                                                    }  
                                                });  
                                            filter.addAction(bdevice.ACTION_FOUND);  
                                            filter.addAction(BAdapter  
                                            .ACTION_DISCOVERY_STARTED);  
                                            filter.addAction(BAdapter  
                                                .ACTION_DISCOVERY_FINISHED);  
                                            filter.addAction(BAdapter.ACTION_STATE_CHANGED);  
                                            main.registerReceiver(receiver, filter); //注册监听  
                                        }  
                                    })  
                                }  
                            },  
                        })  
                    }  
                })  
            },  

            //建立连接  
            createBLEConnection(mac_address) {  
                // mac_address为获取到蓝牙数据中的address字段  
                var main = plus.android.runtimeMainActivity();  
                var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");  
                var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");  
                var UUID = plus.android.importClass("java.util.UUID");  
                var uuid = UUID.fromString("00001101-0000-1000-8000-00805f9B34FB");  
                // this.bluetoothSocket = BluetoothDevice.createRfcommSocketToServiceRecord(uuid)  
                // console.log('bluetoothSocket',this.bluetoothSocket)  
                var BAdapter = BluetoothAdapter.getDefaultAdapter();  
                var device = BAdapter.getRemoteDevice(mac_address);  
                plus.android.importClass(device);  
                var bdevice = new BluetoothDevice();  
                var that = this;  
                //判断是否配对    
                if (device.getBondState() == bdevice.BOND_NONE) {  
                    console.log("未配对蓝牙设备:" + device.getName() + '    ' + device.getAddress());  
                    //参数如果跟取得的mac地址一样就配对    
                    if (mac_address == device.getAddress()) {  
                        // console.log("111")  
                        if (device.createBond()) { //配对命令.createBond()   
                            console.log("配对成功")  
                            var cha = setInterval(function() {  
                                if (device.getBondState() == bdevice.BOND_BONDED) {  
                                    clearInterval(cha);  
                                    //删除未配对蓝牙,添加到已配对  
                                    for (var i = 0; i < that.unpairedList.length; i++) {  
                                        if (that.unpairedList[i].address == mac_address) {  
                                            that.pairedList.push(that.unpairedList[i]);  
                                            that.unpairedList.splice(i, 1);  
                                            break;  
                                        }  
                                    }  
                                }  
                            }, 1000)  
                        }  
                    }  
                }  
            },  
        },  
0 关注 分享

要回复文章请先登录注册

eyesky

eyesky

回复 徐州老铁 :
这个接收数据 有处理好吗
2025-01-02 18:02
7***@qq.com

7***@qq.com

大佬这个只适用于安卓吗
2024-10-23 10:25
徐州老铁

徐州老铁 (作者)

我目前的问题是,接收设备发送的数据的时候,使用inputStream.read()方法,每次只能读取一个字节,然后拼起来,速度太慢,查看官方文档https://developer.android.google.cn/reference/java/io/InputStream 发现public int read (byte[] b, int off, int len),然而这是java的写法,在js中未找到解决方案,不知道各位有没有思路
2024-07-04 08:58
徐州老铁

徐州老铁 (作者)

```点击配对列表之后,进入详情页
<template>
<view class="content">
<view class="">
设备名称:{{name}}
</view>
<view class="">
设备ID:{{address}}
</view>
<view class="ssinput">
<view class="flex">
<!-- <button size="default" type="primary" style="margin: 10px auto;" @click="Auth()">认证</button> -->
<button size="default" type="primary" style="margin: 10px auto;" @click="getList()">请求文件列表</button>
<view class="">
起始分包号:<input style="width: 200px;height: 40px;border: solid 1px #eee;margin: 10px 0;padding:0 10px"
type="number" placeholder="起始分包号" v-model="start" />
</view>

<button size="default" type="primary" style="margin: 10px auto;" @click="stop()">停止文件传输</button>
</view>
<view class="list" v-for="(item,index) in fileList" @click="getContent(item.lsh,item.fbh,item.fileName)">
<view class="">
文件名:{{item.fileName}}
</view>
<view class="">
文件大小:{{item.fileSize}}
</view>
<view class="">
分包号:{{item.fbh}}
</view>
<view class="">
流水号:{{item.lsh}}
</view>

</view>


</view>

</view>
</template>

<script>
export default {
data() {
return {
start: 1,
sendMessage: '',
resultMessage: '',
name: '',
address: '',
device: null,
bluetoothSocket: {},
fileList: []

};
},
onLoad(e) {
this.name = e.name
this.address = e.address
this.creatSocket(e.address)


},
onBackPress() {
console.log('断开socket')
this.device = null //这里关键
this.bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误
},
methods: {
creatSocket(mac_address) {

let main = plus.android.runtimeMainActivity();
let BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
let UUID = plus.android.importClass("java.util.UUID");
let uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
let BAdapter = BluetoothAdapter.getDefaultAdapter();
this.device = BAdapter.getRemoteDevice(mac_address);
plus.android.importClass(this.device);
//createRfcommSocketToServiceRecord 需要配对
//createInsecureRfcommSocketToServiceRecord 不需要配对
this.bluetoothSocket = this.device.createInsecureRfcommSocketToServiceRecord(uuid);
plus.android.importClass(this.bluetoothSocket);


if (!this.bluetoothSocket.isConnected()) {
console.log('检测到设备未连接,尝试连接....');
this.bluetoothSocket.connect();
uni.hideLoading()

}


},

//请求文件列表
getList() {
console.log('请求文件列表')
let that = this
uni.request({
url: `http://192.168.1.118:6034/down_stream/requestFileList`,
success(result) {
console.log('result', result.data.response)
let byte = that.hexStringToByteArray(result.data.response);
console.log('byte', byte)
if (that.bluetoothSocket.isConnected()) {
console.log('已连接')
let inputStream = that.bluetoothSocket.getInputStream(); //接收指令
let outputStream = that.bluetoothSocket.getOutputStream(); //发送指令
plus.android.importClass(inputStream);
plus.android.importClass(outputStream);
console.log('写入数据', [0x23, 0x23, 0x02, 0x00, 0x00, 0x02]);
outputStream.write(byte)
outputStream.flush()
uni.showLoading({
title: '正在拉取文件列表'
})
let invoke = plus.android.invoke;
var str = ''
let i = 0
while (true) {
console.log('begin read')
try {
var buffer = new ArrayBuffer(10);

// 创建一个Uint8Array视图来操作这个ArrayBuffer
var data = new Uint8Array(buffer);
console.log('data',data)

var aaaa = inputStream.read([data])
// i+=10
// console.log('inputStream.available() : ', inputStream.available())
// console.log('aaa exist : ', aaaa)
// console.log('aaaa', aaaa.toString(16));
str += aaaa.toString(16).padStart(2, 0)
// console.log('str:',str)
if (inputStream.available() === 0) break

} catch (e) {
console.log('read error : ', e)
//TODO handle the exception
}

}

that.resultMessage = str
uni.hideLoading()
uni.request({
url: `http://192.168.1.118:6034/down_stream/getFileList?contentBytes=${str}`,
success(result) {
console.log('result', result)
that.fileList = result.data.response

}
})
}
}
})



},

hexStringToByteArray(hexString) {
var result = [];
for (var i = 0; i < hexString.length; i += 2) {
result.push(parseInt(hexString.substr(i, 2), 16));
}
return result;
},
//请求文件内容
getContent(lsh, fbh, name) {
let that = this
uni.request({
url: `http://192.168.1.118:6034/down_stream/requestFile?lsh=${lsh}&fileName=${name}&fbh=${fbh}`,
success(result) {
console.log('result', result.data.response)
// var MainActivity = plus.android.runtimeMainActivity();
// var BluetoothClass = plus.android.importClass("com.example.bluetooth.BluetoothClass");
// var bluetoothInstance = new BluetoothClass(MainActivity);
var byteArray = that.hexStringToByteArray(result.data.response);
console.log('byteArray', byteArray)
// 调用原生方法
//plus.android.invoke(bluetoothInstance, "sendData", byteArray);

if (that.bluetoothSocket.isConnected()) {
console.log('已连接')
let inputStream = that.bluetoothSocket.getInputStream(); //接收指令
let outputStream = that.bluetoothSocket.getOutputStream(); //发送指令
plus.android.importClass(inputStream);
plus.android.importClass(outputStream);
console.log('请求文件');
uni.showLoading({
title: '正在下载文件'
})
outputStream.write(byteArray)
outputStream.flush()
var text = ''
while (true) {
try {
var aaaa = inputStream.read()
text += aaaa.toString(16).padStart(2, 0)
//console.log('str:',str)
if (inputStream.available() === 0) break


} catch (e) {
console.log('read error : ', e)
//TODO handle the exception
}

}
uni.hideLoading()
console.log('下载完成');


}

}
})
},
//停止文件传输
stop() {
let bytes = this.stringTobuffer('2323') //指令
if (this.bluetoothSocket.isConnected()) {
let inputStream = this.bluetoothSocket.getInputStream(); //接收指令
let outputStream = this.bluetoothSocket.getOutputStream(); //发送指令
plus.android.importClass(inputStream);
plus.android.importClass(outputStream);
console.log('bytes', bytes)
outputStream.write(bytes)
let invoke = plus.android.invoke;
while (invoke(inputStream, "available") !== 0) {
let data = invoke(this.inputStream, "read");
this.resultMessage = data; // 不阻塞
console.log('this.resultMessage', this.resultMessage);
}
}
},

}
}
</script>

<style lang="scss">
.content {
padding: 15px;
}

.list {
border: solid 1px #eee;
padding: 10px;
margin: 5px 0;
border-radius: 6px;
}
</style>
2024-07-04 08:53