[WIFI-10904] Websocket more resilient in case of disconnection

Signed-off-by: Charles <charles.bourque96@gmail.com>
This commit is contained in:
Charles
2022-09-23 12:41:00 +01:00
parent 8ead4c4708
commit 78c48e004c
2 changed files with 20 additions and 14 deletions

View File

@@ -39,24 +39,29 @@ export const WebSocketProvider = ({ children, setNewConnectionData }) => {
} }
}, []); }, []);
// useEffect for created the WebSocket and 'storing' it in useRef const onStartWebSocket = () => {
useEffect(() => { ws.current = new WebSocket(`${endpoints.owgw?.replace('https', 'wss')}/api/v1/ws`);
if (endpoints?.owgw !== undefined) {
ws.current = new WebSocket(`${endpoints.owgw.replace('https', 'wss')}/api/v1/ws`);
ws.current.onopen = () => { ws.current.onopen = () => {
setIsOpen(true); setIsOpen(true);
ws.current?.send(`token:${currentToken}`); ws.current?.send(`token:${currentToken}`);
}; };
ws.current.onclose = () => { ws.current.onclose = () => {
setIsOpen(false); setIsOpen(false);
setTimeout(onStartWebSocket, 3000);
}; };
ws.current.onerror = () => { ws.current.onerror = () => {
setIsOpen(false); setIsOpen(false);
}; };
};
// useEffect for created the WebSocket and 'storing' it in useRef
useEffect(() => {
if (endpoints?.owgw !== undefined) {
onStartWebSocket();
} }
const wsCurrent = ws?.current; const wsCurrent = ws?.current;
return () => wsCurrent?.close(); return () => wsCurrent?.close();
}, []); }, [endpoints]);
// useEffect for generating global notifications // useEffect for generating global notifications
useEffect(() => { useEffect(() => {
@@ -69,6 +74,7 @@ export const WebSocketProvider = ({ children, setNewConnectionData }) => {
if (wsCurrent) wsCurrent.removeEventListener('message', onMessage); if (wsCurrent) wsCurrent.removeEventListener('message', onMessage);
}; };
}, [ws?.current]); }, [ws?.current]);
const values = useMemo( const values = useMemo(
() => ({ () => ({
lastMessage, lastMessage,

View File

@@ -80,8 +80,8 @@ const SidebarDevices = ({ newData }) => {
borderTop: '3px solid #d8dbe0', borderTop: '3px solid #d8dbe0',
color: 'white', color: 'white',
textAlign: 'center', textAlign: 'center',
paddingTop: '5px', paddingTop: '15px',
paddingBottom: '5px', paddingBottom: '25px',
}} }}
> >
<h3 style={{ marginBottom: '0px' }}>{stats?.connectedDevices ?? stats?.numberOfDevices}</h3> <h3 style={{ marginBottom: '0px' }}>{stats?.connectedDevices ?? stats?.numberOfDevices}</h3>