2 * Copyright (c) 2010-2021 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.Collections;
25 import java.util.HashMap;
26 import java.util.List;
28 import java.util.Objects;
29 import java.util.Optional;
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.openhab.binding.gree.internal.GreeCryptoUtil;
33 import org.openhab.binding.gree.internal.GreeException;
34 import org.openhab.binding.gree.internal.gson.GreeBindRequestPackDTO;
35 import org.openhab.binding.gree.internal.gson.GreeBindResponseDTO;
36 import org.openhab.binding.gree.internal.gson.GreeBindResponsePackDTO;
37 import org.openhab.binding.gree.internal.gson.GreeExecResponseDTO;
38 import org.openhab.binding.gree.internal.gson.GreeExecResponsePackDTO;
39 import org.openhab.binding.gree.internal.gson.GreeExecuteCommandPackDTO;
40 import org.openhab.binding.gree.internal.gson.GreeReqStatusPackDTO;
41 import org.openhab.binding.gree.internal.gson.GreeRequestDTO;
42 import org.openhab.binding.gree.internal.gson.GreeScanResponseDTO;
43 import org.openhab.binding.gree.internal.gson.GreeStatusResponseDTO;
44 import org.openhab.binding.gree.internal.gson.GreeStatusResponsePackDTO;
45 import org.openhab.core.library.types.QuantityType;
46 import org.openhab.core.library.unit.SIUnits;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
50 import com.google.gson.Gson;
51 import com.google.gson.JsonSyntaxException;
54 * The GreeDevice object repesents a Gree Airconditioner and provides
55 * device specific attributes as well a the functionality for the Air Conditioner
57 * @author John Cunha - Initial contribution
58 * @author Markus Michels - Refactoring, adapted to OH 2.5x
61 public class GreeAirDevice {
62 private final Logger logger = LoggerFactory.getLogger(GreeAirDevice.class);
63 private final static Gson gson = new Gson();
64 private boolean isBound = false;
65 private final InetAddress ipAddress;
67 private String encKey = "";
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);
82 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 encryptedStatusReqPacket = GreeCryptoUtil.encryptPack(getKey(), reqStatusPackStr);
123 DatagramPacket sendPacket = createPackRequest(0,
124 new String(encryptedStatusReqPacket.getBytes(), StandardCharsets.UTF_8));
125 clientSocket.send(sendPacket);
127 // Keep a copy of the old response to be used to check if values have changed
128 // If first time running, there will not be a previous GreeStatusResponsePack4Gson
129 if (statusResponseGson.isPresent() && statusResponseGson.get().packJson != null) {
130 prevStatusResponsePackGson = Optional
131 .of(new GreeStatusResponsePackDTO(statusResponseGson.get().packJson));
134 // Read the response, create the JSON to hold the response values
135 GreeStatusResponseDTO resp = receiveResponse(clientSocket, GreeStatusResponseDTO.class);
136 resp.decryptedPack = GreeCryptoUtil.decryptPack(getKey(), resp.pack);
137 logger.debug("Response from device: {}", resp.decryptedPack);
138 resp.packJson = gson.fromJson(resp.decryptedPack, GreeStatusResponsePackDTO.class);
141 statusResponseGson = Optional.of(resp);
143 } catch (IOException | JsonSyntaxException e) {
144 throw new GreeException("I/O exception while updating status", e);
145 } catch (RuntimeException e) {
146 logger.debug("Exception", e);
147 String json = statusResponseGson.map(r -> r.packJson.toString()).orElse("n/a");
148 throw new GreeException("Exception while updating status, JSON=" + json, e);
152 public void bindWithDevice(DatagramSocket clientSocket) throws GreeException {
154 // Prep the Binding Request pack
155 GreeBindRequestPackDTO bindReqPackGson = new GreeBindRequestPackDTO();
156 bindReqPackGson.mac = getId();
157 bindReqPackGson.t = GREE_CMDT_BIND;
158 bindReqPackGson.uid = 0;
159 String bindReqPackStr = gson.toJson(bindReqPackGson);
161 // Encrypt and send the Binding Request pack
162 String encryptedBindReqPacket = GreeCryptoUtil.encryptPack(GreeCryptoUtil.getAESGeneralKeyByteArray(),
164 DatagramPacket sendPacket = createPackRequest(1, encryptedBindReqPacket);
165 clientSocket.send(sendPacket);
167 // Recieve a response, create the JSON to hold the response values
168 GreeBindResponseDTO resp = receiveResponse(clientSocket, GreeBindResponseDTO.class);
169 resp.decryptedPack = GreeCryptoUtil.decryptPack(GreeCryptoUtil.getAESGeneralKeyByteArray(), resp.pack);
170 resp.packJson = gson.fromJson(resp.decryptedPack, GreeBindResponsePackDTO.class);
172 // Now set the key and flag to indicate the bind was succesful
173 encKey = resp.packJson.key;
177 } catch (IOException | JsonSyntaxException e) {
178 throw new GreeException("Unable to bind to device", e);
182 public void setDevicePower(DatagramSocket clientSocket, int value) throws GreeException {
183 setCommandValue(clientSocket, GREE_PROP_POWER, value);
186 public void setDeviceMode(DatagramSocket clientSocket, int value) throws GreeException {
187 if ((value < 0 || value > 4)) {
188 throw new GreeException("Device mode out of range!");
190 setCommandValue(clientSocket, GREE_PROP_MODE, value);
194 * SwUpDn: controls the swing mode of the vertical air blades
197 * 1: swing in full range
198 * 2: fixed in the upmost position (1/5)
199 * 3: fixed in the middle-up position (2/5)
200 * 4: fixed in the middle position (3/5)
201 * 5: fixed in the middle-low position (4/5)
202 * 6: fixed in the lowest position (5/5)
203 * 7: swing in the downmost region (5/5)
204 * 8: swing in the middle-low region (4/5)
205 * 9: swing in the middle region (3/5)
206 * 10: swing in the middle-up region (2/5)
207 * 11: swing in the upmost region (1/5)
209 public void setDeviceSwingUpDown(DatagramSocket clientSocket, int value) throws GreeException {
210 if (value < 0 || value > 11) {
211 throw new GreeException("SwingUpDown value is out of range!");
213 setCommandValue(clientSocket, GREE_PROP_SWINGUPDOWN, value);
217 * SwingLfRig: controls the swing mode of the horizontal air blades (available on limited number of devices, e.g.
218 * some Cooper & Hunter units - thanks to mvmn)
222 * 2-6: fixed position from leftmost to rightmost
223 * Full swing, like for SwUpDn is not supported
225 public void setDeviceSwingLeftRight(DatagramSocket clientSocket, int value) throws GreeException {
226 if (value < 0 || value > 6) {
227 throw new GreeException("SwingLeftRight value is out of range!");
229 setCommandValue(clientSocket, GREE_PROP_SWINGLEFTRIGHT, value, 0, 6);
233 * Only allow this to happen if this device has been bound and values are valid
234 * Possible values are :
242 public void setDeviceWindspeed(DatagramSocket clientSocket, int value) throws GreeException {
243 if (value < 0 || value > 5) {
244 throw new GreeException("Value out of range!");
247 HashMap<String, Integer> parameters = new HashMap<>();
248 parameters.put(GREE_PROP_WINDSPEED, value);
249 parameters.put(GREE_PROP_QUIET, 0);
250 parameters.put(GREE_PROP_TURBO, 0);
251 parameters.put(GREE_PROP_NOISE, 0);
252 executeCommand(clientSocket, parameters);
256 * Tur: sets fan speed to the maximum. Fan speed cannot be changed while active and only available in Dry and Cool
262 public void setDeviceTurbo(DatagramSocket clientSocket, int value) throws GreeException {
263 setCommandValue(clientSocket, GREE_PROP_TURBO, value, 0, 1);
266 public void setQuietMode(DatagramSocket clientSocket, int value) throws GreeException {
267 setCommandValue(clientSocket, GREE_PROP_QUIET, value, 0, 2);
270 public void setDeviceLight(DatagramSocket clientSocket, int value) throws GreeException {
271 setCommandValue(clientSocket, GREE_PROP_LIGHT, value);
275 * @param value set temperature in degrees Celsius or Fahrenheit
277 public void setDeviceTempSet(DatagramSocket clientSocket, QuantityType<?> temp) throws GreeException {
278 // If commanding Fahrenheit set halfStep to 1 or 0 to tell the A/C which F integer
279 // temperature to use as celsius alone is ambigious
280 double newVal = temp.doubleValue();
281 int CorF = SIUnits.CELSIUS.equals(temp.getUnit()) ? TEMP_UNIT_CELSIUS : TEMP_UNIT_FAHRENHEIT; // 0=Celsius,
283 if (((CorF == TEMP_UNIT_CELSIUS) && (newVal < TEMP_MIN_C || newVal > TEMP_MAX_C))
284 || ((CorF == TEMP_UNIT_FAHRENHEIT) && (newVal < TEMP_MIN_F || newVal > TEMP_MAX_F))) {
285 throw new IllegalArgumentException("Temp Value out of Range");
288 // Default for Celsius
289 int outVal = (int) newVal;
290 int halfStep = TEMP_HALFSTEP_NO; // for whatever reason halfStep is not supported for Celsius
292 // If value argument is degrees F, convert Fahrenheit to Celsius,
293 // SetTem input to A/C always in Celsius despite passing in 1 to TemUn
294 // ******************TempRec TemSet Mapping for setting Fahrenheit****************************
296 // 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,
299 // TemSet = [20..30] or [68..86]
300 // TemRec = value - (value) > 0 ? 1 : 1 -> when xx.5 is request xx will become TemSet and halfStep the indicator
301 // for "half on top of TemSet"
302 // ******************TempRec TemSet Mapping for setting Fahrenheit****************************
303 // subtract the float version - the int version to get the fractional difference
304 // if the difference is positive set halfStep to 1, negative to 0
305 if (CorF == TEMP_UNIT_FAHRENHEIT) { // If Fahrenheit,
306 halfStep = newVal - outVal > 0 ? TEMP_HALFSTEP_YES : TEMP_HALFSTEP_NO;
308 logger.debug("Converted temp from {}{} to temp={}, halfStep={}, unit={})", newVal, temp.getUnit(), outVal,
309 halfStep, CorF == TEMP_UNIT_CELSIUS ? "C" : "F");
311 // Set the values in the HashMap
312 HashMap<String, Integer> parameters = new HashMap<>();
313 parameters.put(GREE_PROP_TEMPUNIT, CorF);
314 parameters.put(GREE_PROP_SETTEMP, outVal);
315 parameters.put(GREE_PROP_TEMPREC, halfStep);
316 executeCommand(clientSocket, parameters);
319 public void setDeviceAir(DatagramSocket clientSocket, int value) throws GreeException {
320 setCommandValue(clientSocket, GREE_PROP_AIR, value);
323 public void setDeviceDry(DatagramSocket clientSocket, int value) throws GreeException {
324 setCommandValue(clientSocket, GREE_PROP_DRY, value);
327 public void setDeviceHealth(DatagramSocket clientSocket, int value) throws GreeException {
328 setCommandValue(clientSocket, GREE_PROP_HEALTH, value);
331 public void setDevicePwrSaving(DatagramSocket clientSocket, int value) throws GreeException {
332 // Set the values in the HashMap
333 HashMap<String, Integer> parameters = new HashMap<>();
334 parameters.put(GREE_PROP_PWR_SAVING, value);
335 parameters.put(GREE_PROP_WINDSPEED, 0);
336 parameters.put(GREE_PROP_QUIET, 0);
337 parameters.put(GREE_PROP_TURBO, 0);
338 parameters.put(GREE_PROP_SLEEP, 0);
339 parameters.put(GREE_PROP_SLEEPMODE, 0);
340 executeCommand(clientSocket, parameters);
343 public int getIntStatusVal(String valueName) {
345 * Note : Values can be:
346 * "Pow": Power (0 or 1)
347 * "Mod": Mode: Auto: 0, Cool: 1, Dry: 2, Fan: 3, Heat: 4
348 * "SetTem": Requested Temperature
349 * "WdSpd": Fan Speed : Low:1, Medium Low:2, Medium :3, Medium High :4, High :5
350 * "Air": Air Mode Enabled
356 * "SwingLfRig": Swing Left Right
357 * "SwUpDn": Swing Up Down: // Ceiling:0, Upwards : 10, Downwards : 11, Full range : 1
358 * "Quiet": Quiet mode
361 * "TemUn": Temperature unit, 0 for Celsius, 1 for Fahrenheit
363 * "TemRec": (0 or 1), Send with SetTem, when TemUn==1, distinguishes between upper and lower integer Fahrenheit
365 * "SvSt": Power Saving
367 // Find the valueName in the Returned Status object
368 if (isStatusAvailable()) {
369 List<String> colList = Arrays.asList(statusResponseGson.get().packJson.cols);
370 List<Integer> valList = Arrays.asList(statusResponseGson.get().packJson.dat);
371 int valueArrayposition = colList.indexOf(valueName);
372 if (valueArrayposition != -1) {
373 // get the Corresponding value
374 Integer value = valList.get(valueArrayposition);
382 public boolean isStatusAvailable() {
383 return statusResponseGson.isPresent() && (statusResponseGson.get().packJson.cols != null)
384 && (statusResponseGson.get().packJson.dat != null);
387 public boolean hasStatusValChanged(String valueName) throws GreeException {
388 if (!prevStatusResponsePackGson.isPresent()) {
389 return true; // update value if there is no previous one
391 // Find the valueName in the Current Status object
392 List<String> currcolList = Arrays.asList(statusResponseGson.get().packJson.cols);
393 List<Integer> currvalList = Arrays.asList(statusResponseGson.get().packJson.dat);
394 int currvalueArrayposition = currcolList.indexOf(valueName);
395 if (currvalueArrayposition == -1) {
396 throw new GreeException("Unable to decode device status");
399 // Find the valueName in the Previous Status object
400 List<String> prevcolList = Arrays.asList(prevStatusResponsePackGson.get().cols);
401 List<Integer> prevvalList = Arrays.asList(prevStatusResponsePackGson.get().dat);
402 int prevvalueArrayposition = prevcolList.indexOf(valueName);
403 if (prevvalueArrayposition == -1) {
404 throw new GreeException("Unable to get status value");
407 // Finally Compare the values
408 return !Objects.equals(currvalList.get(currvalueArrayposition), prevvalList.get(prevvalueArrayposition));
411 protected void executeCommand(DatagramSocket clientSocket, Map<String, Integer> parameters) throws GreeException {
412 // Only allow this to happen if this device has been bound
414 throw new GreeException("Device is not bound!");
418 // Convert the parameter map values to arrays
419 String[] keyArray = parameters.keySet().toArray(new String[0]);
420 Integer[] valueArray = parameters.values().toArray(new Integer[0]);
422 // Prep the Command Request pack
423 GreeExecuteCommandPackDTO execCmdPackGson = new GreeExecuteCommandPackDTO();
424 execCmdPackGson.opt = keyArray;
425 execCmdPackGson.p = valueArray;
426 execCmdPackGson.t = GREE_CMDT_CMD;
427 String execCmdPackStr = gson.toJson(execCmdPackGson);
429 // Now encrypt and send the Command Request pack
430 String encryptedCommandReqPacket = GreeCryptoUtil.encryptPack(getKey(), execCmdPackStr);
431 DatagramPacket sendPacket = createPackRequest(0, encryptedCommandReqPacket);
432 clientSocket.send(sendPacket);
434 // Receive and decode result
435 GreeExecResponseDTO execResponseGson = receiveResponse(clientSocket, GreeExecResponseDTO.class);
436 execResponseGson.decryptedPack = GreeCryptoUtil.decryptPack(getKey(), execResponseGson.pack);
438 // Create the JSON to hold the response values
439 execResponseGson.packJson = gson.fromJson(execResponseGson.decryptedPack, GreeExecResponsePackDTO.class);
440 } catch (IOException | JsonSyntaxException e) {
441 throw new GreeException("Exception on command execution", e);
445 private void setCommandValue(DatagramSocket clientSocket, String command, int value) throws GreeException {
446 executeCommand(clientSocket, Collections.singletonMap(command, value));
449 private void setCommandValue(DatagramSocket clientSocket, String command, int value, int min, int max)
450 throws GreeException {
451 if ((value < min) || (value > max)) {
452 throw new GreeException("Command value out of range!");
454 executeCommand(clientSocket, Collections.singletonMap(command, value));
457 private DatagramPacket createPackRequest(int i, String pack) {
458 GreeRequestDTO request = new GreeRequestDTO();
459 request.cid = GREE_CID;
461 request.t = GREE_CMDT_PACK;
463 request.tcid = getId();
465 byte[] sendData = gson.toJson(request).getBytes(StandardCharsets.UTF_8);
466 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, port);
470 private <T> T receiveResponse(DatagramSocket clientSocket, Class<T> classOfT)
471 throws IOException, JsonSyntaxException {
472 byte[] receiveData = new byte[1024];
473 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
474 clientSocket.receive(receivePacket);
475 String json = new String(receivePacket.getData(), StandardCharsets.UTF_8).replace("\\u0000", "").trim();
476 return gson.fromJson(json, classOfT);
479 private void updateTempFtoC() {
480 // Status message back from A/C always reports degrees C
481 // If using Fahrenheit, us SetTem, TemUn and TemRec to reconstruct the Fahrenheit temperature
482 // Get Celsius or Fahrenheit from status message
483 int CorF = getIntStatusVal(GREE_PROP_TEMPUNIT);
484 int newVal = getIntStatusVal(GREE_PROP_SETTEMP);
485 int halfStep = getIntStatusVal(GREE_PROP_TEMPREC);
487 if ((CorF == -1) || (newVal == -1) || (halfStep == -1)) {
488 throw new IllegalArgumentException("SetTem,TemUn or TemRec is invalid, not performing conversion");
489 } else if (CorF == 1) { // convert SetTem to Fahrenheit
490 // Find the valueName in the Returned Status object
491 String[] columns = statusResponseGson.get().packJson.cols;
492 Integer[] values = statusResponseGson.get().packJson.dat;
493 List<String> colList = Arrays.asList(columns);
494 int valueArrayposition = colList.indexOf(GREE_PROP_SETTEMP);
495 if (valueArrayposition != -1) {
496 // convert Celsius to Fahrenheit,
497 // SetTem status returns degrees C regardless of TempUn setting
499 // Perform the float Celsius to Fahrenheit conversion add or subtract 0.5 based on the value of TemRec
500 // (0 = -0.5, 1 = +0.5). Pass into a rounding function, this yeild the correct Fahrenheit Temperature to
502 newVal = (int) (Math.round(((newVal * 9.0 / 5.0) + 32.0) + halfStep - 0.5));
504 // Update the status array with F temp, assume this is updating the array in situ
505 values[valueArrayposition] = newVal;
510 public InetAddress getAddress() {
514 public boolean getIsBound() {
518 public byte[] getKey() {
519 return encKey.getBytes(StandardCharsets.UTF_8);
522 public String getId() {
523 return scanResponseGson.isPresent() ? scanResponseGson.get().packJson.mac : "";
526 public String getName() {
527 return scanResponseGson.isPresent() ? scanResponseGson.get().packJson.name : "";
530 public String getVendor() {
531 return scanResponseGson.isPresent()
532 ? scanResponseGson.get().packJson.brand + " " + scanResponseGson.get().packJson.vender
536 public String getModel() {
537 return scanResponseGson.isPresent()
538 ? scanResponseGson.get().packJson.series + " " + scanResponseGson.get().packJson.model
542 public void setScanResponseGson(GreeScanResponseDTO gson) {
543 scanResponseGson = Optional.of(gson);