2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.bluetooth.govee.internal.command.hygrometer;
15 import java.nio.ByteBuffer;
16 import java.nio.ByteOrder;
17 import java.util.concurrent.CompletableFuture;
19 import javax.measure.quantity.Dimensionless;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.core.library.types.OnOffType;
24 import org.openhab.core.library.types.QuantityType;
25 import org.openhab.core.library.unit.Units;
28 * @author Connor Petty - Initial Contribution
32 public class GetOrSetHumWarningCommand extends GoveeCommand {
34 private final @Nullable WarningSettingsDTO<Dimensionless> settings;
35 private final CompletableFuture<@Nullable WarningSettingsDTO<Dimensionless>> resultHandler;
37 public GetOrSetHumWarningCommand(CompletableFuture<@Nullable WarningSettingsDTO<Dimensionless>> resultHandler) {
39 this.resultHandler = resultHandler;
42 public GetOrSetHumWarningCommand(WarningSettingsDTO<Dimensionless> settings,
43 CompletableFuture<@Nullable WarningSettingsDTO<Dimensionless>> resultHandler) {
44 this.settings = settings;
45 this.resultHandler = resultHandler;
49 public byte getCommandType() {
50 return settings == null ? READ_TYPE : WRITE_TYPE;
54 public byte getCommandCode() {
58 private static short convertQuantity(QuantityType<Dimensionless> quantity) {
59 var percentQuantity = quantity.toUnit(Units.PERCENT);
60 if (percentQuantity == null) {
61 throw new IllegalArgumentException("Unable to convert quantity to percent");
63 return (short) (percentQuantity.doubleValue() * 100);
67 protected byte @Nullable [] getData() {
68 if (settings == null) {
72 ByteBuffer buffer = ByteBuffer.allocate(5).order(ByteOrder.LITTLE_ENDIAN);
73 buffer.put(settings.enableAlarm == OnOffType.ON ? (byte) 1 : 0);
74 buffer.putShort(convertQuantity(settings.min));
75 buffer.putShort(convertQuantity(settings.max));
76 return buffer.array();
80 public void handleResponse(byte @Nullable [] data, @Nullable Throwable th) {
82 resultHandler.completeExceptionally(th);
85 WarningSettingsDTO<Dimensionless> result = new WarningSettingsDTO<Dimensionless>();
87 ByteBuffer buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
88 result.enableAlarm = OnOffType.from(buffer.get() == 1);
89 result.min = new QuantityType<Dimensionless>(buffer.getShort() / 100.0, Units.PERCENT);
90 result.max = new QuantityType<Dimensionless>(buffer.getShort() / 100.0, Units.PERCENT);
92 resultHandler.complete(result);
94 resultHandler.complete(null);