]> git.basschouten.com Git - openhab-addons.git/blob
1606e438439b071c4e7748727dbfda81d1b83f2a
[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.ArrayList;
16 import java.util.HashMap;
17 import java.util.Iterator;
18 import java.util.Map;
19 import java.util.concurrent.ScheduledExecutorService;
20
21 /**
22  * The {@link AbstractMultiRateChannelThrottler} is abstract class implementing
23  * a throttler with multiple global execution rates, or rate limiters
24  *
25  * @author Karel Goderis - Initial contribution
26  */
27 abstract class AbstractMultiRateChannelThrottler implements ChannelThrottler {
28
29     protected final TimeProvider timeProvider;
30     protected final ScheduledExecutorService scheduler;
31     protected final Map<Object, Rate> channels = new HashMap<>();
32     protected final ArrayList<Rate> rates = new ArrayList<>();
33
34     protected AbstractMultiRateChannelThrottler(Rate rate, ScheduledExecutorService scheduler,
35             Map<Object, Rate> channels, TimeProvider timeProvider) {
36         this.rates.add(rate);
37         this.scheduler = scheduler;
38         this.channels.putAll(channels);
39         this.timeProvider = timeProvider;
40     }
41
42     public synchronized void addRate(Rate rate) {
43         this.rates.add(rate);
44     }
45
46     protected synchronized long callTime(Rate channel) {
47         long maxCallTime = 0;
48         long finalCallTime = 0;
49         long now = timeProvider.getCurrentTimeInMillis();
50         Iterator<Rate> iterator = rates.iterator();
51         while (iterator.hasNext()) {
52             Rate someRate = iterator.next();
53             maxCallTime = Math.max(maxCallTime, someRate.callTime(now));
54         }
55
56         if (channel != null) {
57             finalCallTime = Math.max(maxCallTime, channel.callTime(now));
58             channel.addCall(finalCallTime);
59         }
60
61         iterator = rates.iterator();
62         while (iterator.hasNext()) {
63             Rate someRate = iterator.next();
64             someRate.addCall(finalCallTime);
65         }
66
67         return finalCallTime;
68     }
69
70     protected long getThrottleDelay(Object channelKey) {
71         long delay = callTime(channels.get(channelKey)) - timeProvider.getCurrentTimeInMillis();
72         return delay < 0 ? 0 : delay;
73     }
74 }