-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
68 lines (53 loc) · 2.08 KB
/
index.ts
File metadata and controls
68 lines (53 loc) · 2.08 KB
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
import { useCallback, useEffect, useMemo, useRef, useState, } from 'react';
import { createCommander, } from './Commander';
import { createDeviceLink, } from './DeviceLink';
import { createDeviceStore, } from './DeviceStore';
type onStream = (data : Int16Array) => void;
export const useDevice = (url : string, initialState : Record<string, any>, onStream? : onStream, heartbeatInterval? : number, webSocket? : WebSocket) => {
const store = useMemo(() => createDeviceStore(initialState), [ initialState, ]);
const [ status, setStatus, ] = useState<'connected' | 'disconnected' | 'error'>('disconnected');
const linkRef = useRef<ReturnType<typeof createDeviceLink> | null>(null);
const commanderRef = useRef<ReturnType<typeof createCommander> | null>(null);
const connect = useCallback(() => {
linkRef.current = createDeviceLink({
url,
onStatus : (s, e) => {
setStatus(s);
if (s === 'error' && e) console.error(e);
},
onMessage : data => store.update(data),
onStream : data => {
onStream?.(data);
},
webSocket,
});
commanderRef.current = createCommander(linkRef.current, heartbeatInterval);
const unsubscribe = store.subscribe(store.update);
return () => {
unsubscribe();
commanderRef.current?.dispose();
};
}, [ url, onStream, heartbeatInterval, store, webSocket, ]);
useEffect(() => {
const interval = setInterval(() => {
if (status === 'disconnected') connect();
}, 5000);
connect();
return () => clearInterval(interval);
}, [ status, connect, ]);
return {
status,
store,
execute : ({
type,
payload,
} : {
type : string,
payload? : Record<string, any>,
}) => commanderRef.current?.sendCommand({
type,
payload,
}),
stream : (data : Uint8Array) => linkRef.current?.stream(data),
};
};