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.lcn.internal.connection;
15 import java.util.function.Function;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * Base class for state machines.
25 * @param <T> type of the state machine implementation
26 * @param <U> type of the state implementation
28 * @author Fabian Wolter - Initial Contribution
31 public abstract class AbstractStateMachine<T extends AbstractStateMachine<T, U>, U extends AbstractState<T, U>> {
32 private final Logger logger = LoggerFactory.getLogger(AbstractStateMachine.class);
33 /** The StateMachine's current state */
34 protected @Nullable volatile U state;
37 * Sets the current state.
39 * @param newStateFactory the new state's factory
41 protected synchronized void setState(Function<T, U> newStateFactory) {
44 if (localState != null) {
45 localState.cancelAllTimers();
48 @SuppressWarnings("unchecked")
49 U newState = newStateFactory.apply((T) this);
51 if (localState != null) {
52 logger.debug("Changing state {} -> {}", localState.getClass().getSimpleName(),
53 newState.getClass().getSimpleName());
58 newState.startWorking();
61 @SuppressWarnings("PMD.CompareObjectsWithEquals")
62 protected boolean isStateActive(AbstractState<?, ?> otherState) {
63 return state == otherState; // compare by identity