]> git.basschouten.com Git - openhab-addons.git/blob
d66b64a9141c239232486565ba19b46c68f35374
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.nikohomecontrol.internal.protocol.nhc1;
14
15 import static org.openhab.binding.nikohomecontrol.internal.NikoHomeControlBindingConstants.THREAD_NAME_PREFIX;
16
17 import java.io.BufferedReader;
18 import java.io.IOException;
19 import java.io.InputStreamReader;
20 import java.io.PrintWriter;
21 import java.net.InetAddress;
22 import java.net.Socket;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Optional;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.function.Consumer;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcAction;
33 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcControllerEvent;
34 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcThermostat;
35 import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlCommunication;
36 import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlConstants.ActionType;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import com.google.gson.Gson;
41 import com.google.gson.GsonBuilder;
42 import com.google.gson.JsonParseException;
43
44 /**
45  * The {@link NikoHomeControlCommunication1} class is able to do the following tasks with Niko Home Control I
46  * systems:
47  * <ul>
48  * <li>Start and stop TCP socket connection with Niko Home Control IP-interface.
49  * <li>Read all setup and status information from the Niko Home Control Controller.
50  * <li>Execute Niko Home Control commands.
51  * <li>Listen to events from Niko Home Control.
52  * </ul>
53  *
54  * @author Mark Herwege - Initial Contribution
55  */
56 @NonNullByDefault
57 public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication {
58
59     private Logger logger = LoggerFactory.getLogger(NikoHomeControlCommunication1.class);
60
61     private String eventThreadName = THREAD_NAME_PREFIX;
62
63     private final NhcSystemInfo1 systemInfo = new NhcSystemInfo1();
64     private final Map<String, NhcLocation1> locations = new ConcurrentHashMap<>();
65
66     private @Nullable Socket nhcSocket;
67     private @Nullable PrintWriter nhcOut;
68     private @Nullable BufferedReader nhcIn;
69
70     private volatile boolean listenerStopped;
71     private volatile boolean nhcEventsRunning;
72
73     private ScheduledExecutorService scheduler;
74
75     // We keep only 2 gson adapters used to serialize and deserialize all messages sent and received
76     protected final Gson gsonOut = new Gson();
77     protected Gson gsonIn;
78
79     /**
80      * Constructor for Niko Home Control I communication object, manages communication with
81      * Niko Home Control IP-interface.
82      *
83      */
84     public NikoHomeControlCommunication1(NhcControllerEvent handler, ScheduledExecutorService scheduler,
85             String eventThreadName) {
86         super(handler);
87         this.scheduler = scheduler;
88         this.eventThreadName = eventThreadName;
89
90         // When we set up this object, we want to get the proper gson adapter set up once
91         GsonBuilder gsonBuilder = new GsonBuilder();
92         gsonBuilder.registerTypeAdapter(NhcMessageBase1.class, new NikoHomeControlMessageDeserializer1());
93         gsonIn = gsonBuilder.create();
94     }
95
96     @Override
97     public synchronized void startCommunication() {
98         try {
99             for (int i = 1; nhcEventsRunning && (i <= 5); i++) {
100                 // the events listener thread did not finish yet, so wait max 5000ms before restarting
101                 Thread.sleep(1000);
102             }
103             if (nhcEventsRunning) {
104                 logger.debug("starting but previous connection still active after 5000ms");
105                 throw new IOException();
106             }
107
108             InetAddress addr = handler.getAddr();
109             int port = handler.getPort();
110
111             Socket socket = new Socket(addr, port);
112             nhcSocket = socket;
113             nhcOut = new PrintWriter(socket.getOutputStream(), true);
114             nhcIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
115             logger.debug("connected via local port {}", socket.getLocalPort());
116
117             // initialize all info in local fields
118             initialize();
119
120             // Start Niko Home Control event listener. This listener will act on all messages coming from
121             // IP-interface.
122             (new Thread(this::runNhcEvents, eventThreadName)).start();
123
124         } catch (IOException | InterruptedException e) {
125             stopCommunication();
126             handler.controllerOffline("@text/offline.communication-error");
127         }
128     }
129
130     /**
131      * Cleanup socket when the communication with Niko Home Control IP-interface is closed.
132      *
133      */
134     @Override
135     public synchronized void stopCommunication() {
136         listenerStopped = true;
137
138         Socket socket = nhcSocket;
139         if (socket != null) {
140             try {
141                 socket.close();
142             } catch (IOException ignore) {
143                 // ignore IO Error when trying to close the socket if the intention is to close it anyway
144             }
145         }
146         nhcSocket = null;
147
148         logger.debug("communication stopped");
149     }
150
151     @Override
152     public boolean communicationActive() {
153         return (nhcSocket != null);
154     }
155
156     /**
157      * Method that handles inbound communication from Niko Home Control, to be called on a separate thread.
158      * <p>
159      * The thread listens to the TCP socket opened at instantiation of the {@link NikoHomeControlCommunication} class
160      * and interprets all inbound json messages. It triggers state updates for active channels linked to the Niko Home
161      * Control actions. It is started after initialization of the communication.
162      *
163      */
164     private void runNhcEvents() {
165         String nhcMessage;
166
167         logger.debug("listening for events");
168         listenerStopped = false;
169         nhcEventsRunning = true;
170
171         try {
172             BufferedReader in = nhcIn;
173             if (in != null) {
174                 while (!listenerStopped && ((nhcMessage = in.readLine()) != null)) {
175                     readMessage(nhcMessage);
176                 }
177             }
178         } catch (IOException e) {
179             if (!listenerStopped) {
180                 nhcEventsRunning = false;
181                 // this is a socket error, not a communication stop triggered from outside this runnable
182                 logger.debug("IO error in listener");
183                 // the IO has stopped working, so we need to close cleanly and try to restart
184                 restartCommunication();
185                 return;
186             }
187         } finally {
188             nhcEventsRunning = false;
189         }
190
191         nhcEventsRunning = false;
192         // this is a stop from outside the runnable, so just log it and stop
193         logger.debug("event listener thread stopped");
194     }
195
196     /**
197      * After setting up the communication with the Niko Home Control IP-interface, send all initialization messages.
198      * <p>
199      * Only at first initialization, also set the return values. Otherwise use the runnable to get updated values.
200      * While communication is set up for thermostats, tariff data and alarms, only info from locations and actions
201      * is used beyond this point in openHAB. All other elements are for future extensions.
202      *
203      * @throws IOException
204      */
205     private void initialize() throws IOException {
206         sendAndReadMessage("systeminfo");
207         sendAndReadMessage("startevents");
208         sendAndReadMessage("listlocations");
209         sendAndReadMessage("listactions");
210         sendAndReadMessage("listthermostat");
211         sendAndReadMessage("listthermostatHVAC");
212         sendAndReadMessage("readtariffdata");
213         sendAndReadMessage("getalarms");
214     }
215
216     @SuppressWarnings("null")
217     private void sendAndReadMessage(String command) throws IOException {
218         sendMessage(new NhcMessageCmd1(command));
219         readMessage(nhcIn.readLine());
220     }
221
222     /**
223      * Called by other methods to send json cmd to Niko Home Control.
224      *
225      * @param nhcMessage
226      */
227     @SuppressWarnings("null")
228     private synchronized void sendMessage(Object nhcMessage) {
229         String json = gsonOut.toJson(nhcMessage);
230         logger.debug("send json {}", json);
231         nhcOut.println(json);
232         if (nhcOut.checkError()) {
233             logger.debug("error sending message, trying to restart communication");
234             restartCommunication();
235             // retry sending after restart
236             logger.debug("resend json {}", json);
237             nhcOut.println(json);
238             if (nhcOut.checkError()) {
239                 handler.controllerOffline("@text/offline.communication-error");
240             }
241         }
242     }
243
244     /**
245      * Method that interprets all feedback from Niko Home Control and calls appropriate handling methods.
246      *
247      * @param nhcMessage message read from Niko Home Control.
248      */
249     private void readMessage(@Nullable String nhcMessage) {
250         logger.debug("received json {}", nhcMessage);
251
252         try {
253             NhcMessageBase1 nhcMessageGson = gsonIn.fromJson(nhcMessage, NhcMessageBase1.class);
254
255             if (nhcMessageGson == null) {
256                 return;
257             }
258             String cmd = nhcMessageGson.getCmd();
259             String event = nhcMessageGson.getEvent();
260
261             if ("systeminfo".equals(cmd)) {
262                 cmdSystemInfo(((NhcMessageMap1) nhcMessageGson).getData());
263             } else if ("startevents".equals(cmd)) {
264                 cmdStartEvents(((NhcMessageMap1) nhcMessageGson).getData());
265             } else if ("listlocations".equals(cmd)) {
266                 cmdListLocations(((NhcMessageListMap1) nhcMessageGson).getData());
267             } else if ("listactions".equals(cmd)) {
268                 cmdListActions(((NhcMessageListMap1) nhcMessageGson).getData());
269             } else if (("listthermostat").equals(cmd)) {
270                 cmdListThermostat(((NhcMessageListMap1) nhcMessageGson).getData());
271             } else if ("executeactions".equals(cmd)) {
272                 cmdExecuteActions(((NhcMessageMap1) nhcMessageGson).getData());
273             } else if ("executethermostat".equals(cmd)) {
274                 cmdExecuteThermostat(((NhcMessageMap1) nhcMessageGson).getData());
275             } else if ("listactions".equals(event)) {
276                 eventListActions(((NhcMessageListMap1) nhcMessageGson).getData());
277             } else if ("listthermostat".equals(event)) {
278                 eventListThermostat(((NhcMessageListMap1) nhcMessageGson).getData());
279             } else if ("getalarms".equals(event)) {
280                 eventGetAlarms(((NhcMessageMap1) nhcMessageGson).getData());
281             } else {
282                 logger.debug("not acted on json {}", nhcMessage);
283             }
284         } catch (JsonParseException e) {
285             logger.debug("not acted on unsupported json {}", nhcMessage);
286         }
287     }
288
289     private void setIfPresent(Map<String, String> data, String key, Consumer<String> consumer) {
290         String val = data.get(key);
291         if (val != null) {
292             consumer.accept(val);
293         }
294     }
295
296     private synchronized void cmdSystemInfo(Map<String, String> data) {
297         logger.debug("systeminfo");
298
299         setIfPresent(data, "swversion", systemInfo::setSwVersion);
300         setIfPresent(data, "api", systemInfo::setApi);
301         setIfPresent(data, "time", systemInfo::setTime);
302         setIfPresent(data, "language", systemInfo::setLanguage);
303         setIfPresent(data, "currency", systemInfo::setCurrency);
304         setIfPresent(data, "units", systemInfo::setUnits);
305         setIfPresent(data, "DST", systemInfo::setDst);
306         setIfPresent(data, "TZ", systemInfo::setTz);
307         setIfPresent(data, "lastenergyerase", systemInfo::setLastEnergyErase);
308         setIfPresent(data, "lastconfig", systemInfo::setLastConfig);
309     }
310
311     /**
312      * Return the object with system info as read from the Niko Home Control controller.
313      *
314      * @return the systemInfo
315      */
316     public synchronized NhcSystemInfo1 getSystemInfo() {
317         return systemInfo;
318     }
319
320     private void cmdStartEvents(Map<String, String> data) {
321         String errorCodeString = data.get("error");
322         if (errorCodeString != null) {
323             int errorCode = Integer.parseInt(errorCodeString);
324             if (errorCode == 0) {
325                 logger.debug("start events success");
326             } else {
327                 logger.debug("error code {} returned on start events", errorCode);
328             }
329         } else {
330             logger.debug("could not determine error code returned on start events");
331         }
332     }
333
334     private void cmdListLocations(List<Map<String, String>> data) {
335         logger.debug("list locations");
336
337         locations.clear();
338
339         for (Map<String, String> location : data) {
340             String id = location.get("id");
341             String name = location.get("name");
342             if (id == null || name == null) {
343                 logger.debug("id or name null, ignoring entry");
344                 continue;
345             }
346             NhcLocation1 nhcLocation1 = new NhcLocation1(name);
347             locations.put(id, nhcLocation1);
348         }
349     }
350
351     private void cmdListActions(List<Map<String, String>> data) {
352         logger.debug("list actions");
353
354         for (Map<String, String> action : data) {
355             String id = action.get("id");
356             if (id == null) {
357                 logger.debug("id not found in action {}", action);
358                 continue;
359             }
360             String value1 = action.get("value1");
361             int state = ((value1 == null) || value1.isEmpty() ? 0 : Integer.parseInt(value1));
362             String value2 = action.get("value2");
363             int closeTime = ((value2 == null) || value2.isEmpty() ? 0 : Integer.parseInt(value2));
364             String value3 = action.get("value3");
365             int openTime = ((value3 == null) || value3.isEmpty() ? 0 : Integer.parseInt(value3));
366
367             String name = action.get("name");
368             if (name == null) {
369                 logger.debug("name not found in action {}", action);
370                 continue;
371             }
372             String type = Optional.ofNullable(action.get("type")).orElse("");
373             ActionType actionType = ActionType.GENERIC;
374             switch (type) {
375                 case "0":
376                     actionType = ActionType.TRIGGER;
377                     break;
378                 case "1":
379                     actionType = ActionType.RELAY;
380                     break;
381                 case "2":
382                     actionType = ActionType.DIMMER;
383                     break;
384                 case "4":
385                 case "5":
386                     actionType = ActionType.ROLLERSHUTTER;
387                     break;
388                 default:
389                     logger.debug("unknown action type {} for action {}", type, id);
390                     continue;
391             }
392             String locationId = action.get("location");
393             String location = "";
394             if (locationId != null && !locationId.isEmpty()) {
395                 location = locations.getOrDefault(locationId, new NhcLocation1("")).getName();
396             }
397             if (!actions.containsKey(id)) {
398                 // Initial instantiation of NhcAction class for action object
399                 NhcAction nhcAction = new NhcAction1(id, name, actionType, location, this, scheduler);
400                 if (actionType == ActionType.ROLLERSHUTTER) {
401                     nhcAction.setShutterTimes(openTime, closeTime);
402                 }
403                 nhcAction.setState(state);
404                 actions.put(id, nhcAction);
405             } else {
406                 // Action object already exists, so only update state, name and location.
407                 // If we would re-instantiate action, we would lose pointer back from action to thing handler that was
408                 // set in thing handler initialize().
409                 NhcAction nhcAction = actions.get(id);
410                 if (nhcAction != null) {
411                     nhcAction.setName(name);
412                     nhcAction.setLocation(location);
413                     nhcAction.setState(state);
414                 }
415             }
416         }
417     }
418
419     private int parseIntOrThrow(@Nullable String str) throws IllegalArgumentException {
420         if (str == null) {
421             throw new IllegalArgumentException("String is null");
422         }
423         try {
424             return Integer.parseInt(str);
425         } catch (NumberFormatException e) {
426             throw new IllegalArgumentException(e);
427         }
428     }
429
430     private void cmdListThermostat(List<Map<String, String>> data) {
431         logger.debug("list thermostats");
432
433         for (Map<String, String> thermostat : data) {
434             try {
435                 String id = thermostat.get("id");
436                 if (id == null) {
437                     logger.debug("skipping thermostat {}, id not found", thermostat);
438                     continue;
439                 }
440                 int measured = parseIntOrThrow(thermostat.get("measured"));
441                 int setpoint = parseIntOrThrow(thermostat.get("setpoint"));
442                 int mode = parseIntOrThrow(thermostat.get("mode"));
443                 int overrule = parseIntOrThrow(thermostat.get("overrule"));
444                 // overruletime received in "HH:MM" format
445                 String[] overruletimeStrings = thermostat.getOrDefault("overruletime", "").split(":");
446                 int overruletime = 0;
447                 if (overruletimeStrings.length == 2) {
448                     overruletime = Integer.parseInt(overruletimeStrings[0]) * 60
449                             + Integer.parseInt(overruletimeStrings[1]);
450                 }
451                 int ecosave = parseIntOrThrow(thermostat.get("ecosave"));
452
453                 // For parity with NHC II, assume heating/cooling if thermostat is on and setpoint different from
454                 // measured
455                 int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
456
457                 String name = thermostat.get("name");
458                 String locationId = thermostat.get("location");
459                 NhcLocation1 nhcLocation = null;
460                 if (!((locationId == null) || locationId.isEmpty())) {
461                     nhcLocation = locations.get(locationId);
462                 }
463                 String location = (nhcLocation != null) ? nhcLocation.getName() : null;
464                 NhcThermostat t = thermostats.computeIfAbsent(id, i -> {
465                     // Initial instantiation of NhcThermostat class for thermostat object
466                     if (name != null) {
467                         return new NhcThermostat1(i, name, location, this);
468                     }
469                     throw new IllegalArgumentException();
470                 });
471                 if (t != null) {
472                     if (name != null) {
473                         t.setName(name);
474                     }
475                     t.setLocation(location);
476                     t.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
477                 }
478             } catch (IllegalArgumentException e) {
479                 // do nothing
480             }
481         }
482     }
483
484     private void cmdExecuteActions(Map<String, String> data) {
485         try {
486             int errorCode = parseIntOrThrow(data.get("error"));
487             if (errorCode == 0) {
488                 logger.debug("execute action success");
489             } else {
490                 logger.debug("error code {} returned on command execution", errorCode);
491             }
492         } catch (IllegalArgumentException e) {
493             logger.debug("no error code returned on command execution");
494         }
495     }
496
497     private void cmdExecuteThermostat(Map<String, String> data) {
498         try {
499             int errorCode = parseIntOrThrow(data.get("error"));
500             if (errorCode == 0) {
501                 logger.debug("execute thermostats success");
502             } else {
503                 logger.debug("error code {} returned on command execution", errorCode);
504             }
505         } catch (IllegalArgumentException e) {
506             logger.debug("no error code returned on command execution");
507         }
508     }
509
510     private void eventListActions(List<Map<String, String>> data) {
511         for (Map<String, String> action : data) {
512             String id = action.get("id");
513             if (id == null || !actions.containsKey(id)) {
514                 logger.warn("action in controller not known {}", id);
515                 return;
516             }
517             String stateString = action.get("value1");
518             if (stateString != null) {
519                 int state = Integer.parseInt(stateString);
520                 logger.debug("event execute action {} with state {}", id, state);
521                 NhcAction action1 = actions.get(id);
522                 if (action1 != null) {
523                     action1.setState(state);
524                 }
525             }
526         }
527     }
528
529     private void eventListThermostat(List<Map<String, String>> data) {
530         for (Map<String, String> thermostat : data) {
531             try {
532                 String id = thermostat.get("id");
533                 if (!thermostats.containsKey(id)) {
534                     logger.warn("thermostat in controller not known {}", id);
535                     return;
536                 }
537
538                 int measured = parseIntOrThrow(thermostat.get("measured"));
539                 int setpoint = parseIntOrThrow(thermostat.get("setpoint"));
540                 int mode = parseIntOrThrow(thermostat.get("mode"));
541                 int overrule = parseIntOrThrow(thermostat.get("overrule"));
542                 // overruletime received in "HH:MM" format
543                 String[] overruletimeStrings = thermostat.getOrDefault("overruletime", "").split(":");
544                 int overruletime = 0;
545                 if (overruletimeStrings.length == 2) {
546                     overruletime = Integer.parseInt(overruletimeStrings[0]) * 60
547                             + Integer.parseInt(overruletimeStrings[1]);
548                 }
549                 int ecosave = parseIntOrThrow(thermostat.get("ecosave"));
550
551                 int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
552
553                 logger.debug(
554                         "Niko Home Control: event execute thermostat {} with measured {}, setpoint {}, mode {}, overrule {}, overruletime {}, ecosave {}, demand {}",
555                         id, measured, setpoint, mode, overrule, overruletime, ecosave, demand);
556                 NhcThermostat t = thermostats.get(id);
557                 if (t != null) {
558                     t.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
559                 }
560             } catch (IllegalArgumentException e) {
561                 // do nothing
562             }
563         }
564     }
565
566     private void eventGetAlarms(Map<String, String> data) {
567         String alarmText = data.get("text");
568         if (alarmText == null) {
569             logger.debug("message does not contain alarmtext: {}", data);
570             return;
571         }
572         switch (data.getOrDefault("type", "")) {
573             case "0":
574                 logger.debug("alarm - {}", alarmText);
575                 handler.alarmEvent(alarmText);
576                 break;
577             case "1":
578                 logger.debug("notice - {}", alarmText);
579                 handler.noticeEvent(alarmText);
580                 break;
581             default:
582                 logger.debug("unexpected message type {}", data.get("type"));
583         }
584     }
585
586     @Override
587     public void executeAction(String actionId, String value) {
588         NhcMessageCmd1 nhcCmd = new NhcMessageCmd1("executeactions", Integer.parseInt(actionId),
589                 Integer.parseInt(value));
590         sendMessage(nhcCmd);
591     }
592
593     @Override
594     public void executeThermostat(String thermostatId, String mode) {
595         NhcMessageCmd1 nhcCmd = new NhcMessageCmd1("executethermostat", Integer.parseInt(thermostatId))
596                 .withMode(Integer.parseInt(mode));
597         sendMessage(nhcCmd);
598     }
599
600     @Override
601     public void executeThermostat(String thermostatId, int overruleTemp, int overruleTime) {
602         String overruletimeString = String.format("%1$02d:%2$02d", overruleTime / 60, overruleTime % 60);
603         NhcMessageCmd1 nhcCmd = new NhcMessageCmd1("executethermostat", Integer.parseInt(thermostatId))
604                 .withOverrule(overruleTemp).withOverruletime(overruletimeString);
605         sendMessage(nhcCmd);
606     }
607 }