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.automation.pwm.internal.handler.state;
15 import java.util.concurrent.ScheduledExecutorService;
16 import java.util.function.Function;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * The base class of all states.
25 * @author Fabian Wolter - Initial Contribution
28 public abstract class State {
29 private final Logger logger = LoggerFactory.getLogger(State.class);
30 protected StateMachine context;
31 protected ScheduledExecutorService scheduler;
33 public State(StateMachine context) {
34 this.context = context;
35 this.scheduler = context.getScheduler();
39 * Invoked when the duty cycle updated and changed.
41 public abstract void dutyCycleChanged();
44 * Invoked when the duty cycle updated.
46 protected abstract void dutyCycleUpdated();
48 public abstract void dispose();
51 * Sets a new state in the state machine.
53 @SuppressWarnings("PMD.CompareObjectsWithEquals")
54 public synchronized void nextState(Function<StateMachine, ? extends State> nextState) {
55 if (context.getState() != this) { // compare identity
59 context.getState().dispose();
60 State newState = nextState.apply(context);
62 logger.trace("{}: {} -> {}", context.getRuleUID(), context.getState().getClass().getSimpleName(),
63 newState.getClass().getSimpleName());
65 context.setState(newState);
69 * Calculates the ON duration by the duty cycle.
71 * @param dutyCycleInPercent the duty cycle in percent
72 * @return the ON duration in ms
74 protected long calculateOnTimeMs(double dutyCycleInPercent) {
75 return (long) (context.getPeriodMs() / 100 * dutyCycleInPercent);
79 * Switches the output on or off.
81 * @param on true, if the output shall be switched on.
83 protected void controlOutput(boolean on) {
84 context.controlOutput(on);