Initial commit of akmon project

This commit is contained in:
2026-01-20 08:04:15 +08:00
commit 77a2bab985
1309 changed files with 343305 additions and 0 deletions

View File

@@ -0,0 +1,286 @@
import type {
BleDevice,
BleConnectionState,
BleEvent,
BleEventCallback,
BleEventPayload,
BleConnectOptionsExt,
AutoBleInterfaces,
BleDataPayload,
SendDataPayload,
BleOptions,
MultiProtocolDevice,
BleProtocolType,
ScanDevicesOptions
} from '../interface.uts';
import { ProtocolHandler } from '../protocol_handler.uts';
import { BluetoothService } from '../interface.uts';
import { DeviceManager } from './device_manager.uts';
type RawProtocolHandler = {
protocol?: BleProtocolType;
scanDevices?: (options?: ScanDevicesOptions) => Promise<void>;
connect?: (device: BleDevice, options?: BleConnectOptionsExt) => Promise<void>;
disconnect?: (device: BleDevice) => Promise<void>;
sendData?: (device: BleDevice, payload?: SendDataPayload, options?: BleOptions) => Promise<void>;
autoConnect?: (device: BleDevice, options?: BleConnectOptionsExt) => Promise<AutoBleInterfaces>;
}
class DeviceContext {
device: BleDevice;
protocol: BleProtocolType;
state: BleConnectionState;
handler: ProtocolHandler;
constructor(device: BleDevice, protocol: BleProtocolType, handler: ProtocolHandler) {
this.device = device;
this.protocol = protocol;
this.state = 0;
this.handler = handler;
}
}
const deviceMap = new Map<string, DeviceContext>();
let activeProtocol: BleProtocolType = 'standard';
let activeHandler: ProtocolHandler | null = null;
const eventListeners = new Map<BleEvent, Set<BleEventCallback>>();
let defaultBluetoothService: BluetoothService | null = null;
let connectionHooked = false;
function emit(event: BleEvent, payload: BleEventPayload) {
const listeners = eventListeners.get(event);
if (listeners != null) {
listeners.forEach(cb => {
try { cb(payload); } catch (e) { }
});
}
}
class ProtocolHandlerWrapper extends ProtocolHandler {
private _raw: RawProtocolHandler | null;
constructor(raw?: RawProtocolHandler, bluetoothService?: BluetoothService) {
super(bluetoothService);
this._raw = raw ?? null;
}
override async scanDevices(options?: ScanDevicesOptions): Promise<void> {
const rawTyped = this._raw;
if (rawTyped != null && typeof rawTyped.scanDevices == 'function') {
await rawTyped.scanDevices(options);
}
return;
}
override async connect(device: BleDevice, options?: BleConnectOptionsExt): Promise<void> {
const rawTyped = this._raw;
if (rawTyped != null && typeof rawTyped.connect == 'function') {
await rawTyped.connect(device, options);
}
return;
}
override async disconnect(device: BleDevice): Promise<void> {
const rawTyped = this._raw;
if (rawTyped != null && typeof rawTyped.disconnect == 'function') {
await rawTyped.disconnect(device);
}
return;
}
override async sendData(device: BleDevice, payload?: SendDataPayload, options?: BleOptions): Promise<void> {
const rawTyped = this._raw;
if (rawTyped != null && typeof rawTyped.sendData == 'function') {
await rawTyped.sendData(device, payload, options);
}
return;
}
override async autoConnect(device: BleDevice, options?: BleConnectOptionsExt): Promise<AutoBleInterfaces> {
const rawTyped = this._raw;
if (rawTyped != null && typeof rawTyped.autoConnect == 'function') {
return await rawTyped.autoConnect(device, options);
}
return { serviceId: '', writeCharId: '', notifyCharId: '' };
}
}
function isRawProtocolHandler(x: any): boolean {
if (x == null || typeof x !== 'object') return false;
const r = x as Record<string, unknown>;
if (typeof r['scanDevices'] == 'function') return true;
if (typeof r['connect'] == 'function') return true;
if (typeof r['disconnect'] == 'function') return true;
if (typeof r['sendData'] == 'function') return true;
if (typeof r['autoConnect'] == 'function') return true;
if (typeof r['protocol'] == 'string') return true;
return false;
}
function ensureConnectionHook() {
if (connectionHooked) return;
connectionHooked = true;
const dm = DeviceManager.getInstance();
dm.onConnectionStateChange((deviceId, state) => {
let matched = false;
deviceMap.forEach((ctx) => {
if (ctx.device.deviceId == deviceId) {
ctx.state = state;
emit('connectionStateChanged', { event: 'connectionStateChanged', device: ctx.device, protocol: ctx.protocol, state });
matched = true;
}
});
if (!matched) {
emit('connectionStateChanged', { event: 'connectionStateChanged', device: { deviceId, name: '', rssi: 0 }, protocol: activeProtocol, state });
}
});
}
export const registerProtocolHandler = (handler: any) => {
if (handler == null) return;
let proto: BleProtocolType = 'standard';
if (handler instanceof ProtocolHandler) {
try { proto = (handler as ProtocolHandler).protocol as BleProtocolType; } catch (e) { }
activeHandler = handler as ProtocolHandler;
} else if (isRawProtocolHandler(handler)) {
try { proto = (handler as RawProtocolHandler).protocol as BleProtocolType; } catch (e) { }
activeHandler = new ProtocolHandlerWrapper(handler as RawProtocolHandler, defaultBluetoothService);
(activeHandler as ProtocolHandler).protocol = proto;
} else {
console.warn('[AKBLE] registerProtocolHandler: unsupported handler type, ignoring', handler);
return;
}
activeProtocol = proto;
ensureConnectionHook();
}
export const scanDevices = async (options?: ScanDevicesOptions): Promise<void> => {
ensureDefaultProtocolHandler();
if (activeHandler == null) {
console.log('[AKBLE] no active scan handler registered');
return;
}
const handler = activeHandler as ProtocolHandler;
const original = options ?? null;
const scanOptions: ScanDevicesOptions = {} as ScanDevicesOptions;
if (original != null) {
if (original.protocols != null) scanOptions.protocols = original.protocols;
if (original.optionalServices != null) scanOptions.optionalServices = original.optionalServices;
if (original.timeout != null) scanOptions.timeout = original.timeout;
}
const userFound = original?.onDeviceFound ?? null;
scanOptions.onDeviceFound = (device: BleDevice) => {
emit('deviceFound', { event: 'deviceFound', device });
if (userFound != null) {
try { userFound(device); } catch (err) { }
}
};
const userFinished = original?.onScanFinished ?? null;
scanOptions.onScanFinished = () => {
emit('scanFinished', { event: 'scanFinished' });
if (userFinished != null) {
try { userFinished(); } catch (err) { }
}
};
try {
await handler.scanDevices(scanOptions);
} catch (e) {
console.warn('[AKBLE] scanDevices handler error', e);
}
}
export const connectDevice = async (deviceId: string, protocol: BleProtocolType, options?: BleConnectOptionsExt): Promise<void> => {
const handler = activeHandler;
if (handler == null) throw new Error('No protocol handler');
const device: BleDevice = { deviceId, name: '', rssi: 0 };
await handler.connect(device, options);
const ctx = new DeviceContext(device, protocol, handler);
ctx.state = 2;
deviceMap.set(getDeviceKey(deviceId, protocol), ctx);
emit('connectionStateChanged', { event: 'connectionStateChanged', device, protocol, state: 2 });
}
export const disconnectDevice = async (deviceId: string, protocol: BleProtocolType): Promise<void> => {
const ctx = deviceMap.get(getDeviceKey(deviceId, protocol));
if (ctx == null || ctx.handler == null) return;
await ctx.handler.disconnect(ctx.device);
ctx.state = 0;
emit('connectionStateChanged', { event: 'connectionStateChanged', device: ctx.device, protocol, state: 0 });
deviceMap.delete(getDeviceKey(deviceId, protocol));
}
export const sendData = async (payload: SendDataPayload, options?: BleOptions): Promise<void> => {
const ctx = deviceMap.get(getDeviceKey(payload.deviceId, payload.protocol));
if (ctx == null) throw new Error('Device not connected');
const deviceCtx = ctx as DeviceContext;
if (deviceCtx.handler == null) throw new Error('sendData not supported for this protocol');
await deviceCtx.handler.sendData(deviceCtx.device, payload, options);
emit('dataSent', { event: 'dataSent', device: deviceCtx.device, protocol: payload.protocol, data: payload.data });
}
export const getConnectedDevices = (): MultiProtocolDevice[] => {
const result: MultiProtocolDevice[] = [];
deviceMap.forEach((ctx: DeviceContext) => {
const dev: MultiProtocolDevice = {
deviceId: ctx.device.deviceId,
name: ctx.device.name,
rssi: ctx.device.rssi,
protocol: ctx.protocol
};
result.push(dev);
});
return result;
}
export const getConnectionState = (deviceId: string, protocol: BleProtocolType): BleConnectionState => {
const ctx = deviceMap.get(getDeviceKey(deviceId, protocol));
if (ctx == null) return 0;
return ctx.state;
}
export const on = (event: BleEvent, callback: BleEventCallback) => {
if (!eventListeners.has(event)) eventListeners.set(event, new Set());
eventListeners.get(event)!.add(callback);
}
export const off = (event: BleEvent, callback?: BleEventCallback) => {
if (callback == null) {
eventListeners.delete(event);
} else {
eventListeners.get(event)?.delete(callback as BleEventCallback);
}
}
function getDeviceKey(deviceId: string, protocol: BleProtocolType): string {
return `${deviceId}|${protocol}`;
}
export const autoConnect = async (deviceId: string, protocol: BleProtocolType, options?: BleConnectOptionsExt): Promise<AutoBleInterfaces> => {
const handler = activeHandler;
if (handler == null) throw new Error('autoConnect not supported for this protocol');
const device: BleDevice = { deviceId, name: '', rssi: 0 };
return await handler.autoConnect(device, options) as AutoBleInterfaces;
}
function ensureDefaultProtocolHandler(): void {
if (activeHandler != null) return;
const service = defaultBluetoothService;
if (service == null) return;
try {
const dm = DeviceManager.getInstance();
const raw: RawProtocolHandler = {
protocol: 'standard',
scanDevices: (options?: ScanDevicesOptions) => {
return dm.startScan(options ?? {} as ScanDevicesOptions);
},
connect: (device, options?: BleConnectOptionsExt) => dm.connectDevice(device.deviceId, options),
disconnect: (device) => dm.disconnectDevice(device.deviceId),
autoConnect: () => Promise.resolve({ serviceId: '', writeCharId: '', notifyCharId: '' })
};
const wrapper = new ProtocolHandlerWrapper(raw, service);
activeHandler = wrapper;
activeProtocol = raw.protocol as BleProtocolType;
ensureConnectionHook();
console.log('[AKBLE] default protocol handler registered', activeProtocol);
} catch (e) {
console.warn('[AKBLE] failed to register default protocol handler', e);
}
}
export const setDefaultBluetoothService = (service: BluetoothService) => {
defaultBluetoothService = service;
ensureDefaultProtocolHandler();
};

