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.jeelink.internal;
15 import java.util.concurrent.ScheduledExecutorService;
16 import java.util.concurrent.ScheduledFuture;
17 import java.util.concurrent.TimeUnit;
20 * Computes a rolling average of readings that is passed on to the next publisher
21 * after a given time frame.
23 * @author Volker Bier - Initial contribution
25 public abstract class RollingAveragePublisher<R extends Reading> implements ReadingPublisher<R> {
26 private final ReadingPublisher<R> publisher;
28 private ScheduledFuture<?> valueUpdateJob;
29 private RollingReadingAverage<R> rollingAvg;
31 public RollingAveragePublisher(int bufferSize, int interval, ReadingPublisher<R> p,
32 ScheduledExecutorService execService) {
35 valueUpdateJob = createUpdateJob(execService, interval);
36 rollingAvg = createRollingReadingAverage(bufferSize);
39 public abstract RollingReadingAverage<R> createRollingReadingAverage(int bufferSize);
42 public void publish(R reading) {
43 rollingAvg.add(reading);
47 public void dispose() {
48 if (valueUpdateJob != null) {
49 valueUpdateJob.cancel(true);
50 valueUpdateJob = null;
56 private ScheduledFuture<?> createUpdateJob(ScheduledExecutorService execService, final int updateInterval) {
57 return execService.scheduleWithFixedDelay(() -> {
58 publisher.publish(rollingAvg.getAverage());
59 }, updateInterval, updateInterval, TimeUnit.SECONDS);