2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.tesla.internal.throttler;
15 import java.util.HashMap;
17 import java.util.concurrent.ScheduledExecutorService;
20 * The {@link AbstractChannelThrottler} is abstract class implementing a
21 * throttler with one global execution rate, or rate limiter
23 * @author Karel Goderis - Initial contribution
25 abstract class AbstractChannelThrottler implements ChannelThrottler {
27 protected final Rate totalRate;
28 protected final TimeProvider timeProvider;
29 protected final ScheduledExecutorService scheduler;
30 protected final Map<Object, Rate> channels = new HashMap<>();
32 protected AbstractChannelThrottler(Rate totalRate, ScheduledExecutorService scheduler, Map<Object, Rate> channels,
33 TimeProvider timeProvider) {
34 this.totalRate = totalRate;
35 this.scheduler = scheduler;
36 this.channels.putAll(channels);
37 this.timeProvider = timeProvider;
40 protected synchronized long callTime(Rate channel) {
41 long now = timeProvider.getCurrentTimeInMillis();
42 long callTime = totalRate.callTime(now);
43 if (channel != null) {
44 callTime = Math.max(callTime, channel.callTime(now));
45 channel.addCall(callTime);
47 totalRate.addCall(callTime);
51 protected long getThrottleDelay(Object channelKey) {
52 long delay = callTime(channels.get(channelKey)) - timeProvider.getCurrentTimeInMillis();
53 return delay < 0 ? 0 : delay;