View File

@@ -0,0 +1,5 @@
{
"dependencies": [
]
}

View File

@@ -0,0 +1,250 @@
import type { BleDevice, BleConnectOptionsExt, BleConnectionState, BleConnectionStateChangeCallback, ScanDevicesOptions } from '../interface.uts';
declare const wx: any;
type PendingConnect = {
resolve: () => void;
reject: (err?: any) => void;
timer?: number;
};
function now(): number {
return Date.now();
}
export class DeviceManager {
private static instance: DeviceManager | null = null;
private devices = new Map<string, BleDevice>();
private connectionStates = new Map<string, BleConnectionState>();
private connectionListeners: BleConnectionStateChangeCallback[] = [];
private pendingConnects = new Map<string, PendingConnect>();
private scanOptions: ScanDevicesOptions | null = null;
private scanTimer: number | null = null;
private adapterReady: boolean = false;
private adapterPromise: Promise<void> | null = null;
private discoveryActive: boolean = false;
private deviceFoundRegistered: boolean = false;
private connectionEventRegistered: boolean = false;
private constructor() {}
static getInstance(): DeviceManager {
if (DeviceManager.instance == null) {
DeviceManager.instance = new DeviceManager();
}
return DeviceManager.instance!;
}
private ensureAdapter(): Promise<void> {
if (this.adapterReady) return Promise.resolve();
if (this.adapterPromise != null) return this.adapterPromise!;
this.adapterPromise = new Promise<void>((resolve, reject) => {
wx.openBluetoothAdapter({
success: () => {
this.adapterReady = true;
this.adapterPromise = null;
this.ensureEventHandlers();
resolve();
},
fail: (err: any) => {
this.adapterPromise = null;
reject(err ?? new Error('openBluetoothAdapter failed'));
}
});
});
return this.adapterPromise!;
}
private ensureEventHandlers() {
if (!this.deviceFoundRegistered) {
this.deviceFoundRegistered = true;
wx.onBluetoothDeviceFound((res: any) => {
try { this.handleDeviceFound(res); } catch (e) { }
});
}
if (!this.connectionEventRegistered) {
this.connectionEventRegistered = true;
wx.onBLEConnectionStateChange((res: any) => {
try { this.handleConnectionState(res); } catch (e) { }
});
}
}
startScan(options: ScanDevicesOptions): Promise<void> {
return this.ensureAdapter().then(() => {
return this.beginScan(options ?? {} as ScanDevicesOptions);
});
}
private beginScan(options: ScanDevicesOptions): Promise<void> {
if (this.discoveryActive) {
this.stopScanInternal();
}
this.scanOptions = options;
const services = options.optionalServices ?? null;
return new Promise<void>((resolve, reject) => {
wx.startBluetoothDevicesDiscovery({
services: services ?? undefined,
allowDuplicatesKey: false,
success: () => {
this.discoveryActive = true;
if (options.timeout != null && options.timeout > 0) {
this.scanTimer = setTimeout(() => {
this.stopScanInternal();
}, options.timeout);
}
resolve();
},
fail: (err: any) => {
this.discoveryActive = false;
reject(err ?? new Error('startBluetoothDevicesDiscovery failed'));
}
});
});
}
stopScan(): void {
this.stopScanInternal();
}
private stopScanInternal() {
if (!this.discoveryActive) return;
this.discoveryActive = false;
try {
wx.stopBluetoothDevicesDiscovery({});
} catch (e) { }
if (this.scanTimer != null) {
clearTimeout(this.scanTimer);
this.scanTimer = null;
}
const finished = this.scanOptions?.onScanFinished;
this.scanOptions = null;
if (finished != null) {
try { finished(); } catch (e) { }
}
}
private handleDeviceFound(res: any) {
const list: any[] = res?.devices ?? [];
for (let i = 0; i < list.length; i++) {
const item = list[i];
if (item == null) continue;
const deviceId = item.deviceId ?? item.deviceId ?? '';
if (!deviceId) continue;
const name = item.name ?? item.localName ?? 'Unknown';
const rssi = item.RSSI ?? item.rssi ?? 0;
let device = this.devices.get(deviceId);
if (device == null) {
device = { deviceId, name, rssi, lastSeen: now() };
this.devices.set(deviceId, device);
} else {
device.name = name;
device.rssi = rssi;
device.lastSeen = now();
}
const cb = this.scanOptions?.onDeviceFound;
if (cb != null) {
try { cb(device); } catch (e) { }
}
}
}
private handleConnectionState(res: any) {
const deviceId = res?.deviceId ?? '';
if (!deviceId) return;
const connected = res?.connected === true;
const state: BleConnectionState = connected ? 2 : 0;
this.connectionStates.set(deviceId, state);
const pending = this.pendingConnects.get(deviceId);
if (pending != null) {
this.pendingConnects.delete(deviceId);
if (pending.timer != null) clearTimeout(pending.timer);
if (connected) {
try { pending.resolve(); } catch (e) { }
} else {
try { pending.reject(new Error('连接断开')); } catch (e) { }
}
}
for (let i = 0; i < this.connectionListeners.length; i++) {
const listener = this.connectionListeners[i];
try { listener(deviceId, state); } catch (e) { }
}
}
connectDevice(deviceId: string, options?: BleConnectOptionsExt): Promise<void> {
return this.ensureAdapter().then(() => {
const timeout = options?.timeout ?? 15000;
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
this.pendingConnects.delete(deviceId);
reject(new Error('连接超时'));
}, timeout);
this.pendingConnects.set(deviceId, { resolve, reject, timer });
wx.createBLEConnection({
deviceId,
timeout,
success: () => {
this.pendingConnects.delete(deviceId);
clearTimeout(timer);
this.connectionStates.set(deviceId, 2);
resolve();
},
fail: (err: any) => {
this.pendingConnects.delete(deviceId);
clearTimeout(timer);
reject(err ?? new Error('createBLEConnection failed'));
}
});
});
});
}
disconnectDevice(deviceId: string): Promise<void> {
return new Promise((resolve, reject) => {
wx.closeBLEConnection({
deviceId,
success: () => {
this.connectionStates.set(deviceId, 0);
resolve();
},
fail: (err: any) => {
reject(err ?? new Error('closeBLEConnection failed'));
}
});
});
}
reconnectDevice(deviceId: string, options?: BleConnectOptionsExt): Promise<void> {
const attempts = options?.maxAttempts ?? 3;
const interval = options?.interval ?? 3000;
let count = 0;
const attempt = (): Promise<void> => {
return this.connectDevice(deviceId, options).catch((err) => {
count++;
if (count >= attempts) throw err;
return new Promise<void>((resolve) => {
setTimeout(() => resolve(attempt()), interval);
});
});
};
return attempt();
}
getConnectedDevices(): BleDevice[] {
const result: BleDevice[] = [];
this.devices.forEach((device, id) => {
if (this.connectionStates.get(id) == 2) {
result.push(device);
}
});
return result;
}
onConnectionStateChange(listener: BleConnectionStateChangeCallback) {
this.connectionListeners.push(listener);
}
getDevice(deviceId: string): BleDevice | null {
return this.devices.get(deviceId) ?? null;
}
}

