]> git.basschouten.com Git - openhab-addons.git/blob
1637ac8d0c788ba2efe09a91c5efec83dc799781
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.jeelink.internal;
14
15 /**
16  * Computes a rolling average of readings.
17  *
18  * @author Volker Bier - Initial contribution
19  */
20 public abstract class RollingReadingAverage<R extends Reading> {
21     private int size = 0;
22     private int maxSize;
23     private R total = null;
24     private int index = 0;
25     private R[] samples;
26
27     public RollingReadingAverage(R[] array) {
28         maxSize = array.length;
29         samples = array;
30     }
31
32     public void add(R reading) {
33         if (size < maxSize) {
34             size++;
35         }
36
37         if (total == null) {
38             total = reading;
39         } else {
40             total = add(total, reading);
41             total = substract(total, samples[index]);
42         }
43
44         samples[index] = reading;
45         if (++index == maxSize) {
46             index = 0;
47         }
48     }
49
50     public R getAverage() {
51         if (total == null) {
52             return null;
53         }
54         return divide(total, size);
55     }
56
57     protected abstract R add(R value1, R value2);
58
59     protected abstract R substract(R from, R value);
60
61     protected abstract R divide(R value, int count);
62 }