]> git.basschouten.com Git - openhab-addons.git/blob
9fc42221ca03893b6d2e83ff8f5809d195bd3ba7
[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.omnilink.internal.handler;
14
15 import java.util.Optional;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.core.thing.Bridge;
19 import org.openhab.core.thing.ChannelUID;
20 import org.openhab.core.thing.Thing;
21 import org.openhab.core.thing.ThingStatus;
22 import org.openhab.core.thing.ThingStatusDetail;
23
24 import com.digitaldan.jomnilinkII.MessageTypes.statuses.Status;
25
26 /**
27  * The {@link AbstractOmnilinkStatusHandler} defines some methods that can be used across
28  * the many different units exposed by the OmniLink protocol to retrive updated status information.
29  *
30  * @author Craig Hamilton - Initial contribution
31  * @author Ethan Dye - openHAB3 rewrite
32  */
33 @NonNullByDefault
34 public abstract class AbstractOmnilinkStatusHandler<T extends Status> extends AbstractOmnilinkHandler {
35     public AbstractOmnilinkStatusHandler(Thing thing) {
36         super(thing);
37     }
38
39     private volatile Optional<T> status = Optional.empty();
40
41     @Override
42     public void initialize() {
43         updateHandlerStatus();
44     }
45
46     /**
47      * Attempt to retrieve an updated status for this handler type.
48      *
49      * @return Optional with updated status if possible, empty optional otherwise.
50      */
51     protected abstract Optional<T> retrieveStatus();
52
53     /**
54      * Update channels associated with handler
55      *
56      * @param t Status object to update channels with
57      */
58     protected abstract void updateChannels(T t);
59
60     /**
61      * Process a status update for this handler. This will dispatch updateChannels where appropriate.
62      *
63      * @param t Status to process.
64      */
65     public void handleStatus(T t) {
66         this.status = Optional.of(t);
67         updateChannels(t);
68     }
69
70     @Override
71     public void channelLinked(ChannelUID channelUID) {
72         status.ifPresent(this::updateChannels);
73     }
74
75     private void updateHandlerStatus() {
76         Bridge bridge = getBridge();
77         if (bridge != null && bridge.getStatus() == ThingStatus.ONLINE) {
78             updateStatus(ThingStatus.ONLINE);
79             retrieveStatus().ifPresentOrElse(this::updateChannels, () -> updateStatus(ThingStatus.OFFLINE,
80                     ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Received null status update!"));
81         }
82     }
83 }