]> git.basschouten.com Git - openhab-addons.git/blob
7bc71b2573bf8c4394dfabd781a0c169b9d21da2
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.tesla.internal.throttler;
14
15 import java.util.HashMap;
16 import java.util.Map;
17 import java.util.concurrent.ScheduledExecutorService;
18
19 /**
20  * The {@link AbstractChannelThrottler} is abstract class implementing a
21  * throttler with one global execution rate, or rate limiter
22  *
23  * @author Karel Goderis - Initial contribution
24  */
25 abstract class AbstractChannelThrottler implements ChannelThrottler {
26
27     protected final Rate totalRate;
28     protected final TimeProvider timeProvider;
29     protected final ScheduledExecutorService scheduler;
30     protected final Map<Object, Rate> channels = new HashMap<>();
31
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;
38     }
39
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);
46         }
47         totalRate.addCall(callTime);
48         return callTime;
49     }
50
51     protected long getThrottleDelay(Object channelKey) {
52         long delay = callTime(channels.get(channelKey)) - timeProvider.getCurrentTimeInMillis();
53         return delay < 0 ? 0 : delay;
54     }
55 }