Skip to content

Commit

Permalink
Merge pull request #23 from lolodomo/netatmo_request_counter_lolodomo
Browse files Browse the repository at this point in the history
Use a deque to keep all timestamps of requests run during the last hour
  • Loading branch information
clinique authored Oct 7, 2022
2 parents 9f282c9 + 127fbed commit 01ed5c8
Showing 1 changed file with 14 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@
import java.lang.reflect.Constructor;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
Expand Down Expand Up @@ -91,7 +94,7 @@ public class ApiBridgeHandler extends BaseBridgeHandler {
private Map<Class<? extends RestManager>, RestManager> managers = new HashMap<>();
private @Nullable WebhookServlet webHookServlet;
private @Nullable GrantServlet grantServlet;
private int requestCount = -1;
private Deque<LocalDateTime> requestsTimestamps;
private final ChannelUID requestCountChannelUID;

public ApiBridgeHandler(Bridge bridge, HttpClient httpClient, NADeserializer deserializer,
Expand All @@ -102,6 +105,7 @@ public ApiBridgeHandler(Bridge bridge, HttpClient httpClient, NADeserializer des
this.httpClient = httpClient;
this.deserializer = deserializer;
this.httpService = httpService;
this.requestsTimestamps = new ArrayDeque<>(200);
this.requestCountChannelUID = new ChannelUID(getThing().getUID(), GROUP_BRIDGE, CHANNEL_REQUEST_COUNT);
}

Expand All @@ -112,9 +116,6 @@ public void initialize() {
GrantServlet servlet = new GrantServlet(this, httpService);
servlet.startListening();
grantServlet = servlet;
scheduler.scheduleAtFixedRate(() -> {
requestCount = 0;
}, 0l, 1l, TimeUnit.HOURS);
scheduler.execute(() -> openConnection(null, null));
}

Expand Down Expand Up @@ -244,8 +245,15 @@ public synchronized <T> T executeUri(URI uri, HttpMethod method, Class<T> clazz,
}
}

requestCount++;
updateState(requestCountChannelUID, new DecimalType(requestCount));
if (isLinked(requestCountChannelUID)) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime oneHourAgo = now.minusHours(1);
requestsTimestamps.addLast(now);
while (requestsTimestamps.getFirst().isBefore(oneHourAgo)) {
requestsTimestamps.removeFirst();
}
updateState(requestCountChannelUID, new DecimalType(requestsTimestamps.size()));
}
ContentResponse response = request.send();

Code statusCode = HttpStatus.getCode(response.getStatus());
Expand Down

0 comments on commit 01ed5c8

Please sign in to comment.