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

发布于 1周前 作者 songsunli 来自 Uni-App

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

代码示例

JavaScript 代码

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) {  
                    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);  
            } 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);  
},  

//判断蓝牙打开状态  
bluetoothStatus() {  
    var that = this;  
    const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter');  
    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;  
            }  

            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'  
                })  
            }  

            that.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');  
                const blueadapter = BluetoothAdapter.getDefaultAdapter();  
                if (blueadapter != null) {  
                    that.bluetooth = 0;  
                    that.backgroundColor = "#8A2BCF";  
                    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');  
                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);  
                    } else {  
                        console.log('GPS功能已开启');  
                    }  
                }  
            });  
            return false  
        } else {  
            console.log('GPS功能已开启');  
            that.searchDevices()  
            return true  
        }  
    }  
},  

//搜索蓝牙  
searchDevices() {  
    var that = this;  
    that.unpairedList = [];  

    uni.openBluetoothAdapter({  
        success(res) {  
            uni.getBluetoothAdapterState({  
                success: function(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 filter = new IntentFilter();  
                                var bdevice = new BluetoothDevice();  
                                BAdapter.startDiscovery();  
                                var receiver;  
                                receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {  
                                    onReceive: function(context, intent) {  
                                        plus.android.importClass(intent);  
                                        if (intent.getAction() == "android.bluetooth.adapter.action.DISCOVERY_FINISHED") {  
                                            main.unregisterReceiver(receiver);  
                                            console.log("搜索结束");  
                                            console.log(that.unpairedList);  
                                            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) {  
    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");  
    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());  
        if (mac_address == device.getAddress()) {  
            if (device.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)  
            }  
        }  
    }  
},  

开发环境与版本信息

项目创建方式 版本号

1 回复

在uni-app中实现经典蓝牙串口通信,通常需要依赖原生插件或SDK,因为uni-app本身是基于Vue.js的多端开发框架,不直接支持底层的蓝牙操作。以下是一个基本的思路和代码案例,展示如何在uni-app中集成并使用经典蓝牙串口通信。

步骤一:创建原生插件

由于uni-app需要通过原生插件来访问蓝牙功能,你需要首先创建一个原生插件。这里以Android为例,创建一个插件用于蓝牙串口通信。

Android原生插件代码示例(BluetoothSerialPlugin.java)

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.util.Log;

import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;

public class BluetoothSerialPlugin implements WXModule {
    // 省略了详细的蓝牙连接、读写等方法实现
    
    @JSMethod(uiThread = true)
    public void connectDevice(String address, JSCallback callback) {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
        
        try {
            BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
            socket.connect();
            callback.invoke("Connected");
        } catch (Exception e) {
            callback.invoke("Failed: " + e.getMessage());
        }
    }
    
    // 其他蓝牙操作如读写、关闭连接等类似实现
}

步骤二:在uni-app中调用原生插件

在uni-app项目中,你需要配置并调用这个原生插件。

manifest.json配置

"nativePlugins": [
    {
        "plugins": {
            "BluetoothSerialPlugin": {
                "package": "com.example.bluetoothserialplugin",
                "provider": "BluetoothSerialPlugin"
            }
        }
    }
]

在Vue组件中调用插件

export default {
    methods: {
        connectBluetooth() {
            const deviceAddress = 'XX:XX:XX:XX:XX:XX'; // 替换为实际设备地址
            uni.requireNativePlugin('BluetoothSerialPlugin').connectDevice(
                deviceAddress,
                (result) => {
                    console.log(result); // 处理连接结果
                }
            );
        }
    }
}

注意事项

  1. 权限配置:确保在AndroidManifest.xml中配置了蓝牙相关权限。
  2. UUIDMY_UUID需要替换为实际的蓝牙服务UUID。
  3. 错误处理:在实际应用中,应添加更完善的错误处理和重连机制。
  4. iOS支持:iOS平台需要类似地实现原生插件,但由于iOS的蓝牙API与Android不同,实现细节会有所差异。

上述代码仅提供了一个基本框架,实际项目中需要根据具体需求进行扩展和完善。

回到顶部