File size: 5,324 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
import {useEffect, useRef, useState} from "react"

import BluetoothSdk, {DeviceModels} from "../index"
import type {Device, DeviceModel, ScanDiagnostic} from "../BluetoothSdk.types"

export type BluetoothScanDedupe = "id" | "name" | ((device: Device) => string)

export type UseBluetoothScanOptions = {
  dedupe?: BluetoothScanDedupe
  model?: DeviceModel
  onError?: (error: unknown) => void
  timeoutMs?: number
}

export type BluetoothScanHookResult = {
  clearResults: () => void
  devices: Device[]
  diagnostic: ScanDiagnostic | null
  error: unknown | null
  model: DeviceModel
  scanning: boolean
  selectedDevice: Device | null
  selectDevice: (device: Device | null) => void
  setModel: (model: DeviceModel) => void
  startScan: (model?: DeviceModel) => Promise<Device[]>
  stopScan: () => Promise<void>
}

function dedupeKey(device: Device, dedupe: BluetoothScanDedupe): string {
  if (typeof dedupe === "function") {
    return dedupe(device)
  }
  if (dedupe === "name") {
    return `${device.model}:${device.name}`
  }
  return device.id
}

function dedupeDevices(devices: Device[], dedupe: BluetoothScanDedupe): Device[] {
  const seen = new Set<string>()
  const nextDevices: Device[] = []

  devices.forEach((device) => {
    const key = dedupeKey(device, dedupe)
    if (seen.has(key)) {
      return
    }
    seen.add(key)
    nextDevices.push(device)
  })

  return nextDevices
}

function hasDevice(devices: Device[], selectedDevice: Device | null, dedupe: BluetoothScanDedupe): boolean {
  if (!selectedDevice) {
    return true
  }
  const selectedKey = dedupeKey(selectedDevice, dedupe)
  return devices.some((device) => dedupeKey(device, dedupe) === selectedKey)
}

export function useBluetoothScan(options: UseBluetoothScanOptions = {}): BluetoothScanHookResult {
  const [devices, setDevices] = useState<Device[]>([])
  const [diagnostic, setDiagnostic] = useState<ScanDiagnostic | null>(null)
  const [error, setError] = useState<unknown | null>(null)
  const [model, setModelState] = useState<DeviceModel>(options.model ?? DeviceModels.MentraLive)
  const [scanning, setScanning] = useState(false)
  const [selectedDevice, selectDevice] = useState<Device | null>(null)
  const activeScanRef = useRef(0)
  const dedupeRef = useRef<BluetoothScanDedupe>(options.dedupe ?? "id")
  const onErrorRef = useRef(options.onError)
  const scanningRef = useRef(false)
  const timeoutMsRef = useRef(options.timeoutMs)

  useEffect(() => {
    dedupeRef.current = options.dedupe ?? "id"
    onErrorRef.current = options.onError
    timeoutMsRef.current = options.timeoutMs
  }, [options.dedupe, options.onError, options.timeoutMs])

  useEffect(() => {
    scanningRef.current = scanning
  }, [scanning])

  useEffect(() => {
    if (!hasDevice(devices, selectedDevice, dedupeRef.current)) {
      selectDevice(null)
    }
  }, [devices, selectedDevice])

  useEffect(() => {
    return () => {
      if (!scanningRef.current) {
        return
      }
      activeScanRef.current += 1
      void BluetoothSdk.stopScan().catch(() => undefined)
    }
  }, [])

  function clearResults() {
    setDiagnostic(null)
    setDevices([])
    selectDevice(null)
  }

  function setModel(nextModel: DeviceModel) {
    if (scanningRef.current) void stopScan()
    setModelState(nextModel)
    clearResults()
  }

  async function startScan(nextModel?: DeviceModel): Promise<Device[]> {
    const scanId = activeScanRef.current + 1
    activeScanRef.current = scanId
    const scanModel = nextModel ?? model
    if (nextModel && nextModel !== model) {
      setModelState(nextModel)
    }

    setError(null)
    setDiagnostic(null)
    setScanning(true)
    scanningRef.current = true
    setDevices([])
    selectDevice(null)

    try {
      const nextDevices = await BluetoothSdk.scan(scanModel, {
        ...(timeoutMsRef.current == null ? {} : {timeoutMs: timeoutMsRef.current}),
        onDiagnostic: (hint) => {
          if (activeScanRef.current === scanId) setDiagnostic(hint)
        },
        onResults: (results) => {
          if (activeScanRef.current !== scanId) {
            return
          }
          if (results.length > 0) setDiagnostic(null)
          setDevices(dedupeDevices(results, dedupeRef.current))
        },
      })
      const finalDevices = dedupeDevices(nextDevices, dedupeRef.current)
      if (activeScanRef.current === scanId) {
        setDevices(finalDevices)
        setError(null)
      }
      return finalDevices
    } catch (nextError) {
      if (activeScanRef.current === scanId) {
        setError(nextError)
        onErrorRef.current?.(nextError)
      }
      throw nextError
    } finally {
      if (activeScanRef.current === scanId) {
        setScanning(false)
        scanningRef.current = false
      }
    }
  }

  async function stopScan() {
    setDiagnostic(null)
    activeScanRef.current += 1
    setScanning(false)
    scanningRef.current = false
    await BluetoothSdk.stopScan()
  }

  return {
    clearResults,
    devices,
    diagnostic,
    error,
    model,
    scanning,
    selectedDevice,
    selectDevice,
    setModel,
    startScan,
    stopScan,
  }
}