55 lines
1.5 KiB
JavaScript
55 lines
1.5 KiB
JavaScript
/**
|
|
* 统一等待 UUID_STATE 通知。
|
|
*
|
|
* @param {object} ble createBleCore 实例
|
|
* @param {object} options 等待配置
|
|
* @param {number[]} options.allowedCodes 允许通过的状态码;为空则接收任意状态码
|
|
* @param {boolean} options.rejectOnUnexpected 收到非 allowedCodes 状态码时是否立刻失败
|
|
* @param {number} options.timeout 超时时间(ms)
|
|
* @param {string} options.timeoutMessage 超时提示
|
|
* @param {string} options.unexpectedMessage 非预期状态提示前缀
|
|
*/
|
|
export function waitForProtocolState(ble, options = {}) {
|
|
const {
|
|
allowedCodes = [],
|
|
rejectOnUnexpected = false,
|
|
timeout = 6000,
|
|
timeoutMessage = '等待 UUID_STATE 超时',
|
|
unexpectedMessage = '收到非预期 UUID_STATE 状态码'
|
|
} = options
|
|
|
|
return new Promise((resolve, reject) => {
|
|
let timer = null
|
|
let off = null
|
|
|
|
const finish = (callback) => {
|
|
if (timer) {
|
|
clearTimeout(timer)
|
|
}
|
|
|
|
if (off) {
|
|
off()
|
|
}
|
|
|
|
callback()
|
|
}
|
|
|
|
timer = setTimeout(() => {
|
|
finish(() => reject(new Error(timeoutMessage)))
|
|
}, timeout)
|
|
|
|
off = ble.on('protocol:state', (payload) => {
|
|
const stateCode = Number(payload?.stateCode)
|
|
|
|
if (!allowedCodes.length || allowedCodes.includes(stateCode)) {
|
|
finish(() => resolve(payload))
|
|
return
|
|
}
|
|
|
|
if (rejectOnUnexpected) {
|
|
finish(() => reject(new Error(`${unexpectedMessage}: ${stateCode}`)))
|
|
}
|
|
})
|
|
})
|
|
}
|