]> git.basschouten.com Git - openhab-addons.git/blob
6072c3a6dbaa5430d81291b9928af4380ace5791
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.bluetooth.govee.internal;
14
15 import static org.openhab.binding.bluetooth.govee.internal.GoveeBindingConstants.*;
16
17 import java.nio.ByteBuffer;
18 import java.nio.ByteOrder;
19 import java.util.Map;
20 import java.util.UUID;
21 import java.util.concurrent.CompletableFuture;
22 import java.util.concurrent.CompletionException;
23 import java.util.concurrent.Future;
24 import java.util.concurrent.ScheduledExecutorService;
25 import java.util.concurrent.TimeUnit;
26 import java.util.function.Consumer;
27
28 import javax.measure.Quantity;
29 import javax.measure.quantity.Dimensionless;
30 import javax.measure.quantity.Temperature;
31
32 import org.eclipse.jdt.annotation.NonNullByDefault;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.openhab.binding.bluetooth.BluetoothCharacteristic;
35 import org.openhab.binding.bluetooth.BluetoothDevice.ConnectionState;
36 import org.openhab.binding.bluetooth.ConnectedBluetoothHandler;
37 import org.openhab.binding.bluetooth.gattserial.MessageServicer;
38 import org.openhab.binding.bluetooth.gattserial.SimpleGattSocket;
39 import org.openhab.binding.bluetooth.govee.internal.command.hygrometer.GetBatteryCommand;
40 import org.openhab.binding.bluetooth.govee.internal.command.hygrometer.GetOrSetHumCaliCommand;
41 import org.openhab.binding.bluetooth.govee.internal.command.hygrometer.GetOrSetHumWarningCommand;
42 import org.openhab.binding.bluetooth.govee.internal.command.hygrometer.GetOrSetTemCaliCommand;
43 import org.openhab.binding.bluetooth.govee.internal.command.hygrometer.GetOrSetTemWarningCommand;
44 import org.openhab.binding.bluetooth.govee.internal.command.hygrometer.GetTemHumCommand;
45 import org.openhab.binding.bluetooth.govee.internal.command.hygrometer.GoveeMessage;
46 import org.openhab.binding.bluetooth.govee.internal.command.hygrometer.TemHumDTO;
47 import org.openhab.binding.bluetooth.govee.internal.command.hygrometer.WarningSettingsDTO;
48 import org.openhab.binding.bluetooth.notification.BluetoothScanNotification;
49 import org.openhab.binding.bluetooth.util.HeritableFuture;
50 import org.openhab.binding.bluetooth.util.RetryException;
51 import org.openhab.binding.bluetooth.util.RetryFuture;
52 import org.openhab.core.library.types.OnOffType;
53 import org.openhab.core.library.types.QuantityType;
54 import org.openhab.core.library.unit.SIUnits;
55 import org.openhab.core.library.unit.Units;
56 import org.openhab.core.thing.ChannelUID;
57 import org.openhab.core.thing.Thing;
58 import org.openhab.core.thing.ThingStatus;
59 import org.openhab.core.thing.ThingStatusDetail;
60 import org.openhab.core.types.Command;
61 import org.openhab.core.types.RefreshType;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 /**
66  * @author Connor Petty - Initial contribution
67  *
68  */
69 @NonNullByDefault
70 public class GoveeHygrometerHandler extends ConnectedBluetoothHandler {
71
72     private static final UUID SERVICE_UUID = UUID.fromString("494e5445-4c4c-495f-524f-434b535f4857");
73     private static final UUID PROTOCOL_CHAR_UUID = UUID.fromString("494e5445-4c4c-495f-524f-434b535f2011");
74     private static final UUID KEEP_ALIVE_CHAR_UUID = UUID.fromString("494e5445-4c4c-495f-524f-434b535f2012");
75
76     private static final byte[] SCAN_HEADER = { (byte) 0xFF, (byte) 0x88, (byte) 0xEC };
77
78     private final Logger logger = LoggerFactory.getLogger(GoveeHygrometerHandler.class);
79
80     private final CommandSocket commandSocket = new CommandSocket();
81
82     private GoveeHygrometerConfiguration config = new GoveeHygrometerConfiguration();
83     private GoveeModel model = GoveeModel.H5074;// we use this as our default model
84
85     private CompletableFuture<?> initializeJob = CompletableFuture.completedFuture(null);// initially set to a dummy
86                                                                                          // future
87     private Future<?> scanJob = CompletableFuture.completedFuture(null);
88     private Future<?> keepAliveJob = CompletableFuture.completedFuture(null);
89
90     public GoveeHygrometerHandler(Thing thing) {
91         super(thing);
92     }
93
94     @Override
95     public void initialize() {
96         super.initialize();
97         if (thing.getStatus() == ThingStatus.OFFLINE) {
98             // something went wrong in super.initialize() so we shouldn't initialize further here either
99             return;
100         }
101
102         config = getConfigAs(GoveeHygrometerConfiguration.class);
103
104         Map<String, String> properties = thing.getProperties();
105         String modelProp = properties.get(Thing.PROPERTY_MODEL_ID);
106         model = GoveeModel.H5074;
107         if (modelProp != null) {
108             try {
109                 model = GoveeModel.valueOf(modelProp);
110             } catch (IllegalArgumentException ex) {
111                 // ignore
112             }
113         }
114
115         logger.debug("Initializing Govee Hygrometer {} model: {}", address, model);
116         initializeJob = RetryFuture.composeWithRetry(this::createInitSettingsJob, scheduler)//
117                 .thenRun(() -> {
118                     updateStatus(ThingStatus.ONLINE);
119                 });
120         scanJob = scheduler.scheduleWithFixedDelay(() -> {
121             try {
122                 if (initializeJob.isDone() && !initializeJob.isCompletedExceptionally()) {
123                     logger.debug("refreshing temperature, humidity, and battery");
124                     refreshBattery().join();
125                     refreshTemperatureAndHumidity().join();
126                     disconnect();
127                     updateStatus(ThingStatus.ONLINE);
128                 }
129             } catch (RuntimeException ex) {
130                 logger.warn("unable to refresh", ex);
131             }
132         }, 0, config.refreshInterval, TimeUnit.SECONDS);
133         keepAliveJob = scheduler.scheduleWithFixedDelay(() -> {
134             if (device.getConnectionState() == ConnectionState.CONNECTED) {
135                 try {
136                     GoveeMessage message = new GoveeMessage((byte) 0xAA, (byte) 1, null);
137                     writeCharacteristic(SERVICE_UUID, KEEP_ALIVE_CHAR_UUID, message.getPayload(), false);
138                 } catch (RuntimeException ex) {
139                     logger.warn("unable to send keep alive", ex);
140                 }
141             }
142         }, 1, 2, TimeUnit.SECONDS);
143     }
144
145     @Override
146     public void dispose() {
147         initializeJob.cancel(false);
148         scanJob.cancel(false);
149         keepAliveJob.cancel(false);
150         super.dispose();
151     }
152
153     private CompletableFuture<@Nullable ?> createInitSettingsJob() {
154
155         logger.debug("Initializing Govee Hygrometer {} settings", address);
156
157         QuantityType<Temperature> temCali = config.getTemperatureCalibration();
158         QuantityType<Dimensionless> humCali = config.getHumidityCalibration();
159         WarningSettingsDTO<Temperature> temWarnSettings = config.getTemperatureWarningSettings();
160         WarningSettingsDTO<Dimensionless> humWarnSettings = config.getHumidityWarningSettings();
161
162         final CompletableFuture<@Nullable ?> parent = new HeritableFuture<>();
163         CompletableFuture<@Nullable ?> future = parent;
164         future.complete(null);
165
166         if (temCali != null) {
167             future = future.thenCompose(v -> {
168                 CompletableFuture<@Nullable QuantityType<Temperature>> caliFuture = parent.newIncompleteFuture();
169                 commandSocket.sendMessage(new GetOrSetTemCaliCommand(temCali, caliFuture));
170                 return caliFuture;
171             });
172         }
173         if (humCali != null) {
174             future = future.thenCompose(v -> {
175                 CompletableFuture<@Nullable QuantityType<Dimensionless>> caliFuture = parent.newIncompleteFuture();
176                 commandSocket.sendMessage(new GetOrSetHumCaliCommand(humCali, caliFuture));
177                 return caliFuture;
178             });
179         }
180         if (model.supportsWarningBroadcast()) {
181             future = future.thenCompose(v -> {
182                 CompletableFuture<@Nullable WarningSettingsDTO<Temperature>> temWarnFuture = parent
183                         .newIncompleteFuture();
184                 commandSocket.sendMessage(new GetOrSetTemWarningCommand(temWarnSettings, temWarnFuture));
185                 return temWarnFuture;
186             }).thenCompose(v -> {
187                 CompletableFuture<@Nullable WarningSettingsDTO<Dimensionless>> humWarnFuture = parent
188                         .newIncompleteFuture();
189                 commandSocket.sendMessage(new GetOrSetHumWarningCommand(humWarnSettings, humWarnFuture));
190                 return humWarnFuture;
191             });
192         }
193
194         // CompletableFuture.exceptionallyCompose isn't available yet so we have to compose it manually for now.
195         CompletableFuture<@Nullable Void> retFuture = future.newIncompleteFuture();
196         future.whenComplete((v, th) -> {
197             if (th instanceof CompletionException) {
198                 th = th.getCause();
199             }
200             if (th instanceof RuntimeException) {
201                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
202                         "Failed to initialize device: " + th.getMessage());
203                 retFuture.completeExceptionally(th);
204             } else if (th != null) {
205                 logger.debug("Failure to initialize device: {}. Retrying in 30 seconds", th.getMessage());
206                 retFuture.completeExceptionally(new RetryException(30, TimeUnit.SECONDS));
207             } else {
208                 retFuture.complete(null);
209             }
210         });
211         return retFuture;
212     }
213
214     @Override
215     public void handleCommand(ChannelUID channelUID, Command command) {
216         super.handleCommand(channelUID, command);
217
218         switch (channelUID.getId()) {
219             case CHANNEL_ID_BATTERY:
220                 if (command == RefreshType.REFRESH) {
221                     refreshBattery();
222                 }
223                 return;
224             case CHANNEL_ID_TEMPERATURE:
225             case CHANNEL_ID_HUMIDITY:
226                 if (command == RefreshType.REFRESH) {
227                     refreshTemperatureAndHumidity();
228                 }
229                 return;
230         }
231     }
232
233     private CompletableFuture<@Nullable ?> refreshBattery() {
234         CompletableFuture<@Nullable QuantityType<Dimensionless>> future = new CompletableFuture<>();
235         commandSocket.sendMessage(new GetBatteryCommand(future));
236         future.whenCompleteAsync(this::updateBattery, scheduler);
237         return future;
238     }
239
240     private void updateBattery(@Nullable QuantityType<Dimensionless> result, @Nullable Throwable th) {
241         if (th != null) {
242             logger.debug("Failed to get battery: {}", th.getMessage());
243         }
244         if (result == null) {
245             return;
246         }
247         updateState(CHANNEL_ID_BATTERY, result);
248     }
249
250     private CompletableFuture<@Nullable ?> refreshTemperatureAndHumidity() {
251         CompletableFuture<@Nullable TemHumDTO> future = new CompletableFuture<>();
252         commandSocket.sendMessage(new GetTemHumCommand(future));
253         future.whenCompleteAsync(this::updateTemperatureAndHumidity, scheduler);
254         return future;
255     }
256
257     private void updateTemperatureAndHumidity(@Nullable TemHumDTO result, @Nullable Throwable th) {
258         if (th != null) {
259             logger.debug("Failed to get temperature/humidity: {}", th.getMessage());
260         }
261         if (result == null) {
262             return;
263         }
264         QuantityType<Temperature> tem = result.temperature;
265         QuantityType<Dimensionless> hum = result.humidity;
266         if (tem == null || hum == null) {
267             return;
268         }
269         updateState(CHANNEL_ID_TEMPERATURE, tem);
270         updateState(CHANNEL_ID_HUMIDITY, hum);
271         if (model.supportsWarningBroadcast()) {
272             updateAlarm(CHANNEL_ID_TEMPERATURE_ALARM, tem, config.getTemperatureWarningSettings());
273             updateAlarm(CHANNEL_ID_HUMIDITY_ALARM, hum, config.getHumidityWarningSettings());
274         }
275     }
276
277     private <T extends Quantity<T>> void updateAlarm(String channelName, QuantityType<T> quantity,
278             WarningSettingsDTO<T> settings) {
279         boolean outOfRange = quantity.compareTo(settings.min) < 0 || settings.max.compareTo(quantity) < 0;
280         updateState(channelName, OnOffType.from(outOfRange));
281     }
282
283     private int scanPacketSize() {
284         switch (model) {
285             case B5175:
286             case B5178:
287                 return 10;
288             case H5179:
289                 return 8;
290             default:
291                 return 7;
292         }
293     }
294
295     @Override
296     public void onScanRecordReceived(BluetoothScanNotification scanNotification) {
297         super.onScanRecordReceived(scanNotification);
298         byte[] scanData = scanNotification.getData();
299         int dataPacketSize = scanPacketSize();
300         int recordIndex = indexOfTemHumRecord(scanData);
301         if (recordIndex == -1 || recordIndex + dataPacketSize >= scanData.length) {
302             return;
303         }
304
305         ByteBuffer data = ByteBuffer.wrap(scanData, recordIndex, dataPacketSize);
306
307         short temperature;
308         int humidity;
309         int battery;
310         int wifiLevel = 0;
311
312         switch (model) {
313             default:
314                 data.position(2);// we throw this away
315                 // fall through
316             case H5072:
317             case H5075:
318                 data.order(ByteOrder.BIG_ENDIAN);
319                 int l = data.getInt();
320                 l = l & 0xFFFFFF;
321
322                 boolean positive = (l & 0x800000) == 0;
323                 int tem = (short) ((l / 1000) * 10);
324                 if (!positive) {
325                     tem = -tem;
326                 }
327                 temperature = (short) tem;
328                 humidity = (l % 1000) * 10;
329                 battery = data.get();
330                 break;
331             case H5179:
332                 data.order(ByteOrder.LITTLE_ENDIAN);
333                 data.position(3);
334                 temperature = data.getShort();
335                 humidity = data.getShort();
336                 battery = Byte.toUnsignedInt(data.get());
337                 break;
338             case H5051:
339             case H5052:
340             case H5071:
341             case H5074:
342                 data.order(ByteOrder.LITTLE_ENDIAN);
343                 boolean hasWifi = data.get() == 0;
344                 temperature = data.getShort();
345                 humidity = Short.toUnsignedInt(data.getShort());
346                 battery = Byte.toUnsignedInt(data.get());
347                 wifiLevel = hasWifi ? Byte.toUnsignedInt(data.get()) : 0;
348                 break;
349         }
350         updateTemHumBattery(temperature, humidity, battery, wifiLevel);
351     }
352
353     private static int indexOfTemHumRecord(byte @Nullable [] scanData) {
354         if (scanData == null || scanData.length != 62) {
355             return -1;
356         }
357         int i = 0;
358         while (i < 57) {
359             int recordLength = scanData[i] & 0xFF;
360             if (scanData[i + 1] == SCAN_HEADER[0]//
361                     && scanData[i + 2] == SCAN_HEADER[1]//
362                     && scanData[i + 3] == SCAN_HEADER[2]) {
363                 return i + 4;
364             }
365
366             i += recordLength + 1;
367         }
368         return -1;
369     }
370
371     private void updateTemHumBattery(short tem, int hum, int battery, int wifiLevel) {
372         if (Short.toUnsignedInt(tem) == 0xFFFF || hum == 0xFFFF) {
373             logger.trace("Govee device [{}] received invalid data", this.address);
374             return;
375         }
376
377         logger.debug("Govee device [{}] received broadcast: tem = {}, hum = {}, battery = {}, wifiLevel = {}",
378                 this.address, tem, hum, battery, wifiLevel);
379
380         if (tem == 0 && hum == 0 && battery == 0) {
381             logger.trace("Govee device [{}] values are zero", this.address);
382             return;
383         }
384         if (tem < -4000 || tem > 10000) {
385             logger.trace("Govee device [{}] invalid temperature value: {}", this.address, tem);
386             return;
387         }
388         if (hum > 10000) {
389             logger.trace("Govee device [{}] invalid humidity valie: {}", this.address, hum);
390             return;
391         }
392
393         TemHumDTO temhum = new TemHumDTO();
394         temhum.temperature = new QuantityType<>(tem / 100.0, SIUnits.CELSIUS);
395         temhum.humidity = new QuantityType<>(hum / 100.0, Units.PERCENT);
396         updateTemperatureAndHumidity(temhum, null);
397
398         updateBattery(new QuantityType<>(battery, Units.PERCENT), null);
399     }
400
401     @Override
402     public void onCharacteristicUpdate(BluetoothCharacteristic characteristic, byte[] value) {
403         super.onCharacteristicUpdate(characteristic, value);
404         commandSocket.receivePacket(value);
405     }
406
407     private class CommandSocket extends SimpleGattSocket<GoveeMessage> {
408
409         @Override
410         protected ScheduledExecutorService getScheduler() {
411             return scheduler;
412         }
413
414         @Override
415         public void sendMessage(MessageServicer<GoveeMessage, GoveeMessage> messageServicer) {
416             logger.debug("sending message: {}", messageServicer.getClass().getSimpleName());
417             super.sendMessage(messageServicer);
418         }
419
420         @Override
421         protected void parsePacket(byte[] packet, Consumer<GoveeMessage> messageHandler) {
422             messageHandler.accept(new GoveeMessage(packet));
423         }
424
425         @Override
426         protected CompletableFuture<@Nullable Void> sendPacket(byte[] data) {
427             return writeCharacteristic(SERVICE_UUID, PROTOCOL_CHAR_UUID, data, true);
428         }
429     }
430 }