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