]> git.basschouten.com Git - openhab-addons.git/blob
14400945cbd18f67217a863f58bc665701db317a
[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.Objects;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22
23 import javax.measure.Unit;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.deconz.internal.Util;
28 import org.openhab.binding.deconz.internal.dto.DeconzBaseMessage;
29 import org.openhab.binding.deconz.internal.dto.SensorConfig;
30 import org.openhab.binding.deconz.internal.dto.SensorMessage;
31 import org.openhab.binding.deconz.internal.dto.SensorState;
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 {
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 void processStateResponse(DeconzBaseMessage stateResponse) {
110         if (!(stateResponse instanceof SensorMessage)) {
111             return;
112         }
113
114         SensorMessage sensorMessage = (SensorMessage) stateResponse;
115         sensorConfig = Objects.requireNonNullElse(sensorMessage.config, new SensorConfig());
116         sensorState = Objects.requireNonNullElse(sensorMessage.state, new SensorState());
117
118         // Add some information about the sensor
119         if (!sensorConfig.reachable) {
120             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE, "Not reachable");
121             return;
122         }
123
124         if (!sensorConfig.on) {
125             updateStatus(ThingStatus.OFFLINE);
126             return;
127         }
128
129         Map<String, String> editProperties = editProperties();
130         editProperties.put(UNIQUE_ID, sensorMessage.uniqueid);
131         editProperties.put(Thing.PROPERTY_FIRMWARE_VERSION, sensorMessage.swversion);
132         editProperties.put(Thing.PROPERTY_VENDOR, sensorMessage.manufacturername);
133         editProperties.put(Thing.PROPERTY_MODEL_ID, sensorMessage.modelid);
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         // "Last seen" is the last "ping" from the device, whereas "last update" is the last status changed.
150         // For example, for a fire sensor, the device pings regularly, without necessarily updating channels.
151         // So to monitor a sensor is still alive, the "last seen" is necessary.
152         // Because "last seen" is never updated by the WebSocket API - if this is supported, then we have to
153         // manually poll it after the defined time
154         String lastSeen = sensorMessage.lastseen;
155         if (lastSeen != null && config.lastSeenPolling > 0) {
156             createChannel(CHANNEL_LAST_SEEN, ChannelKind.STATE);
157             updateState(CHANNEL_LAST_SEEN, Util.convertTimestampToDateTime(lastSeen));
158             lastSeenPollingJob = scheduler.schedule(() -> requestState(this::processLastSeen), config.lastSeenPolling,
159                     TimeUnit.MINUTES);
160             logger.trace("lastSeen polling enabled for thing {} with interval of {} minutes", thing.getUID(),
161                     config.lastSeenPolling);
162         }
163
164         // Initial data
165         updateChannels(sensorConfig);
166         updateChannels(sensorState, true);
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         if (thing.getChannel(channelId) != null) {
180             // channel already exists, no update necessary
181             return;
182         }
183
184         ThingHandlerCallback callback = getCallback();
185         if (callback != null) {
186             ChannelUID channelUID = new ChannelUID(thing.getUID(), channelId);
187             ChannelTypeUID channelTypeUID;
188             switch (channelId) {
189                 case CHANNEL_BATTERY_LEVEL:
190                     channelTypeUID = new ChannelTypeUID("system:battery-level");
191                     break;
192                 case CHANNEL_BATTERY_LOW:
193                     channelTypeUID = new ChannelTypeUID("system:low-battery");
194                     break;
195                 default:
196                     channelTypeUID = new ChannelTypeUID(BINDING_ID, channelId);
197                     break;
198             }
199             Channel channel = callback.createChannelBuilder(channelUID, channelTypeUID).withKind(kind).build();
200             updateThing(editThing().withChannel(channel).build());
201         }
202     }
203
204     /**
205      * Update channel value from {@link SensorConfig} object - override to include further channels
206      *
207      * @param channelUID
208      * @param newConfig
209      */
210     protected void valueUpdated(ChannelUID channelUID, SensorConfig newConfig) {
211         Integer batteryLevel = newConfig.battery;
212         switch (channelUID.getId()) {
213             case CHANNEL_BATTERY_LEVEL:
214                 if (batteryLevel != null) {
215                     updateState(channelUID, new DecimalType(batteryLevel.longValue()));
216                 }
217                 break;
218             case CHANNEL_BATTERY_LOW:
219                 if (batteryLevel != null) {
220                     updateState(channelUID, OnOffType.from(batteryLevel <= 10));
221                 }
222                 break;
223             default:
224                 // other cases covered by sub-class
225         }
226     }
227
228     /**
229      * Update channel value from {@link SensorState} object - override to include further channels
230      *
231      * @param channelID
232      * @param newState
233      * @param initializing
234      */
235     protected void valueUpdated(String channelID, SensorState newState, boolean initializing) {
236         switch (channelID) {
237             case CHANNEL_LAST_UPDATED:
238                 String lastUpdated = newState.lastupdated;
239                 if (lastUpdated != null && !"none".equals(lastUpdated)) {
240                     updateState(channelID, Util.convertTimestampToDateTime(lastUpdated));
241                 }
242                 break;
243             default:
244                 // other cases covered by sub-class
245         }
246     }
247
248     @Override
249     public void messageReceived(String sensorID, DeconzBaseMessage message) {
250         logger.trace("{} received {}", thing.getUID(), message);
251         if (message instanceof SensorMessage) {
252             SensorMessage sensorMessage = (SensorMessage) message;
253             SensorConfig sensorConfig = sensorMessage.config;
254             if (sensorConfig != null) {
255                 this.sensorConfig = sensorConfig;
256                 updateChannels(sensorConfig);
257             }
258             SensorState sensorState = sensorMessage.state;
259             if (sensorState != null) {
260                 updateChannels(sensorState, false);
261             }
262         }
263     }
264
265     private void updateChannels(SensorConfig newConfig) {
266         List<String> configChannels = getConfigChannels();
267         thing.getChannels().stream().map(Channel::getUID)
268                 .filter(channelUID -> configChannels.contains(channelUID.getId()))
269                 .forEach((channelUID) -> valueUpdated(channelUID, newConfig));
270     }
271
272     protected void updateChannels(SensorState newState, boolean initializing) {
273         sensorState = newState;
274         thing.getChannels().forEach(channel -> valueUpdated(channel.getUID().getId(), newState, initializing));
275     }
276
277     protected void updateSwitchChannel(String channelID, @Nullable Boolean value) {
278         if (value == null) {
279             return;
280         }
281         updateState(channelID, OnOffType.from(value));
282     }
283
284     protected void updateDecimalTypeChannel(String channelID, @Nullable Number value) {
285         if (value == null) {
286             return;
287         }
288         updateState(channelID, new DecimalType(value.longValue()));
289     }
290
291     protected void updateQuantityTypeChannel(String channelID, @Nullable Number value, Unit<?> unit) {
292         updateQuantityTypeChannel(channelID, value, unit, 1.0);
293     }
294
295     protected void updateQuantityTypeChannel(String channelID, @Nullable Number value, Unit<?> unit, double scaling) {
296         if (value == null) {
297             return;
298         }
299         updateState(channelID, new QuantityType<>(value.doubleValue() * scaling, unit));
300     }
301 }