Uts 蓝牙连接(2)

2024-06-19  本文已影响0人  空腹无才

一、连接蓝牙步骤

二、案例

import BluetoothAdapter from "android.bluetooth.BluetoothAdapter";
import BluetoothGattCallback from "android.bluetooth.BluetoothGattCallback";
import BluetoothGatt from "android.bluetooth.BluetoothGatt"
import BluetoothProfile from 'android.bluetooth.BluetoothProfile';
import BluetoothDevice from "android.bluetooth.BluetoothDevice";
import UUID from 'java.util.UUID';
import BluetoothGattService from 'android.bluetooth.BluetoothGattService';
import BluetoothGattCharacteristic from 'android.bluetooth.BluetoothGattCharacteristic';
import Base64 from "android.util.Base64";

const serverUUID = "xxxxx-xxx-xxx-xx-xxxx";
const characteristicUUID = "xxxxxx-xxx-xxx-xx-xxxx"
const notifyCharacteristicUUID = "xxx-xxx-xxx-xx-xxxx"  // 有些设备 characteristicUUID 和notifyCharacteristicUUID 是一样的
// 蓝牙Gatt服务
let bluetoothGatt : BluetoothGatt | null = null;

function sendBle(deviceAddress: string) {
    // 获取设备对象
    let device = bluetoothAdapter?.getRemoteDevice(deviceAddress);
    if(bluetoothGatt == null) {
        // 连接蓝牙
        bluetoothGatt = (device as BluetoothDevice).connectGatt(UTSAndroid.getUniActivity(), false, new BCallback()) as BluetoothGatt;
    }
}

class BCallback extends BluetoothGattCallback {
    constructor() {super()};
    // 监听蓝牙连接状态
    override onConnectionStateChange(gatt : BluetoothGatt, status : Int, newState : Int) {
        if (newState == BluetoothProfile.STATE_CONNECTED.toInt()) {
            // 修改 MTU值
            bluetoothGatt?.requestMtu(512)
            // 获取蓝牙服务信息
            gatt.discoverServices();
        }else if (newState == BluetoothProfile.STATE_DISCONNECTED.toInt()) {
            // 连接失败
            clearConnect();
        }   
    }
    
    // 获取服务、特征
    override onServicesDiscovered(gatt : BluetoothGatt, status : Int) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            // 找到服
            const service:BluetoothGattService | null  = gatt.getService(UUID.fromString(serverUUID)) as BluetoothGattService;
            if (service !== null) {
                // 找到获取特征
                const characteristic = (service as BluetoothGattService).getCharacteristic(UUID.fromString(characteristicUUID));
                const notifyCharacteristic = (service as BluetoothGattService).getCharacteristic(UUID.fromString(notifyCharacteristicUUID))
                if (characteristic !== null) {
                    //  启动 notify
                    gatt.setCharacteristicNotification(notifyCharacteristic, true);
                    // 写入信息
                    this.writeData(gatt, characteristic as BluetoothGattCharacteristic)
                }  else {
                    gatt.disconnect();
                }
            } else {
                gatt.disconnect();
            }
        } else {
            // 断开连接
            gatt.disconnect();
        }
    }
    
    // 处理特征值写入事件
    override onCharacteristicWrite(gatt : BluetoothGatt, characteristic : BluetoothGattCharacteristic, status : Int) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            // 写入成功
        } else {
            // 写入失败
        }
    }
    
    // 监听低功率蓝牙设备回调
    override onCharacteristicChanged(gatt : BluetoothGatt, characteristic : BluetoothGattCharacteristic) {
        // 处理回调信息
        const data = characteristic.getValue();
        const base64String = Base64.encodeToString(data, Base64.DEFAULT);
        // 现在base64String是Base64编码的字符串
        const originalString = String(Base64.decode(base64String, Base64.DEFAULT), Charsets.UTF_8);
        
        //其他操作
        // ...
        gatt.disconnect()
    }
    
    // 处理写入事件
    writeData(gatt : BluetoothGatt, characteristic : BluetoothGattCharacteristic) {
        // 将传输内容转换成字节
        const bytes = ("12345").toByteArray(Charsets.UTF_8);
        if (this.canWrite(characteristic)) {
            characteristic.setValue(bytes);
            gatt.writeCharacteristic(characteristic);
        } else {
            // 蓝牙设备不支持写入
            gatt.disconnect()
        }
    }
    
    private canWrite(characteristic : BluetoothGattCharacteristic) : Boolean {
        const writeType = characteristic.getWriteType();
        return writeType == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE || writeType == BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT;
    }
}

// 清理蓝牙连接服务
function clearConnect() {
    if(bluetoothGatt !== null) {
        (bluetoothGatt as BluetoothGatt).close();
        bluetoothGatt = null;
        console.log("清空蓝牙信息")
    }
}
上一篇下一篇

猜你喜欢

热点阅读