File size: 6,767 Bytes
b450976 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | import {useEffect, useRef, useState} from "react"
import BluetoothSdk from "../index"
import type {ConnectOptions, Device, DeviceModel} from "../BluetoothSdk.types"
import {useBluetoothScan, type BluetoothScanHookResult} from "./useBluetoothScan"
import {useBluetoothStatus, type BluetoothStatusHookResult} from "./useBluetoothStatus"
export type DefaultDeviceStorage = {
load: () => Promise<Device | null>
save: (device: Device | null) => Promise<void>
}
export type GlassesConnectionAction =
| "idle"
| "scanning"
| "connecting"
| "disconnecting"
| "forgetting"
export type UseGlassesConnectionOptions = {
autoConnectDefault?: boolean
defaultDeviceStorage?: DefaultDeviceStorage
onError?: (error: unknown) => void
/**
* Whether iOS should require ANCS authorization when automatically connecting.
* Defaults to true. Android accepts this option as a no-op.
*/
requiresAncs?: boolean
scanModel?: DeviceModel
scanTimeoutMs?: number
}
export type GlassesConnectionHookResult = BluetoothStatusHookResult & {
action: GlassesConnectionAction
busy: boolean
clearDefaultDevice: () => Promise<void>
connect: (device?: Device, options?: ConnectOptions) => Promise<void>
connectDefault: (options?: ConnectOptions) => Promise<void>
defaultDevice: Device | null
disconnect: () => Promise<void>
forget: () => Promise<void>
scan: BluetoothScanHookResult
setDefaultDevice: (device: Device | null) => Promise<void>
}
export function useGlassesConnection(
options: UseGlassesConnectionOptions = {},
): GlassesConnectionHookResult {
const status = useBluetoothStatus({onError: options.onError})
const scan = useBluetoothScan({
model: options.scanModel,
onError: options.onError,
timeoutMs: options.scanTimeoutMs,
})
const [action, setAction] = useState<GlassesConnectionAction>("idle")
const [defaultDevice, setDefaultDeviceState] = useState<Device | null>(null)
const [operationError, setOperationError] = useState<unknown | null>(null)
const autoConnectAttemptedRef = useRef(false)
const defaultDeviceStorageRef = useRef(options.defaultDeviceStorage)
const onErrorRef = useRef(options.onError)
useEffect(() => {
defaultDeviceStorageRef.current = options.defaultDeviceStorage
onErrorRef.current = options.onError
}, [options.defaultDeviceStorage, options.onError])
useEffect(() => {
let mounted = true
const loadDefaultDevice = async () => {
try {
const [nativeDefaultDevice, storedDefaultDevice] = await Promise.all([
BluetoothSdk.getDefaultDevice(),
defaultDeviceStorageRef.current?.load() ?? Promise.resolve(null),
])
if (!mounted) {
return
}
const nextDefaultDevice = storedDefaultDevice ?? nativeDefaultDevice
if (nextDefaultDevice) {
await BluetoothSdk.setDefaultDevice(nextDefaultDevice)
}
if (mounted) {
setDefaultDeviceState(nextDefaultDevice)
setOperationError(null)
}
} catch (nextError) {
if (!mounted) {
return
}
setOperationError(nextError)
onErrorRef.current?.(nextError)
}
}
void loadDefaultDevice()
return () => {
mounted = false
}
}, [])
useEffect(() => {
const subscription = BluetoothSdk.addListener("default_device_changed", (event) => {
const nextDefaultDevice = event.device ?? null
setDefaultDeviceState(nextDefaultDevice)
void defaultDeviceStorageRef.current?.save(nextDefaultDevice).catch((nextError) => {
setOperationError(nextError)
onErrorRef.current?.(nextError)
})
})
return () => {
subscription.remove()
}
}, [])
useEffect(() => {
if (!options.autoConnectDefault || autoConnectAttemptedRef.current || status.connected || !defaultDevice) {
return
}
autoConnectAttemptedRef.current = true
void connectDefault({requiresAncs: options.requiresAncs ?? true}).catch(() => undefined)
}, [defaultDevice, options.autoConnectDefault, options.requiresAncs, status.connected])
async function runConnectionAction<T>(
nextAction: Exclude<GlassesConnectionAction, "idle" | "scanning">,
operation: () => Promise<T>,
): Promise<T> {
setAction(nextAction)
setOperationError(null)
try {
const result = await operation()
setOperationError(null)
return result
} catch (nextError) {
setOperationError(nextError)
onErrorRef.current?.(nextError)
throw nextError
} finally {
setAction("idle")
}
}
async function setDefaultDevice(device: Device | null) {
await runConnectionAction("connecting", async () => {
await BluetoothSdk.setDefaultDevice(device)
await defaultDeviceStorageRef.current?.save(device)
setDefaultDeviceState(device)
})
}
async function clearDefaultDevice() {
await runConnectionAction("forgetting", async () => {
await BluetoothSdk.clearDefaultDevice()
await defaultDeviceStorageRef.current?.save(null)
setDefaultDeviceState(null)
scan.selectDevice(null)
})
}
async function connect(device?: Device, connectOptions?: ConnectOptions) {
await runConnectionAction("connecting", async () => {
const targetDevice = device ?? scan.selectedDevice
if (targetDevice) {
await BluetoothSdk.connect(targetDevice, connectOptions)
if (connectOptions?.saveAsDefault !== false) {
await defaultDeviceStorageRef.current?.save(targetDevice)
setDefaultDeviceState(targetDevice)
}
return
}
await BluetoothSdk.connectDefault(connectOptions)
})
}
async function connectDefault(connectOptions?: ConnectOptions) {
await runConnectionAction("connecting", async () => {
await BluetoothSdk.connectDefault(connectOptions)
})
}
async function disconnect() {
await runConnectionAction("disconnecting", async () => {
await BluetoothSdk.disconnect()
})
}
async function forget() {
await runConnectionAction("forgetting", async () => {
await BluetoothSdk.forget()
scan.clearResults()
})
}
const busy = action !== "idle" || scan.scanning || status.loading
return {
...status,
action: scan.scanning ? "scanning" : action,
busy,
clearDefaultDevice,
connect,
connectDefault,
defaultDevice,
disconnect,
error: operationError ?? scan.error ?? status.error,
forget,
scan,
setDefaultDevice,
}
}
|