]> git.basschouten.com Git - openhab-addons.git/blob
20216ed29e389e2aade8687809e273990d4ff6ec
[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.mikrotik.internal.util;
14
15 import java.math.BigDecimal;
16 import java.math.BigInteger;
17 import java.time.LocalDateTime;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.threeten.extra.Seconds;
22
23 /**
24  * The {@link RateCalculator} is used to calculate data changing rate as number per second. Has a separate method
25  * to get megabits per second rate out of byte number.
26  *
27  * @author Oleg Vivtash - Initial contribution
28  */
29 @NonNullByDefault
30 public class RateCalculator {
31     public static final int BYTES_IN_MEGABIT = 125000;
32
33     private BigDecimal value;
34     float rate;
35     LocalDateTime lastUpdated;
36
37     public RateCalculator(BigDecimal initialValue) {
38         this.value = initialValue;
39         this.lastUpdated = LocalDateTime.now();
40         this.rate = 0.0F;
41     }
42
43     public float getRate() {
44         return this.rate;
45     }
46
47     public float getMegabitRate() {
48         return getRate() / BYTES_IN_MEGABIT;
49     }
50
51     public void update(@Nullable BigDecimal currentValue) {
52         if (currentValue != null) {
53             synchronized (this) {
54                 LocalDateTime thisUpdated = LocalDateTime.now();
55                 Seconds secDiff = Seconds.between(lastUpdated, thisUpdated);
56                 this.rate = currentValue.subtract(value).floatValue() / secDiff.getAmount();
57                 this.value = currentValue;
58                 this.lastUpdated = thisUpdated;
59             }
60         }
61     }
62
63     public void update(@Nullable BigInteger currentValue) {
64         BigInteger val = currentValue == null ? BigInteger.ZERO : currentValue;
65         this.update(new BigDecimal(val));
66     }
67 }