Files
akbleserver/uni_modules/ak-sbsrv/utssdk/app-android/index.uts
2026-03-16 10:37:46 +08:00

111 lines
5.5 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import * as BluetoothManager from './bluetooth_manager.uts';
import { ServiceManager } from './service_manager.uts';
import type { ScanDevicesOptions, BleConnectOptionsExt, MultiProtocolDevice, BleEvent, BleEventCallback, BleService, BleCharacteristic, WriteCharacteristicOptions, AutoBleInterfaces, BleDataReceivedCallback } from '../interface.uts';
import { DeviceManager } from './device_manager.uts';
const serviceManager = ServiceManager.getInstance();
export class BluetoothService {
scanDevices(options?: ScanDevicesOptions) { return BluetoothManager.scanDevices(options); }
connectDevice(deviceId: string, protocol: string, options?: BleConnectOptionsExt) { return BluetoothManager.connectDevice(deviceId, protocol, options); }
disconnectDevice(deviceId: string, protocol: string) { return BluetoothManager.disconnectDevice(deviceId, protocol); }
getConnectedDevices(): MultiProtocolDevice[] { return BluetoothManager.getConnectedDevices(); }
on(event: BleEvent, callback: BleEventCallback) { return BluetoothManager.on(event, callback); }
off(event: BleEvent, callback?: BleEventCallback) { return BluetoothManager.off(event, callback); }
getServices(deviceId: string): Promise<BleService[]> {
return new Promise((resolve, reject) => {
serviceManager.getServices(deviceId, (list, err) => {
console.log('getServices:', list, err); // 新增日志
if (err != null) reject(err);
else resolve((list as BleService[]) ?? []);
});
});
}
getCharacteristics(deviceId: string, serviceId: string): Promise<BleCharacteristic[]> {
return new Promise((resolve, reject) => {
console.log(deviceId,serviceId)
serviceManager.getCharacteristics(deviceId, serviceId, (list, err) => {
if (err != null) reject(err);
else resolve((list as BleCharacteristic[]) ?? []);
});
});
}
/**
* 自动发现服务和特征返回可用的写入和通知特征ID
* @param deviceId 设备ID
* @returns {Promise<AutoBleInterfaces>}
*/
async getAutoBleInterfaces(deviceId: string): Promise<AutoBleInterfaces> {
// 1. 获取服务列表
const services = await this.getServices(deviceId);
if (services == null || services.length == 0) throw new Error('未发现服务');
// 2. 选择目标服务优先bae前缀可根据需要调整
let serviceId = '';
for (let i = 0; i < services.length; i++) {
const s = services[i];
const uuidCandidate: string | null = (s.uuid != null ? s.uuid : null)
const uuid: string = uuidCandidate != null ? uuidCandidate : ''
// prefer regex test to avoid nullable receiver calls in generated Kotlin
if (/^bae/i.test(uuid)) {
serviceId = uuid
break;
}
}
console.log(serviceId)
if (serviceId == null || serviceId == '') serviceId = services[0].uuid;
// 3. 获取特征列表
const characteristics = await this.getCharacteristics(deviceId, serviceId);
console.log(characteristics)
if (characteristics == null || characteristics.length == 0) throw new Error('未发现特征值');
// 4. 筛选write和notify特征
let writeCharId = '';
let notifyCharId = '';
for (let i = 0; i < characteristics.length; i++) {
const c = characteristics[i];
console.log(c)
if ((writeCharId == null || writeCharId == '') && c.properties != null && (c.properties.write || c.properties.writeWithoutResponse==true)) writeCharId = c.uuid;
if ((notifyCharId == null || notifyCharId == '') && c.properties != null && (c.properties.notify || c.properties.indicate)) notifyCharId = c.uuid;
}
console.log(serviceId, writeCharId, notifyCharId);
if ((writeCharId == null || writeCharId == '') || (notifyCharId == null || notifyCharId == '')) throw new Error('未找到合适的写入或通知特征');
console.log(serviceId, writeCharId, notifyCharId);
// // 发现服务和特征后
const deviceManager = DeviceManager.getInstance();
console.log(deviceManager);
const device = deviceManager.getDevice(deviceId);
console.log(deviceId,device)
device!.serviceId = serviceId;
device!.writeCharId = writeCharId;
device!.notifyCharId = notifyCharId;
console.log(device);
return { serviceId, writeCharId, notifyCharId };
}
async subscribeCharacteristic(deviceId: string, serviceId: string, characteristicId: string, onData: BleDataReceivedCallback): Promise<void> {
return serviceManager.subscribeCharacteristic(deviceId, serviceId, characteristicId, onData);
}
async readCharacteristic(deviceId: string, serviceId: string, characteristicId: string): Promise<ArrayBuffer> {
return serviceManager.readCharacteristic(deviceId, serviceId, characteristicId);
}
async writeCharacteristic(deviceId: string, serviceId: string, characteristicId: string, data: Uint8Array, options?: WriteCharacteristicOptions): Promise<boolean> {
return serviceManager.writeCharacteristic(deviceId, serviceId, characteristicId, data, options);
}
async unsubscribeCharacteristic(deviceId: string, serviceId: string, characteristicId: string): Promise<void> {
return serviceManager.unsubscribeCharacteristic(deviceId, serviceId, characteristicId);
}
async autoDiscoverAll(deviceId: string): Promise<any> {
return serviceManager.autoDiscoverAll(deviceId);
}
async subscribeAllNotifications(deviceId: string, onData: BleDataReceivedCallback): Promise<void> {
return serviceManager.subscribeAllNotifications(deviceId, onData);
}
}
export const bluetoothService = new BluetoothService();
// Ensure protocol handlers are registered when this module is imported.
// import './protocol_registry.uts';