]> git.basschouten.com Git - openhab-addons.git/blob
3badddd04fc7fde29f67627948781a33f99f59b8
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.openwebnet.handler;
14
15 import static org.openhab.binding.openwebnet.OpenWebNetBindingConstants.*;
16
17 import java.util.Map;
18 import java.util.concurrent.ScheduledFuture;
19 import java.util.concurrent.TimeUnit;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.core.thing.Bridge;
24 import org.openhab.core.thing.ChannelUID;
25 import org.openhab.core.thing.Thing;
26 import org.openhab.core.thing.ThingStatus;
27 import org.openhab.core.thing.ThingStatusDetail;
28 import org.openhab.core.thing.binding.BaseThingHandler;
29 import org.openhab.core.types.Command;
30 import org.openhab.core.types.RefreshType;
31 import org.openwebnet4j.OpenGateway;
32 import org.openwebnet4j.communication.OWNException;
33 import org.openwebnet4j.communication.Response;
34 import org.openwebnet4j.message.BaseOpenMessage;
35 import org.openwebnet4j.message.OpenMessage;
36 import org.openwebnet4j.message.Where;
37 import org.openwebnet4j.message.WhereLightAutom;
38 import org.openwebnet4j.message.WhereZigBee;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * The {@link OpenWebNetThingHandler} is responsible for handling commands for a OpenWebNet device.
44  * It's the abstract class for all OpenWebNet things. It should be extended by each specific OpenWebNet category of
45  * device (WHO).
46  *
47  * @author Massimo Valla - Initial contribution
48  */
49 @NonNullByDefault
50 public abstract class OpenWebNetThingHandler extends BaseThingHandler {
51
52     private final Logger logger = LoggerFactory.getLogger(OpenWebNetThingHandler.class);
53
54     protected @Nullable OpenWebNetBridgeHandler bridgeHandler;
55     protected @Nullable String ownId; // OpenWebNet identifier for this device: WHO.WHERE
56     protected @Nullable Where deviceWhere; // this device Where address
57
58     protected @Nullable ScheduledFuture<?> refreshTimeout;
59
60     public OpenWebNetThingHandler(Thing thing) {
61         super(thing);
62     }
63
64     @Override
65     public void initialize() {
66         Bridge bridge = getBridge();
67         if (bridge != null) {
68             OpenWebNetBridgeHandler brH = (OpenWebNetBridgeHandler) bridge.getHandler();
69             if (brH != null) {
70                 bridgeHandler = brH;
71                 Object deviceWhereConfig = getConfig().get(CONFIG_PROPERTY_WHERE);
72                 if (!(deviceWhereConfig instanceof String)) {
73                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
74                             "WHERE parameter in configuration is null or invalid");
75                     return;
76                 } else {
77                     String deviceWhereStr = (String) getConfig().get(CONFIG_PROPERTY_WHERE);
78                     Where w;
79                     if (brH.isBusGateway()) {
80                         w = new WhereLightAutom(deviceWhereStr);
81                     } else {
82                         w = new WhereZigBee(deviceWhereStr);
83                     }
84                     deviceWhere = w;
85                     final String oid = brH.ownIdFromDeviceWhere(w.value(), this);
86                     ownId = oid;
87                     Map<String, String> properties = editProperties();
88                     properties.put(PROPERTY_OWNID, oid);
89                     updateProperties(properties);
90                     brH.registerDevice(oid, this);
91                     logger.debug("associated thing to bridge with ownId={}", ownId);
92                     updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.NONE, "waiting state update...");
93                 }
94                 return;
95             }
96         }
97         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
98                 "No bridge associated, please assign a bridge in thing configuration.");
99     }
100
101     @Override
102     public void handleCommand(ChannelUID channel, Command command) {
103         logger.debug("handleCommand() (command={} - channel={})", command, channel);
104         OpenWebNetBridgeHandler handler = bridgeHandler;
105         if (handler != null) {
106             OpenGateway gw = handler.gateway;
107             if (gw != null && !gw.isConnected()) {
108                 logger.info("Cannot handle command {}:{} for {}: gateway is not connected", channel, command,
109                         getThing().getUID());
110                 return;
111             }
112             if (command instanceof RefreshType) {
113                 requestChannelState(channel);
114                 // set a schedule to put device OFFLINE if no answer is received after THING_STATE_REQ_TIMEOUT_SEC
115                 refreshTimeout = scheduler.schedule(() -> {
116                     if (thing.getStatus().equals(ThingStatus.UNKNOWN)) {
117                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
118                                 "Could not get channel state (timer expired)");
119                     }
120                 }, THING_STATE_REQ_TIMEOUT_SEC, TimeUnit.SECONDS);
121             } else {
122                 handleChannelCommand(channel, command);
123             }
124         } else {
125             logger.debug("Thing {} is not associated to any gateway, skipping command", getThing().getUID());
126         }
127     }
128
129     /**
130      * Handles a command for the specific channel for this thing.
131      * It must be implemented by each specific OpenWebNet category of device (WHO), based on channel
132      *
133      * @param channel specific ChannleUID
134      * @param command the Command to be executed
135      */
136     protected abstract void handleChannelCommand(ChannelUID channel, Command command);
137
138     /**
139      * Handle incoming message from OWN network via bridge Thing, directed to this device. It should be further
140      * implemented by each specific device handler.
141      *
142      * @param msg the message to handle
143      */
144     protected void handleMessage(BaseOpenMessage msg) {
145         ThingStatus ts = getThing().getStatus();
146         if (ThingStatus.ONLINE != ts && ThingStatus.REMOVING != ts && ThingStatus.REMOVED != ts) {
147             updateStatus(ThingStatus.ONLINE);
148         }
149     }
150
151     /**
152      * Helper method to send OWN messages from ThingsHandlers
153      */
154     protected @Nullable Response send(OpenMessage msg) throws OWNException {
155         OpenWebNetBridgeHandler handler = bridgeHandler;
156         if (handler != null) {
157             OpenGateway gw = handler.gateway;
158             if (gw != null) {
159                 return gw.send(msg);
160             }
161         }
162         return null;
163     }
164
165     /**
166      * Helper method to send with high priority OWN messages from ThingsHandlers
167      */
168     protected @Nullable Response sendHighPriority(OpenMessage msg) throws OWNException {
169         OpenWebNetBridgeHandler handler = bridgeHandler;
170         if (handler != null) {
171             OpenGateway gw = handler.gateway;
172             if (gw != null) {
173                 return gw.sendHighPriority(msg);
174             }
175         }
176         return null;
177     }
178
179     /**
180      * Request to gateway state for thing channel. It must be implemented by each specific device handler.
181      *
182      * @param channel the channel to request the state for
183      */
184     protected abstract void requestChannelState(ChannelUID channel);
185
186     @Override
187     public void dispose() {
188         OpenWebNetBridgeHandler bh = bridgeHandler;
189         String oid = ownId;
190         if (bh != null && oid != null) {
191             bh.unregisterDevice(oid);
192         }
193         ScheduledFuture<?> sc = refreshTimeout;
194         if (sc != null) {
195             sc.cancel(true);
196         }
197         super.dispose();
198     }
199
200     /**
201      * Returns a prefix String for ownId specific for each handler. To be implemented by sub-classes.
202      *
203      * @return
204      */
205     protected abstract String ownIdPrefix();
206 }