View File

@@ -0,0 +1,9 @@
import type { DfuManagerType, DfuOptions } from '../interface.uts';
class MpWeixinDfuManager implements DfuManagerType {
async startDfu(_deviceId: string, _firmwareBytes: Uint8Array, _options?: DfuOptions): Promise<void> {
throw new Error('小程序平台暂未实现 DFU 功能');
}
}
export const dfuManager = new MpWeixinDfuManager();

View File

@@ -0,0 +1,90 @@
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, BleProtocolType, BluetoothService as BluetoothServiceContract } from '../interface.uts';
const serviceManager = ServiceManager.getInstance();
class MpWeixinBluetoothService implements BluetoothServiceContract {
scanDevices(options?: ScanDevicesOptions | null): Promise<void> {
return BluetoothManager.scanDevices(options ?? null);
}
async connectDevice(deviceId: string, protocol?: string, options?: BleConnectOptionsExt | null): Promise<void> {
const proto = (protocol != null && protocol !== '') ? (protocol as BleProtocolType) : 'standard';
return BluetoothManager.connectDevice(deviceId, proto, options ?? null);
}
async disconnectDevice(deviceId: string, protocol?: string): Promise<void> {
const proto = (protocol != null && protocol !== '') ? (protocol as BleProtocolType) : 'standard';
return BluetoothManager.disconnectDevice(deviceId, proto);
}
getConnectedDevices(): MultiProtocolDevice[] {
return BluetoothManager.getConnectedDevices();
}
on(event: BleEvent | string, callback: BleEventCallback): void {
BluetoothManager.on(event as BleEvent, callback);
}
off(event: BleEvent | string, callback?: BleEventCallback | null): void {
BluetoothManager.off(event as BleEvent, callback ?? null);
}
getServices(deviceId: string): Promise<BleService[]> {
return serviceManager.getServices(deviceId);
}
getCharacteristics(deviceId: string, serviceId: string): Promise<BleCharacteristic[]> {
return serviceManager.getCharacteristics(deviceId, serviceId);
}
async getAutoBleInterfaces(deviceId: string): Promise<AutoBleInterfaces> {
const services = await this.getServices(deviceId);
if (services.length == 0) throw new Error('未发现服务');
let serviceId = services[0].uuid;
for (let i = 0; i < services.length; i++) {
const uuid = services[i].uuid ?? '';
if (/^bae/i.test(uuid)) {
serviceId = uuid;
break;
}
}
const characteristics = await this.getCharacteristics(deviceId, serviceId);
if (characteristics.length == 0) throw new Error('未发现特征值');
let writeCharId = '';
let notifyCharId = '';
for (let i = 0; i < characteristics.length; i++) {
const c = characteristics[i];
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;
}
}
if (writeCharId == '' || notifyCharId == '') throw new Error('未找到合适的写入或通知特征');
return { serviceId, writeCharId, notifyCharId };
}
subscribeCharacteristic(deviceId: string, serviceId: string, characteristicId: string, onData: BleDataReceivedCallback): Promise<void> {
return serviceManager.subscribeCharacteristic(deviceId, serviceId, characteristicId, onData);
}
readCharacteristic(deviceId: string, serviceId: string, characteristicId: string): Promise<ArrayBuffer> {
return serviceManager.readCharacteristic(deviceId, serviceId, characteristicId);
}
writeCharacteristic(deviceId: string, serviceId: string, characteristicId: string, value: Uint8Array | ArrayBuffer, options?: WriteCharacteristicOptions): Promise<boolean> {
return serviceManager.writeCharacteristic(deviceId, serviceId, characteristicId, value, options);
}
unsubscribeCharacteristic(deviceId: string, serviceId: string, characteristicId: string): Promise<void> {
return serviceManager.unsubscribeCharacteristic(deviceId, serviceId, characteristicId);
}
autoDiscoverAll(deviceId: string): Promise<any> {
return serviceManager.autoDiscoverAll(deviceId);
}
subscribeAllNotifications(deviceId: string, onData: BleDataReceivedCallback): Promise<void> {
return serviceManager.subscribeAllNotifications(deviceId, onData);
}
}
export class BluetoothServiceShape extends MpWeixinBluetoothService {}
const bluetoothServiceInstance = new BluetoothServiceShape();
BluetoothManager.setDefaultBluetoothService(bluetoothServiceInstance);
export const bluetoothService: BluetoothServiceContract = bluetoothServiceInstance;
export function getBluetoothService(): BluetoothServiceShape {
return bluetoothServiceInstance;
}
export { dfuManager } from './dfu_manager.uts';

