]> git.basschouten.com Git - openhab-addons.git/blob
f37a04da055936baba0a0ff58dd131833ecc4727
[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             if (!actions.containsKey(id)) {
368                 // Initial instantiation of NhcAction class for action object
369                 String name = action.get("name");
370                 if (name == null) {
371                     logger.debug("name not found in action {}", action);
372                     continue;
373                 }
374                 String type = Optional.ofNullable(action.get("type")).orElse("");
375                 ActionType actionType = ActionType.GENERIC;
376                 switch (type) {
377                     case "0":
378                         actionType = ActionType.TRIGGER;
379                         break;
380                     case "1":
381                         actionType = ActionType.RELAY;
382                         break;
383                     case "2":
384                         actionType = ActionType.DIMMER;
385                         break;
386                     case "4":
387                     case "5":
388                         actionType = ActionType.ROLLERSHUTTER;
389                         break;
390                     default:
391                         logger.debug("unknown action type {} for action {}", type, id);
392                         continue;
393                 }
394                 String locationId = action.get("location");
395                 String location = "";
396                 if (locationId != null && !locationId.isEmpty()) {
397                     location = locations.getOrDefault(locationId, new NhcLocation1("")).getName();
398                 }
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.
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.setState(state);
412                 }
413             }
414         }
415     }
416
417     private int parseIntOrThrow(@Nullable String str) throws IllegalArgumentException {
418         if (str == null) {
419             throw new IllegalArgumentException("String is null");
420         }
421         try {
422             return Integer.parseInt(str);
423         } catch (NumberFormatException e) {
424             throw new IllegalArgumentException(e);
425         }
426     }
427
428     private void cmdListThermostat(List<Map<String, String>> data) {
429         logger.debug("list thermostats");
430
431         for (Map<String, String> thermostat : data) {
432             try {
433                 String id = thermostat.get("id");
434                 if (id == null) {
435                     logger.debug("skipping thermostat {}, id not found", thermostat);
436                     continue;
437                 }
438                 int measured = parseIntOrThrow(thermostat.get("measured"));
439                 int setpoint = parseIntOrThrow(thermostat.get("setpoint"));
440                 int mode = parseIntOrThrow(thermostat.get("mode"));
441                 int overrule = parseIntOrThrow(thermostat.get("overrule"));
442                 // overruletime received in "HH:MM" format
443                 String[] overruletimeStrings = thermostat.getOrDefault("overruletime", "").split(":");
444                 int overruletime = 0;
445                 if (overruletimeStrings.length == 2) {
446                     overruletime = Integer.parseInt(overruletimeStrings[0]) * 60
447                             + Integer.parseInt(overruletimeStrings[1]);
448                 }
449                 int ecosave = parseIntOrThrow(thermostat.get("ecosave"));
450
451                 // For parity with NHC II, assume heating/cooling if thermostat is on and setpoint different from
452                 // measured
453                 int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
454
455                 NhcThermostat t = thermostats.computeIfAbsent(id, i -> {
456                     // Initial instantiation of NhcThermostat class for thermostat object
457                     String name = thermostat.get("name");
458                     String locationId = thermostat.get("location");
459                     String location = "";
460                     if (!((locationId == null) || locationId.isEmpty())) {
461                         NhcLocation1 nhcLocation = locations.get(locationId);
462                         if (nhcLocation != null) {
463                             location = nhcLocation.getName();
464                         }
465                     }
466                     if (name != null) {
467                         return new NhcThermostat1(i, name, location, this);
468                     }
469                     throw new IllegalArgumentException();
470                 });
471                 if (t != null) {
472                     t.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
473                 }
474             } catch (IllegalArgumentException e) {
475                 // do nothing
476             }
477         }
478     }
479
480     private void cmdExecuteActions(Map<String, String> data) {
481         try {
482             int errorCode = parseIntOrThrow(data.get("error"));
483             if (errorCode == 0) {
484                 logger.debug("execute action success");
485             } else {
486                 logger.debug("error code {} returned on command execution", errorCode);
487             }
488         } catch (IllegalArgumentException e) {
489             logger.debug("no error code returned on command execution");
490         }
491     }
492
493     private void cmdExecuteThermostat(Map<String, String> data) {
494         try {
495             int errorCode = parseIntOrThrow(data.get("error"));
496             if (errorCode == 0) {
497                 logger.debug("execute thermostats success");
498             } else {
499                 logger.debug("error code {} returned on command execution", errorCode);
500             }
501         } catch (IllegalArgumentException e) {
502             logger.debug("no error code returned on command execution");
503         }
504     }
505
506     private void eventListActions(List<Map<String, String>> data) {
507         for (Map<String, String> action : data) {
508             String id = action.get("id");
509             if (id == null || !actions.containsKey(id)) {
510                 logger.warn("action in controller not known {}", id);
511                 return;
512             }
513             String stateString = action.get("value1");
514             if (stateString != null) {
515                 int state = Integer.parseInt(stateString);
516                 logger.debug("event execute action {} with state {}", id, state);
517                 NhcAction action1 = actions.get(id);
518                 if (action1 != null) {
519                     action1.setState(state);
520                 }
521             }
522         }
523     }
524
525     private void eventListThermostat(List<Map<String, String>> data) {
526         for (Map<String, String> thermostat : data) {
527             try {
528                 String id = thermostat.get("id");
529                 if (!thermostats.containsKey(id)) {
530                     logger.warn("thermostat in controller not known {}", id);
531                     return;
532                 }
533
534                 int measured = parseIntOrThrow(thermostat.get("measured"));
535                 int setpoint = parseIntOrThrow(thermostat.get("setpoint"));
536                 int mode = parseIntOrThrow(thermostat.get("mode"));
537                 int overrule = parseIntOrThrow(thermostat.get("overrule"));
538                 // overruletime received in "HH:MM" format
539                 String[] overruletimeStrings = thermostat.getOrDefault("overruletime", "").split(":");
540                 int overruletime = 0;
541                 if (overruletimeStrings.length == 2) {
542                     overruletime = Integer.parseInt(overruletimeStrings[0]) * 60
543                             + Integer.parseInt(overruletimeStrings[1]);
544                 }
545                 int ecosave = parseIntOrThrow(thermostat.get("ecosave"));
546
547                 int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
548
549                 logger.debug(
550                         "Niko Home Control: event execute thermostat {} with measured {}, setpoint {}, mode {}, overrule {}, overruletime {}, ecosave {}, demand {}",
551                         id, measured, setpoint, mode, overrule, overruletime, ecosave, demand);
552                 NhcThermostat t = thermostats.get(id);
553                 if (t != null) {
554                     t.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
555                 }
556             } catch (IllegalArgumentException e) {
557                 // do nothing
558             }
559         }
560     }
561
562     private void eventGetAlarms(Map<String, String> data) {
563         String alarmText = data.get("text");
564         if (alarmText == null) {
565             logger.debug("message does not contain alarmtext: {}", data);
566             return;
567         }
568         switch (data.getOrDefault("type", "")) {
569             case "0":
570                 logger.debug("alarm - {}", alarmText);
571                 handler.alarmEvent(alarmText);
572                 break;
573             case "1":
574                 logger.debug("notice - {}", alarmText);
575                 handler.noticeEvent(alarmText);
576                 break;
577             default:
578                 logger.debug("unexpected message type {}", data.get("type"));
579         }
580     }
581
582     @Override
583     public void executeAction(String actionId, String value) {
584         NhcMessageCmd1 nhcCmd = new NhcMessageCmd1("executeactions", Integer.parseInt(actionId),
585                 Integer.parseInt(value));
586         sendMessage(nhcCmd);
587     }
588
589     @Override
590     public void executeThermostat(String thermostatId, String mode) {
591         NhcMessageCmd1 nhcCmd = new NhcMessageCmd1("executethermostat", Integer.parseInt(thermostatId))
592                 .withMode(Integer.parseInt(mode));
593         sendMessage(nhcCmd);
594     }
595
596     @Override
597     public void executeThermostat(String thermostatId, int overruleTemp, int overruleTime) {
598         String overruletimeString = String.format("%1$02d:%2$02d", overruleTime / 60, overruleTime % 60);
599         NhcMessageCmd1 nhcCmd = new NhcMessageCmd1("executethermostat", Integer.parseInt(thermostatId))
600                 .withOverrule(overruleTemp).withOverruletime(overruletimeString);
601         sendMessage(nhcCmd);
602     }
603 }