]> git.basschouten.com Git - openhab-addons.git/blob
483937d3b1823b4295c99746f41e1bbdf7b37902
[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.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.getRuleUID(), context.getState().getClass().getSimpleName(),
63                 newState.getClass().getSimpleName());
64
65         context.setState(newState);
66     }
67
68     /**
69      * Calculates the ON duration by the duty cycle.
70      *
71      * @param dutyCycleInPercent the duty cycle in percent
72      * @return the ON duration in ms
73      */
74     protected long calculateOnTimeMs(double dutyCycleInPercent) {
75         return (long) (context.getPeriodMs() / 100 * dutyCycleInPercent);
76     }
77
78     /**
79      * Switches the output on or off.
80      *
81      * @param on true, if the output shall be switched on.
82      */
83     protected void controlOutput(boolean on) {
84         context.controlOutput(on);
85     }
86 }