]> git.basschouten.com Git - openhab-addons.git/blob
8467d103914b69eeb5dcc131ed24dcf3c79dcf1f
[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.jeelink.internal;
14
15 import java.util.concurrent.ScheduledExecutorService;
16 import java.util.concurrent.ScheduledFuture;
17 import java.util.concurrent.TimeUnit;
18
19 /**
20  * Computes a rolling average of readings that is passed on to the next publisher
21  * after a given time frame.
22  *
23  * @author Volker Bier - Initial contribution
24  */
25 public abstract class RollingAveragePublisher<R extends Reading> implements ReadingPublisher<R> {
26     private final ReadingPublisher<R> publisher;
27
28     private ScheduledFuture<?> valueUpdateJob;
29     private RollingReadingAverage<R> rollingAvg;
30
31     public RollingAveragePublisher(int bufferSize, int interval, ReadingPublisher<R> p,
32             ScheduledExecutorService execService) {
33         publisher = p;
34
35         valueUpdateJob = createUpdateJob(execService, interval);
36         rollingAvg = createRollingReadingAverage(bufferSize);
37     }
38
39     public abstract RollingReadingAverage<R> createRollingReadingAverage(int bufferSize);
40
41     @Override
42     public void publish(R reading) {
43         rollingAvg.add(reading);
44     }
45
46     @Override
47     public void dispose() {
48         if (valueUpdateJob != null) {
49             valueUpdateJob.cancel(true);
50             valueUpdateJob = null;
51         }
52
53         publisher.dispose();
54     }
55
56     private ScheduledFuture<?> createUpdateJob(ScheduledExecutorService execService, final int updateInterval) {
57         return execService.scheduleWithFixedDelay(() -> {
58             publisher.publish(rollingAvg.getAverage());
59         }, updateInterval, updateInterval, TimeUnit.SECONDS);
60     }
61 }