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.mikrotik.internal.util;
15 import java.math.BigDecimal;
16 import java.math.BigInteger;
17 import java.time.LocalDateTime;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.threeten.extra.Seconds;
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.
27 * @author Oleg Vivtash - Initial contribution
30 public class RateCalculator {
31 public static final int BYTES_IN_MEGABIT = 125000;
33 private BigDecimal value;
35 LocalDateTime lastUpdated;
37 public RateCalculator(BigDecimal initialValue) {
38 this.value = initialValue;
39 this.lastUpdated = LocalDateTime.now();
43 public float getRate() {
47 public float getMegabitRate() {
48 return getRate() / BYTES_IN_MEGABIT;
51 public void update(@Nullable BigDecimal currentValue) {
52 if (currentValue != null) {
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;
63 public void update(@Nullable BigInteger currentValue) {
64 BigInteger val = currentValue == null ? BigInteger.ZERO : currentValue;
65 this.update(new BigDecimal(val));