]> git.basschouten.com Git - openhab-addons.git/blob
d21b60a9b502608f148524b6dfe65529aa85542f
[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.deconz.internal.handler;
14
15 import static org.openhab.binding.deconz.internal.BindingConstants.*;
16
17 import java.util.List;
18 import java.util.Map;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
21
22 import javax.measure.Unit;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.deconz.internal.Util;
27 import org.openhab.binding.deconz.internal.dto.DeconzBaseMessage;
28 import org.openhab.binding.deconz.internal.dto.SensorConfig;
29 import org.openhab.binding.deconz.internal.dto.SensorMessage;
30 import org.openhab.binding.deconz.internal.dto.SensorState;
31 import org.openhab.binding.deconz.internal.netutils.AsyncHttpClient;
32 import org.openhab.binding.deconz.internal.types.ResourceType;
33 import org.openhab.core.library.types.DecimalType;
34 import org.openhab.core.library.types.OnOffType;
35 import org.openhab.core.library.types.QuantityType;
36 import org.openhab.core.thing.Channel;
37 import org.openhab.core.thing.ChannelUID;
38 import org.openhab.core.thing.Thing;
39 import org.openhab.core.thing.ThingStatus;
40 import org.openhab.core.thing.ThingStatusDetail;
41 import org.openhab.core.thing.binding.ThingHandlerCallback;
42 import org.openhab.core.thing.type.ChannelKind;
43 import org.openhab.core.thing.type.ChannelTypeUID;
44 import org.openhab.core.types.Command;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import com.google.gson.Gson;
49
50 /**
51  * This sensor Thing doesn't establish any connections, that is done by the bridge Thing.
52  *
53  * It waits for the bridge to come online, grab the websocket connection and bridge configuration
54  * and registers to the websocket connection as a listener.
55  *
56  * A REST API call is made to get the initial sensor state.
57  *
58  * Every sensor and switch is supported by this Thing, because a unified state is kept
59  * in {@link #sensorState}. Every field that got received by the REST API for this specific
60  * sensor is published to the framework.
61  *
62  * @author David Graeff - Initial contribution
63  * @author Lukas Agethen - Refactored to provide better extensibility
64  */
65 @NonNullByDefault
66 public abstract class SensorBaseThingHandler extends DeconzBaseThingHandler<SensorMessage> {
67     private final Logger logger = LoggerFactory.getLogger(SensorBaseThingHandler.class);
68     /**
69      * The sensor state. Contains all possible fields for all supported sensors and switches
70      */
71     protected SensorConfig sensorConfig = new SensorConfig();
72     protected SensorState sensorState = new SensorState();
73     /**
74      * Prevent a dispose/init cycle while this flag is set. Use for property updates
75      */
76     private boolean ignoreConfigurationUpdate;
77     private @Nullable ScheduledFuture<?> lastSeenPollingJob;
78
79     public SensorBaseThingHandler(Thing thing, Gson gson) {
80         super(thing, gson, ResourceType.SENSORS);
81     }
82
83     @Override
84     public void dispose() {
85         ScheduledFuture<?> lastSeenPollingJob = this.lastSeenPollingJob;
86         if (lastSeenPollingJob != null) {
87             lastSeenPollingJob.cancel(true);
88             this.lastSeenPollingJob = null;
89         }
90
91         super.dispose();
92     }
93
94     @Override
95     public abstract void handleCommand(ChannelUID channelUID, Command command);
96
97     protected abstract void createTypeSpecificChannels(SensorConfig sensorState, SensorState sensorConfig);
98
99     protected abstract List<String> getConfigChannels();
100
101     @Override
102     public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
103         if (!ignoreConfigurationUpdate) {
104             super.handleConfigurationUpdate(configurationParameters);
105         }
106     }
107
108     @Override
109     protected @Nullable SensorMessage parseStateResponse(AsyncHttpClient.Result r) {
110         if (r.getResponseCode() == 403) {
111             return null;
112         } else if (r.getResponseCode() == 200) {
113             return gson.fromJson(r.getBody(), SensorMessage.class);
114         } else {
115             throw new IllegalStateException("Unknown status code " + r.getResponseCode() + " for full state request");
116         }
117     }
118
119     @Override
120     protected void processStateResponse(@Nullable SensorMessage stateResponse) {
121         logger.trace("{} received {}", thing.getUID(), stateResponse);
122         if (stateResponse == null) {
123             return;
124         }
125         SensorConfig newSensorConfig = stateResponse.config;
126         sensorConfig = newSensorConfig != null ? newSensorConfig : new SensorConfig();
127         SensorState newSensorState = stateResponse.state;
128         sensorState = newSensorState != null ? newSensorState : new SensorState();
129
130         // Add some information about the sensor
131         if (!sensorConfig.reachable) {
132             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE, "Not reachable");
133             return;
134         }
135
136         if (!sensorConfig.on) {
137             updateStatus(ThingStatus.OFFLINE);
138             return;
139         }
140
141         Map<String, String> editProperties = editProperties();
142         editProperties.put(Thing.PROPERTY_FIRMWARE_VERSION, stateResponse.swversion);
143         editProperties.put(Thing.PROPERTY_MODEL_ID, stateResponse.modelid);
144         editProperties.put(UNIQUE_ID, stateResponse.uniqueid);
145         ignoreConfigurationUpdate = true;
146         updateProperties(editProperties);
147
148         // Some sensors support optional channels
149         // (see https://github.com/dresden-elektronik/deconz-rest-plugin/wiki/Supported-Devices#sensors)
150         // any battery-powered sensor
151         if (sensorConfig.battery != null) {
152             createChannel(CHANNEL_BATTERY_LEVEL, ChannelKind.STATE);
153             createChannel(CHANNEL_BATTERY_LOW, ChannelKind.STATE);
154         }
155
156         createTypeSpecificChannels(sensorConfig, sensorState);
157
158         ignoreConfigurationUpdate = false;
159
160         // Initial data
161         updateChannels(sensorConfig);
162         updateChannels(sensorState, true);
163
164         // "Last seen" is the last "ping" from the device, whereas "last update" is the last status changed.
165         // For example, for a fire sensor, the device pings regularly, without necessarily updating channels.
166         // So to monitor a sensor is still alive, the "last seen" is necessary.
167         // Because "last seen" is never updated by the WebSocket API - if this is supported, then we have to
168         // manually poll it after the defined time
169         String lastSeen = stateResponse.lastseen;
170         if (lastSeen != null && config.lastSeenPolling > 0) {
171             createChannel(CHANNEL_LAST_SEEN, ChannelKind.STATE);
172             updateState(CHANNEL_LAST_SEEN, Util.convertTimestampToDateTime(lastSeen));
173             lastSeenPollingJob = scheduler.schedule(() -> requestState(this::processLastSeen), config.lastSeenPolling,
174                     TimeUnit.MINUTES);
175             logger.trace("lastSeen polling enabled for thing {} with interval of {} minutes", thing.getUID(),
176                     config.lastSeenPolling);
177         }
178
179         updateStatus(ThingStatus.ONLINE);
180     }
181
182     private void processLastSeen(@Nullable SensorMessage stateResponse) {
183         if (stateResponse == null) {
184             return;
185         }
186         String lastSeen = stateResponse.lastseen;
187         if (lastSeen != null) {
188             updateState(CHANNEL_LAST_SEEN, Util.convertTimestampToDateTime(lastSeen));
189         }
190     }
191
192     protected void createChannel(String channelId, ChannelKind kind) {
193         ThingHandlerCallback callback = getCallback();
194         if (callback != null) {
195             ChannelUID channelUID = new ChannelUID(thing.getUID(), channelId);
196             ChannelTypeUID channelTypeUID;
197             switch (channelId) {
198                 case CHANNEL_BATTERY_LEVEL:
199                     channelTypeUID = new ChannelTypeUID("system:battery-level");
200                     break;
201                 case CHANNEL_BATTERY_LOW:
202                     channelTypeUID = new ChannelTypeUID("system:low-battery");
203                     break;
204                 default:
205                     channelTypeUID = new ChannelTypeUID(BINDING_ID, channelId);
206                     break;
207             }
208             Channel channel = callback.createChannelBuilder(channelUID, channelTypeUID).withKind(kind).build();
209             updateThing(editThing().withoutChannel(channelUID).withChannel(channel).build());
210         }
211     }
212
213     /**
214      * Update channel value from {@link SensorConfig} object - override to include further channels
215      *
216      * @param channelUID
217      * @param newConfig
218      */
219     protected void valueUpdated(ChannelUID channelUID, SensorConfig newConfig) {
220         Integer batteryLevel = newConfig.battery;
221         switch (channelUID.getId()) {
222             case CHANNEL_BATTERY_LEVEL:
223                 if (batteryLevel != null) {
224                     updateState(channelUID, new DecimalType(batteryLevel.longValue()));
225                 }
226                 break;
227             case CHANNEL_BATTERY_LOW:
228                 if (batteryLevel != null) {
229                     updateState(channelUID, OnOffType.from(batteryLevel <= 10));
230                 }
231                 break;
232             default:
233                 // other cases covered by sub-class
234         }
235     }
236
237     /**
238      * Update channel value from {@link SensorState} object - override to include further channels
239      *
240      * @param channelID
241      * @param newState
242      * @param initializing
243      */
244     protected void valueUpdated(String channelID, SensorState newState, boolean initializing) {
245         switch (channelID) {
246             case CHANNEL_LAST_UPDATED:
247                 String lastUpdated = newState.lastupdated;
248                 if (lastUpdated != null && !"none".equals(lastUpdated)) {
249                     updateState(channelID, Util.convertTimestampToDateTime(lastUpdated));
250                 }
251                 break;
252             default:
253                 // other cases covered by sub-class
254         }
255     }
256
257     @Override
258     public void messageReceived(String sensorID, DeconzBaseMessage message) {
259         logger.trace("{} received {}", thing.getUID(), message);
260         if (message instanceof SensorMessage) {
261             SensorMessage sensorMessage = (SensorMessage) message;
262             SensorConfig sensorConfig = sensorMessage.config;
263             if (sensorConfig != null) {
264                 this.sensorConfig = sensorConfig;
265                 updateChannels(sensorConfig);
266             }
267             SensorState sensorState = sensorMessage.state;
268             if (sensorState != null) {
269                 updateChannels(sensorState, false);
270             }
271         }
272     }
273
274     private void updateChannels(SensorConfig newConfig) {
275         List<String> configChannels = getConfigChannels();
276         thing.getChannels().stream().map(Channel::getUID)
277                 .filter(channelUID -> configChannels.contains(channelUID.getId()))
278                 .forEach((channelUID) -> valueUpdated(channelUID, newConfig));
279     }
280
281     protected void updateChannels(SensorState newState, boolean initializing) {
282         sensorState = newState;
283         thing.getChannels().forEach(channel -> valueUpdated(channel.getUID().getId(), newState, initializing));
284     }
285
286     protected void updateSwitchChannel(String channelID, @Nullable Boolean value) {
287         if (value == null) {
288             return;
289         }
290         updateState(channelID, OnOffType.from(value));
291     }
292
293     protected void updateDecimalTypeChannel(String channelID, @Nullable Number value) {
294         if (value == null) {
295             return;
296         }
297         updateState(channelID, new DecimalType(value.longValue()));
298     }
299
300     protected void updateQuantityTypeChannel(String channelID, @Nullable Number value, Unit<?> unit) {
301         updateQuantityTypeChannel(channelID, value, unit, 1.0);
302     }
303
304     protected void updateQuantityTypeChannel(String channelID, @Nullable Number value, Unit<?> unit, double scaling) {
305         if (value == null) {
306             return;
307         }
308         updateState(channelID, new QuantityType<>(value.doubleValue() * scaling, unit));
309     }
310 }