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.gree.internal.handler;
15 import static org.openhab.binding.gree.internal.GreeBindingConstants.*;
17 import java.io.IOException;
18 import java.net.DatagramPacket;
19 import java.net.DatagramSocket;
20 import java.net.InetAddress;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.Objects;
28 import java.util.Optional;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.openhab.binding.gree.internal.GreeCryptoUtil;
32 import org.openhab.binding.gree.internal.GreeException;
33 import org.openhab.binding.gree.internal.gson.GreeBindRequestPackDTO;
34 import org.openhab.binding.gree.internal.gson.GreeBindResponseDTO;
35 import org.openhab.binding.gree.internal.gson.GreeBindResponsePackDTO;
36 import org.openhab.binding.gree.internal.gson.GreeExecResponseDTO;
37 import org.openhab.binding.gree.internal.gson.GreeExecResponsePackDTO;
38 import org.openhab.binding.gree.internal.gson.GreeExecuteCommandPackDTO;
39 import org.openhab.binding.gree.internal.gson.GreeReqStatusPackDTO;
40 import org.openhab.binding.gree.internal.gson.GreeRequestDTO;
41 import org.openhab.binding.gree.internal.gson.GreeScanResponseDTO;
42 import org.openhab.binding.gree.internal.gson.GreeStatusResponseDTO;
43 import org.openhab.binding.gree.internal.gson.GreeStatusResponsePackDTO;
44 import org.openhab.core.library.types.QuantityType;
45 import org.openhab.core.library.unit.SIUnits;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 import com.google.gson.Gson;
50 import com.google.gson.JsonSyntaxException;
53 * The GreeDevice object repesents a Gree Airconditioner and provides
54 * device specific attributes as well a the functionality for the Air Conditioner
56 * @author John Cunha - Initial contribution
57 * @author Markus Michels - Refactoring, adapted to OH 2.5x
60 public class GreeAirDevice {
61 private final Logger logger = LoggerFactory.getLogger(GreeAirDevice.class);
62 private static final Gson GSON = new Gson();
63 private boolean isBound = false;
64 private final InetAddress ipAddress;
66 private String encKey = "";
67 private GreeCryptoUtil.EncryptionTypes encType = GreeCryptoUtil.EncryptionTypes.ECB;
68 private Optional<GreeScanResponseDTO> scanResponseGson = Optional.empty();
69 private Optional<GreeStatusResponseDTO> statusResponseGson = Optional.empty();
70 private Optional<GreeStatusResponsePackDTO> prevStatusResponsePackGson = Optional.empty();
72 public GreeAirDevice() {
73 ipAddress = InetAddress.getLoopbackAddress();
76 public GreeAirDevice(InetAddress ipAddress, int port, GreeScanResponseDTO scanResponse) {
77 this.ipAddress = ipAddress;
79 this.scanResponseGson = Optional.of(scanResponse);
80 this.encType = GreeCryptoUtil.getEncryptionType(scanResponse);
83 public void getDeviceStatus(DatagramSocket clientSocket) throws GreeException {
85 throw new GreeException("Device not bound");
88 // Set the values in the HashMap
89 ArrayList<String> columns = new ArrayList<>();
90 columns.add(GREE_PROP_POWER);
91 columns.add(GREE_PROP_MODE);
92 columns.add(GREE_PROP_SETTEMP);
93 columns.add(GREE_PROP_WINDSPEED);
94 columns.add(GREE_PROP_AIR);
95 columns.add(GREE_PROP_DRY);
96 columns.add(GREE_PROP_HEALTH);
97 columns.add(GREE_PROP_SLEEP);
98 columns.add(GREE_PROP_LIGHT);
99 columns.add(GREE_PROP_SWINGLEFTRIGHT);
100 columns.add(GREE_PROP_SWINGUPDOWN);
101 columns.add(GREE_PROP_QUIET);
102 columns.add(GREE_PROP_TURBO);
103 columns.add(GREE_PROP_TEMPUNIT);
104 columns.add(GREE_PROP_HEAT);
105 columns.add(GREE_PROP_HEATCOOL);
106 columns.add(GREE_PROP_TEMPREC);
107 columns.add(GREE_PROP_PWR_SAVING);
108 columns.add(GREE_PROP_NOISESET);
109 columns.add(GREE_PROP_CURRENT_TEMP_SENSOR);
111 // Convert the parameter map values to arrays
112 String[] colArray = columns.toArray(new String[0]);
114 // Prep the Command Request pack
115 GreeReqStatusPackDTO reqStatusPackGson = new GreeReqStatusPackDTO();
116 reqStatusPackGson.t = GREE_CMDT_STATUS;
117 reqStatusPackGson.cols = colArray;
118 reqStatusPackGson.mac = getId();
119 String reqStatusPackStr = GSON.toJson(reqStatusPackGson);
121 // Encrypt and send the Status Request pack
122 String[] encryptedStatusReqData = GreeCryptoUtil.encrypt(getKey(), reqStatusPackStr, encType);
123 DatagramPacket sendPacket = createPackRequest(0, encryptedStatusReqData);
124 clientSocket.send(sendPacket);
126 // Keep a copy of the old response to be used to check if values have changed
127 // If first time running, there will not be a previous GreeStatusResponsePack4Gson
128 if (statusResponseGson.isPresent() && statusResponseGson.get().packJson != null) {
129 prevStatusResponsePackGson = Optional
130 .of(new GreeStatusResponsePackDTO(statusResponseGson.get().packJson));
133 // Read the response, create the JSON to hold the response values
134 GreeStatusResponseDTO resp = receiveResponse(clientSocket, GreeStatusResponseDTO.class);
135 resp.decryptedPack = GreeCryptoUtil.decrypt(getKey(), resp, encType);
136 logger.debug("Response from device: {}", resp.decryptedPack);
137 resp.packJson = GSON.fromJson(resp.decryptedPack, GreeStatusResponsePackDTO.class);
140 statusResponseGson = Optional.of(resp);
142 } catch (IOException | JsonSyntaxException e) {
143 throw new GreeException("I/O exception while updating status", e);
144 } catch (RuntimeException e) {
145 logger.debug("Exception", e);
146 String json = statusResponseGson.map(r -> r.packJson.toString()).orElse("n/a");
147 throw new GreeException("Exception while updating status, JSON=" + json, e);
151 public void bindWithDevice(DatagramSocket clientSocket) throws GreeException {
153 // Prep the Binding Request pack
154 GreeBindRequestPackDTO bindReqPackGson = new GreeBindRequestPackDTO();
155 bindReqPackGson.mac = getId();
156 bindReqPackGson.t = GREE_CMDT_BIND;
157 bindReqPackGson.uid = 0;
158 String bindReqPackStr = GSON.toJson(bindReqPackGson);
160 // Encrypt and send the Binding Request pack
161 String[] encryptedBindReqData = GreeCryptoUtil.encrypt(GreeCryptoUtil.getGeneralKeyByteArray(encType),
162 bindReqPackStr, encType);
163 DatagramPacket sendPacket = createPackRequest(1, encryptedBindReqData);
164 clientSocket.send(sendPacket);
166 // Recieve a response, create the JSON to hold the response values
167 GreeBindResponseDTO resp = receiveResponse(clientSocket, GreeBindResponseDTO.class);
168 resp.decryptedPack = GreeCryptoUtil.decrypt(resp, encType);
169 resp.packJson = GSON.fromJson(resp.decryptedPack, GreeBindResponsePackDTO.class);
171 // Now set the key and flag to indicate the bind was successful
172 encKey = resp.packJson.key;
176 } catch (IOException | JsonSyntaxException e) {
177 throw new GreeException("Unable to bind to device", e);
181 public void setDevicePower(DatagramSocket clientSocket, int value) throws GreeException {
182 setCommandValue(clientSocket, GREE_PROP_POWER, value);
185 public void setDeviceMode(DatagramSocket clientSocket, int value) throws GreeException {
186 if ((value < 0 || value > 4)) {
187 throw new GreeException("Device mode out of range!");
189 setCommandValue(clientSocket, GREE_PROP_MODE, value);
193 * SwUpDn: controls the swing mode of the vertical air blades
196 * 1: swing in full range
197 * 2: fixed in the upmost position (1/5)
198 * 3: fixed in the middle-up position (2/5)
199 * 4: fixed in the middle position (3/5)
200 * 5: fixed in the middle-low position (4/5)
201 * 6: fixed in the lowest position (5/5)
202 * 7: swing in the downmost region (5/5)
203 * 8: swing in the middle-low region (4/5)
204 * 9: swing in the middle region (3/5)
205 * 10: swing in the middle-up region (2/5)
206 * 11: swing in the upmost region (1/5)
208 public void setDeviceSwingUpDown(DatagramSocket clientSocket, int value) throws GreeException {
209 if (value < 0 || value > 11) {
210 throw new GreeException("SwingUpDown value is out of range!");
212 setCommandValue(clientSocket, GREE_PROP_SWINGUPDOWN, value);
216 * SwingLfRig: controls the swing mode of the horizontal air blades (available on limited number of devices, e.g.
217 * some Cooper and Hunter units - thanks to mvmn)
221 * 2-6: fixed position from leftmost to rightmost
222 * Full swing, like for SwUpDn is not supported
224 public void setDeviceSwingLeftRight(DatagramSocket clientSocket, int value) throws GreeException {
225 if (value < 0 || value > 6) {
226 throw new GreeException("SwingLeftRight value is out of range!");
228 setCommandValue(clientSocket, GREE_PROP_SWINGLEFTRIGHT, value, 0, 6);
232 * Only allow this to happen if this device has been bound and values are valid
233 * Possible values are :
241 public void setDeviceWindspeed(DatagramSocket clientSocket, int value) throws GreeException {
242 if (value < 0 || value > 5) {
243 throw new GreeException("Value out of range!");
246 HashMap<String, Integer> parameters = new HashMap<>();
247 parameters.put(GREE_PROP_WINDSPEED, value);
248 parameters.put(GREE_PROP_QUIET, 0);
249 parameters.put(GREE_PROP_TURBO, 0);
250 parameters.put(GREE_PROP_NOISE, 0);
251 executeCommand(clientSocket, parameters);
255 * Tur: sets fan speed to the maximum. Fan speed cannot be changed while active and only available in Dry and Cool
261 public void setDeviceTurbo(DatagramSocket clientSocket, int value) throws GreeException {
262 setCommandValue(clientSocket, GREE_PROP_TURBO, value, 0, 1);
265 public void setQuietMode(DatagramSocket clientSocket, int value) throws GreeException {
266 setCommandValue(clientSocket, GREE_PROP_QUIET, value, 0, 2);
269 public void setDeviceLight(DatagramSocket clientSocket, int value) throws GreeException {
270 setCommandValue(clientSocket, GREE_PROP_LIGHT, value);
274 * @param temp set temperature in degrees Celsius or Fahrenheit
276 public void setDeviceTempSet(DatagramSocket clientSocket, QuantityType<?> temp) throws GreeException {
277 // If commanding Fahrenheit set halfStep to 1 or 0 to tell the A/C which F integer
278 // temperature to use as celsius alone is ambigious
279 double newVal = temp.doubleValue();
280 int celsiusOrFahrenheit = SIUnits.CELSIUS.equals(temp.getUnit()) ? TEMP_UNIT_CELSIUS : TEMP_UNIT_FAHRENHEIT; // 0=Celsius,
282 if (((celsiusOrFahrenheit == TEMP_UNIT_CELSIUS) && (newVal < TEMP_MIN_C || newVal > TEMP_MAX_C))
283 || ((celsiusOrFahrenheit == TEMP_UNIT_FAHRENHEIT) && (newVal < TEMP_MIN_F || newVal > TEMP_MAX_F))) {
284 throw new IllegalArgumentException("Temp Value out of Range");
287 // Default for Celsius
288 int outVal = (int) newVal;
289 int halfStep = TEMP_HALFSTEP_NO; // for whatever reason halfStep is not supported for Celsius
291 // If value argument is degrees F, convert Fahrenheit to Celsius,
292 // SetTem input to A/C always in Celsius despite passing in 1 to TemUn
293 // ******************TempRec TemSet Mapping for setting Fahrenheit****************************
295 // C = [20.0, 20.5, 21.1, 21.6, 22.2, 22.7, 23.3, 23.8, 24.4, 25.0, 25.5, 26.1, 26.6, 27.2, 27.7, 28.3,
298 // TemSet = [20..30] or [68..86]
299 // TemRec = value - (value) > 0 ? 1 : 1 -> when xx.5 is request xx will become TemSet and halfStep the indicator
300 // for "half on top of TemSet"
301 // ******************TempRec TemSet Mapping for setting Fahrenheit****************************
302 // subtract the float version - the int version to get the fractional difference
303 // if the difference is positive set halfStep to 1, negative to 0
304 if (celsiusOrFahrenheit == TEMP_UNIT_FAHRENHEIT) { // If Fahrenheit,
305 halfStep = newVal - outVal > 0 ? TEMP_HALFSTEP_YES : TEMP_HALFSTEP_NO;
307 logger.debug("Converted temp from {}{} to temp={}, halfStep={}, unit={})", newVal, temp.getUnit(), outVal,
308 halfStep, celsiusOrFahrenheit == TEMP_UNIT_CELSIUS ? "C" : "F");
310 // Set the values in the HashMap
311 HashMap<String, Integer> parameters = new HashMap<>();
312 parameters.put(GREE_PROP_TEMPUNIT, celsiusOrFahrenheit);
313 parameters.put(GREE_PROP_SETTEMP, outVal);
314 parameters.put(GREE_PROP_TEMPREC, halfStep);
315 executeCommand(clientSocket, parameters);
318 public void setDeviceAir(DatagramSocket clientSocket, int value) throws GreeException {
319 setCommandValue(clientSocket, GREE_PROP_AIR, value);
322 public void setDeviceDry(DatagramSocket clientSocket, int value) throws GreeException {
323 setCommandValue(clientSocket, GREE_PROP_DRY, value);
326 public void setDeviceHealth(DatagramSocket clientSocket, int value) throws GreeException {
327 setCommandValue(clientSocket, GREE_PROP_HEALTH, value);
330 public void setDevicePwrSaving(DatagramSocket clientSocket, int value) throws GreeException {
331 // Set the values in the HashMap
332 HashMap<String, Integer> parameters = new HashMap<>();
333 parameters.put(GREE_PROP_PWR_SAVING, value);
334 parameters.put(GREE_PROP_WINDSPEED, 0);
335 parameters.put(GREE_PROP_QUIET, 0);
336 parameters.put(GREE_PROP_TURBO, 0);
337 parameters.put(GREE_PROP_SLEEP, 0);
338 parameters.put(GREE_PROP_SLEEPMODE, 0);
339 executeCommand(clientSocket, parameters);
342 public int getIntStatusVal(String valueName) {
344 * Note : Values can be:
345 * "Pow": Power (0 or 1)
346 * "Mod": Mode: Auto: 0, Cool: 1, Dry: 2, Fan: 3, Heat: 4
347 * "SetTem": Requested Temperature
348 * "WdSpd": Fan Speed : Low:1, Medium Low:2, Medium :3, Medium High :4, High :5
349 * "Air": Air Mode Enabled
355 * "SwingLfRig": Swing Left Right
356 * "SwUpDn": Swing Up Down: // Ceiling:0, Upwards : 10, Downwards : 11, Full range : 1
357 * "Quiet": Quiet mode
360 * "TemUn": Temperature unit, 0 for Celsius, 1 for Fahrenheit
362 * "TemRec": (0 or 1), Send with SetTem, when TemUn==1, distinguishes between upper and lower integer Fahrenheit
364 * "SvSt": Power Saving
366 // Find the valueName in the Returned Status object
367 if (isStatusAvailable()) {
368 List<String> colList = Arrays.asList(statusResponseGson.get().packJson.cols);
369 List<Integer> valList = Arrays.asList(statusResponseGson.get().packJson.dat);
370 int valueArrayposition = colList.indexOf(valueName);
371 if (valueArrayposition != -1) {
372 // get the Corresponding value
373 return valList.get(valueArrayposition);
380 public boolean isStatusAvailable() {
381 return statusResponseGson.isPresent() && (statusResponseGson.get().packJson.cols != null)
382 && (statusResponseGson.get().packJson.dat != null);
385 public boolean hasStatusValChanged(String valueName) throws GreeException {
386 if (prevStatusResponsePackGson.isEmpty()) {
387 return true; // update value if there is no previous one
389 // Find the valueName in the Current Status object
390 List<String> currcolList = Arrays.asList(statusResponseGson.get().packJson.cols);
391 List<Integer> currvalList = Arrays.asList(statusResponseGson.get().packJson.dat);
392 int currvalueArrayposition = currcolList.indexOf(valueName);
393 if (currvalueArrayposition == -1) {
394 throw new GreeException("Unable to decode device status");
397 // Find the valueName in the Previous Status object
398 List<String> prevcolList = Arrays.asList(prevStatusResponsePackGson.get().cols);
399 List<Integer> prevvalList = Arrays.asList(prevStatusResponsePackGson.get().dat);
400 int prevvalueArrayposition = prevcolList.indexOf(valueName);
401 if (prevvalueArrayposition == -1) {
402 throw new GreeException("Unable to get status value");
405 // Finally Compare the values
406 return !Objects.equals(currvalList.get(currvalueArrayposition), prevvalList.get(prevvalueArrayposition));
409 protected void executeCommand(DatagramSocket clientSocket, Map<String, Integer> parameters) throws GreeException {
410 // Only allow this to happen if this device has been bound
412 throw new GreeException("Device is not bound!");
416 // Convert the parameter map values to arrays
417 String[] keyArray = parameters.keySet().toArray(new String[0]);
418 Integer[] valueArray = parameters.values().toArray(new Integer[0]);
420 // Prep the Command Request pack
421 GreeExecuteCommandPackDTO execCmdPackGson = new GreeExecuteCommandPackDTO();
422 execCmdPackGson.opt = keyArray;
423 execCmdPackGson.p = valueArray;
424 execCmdPackGson.t = GREE_CMDT_CMD;
425 String execCmdPackStr = GSON.toJson(execCmdPackGson);
427 // Now encrypt and send the Command Request pack
428 String[] encryptedCommandReqData = GreeCryptoUtil.encrypt(getKey(), execCmdPackStr, encType);
429 DatagramPacket sendPacket = createPackRequest(0, encryptedCommandReqData);
430 clientSocket.send(sendPacket);
432 // Receive and decode result
433 GreeExecResponseDTO execResponseGson = receiveResponse(clientSocket, GreeExecResponseDTO.class);
434 execResponseGson.decryptedPack = GreeCryptoUtil.decrypt(getKey(), execResponseGson, encType);
436 // Create the JSON to hold the response values
437 execResponseGson.packJson = GSON.fromJson(execResponseGson.decryptedPack, GreeExecResponsePackDTO.class);
438 } catch (IOException | JsonSyntaxException e) {
439 throw new GreeException("Exception on command execution", e);
443 private void setCommandValue(DatagramSocket clientSocket, String command, int value) throws GreeException {
444 executeCommand(clientSocket, Map.of(command, value));
447 private void setCommandValue(DatagramSocket clientSocket, String command, int value, int min, int max)
448 throws GreeException {
449 if ((value < min) || (value > max)) {
450 throw new GreeException("Command value out of range!");
452 executeCommand(clientSocket, Map.of(command, value));
455 private DatagramPacket createPackRequest(int i, String[] data) {
456 GreeRequestDTO request = new GreeRequestDTO();
457 request.cid = GREE_CID;
459 request.t = GREE_CMDT_PACK;
461 request.tcid = getId();
462 request.pack = data[0];
463 if (encType == GreeCryptoUtil.EncryptionTypes.GCM) {
464 if (data.length > 1) {
465 request.tag = data[1];
467 logger.warn("Missing string for tag property for GCM encryption data");
470 byte[] sendData = GSON.toJson(request).getBytes(StandardCharsets.UTF_8);
471 return new DatagramPacket(sendData, sendData.length, ipAddress, port);
474 private <T> T receiveResponse(DatagramSocket clientSocket, Class<T> classOfT)
475 throws IOException, JsonSyntaxException {
476 byte[] receiveData = new byte[1024];
477 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
478 clientSocket.receive(receivePacket);
479 String json = new String(receivePacket.getData(), StandardCharsets.UTF_8).replace("\\u0000", "").trim();
480 return GSON.fromJson(json, classOfT);
483 private void updateTempFtoC() {
484 // Status message back from A/C always reports degrees C
485 // If using Fahrenheit, us SetTem, TemUn and TemRec to reconstruct the Fahrenheit temperature
486 // Get Celsius or Fahrenheit from status message
487 int celsiusOrFahrenheit = getIntStatusVal(GREE_PROP_TEMPUNIT);
488 int newVal = getIntStatusVal(GREE_PROP_SETTEMP);
489 int halfStep = getIntStatusVal(GREE_PROP_TEMPREC);
491 if ((celsiusOrFahrenheit == -1) || (newVal == -1) || (halfStep == -1)) {
492 throw new IllegalArgumentException("SetTem,TemUn or TemRec is invalid, not performing conversion");
493 } else if (celsiusOrFahrenheit == 1) { // convert SetTem to Fahrenheit
494 // Find the valueName in the Returned Status object
495 String[] columns = statusResponseGson.get().packJson.cols;
496 Integer[] values = statusResponseGson.get().packJson.dat;
497 List<String> colList = Arrays.asList(columns);
498 int valueArrayposition = colList.indexOf(GREE_PROP_SETTEMP);
499 if (valueArrayposition != -1) {
500 // convert Celsius to Fahrenheit,
501 // SetTem status returns degrees C regardless of TempUn setting
503 // Perform the float Celsius to Fahrenheit conversion add or subtract 0.5 based on the value of TemRec
504 // (0 = -0.5, 1 = +0.5). Pass into a rounding function, this yeild the correct Fahrenheit Temperature to
506 newVal = (int) (Math.round(((newVal * 9.0 / 5.0) + 32.0) + halfStep - 0.5));
508 // Update the status array with F temp, assume this is updating the array in situ
509 values[valueArrayposition] = newVal;
514 public InetAddress getAddress() {
518 public boolean getIsBound() {
522 public byte[] getKey() {
523 return encKey.getBytes(StandardCharsets.UTF_8);
526 public String getId() {
527 return scanResponseGson.isPresent() ? scanResponseGson.get().packJson.mac : "";
530 public String getName() {
531 return scanResponseGson.isPresent() ? scanResponseGson.get().packJson.name : "";
534 public String getVendor() {
535 return scanResponseGson.isPresent()
536 ? scanResponseGson.get().packJson.brand + " " + scanResponseGson.get().packJson.vender
540 public String getModel() {
541 return scanResponseGson.isPresent()
542 ? scanResponseGson.get().packJson.series + " " + scanResponseGson.get().packJson.model
546 public void setScanResponseGson(GreeScanResponseDTO gson) {
547 scanResponseGson = Optional.of(gson);