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.ArrayList;
16 import java.util.Collections;
17 import java.util.List;
18 import java.util.concurrent.ScheduledFuture;
19 import java.util.function.Function;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
24 * Base class for all states used with {@link AbstractStateMachine}.
26 * @param <T> type of the state machine implementation
27 * @param <U> type of the state implementation
29 * @author Fabian Wolter - Initial Contribution
32 public abstract class AbstractState<T extends AbstractStateMachine<T, U>, U extends AbstractState<T, U>> {
33 private final List<ScheduledFuture<?>> usedTimers = Collections.synchronizedList(new ArrayList<>());
34 protected final T context;
36 public AbstractState(T context) {
37 this.context = context;
41 * Invoked when the State shall start its operation.
43 protected abstract void startWorking();
46 * Stops all timers, the State has been started.
48 protected void cancelAllTimers() {
49 synchronized (usedTimers) {
50 usedTimers.forEach(t -> t.cancel(true));
55 * When a state starts a timer, its ScheduledFuture must be registered by this method. All timers added by this
56 * method, are canceled when the StateMachine leaves this State.
58 * @param timer the new timer
60 protected void addTimer(ScheduledFuture<?> timer) {
61 usedTimers.add(timer);
65 * Sets a new State. The current state is torn down gracefully.
67 * @param newStateFactory the lambda returning the new State
69 protected void nextState(Function<T, U> newStateFactory) {
70 synchronized (context) {
71 if (context.isStateActive(this)) {
72 context.setState(newStateFactory);