]> git.basschouten.com Git - openhab-addons.git/blob
2461cc74e3a953333777bc0a01e7eae878b9d55c
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.automation.pwm.internal.handler.state;
14
15 import java.util.concurrent.ScheduledExecutorService;
16 import java.util.function.Function;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 /**
23  * The base class of all states.
24  *
25  * @author Fabian Wolter - Initial Contribution
26  */
27 @NonNullByDefault
28 public abstract class State {
29     private final Logger logger = LoggerFactory.getLogger(State.class);
30     protected StateMachine context;
31     protected ScheduledExecutorService scheduler;
32
33     public State(StateMachine context) {
34         this.context = context;
35         this.scheduler = context.getScheduler();
36     }
37
38     /**
39      * Invoked when the duty cycle updated and changed.
40      */
41     public abstract void dutyCycleChanged();
42
43     /**
44      * Invoked when the duty cycle updated.
45      */
46     protected abstract void dutyCycleUpdated();
47
48     public abstract void dispose();
49
50     /**
51      * Sets a new state in the state machine.
52      */
53     @SuppressWarnings("PMD.CompareObjectsWithEquals")
54     public synchronized void nextState(Function<StateMachine, ? extends State> nextState) {
55         if (context.getState() != this) { // compare identity
56             return;
57         }
58
59         context.getState().dispose();
60         State newState = nextState.apply(context);
61
62         logger.trace("{} -> {}", context.getState().getClass().getSimpleName(), newState.getClass().getSimpleName());
63
64         context.setState(newState);
65     }
66
67     /**
68      * Calculates the ON duration by the duty cycle.
69      *
70      * @param dutyCycleInPercent the duty cycle in percent
71      * @return the ON duration in ms
72      */
73     protected long calculateOnTimeMs(double dutyCycleInPercent) {
74         return (long) (context.getPeriodMs() / 100 * dutyCycleInPercent);
75     }
76
77     /**
78      * Switches the output on or off.
79      *
80      * @param on true, if the output shall be switched on.
81      */
82     protected void controlOutput(boolean on) {
83         context.controlOutput(on);
84     }
85 }