Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Socket issue #1115

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions modern/src/SocketController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import React, { useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector, connect } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { Snackbar } from '@mui/material';
import { devicesActions, sessionActions } from './store';
import {
devicesActions,
sessionActions,
} from './store';
import { useEffectAsync } from './reactHelper';
import { useTranslation } from './common/components/LocalizationProvider';
import { snackBarDurationLongMs } from './common/util/duration';
Expand All @@ -26,11 +29,17 @@ const SocketController = () => {
const [events, setEvents] = useState([]);
const [notifications, setNotifications] = useState([]);

const [lastUpdate, setLastUpdate] = useState();

const soundEvents = useAttributePreference('soundEvents', '');
const soundAlarms = useAttributePreference('soundAlarms', 'sos');

const features = useFeatures();

const resetCounterKeepAlive = () => setLastUpdate(new Date());

const isConnected = () => Math.abs(new Date() - lastUpdate) < 10000;

const connectSocket = () => {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const socket = new WebSocket(`${protocol}//${window.location.host}/api/socket`);
Expand All @@ -44,11 +53,10 @@ const SocketController = () => {
dispatch(sessionActions.updateSocket(false));
if (event.code !== logoutCode) {
try {
const devicesResponse = await fetch('/api/devices');
const [devicesResponse, positionsResponse] = await Promise.all([fetch('/api/devices'), fetch('/api/positions')]);
if (devicesResponse.ok) {
dispatch(devicesActions.update(await devicesResponse.json()));
}
const positionsResponse = await fetch('/api/positions');
if (positionsResponse.ok) {
dispatch(sessionActions.updatePositions(await positionsResponse.json()));
}
Expand All @@ -58,7 +66,7 @@ const SocketController = () => {
} catch (error) {
// ignore errors
}
setTimeout(() => connectSocket(), 60000);
setTimeout(connectSocket, 10000);
}
};

Expand All @@ -76,9 +84,32 @@ const SocketController = () => {
}
setEvents(data.events);
}
if (data) {
resetCounterKeepAlive();
}
};
};

const keepAlive = async () => {
if (!isConnected) {
const socket = socketRef.current;
if (socket) {
socket.close(logoutCode);
}
try {
connectSocket();
} catch (error) {
// ignore errors
}
}
};

useEffect(() => {
if (authenticated) {
setTimeout(keepAlive, 3000);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like this is called only once. Is that by design?

Copy link
Contributor Author

@BIhab BIhab May 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even if the value for the useEffect change?

useEffect(() => {
    if (authenticated) {
      setTimeout(keepAlive, 3000);
    }
  }, [lastUpdate]);

lastUpdate change every time a data in sent via the socket.onmessage, and the code inside the useEffect is re-executed

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I see... but how do you cancel the old timeout?

Copy link
Contributor Author

@BIhab BIhab May 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about doing that?

const [timeOutId, setTimeOutId] = useState();
...
useEffect(() => {
    if (authenticated) {
      clearTimeout(timeOutId);
      setTimeOutId(setTimeout(keepAlive, 3000));
    }
  }, [lastUpdate]);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess it should work.

The only minor nit is use "timeout" as a single word, not "timeOut".

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I push the new changes, I'll give it a try on some devices and came back with the result

}
}, [lastUpdate]);

useEffectAsync(async () => {
if (authenticated) {
const response = await fetch('/api/devices');
Expand All @@ -87,6 +118,7 @@ const SocketController = () => {
} else {
throw Error(await response.text());
}
resetCounterKeepAlive();
connectSocket();
return () => {
const socket = socketRef.current;
Expand Down