View File

@@ -0,0 +1,268 @@
import type { BleService, BleCharacteristic, BleDataReceivedCallback, BleCharacteristicProperties, WriteCharacteristicOptions, AutoDiscoverAllResult } from '../interface.uts';
import type { BleDevice } from '../interface.uts';
import { DeviceManager } from './device_manager.uts';
declare const wx: any;
type PendingRead = {
resolve: (data: ArrayBuffer) => void;
reject: (err?: any) => void;
timer?: number;
};
function toUint8Array(buffer: ArrayBuffer): Uint8Array {
return new Uint8Array(buffer ?? new ArrayBuffer(0));
}
function toArrayBuffer(bytes: Uint8Array | ArrayBuffer): ArrayBuffer {
return bytes instanceof Uint8Array ? bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) : (bytes ?? new ArrayBuffer(0));
}
function makeProperties(item: any): BleCharacteristicProperties {
const props = item?.properties ?? {};
const read = props.read === true;
const write = props.write === true;
const notify = props.notify === true;
const indicate = props.indicate === true;
const writeNoRsp = props.writeNoResponse === true || props.writeWithoutResponse === true;
return {
read,
write,
notify,
indicate,
writeWithoutResponse: writeNoRsp,
canRead: read,
canWrite: write || writeNoRsp,
canNotify: notify || indicate
};
}
export class ServiceManager {
private static instance: ServiceManager | null = null;
private services = new Map<string, BleService[]>();
private characteristics = new Map<string, Map<string, BleCharacteristic[]>>();
private pendingReads = new Map<string, PendingRead>();
private notifyCallbacks = new Map<string, BleDataReceivedCallback>();
private listenersRegistered: boolean = false;
private deviceManager = DeviceManager.getInstance();
private constructor() {}
static getInstance(): ServiceManager {
if (ServiceManager.instance == null) {
ServiceManager.instance = new ServiceManager();
}
return ServiceManager.instance!;
}
private ensureListeners() {
if (this.listenersRegistered) return;
this.listenersRegistered = true;
wx.onBLECharacteristicValueChange((res: any) => {
try { this.handleNotify(res); } catch (e) { }
});
}
private cacheKey(deviceId: string, serviceId: string): string {
return `${deviceId}|${serviceId}`;
}
private notifyKey(deviceId: string, serviceId: string, characteristicId: string): string {
return `${deviceId}|${serviceId}|${characteristicId}`;
}
async getServices(deviceId: string, callback?: (services: BleService[] | null, error?: Error) => void): Promise<BleService[]> {
const cached = this.services.get(deviceId);
if (cached != null && cached.length > 0) {
if (callback != null) callback(cached, null);
return cached;
}
return new Promise((resolve, reject) => {
wx.getBLEDeviceServices({
deviceId,
success: (res: any) => {
const list: BleService[] = [];
const services: any[] = res?.services ?? [];
for (let i = 0; i < services.length; i++) {
const svc = services[i];
if (svc == null) continue;
list.push({ uuid: svc.uuid, isPrimary: svc.isPrimary === true });
}
this.services.set(deviceId, list);
if (callback != null) callback(list, null);
resolve(list);
},
fail: (err: any) => {
const error = err ?? new Error('getBLEDeviceServices failed');
if (callback != null) callback(null, error);
reject(error);
}
});
});
}
async getCharacteristics(deviceId: string, serviceId: string, callback?: (list: BleCharacteristic[] | null, error?: Error) => void): Promise<BleCharacteristic[]> {
const map = this.characteristics.get(deviceId);
const cached = map != null ? map.get(serviceId) : null;
if (cached != null && cached.length > 0) {
if (callback != null) callback(cached, null);
return cached;
}
return new Promise((resolve, reject) => {
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res: any) => {
const list: BleCharacteristic[] = [];
const chars: any[] = res?.characteristics ?? [];
for (let i = 0; i < chars.length; i++) {
const ch = chars[i];
if (ch == null) continue;
list.push({
uuid: ch.uuid,
service: { uuid: serviceId, isPrimary: true },
properties: makeProperties(ch)
});
}
let mapRef = this.characteristics.get(deviceId);
if (mapRef == null) {
mapRef = new Map<string, BleCharacteristic[]>();
this.characteristics.set(deviceId, mapRef);
}
mapRef.set(serviceId, list);
if (callback != null) callback(list, null);
resolve(list);
},
fail: (err: any) => {
const error = err ?? new Error('getBLEDeviceCharacteristics failed');
if (callback != null) callback(null, error);
reject(error);
}
});
});
}
async readCharacteristic(deviceId: string, serviceId: string, characteristicId: string): Promise<ArrayBuffer> {
this.ensureListeners();
return new Promise<ArrayBuffer>((resolve, reject) => {
const key = `${deviceId}|${serviceId}|${characteristicId}|read`;
const timer = setTimeout(() => {
this.pendingReads.delete(key);
reject(new Error('读取超时'));
}, 10000);
this.pendingReads.set(key, { resolve, reject, timer });
wx.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,
fail: (err: any) => {
this.pendingReads.delete(key);
clearTimeout(timer);
reject(err ?? new Error('readBLECharacteristicValue failed'));
}
});
});
}
async writeCharacteristic(deviceId: string, serviceId: string, characteristicId: string, value: Uint8Array | ArrayBuffer, options?: WriteCharacteristicOptions): Promise<boolean> {
const buffer = toArrayBuffer(value);
return new Promise<boolean>((resolve, reject) => {
wx.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,
value: buffer,
fail: (err: any) => {
reject(err ?? new Error('writeBLECharacteristicValue failed'));
},
success: () => {
resolve(true);
}
});
});
}
async subscribeCharacteristic(deviceId: string, serviceId: string, characteristicId: string, callback: BleDataReceivedCallback): Promise<void> {
this.ensureListeners();
const key = this.notifyKey(deviceId, serviceId, characteristicId);
this.notifyCallbacks.set(key, callback);
return new Promise<void>((resolve, reject) => {
wx.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId,
state: true,
success: () => resolve(),
fail: (err: any) => {
this.notifyCallbacks.delete(key);
reject(err ?? new Error('notifyBLECharacteristicValueChange failed'));
}
});
});
}
async unsubscribeCharacteristic(deviceId: string, serviceId: string, characteristicId: string): Promise<void> {
const key = this.notifyKey(deviceId, serviceId, characteristicId);
this.notifyCallbacks.delete(key);
return new Promise<void>((resolve, reject) => {
wx.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId,
state: false,
success: () => resolve(),
fail: (err: any) => {
reject(err ?? new Error('notifyBLECharacteristicValueChange disable failed'));
}
});
});
}
async autoDiscoverAll(deviceId: string): Promise<AutoDiscoverAllResult> {
const services = await this.getServices(deviceId);
const allChars: BleCharacteristic[] = [];
for (let i = 0; i < services.length; i++) {
const svc = services[i];
const chars = await this.getCharacteristics(deviceId, svc.uuid);
for (let j = 0; j < chars.length; j++) {
allChars.push(chars[j]);
}
}
return { services, characteristics: allChars };
}
async subscribeAllNotifications(deviceId: string, callback: BleDataReceivedCallback): Promise<void> {
const services = await this.getServices(deviceId);
for (let i = 0; i < services.length; i++) {
const svc = services[i];
const chars = await this.getCharacteristics(deviceId, svc.uuid);
for (let j = 0; j < chars.length; j++) {
const ch = chars[j];
if (ch.properties != null && (ch.properties.notify || ch.properties.indicate)) {
try {
await this.subscribeCharacteristic(deviceId, svc.uuid, ch.uuid, callback);
} catch (e) { }
}
}
}
}
private handleNotify(res: any) {
const deviceId = res?.deviceId ?? '';
const serviceId = res?.serviceId ?? '';
const characteristicId = res?.characteristicId ?? '';
const key = `${deviceId}|${serviceId}|${characteristicId}|read`;
const buffer: ArrayBuffer = res?.value ?? new ArrayBuffer(0);
const pending = this.pendingReads.get(key);
if (pending != null) {
this.pendingReads.delete(key);
if (pending.timer != null) clearTimeout(pending.timer);
try { pending.resolve(buffer); } catch (e) { }
}
const notifyKey = this.notifyKey(deviceId, serviceId, characteristicId);
const cb = this.notifyCallbacks.get(notifyKey);
if (cb != null) {
try { cb(toUint8Array(buffer)); } catch (e) { }
}
}
}