]> git.basschouten.com Git - openhab-addons.git/blob
a2cb8ba4c42087e481b1d94f5d8b98dd2495dc32
[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.lcn.internal.connection;
14
15 import java.util.function.Function;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 /**
23  * Base class for state machines.
24  *
25  * @param <T> type of the state machine implementation
26  * @param <U> type of the state implementation
27  *
28  * @author Fabian Wolter - Initial Contribution
29  */
30 @NonNullByDefault
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;
35
36     /**
37      * Sets the current state.
38      *
39      * @param newStateFactory the new state's factory
40      */
41     protected synchronized void setState(Function<T, U> newStateFactory) {
42         @Nullable
43         U localState = state;
44         if (localState != null) {
45             localState.cancelAllTimers();
46         }
47
48         @SuppressWarnings("unchecked")
49         U newState = newStateFactory.apply((T) this);
50
51         if (localState != null) {
52             logger.debug("Changing state {} -> {}", localState.getClass().getSimpleName(),
53                     newState.getClass().getSimpleName());
54         }
55
56         state = newState;
57
58         newState.startWorking();
59     }
60
61     @SuppressWarnings("PMD.CompareObjectsWithEquals")
62     protected boolean isStateActive(AbstractState<?, ?> otherState) {
63         return state == otherState; // compare by identity
64     }
65 }