import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
-import java.time.Instant;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class GardenaSmartWebSocket {
private final Logger logger = LoggerFactory.getLogger(GardenaSmartWebSocket.class);
private final GardenaSmartWebSocketListener socketEventListener;
- private final long WEBSOCKET_IDLE_TIMEOUT = 300;
+ private final int MAX_UNANSWERED_PINGS = 5;
private WebSocketSession session;
private WebSocketClient webSocketClient;
private boolean closing;
- private Instant lastPong = Instant.now();
+ private int unansweredPings = 0;
private ScheduledExecutorService scheduler;
private @Nullable ScheduledFuture<?> connectionTracker;
private ByteBuffer pingPayload = ByteBuffer.wrap("ping".getBytes(StandardCharsets.UTF_8));
}
@OnWebSocketConnect
- public void onConnect(Session session) {
+ public synchronized void onConnect(Session session) {
closing = false;
+ unansweredPings = 0;
logger.debug("Connected to Gardena Webservice ({})", socketId);
ScheduledFuture<?> connectionTracker = this.connectionTracker;
}
@OnWebSocketFrame
- public void onFrame(Frame pong) {
+ public synchronized void onFrame(Frame pong) {
if (pong instanceof PongFrame) {
- lastPong = Instant.now();
+ unansweredPings = 0;
logger.trace("Pong received ({})", socketId);
}
}
*/
private synchronized void sendKeepAlivePing() {
final PostOAuth2Response accessToken = token;
- if ((Instant.now().getEpochSecond() - lastPong.getEpochSecond() > WEBSOCKET_IDLE_TIMEOUT) || accessToken == null
- || accessToken.isAccessTokenExpired()) {
+ if (unansweredPings > MAX_UNANSWERED_PINGS || accessToken == null || accessToken.isAccessTokenExpired()) {
session.close(1000, "Timeout manually closing dead connection (" + socketId + ")");
} else {
if (session.isOpen()) {
try {
logger.trace("Sending ping ({})", socketId);
session.getRemote().sendPing(pingPayload);
+ ++unansweredPings;
} catch (IOException ex) {
logger.debug("Error while sending ping: {}", ex.getMessage());
}