Initial web ui and control for robot
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
|
||||
export function useWebSocket(onMessage) {
|
||||
const wsRef = useRef(null)
|
||||
const onMessageRef = useRef(onMessage)
|
||||
onMessageRef.current = onMessage
|
||||
|
||||
useEffect(() => {
|
||||
const ws = new WebSocket(`ws://${window.location.host}/ws`)
|
||||
wsRef.current = ws
|
||||
|
||||
ws.onmessage = (e) => {
|
||||
try { onMessageRef.current(JSON.parse(e.data)) } catch {}
|
||||
}
|
||||
let cleanedUp = false
|
||||
ws.onerror = (e) => {
|
||||
if (!cleanedUp) console.error('WebSocket error', e)
|
||||
}
|
||||
|
||||
return () => {
|
||||
cleanedUp = true
|
||||
ws.close()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return useCallback((data) => {
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN) {
|
||||
wsRef.current.send(JSON.stringify(data))
|
||||
}
|
||||
}, [])
|
||||
}
|
||||
Reference in New Issue
Block a user