feat(manufacturing): extract shared useSerialConnection hook for provisioning wizard

WebSerial port ownership was previously held inside StepFlash, which
made it awkward for other steps (StepVerify) to read from the same
port without fighting over exclusive access. useSerialConnection
centralizes port open/close/read/write so the wizard's steps share one
connection lifecycle instead of each managing their own.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-21 18:35:31 +03:00
co-authored by Claude Sonnet 5
parent d87925516a
commit f036000769
2 changed files with 505 additions and 227 deletions
+113
View File
@@ -0,0 +1,113 @@
// frontend/src/hooks/useSerialConnection.js
// Owns one WebSerial port connection across the Provisioning Wizard's Flash
// and Verify steps. Lifted out of StepFlash so the same live serial session
// (and its accumulated log) survives the step transition — a fresh device
// reboot after flashing is exactly the window the Verify step needs to watch.
import { useState, useRef, useCallback } from 'react'
export function useSerialConnection() {
const [portConnected, setPortConnected] = useState(false)
const [portName, setPortName] = useState('')
const [monitoring, setMonitoring] = useState(false)
const [lines, setLines] = useState([])
const portRef = useRef(null)
const readerRef = useRef(null)
const monitorActiveRef = useRef(false)
const appendLine = useCallback((msg) => {
setLines((prev) => [...prev, String(msg)])
}, [])
const clearLines = useCallback(() => setLines([]), [])
const requestPort = useCallback(async () => {
const port = await navigator.serial.requestPort()
portRef.current = port
const info = port.getInfo?.() || {}
const label = info.usbVendorId
? `USB ${info.usbVendorId.toString(16).toUpperCase()}:${(info.usbProductId || 0).toString(16).toUpperCase()}`
: 'Serial Port'
setPortName(label)
setPortConnected(true)
return port
}, [])
// Starts (or restarts) the 115200-baud monitor on the currently held port.
// Safe to call after esptool has just disconnected its own transport —
// the small delay lets the OS release the port before we reopen it.
const startMonitor = useCallback(async (port, { delayMs = 1000 } = {}) => {
const target = port || portRef.current
if (!target) return
monitorActiveRef.current = true
setMonitoring(true)
if (delayMs) await new Promise((r) => setTimeout(r, delayMs))
try {
await target.open({ baudRate: 115200 })
} catch (openErr) {
appendLine(`[Error opening port: ${openErr.message}]`)
setMonitoring(false)
return
}
let reader
try {
reader = target.readable.getReader()
} catch (readerErr) {
appendLine(`[Error getting reader: ${readerErr.message}]`)
try { await target.close() } catch (_) {}
setMonitoring(false)
return
}
readerRef.current = reader
const dec = new TextDecoder()
let buf = ''
try {
while (monitorActiveRef.current) {
const { value, done } = await reader.read()
if (done) break
buf += dec.decode(value, { stream: true })
const parts = buf.split(/\r?\n/)
buf = parts.pop()
for (const line of parts) { if (line.trim()) appendLine(line) }
}
} catch (_) {
// reader cancelled/port lost — fall through to cleanup
} finally {
try { reader.releaseLock() } catch (_) {}
setMonitoring(false)
}
}, [appendLine])
const stopMonitor = useCallback(async () => {
monitorActiveRef.current = false
try { await readerRef.current?.cancel() } catch (_) {}
try { readerRef.current?.releaseLock() } catch (_) {}
setMonitoring(false)
}, [])
const disconnect = useCallback(async () => {
await stopMonitor()
try { await portRef.current?.close() } catch (_) {}
portRef.current = null
setPortConnected(false)
setPortName('')
appendLine('[Port disconnected]')
}, [stopMonitor, appendLine])
return {
portRef,
portConnected,
portName,
monitoring,
lines,
appendLine,
clearLines,
requestPort,
startMonitor,
stopMonitor,
disconnect,
}
}
export default useSerialConnection