2 * Copyright (c) 2010-2024 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.Temperature;
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.SIUnits;
28 * @author Connor Petty - Initial Contribution
32 public class GetOrSetTemWarningCommand extends GoveeCommand {
33 private final @Nullable WarningSettingsDTO<Temperature> settings;
34 private final CompletableFuture<@Nullable WarningSettingsDTO<Temperature>> resultHandler;
36 public GetOrSetTemWarningCommand(CompletableFuture<@Nullable WarningSettingsDTO<Temperature>> resultHandler) {
38 this.resultHandler = resultHandler;
41 public GetOrSetTemWarningCommand(WarningSettingsDTO<Temperature> settings,
42 CompletableFuture<@Nullable WarningSettingsDTO<Temperature>> resultHandler) {
43 this.settings = settings;
44 this.resultHandler = resultHandler;
48 public byte getCommandType() {
49 return settings == null ? READ_TYPE : WRITE_TYPE;
53 public byte getCommandCode() {
57 private static short convertQuantity(QuantityType<Temperature> quantity) {
58 var celciusQuantity = quantity.toUnit(SIUnits.CELSIUS);
59 if (celciusQuantity == null) {
60 throw new IllegalArgumentException("Unable to convert quantity to celcius");
62 return (short) (celciusQuantity.doubleValue() * 100);
66 protected byte @Nullable [] getData() {
67 var settings = this.settings;
68 if (settings == null) {
71 ByteBuffer buffer = ByteBuffer.allocate(5).order(ByteOrder.LITTLE_ENDIAN);
72 buffer.put(settings.enableAlarm == OnOffType.ON ? (byte) 1 : 0);
73 buffer.putShort(convertQuantity(settings.min));
74 buffer.putShort(convertQuantity(settings.max));
75 return buffer.array();
79 public void handleResponse(byte @Nullable [] data, @Nullable Throwable th) {
81 resultHandler.completeExceptionally(th);
84 WarningSettingsDTO<Temperature> result = new WarningSettingsDTO<Temperature>();
86 ByteBuffer buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
87 result.enableAlarm = OnOffType.from(buffer.get() == 1);
88 result.min = new QuantityType<Temperature>(buffer.getShort() / 100.0, SIUnits.CELSIUS);
89 result.max = new QuantityType<Temperature>(buffer.getShort() / 100.0, SIUnits.CELSIUS);
91 resultHandler.complete(result);
93 resultHandler.complete(null);