]> git.basschouten.com Git - openhab-addons.git/blob
fb21b64a510949ba96d49f4bc2a5ad0c50ff605a
[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.ArrayList;
16 import java.util.Collections;
17 import java.util.List;
18 import java.util.concurrent.ScheduledFuture;
19 import java.util.function.Function;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22
23 /**
24  * Base class for all states used with {@link AbstractStateMachine}.
25  *
26  * @param <T> type of the state machine implementation
27  * @param <U> type of the state implementation
28  *
29  * @author Fabian Wolter - Initial Contribution
30  */
31 @NonNullByDefault
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;
35
36     public AbstractState(T context) {
37         this.context = context;
38     }
39
40     /**
41      * Invoked when the State shall start its operation.
42      */
43     protected abstract void startWorking();
44
45     /**
46      * Stops all timers, the State has been started.
47      */
48     protected void cancelAllTimers() {
49         synchronized (usedTimers) {
50             usedTimers.forEach(t -> t.cancel(true));
51         }
52     }
53
54     /**
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.
57      *
58      * @param timer the new timer
59      */
60     protected void addTimer(ScheduledFuture<?> timer) {
61         usedTimers.add(timer);
62     }
63
64     /**
65      * Sets a new State. The current state is torn down gracefully.
66      *
67      * @param newStateFactory the lambda returning the new State
68      */
69     protected void nextState(Function<T, U> newStateFactory) {
70         synchronized (context) {
71             if (context.isStateActive(this)) {
72                 context.setState(newStateFactory);
73             }
74         }
75     }
76 }