2 * Copyright (c) 2010-2022 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.nikohomecontrol.internal.protocol.nhc1;
15 import static org.openhab.binding.nikohomecontrol.internal.NikoHomeControlBindingConstants.THREAD_NAME_PREFIX;
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;
25 import java.util.Optional;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.function.Consumer;
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;
40 import com.google.gson.Gson;
41 import com.google.gson.GsonBuilder;
42 import com.google.gson.JsonParseException;
45 * The {@link NikoHomeControlCommunication1} class is able to do the following tasks with Niko Home Control I
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.
54 * @author Mark Herwege - Initial Contribution
57 public class NikoHomeControlCommunication1 extends NikoHomeControlCommunication {
59 private Logger logger = LoggerFactory.getLogger(NikoHomeControlCommunication1.class);
61 private String eventThreadName = THREAD_NAME_PREFIX;
63 private final NhcSystemInfo1 systemInfo = new NhcSystemInfo1();
64 private final Map<String, NhcLocation1> locations = new ConcurrentHashMap<>();
66 private @Nullable Socket nhcSocket;
67 private @Nullable PrintWriter nhcOut;
68 private @Nullable BufferedReader nhcIn;
70 private volatile boolean listenerStopped;
71 private volatile boolean nhcEventsRunning;
73 private ScheduledExecutorService scheduler;
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;
80 * Constructor for Niko Home Control I communication object, manages communication with
81 * Niko Home Control IP-interface.
84 public NikoHomeControlCommunication1(NhcControllerEvent handler, ScheduledExecutorService scheduler,
85 String eventThreadName) {
87 this.scheduler = scheduler;
88 this.eventThreadName = eventThreadName;
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();
97 public synchronized void startCommunication() {
99 for (int i = 1; nhcEventsRunning && (i <= 5); i++) {
100 // the events listener thread did not finish yet, so wait max 5000ms before restarting
103 if (nhcEventsRunning) {
104 logger.debug("starting but previous connection still active after 5000ms");
105 throw new IOException();
108 InetAddress addr = handler.getAddr();
109 int port = handler.getPort();
111 Socket socket = new Socket(addr, port);
113 nhcOut = new PrintWriter(socket.getOutputStream(), true);
114 nhcIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
115 logger.debug("connected via local port {}", socket.getLocalPort());
117 // initialize all info in local fields
120 // Start Niko Home Control event listener. This listener will act on all messages coming from
122 (new Thread(this::runNhcEvents, eventThreadName)).start();
124 } catch (IOException | InterruptedException e) {
126 handler.controllerOffline("@text/offline.communication-error");
131 * Cleanup socket when the communication with Niko Home Control IP-interface is closed.
135 public synchronized void stopCommunication() {
136 listenerStopped = true;
138 Socket socket = nhcSocket;
139 if (socket != null) {
142 } catch (IOException ignore) {
143 // ignore IO Error when trying to close the socket if the intention is to close it anyway
148 logger.debug("communication stopped");
152 public boolean communicationActive() {
153 return (nhcSocket != null);
157 * Method that handles inbound communication from Niko Home Control, to be called on a separate thread.
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.
164 private void runNhcEvents() {
167 logger.debug("listening for events");
168 listenerStopped = false;
169 nhcEventsRunning = true;
172 BufferedReader in = nhcIn;
174 while (!listenerStopped && ((nhcMessage = in.readLine()) != null)) {
175 readMessage(nhcMessage);
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();
188 nhcEventsRunning = false;
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");
197 * After setting up the communication with the Niko Home Control IP-interface, send all initialization messages.
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.
203 * @throws IOException
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");
216 @SuppressWarnings("null")
217 private void sendAndReadMessage(String command) throws IOException {
218 sendMessage(new NhcMessageCmd1(command));
219 readMessage(nhcIn.readLine());
223 * Called by other methods to send json cmd to Niko Home Control.
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");
245 * Method that interprets all feedback from Niko Home Control and calls appropriate handling methods.
247 * @param nhcMessage message read from Niko Home Control.
249 private void readMessage(@Nullable String nhcMessage) {
250 logger.debug("received json {}", nhcMessage);
253 NhcMessageBase1 nhcMessageGson = gsonIn.fromJson(nhcMessage, NhcMessageBase1.class);
255 if (nhcMessageGson == null) {
258 String cmd = nhcMessageGson.getCmd();
259 String event = nhcMessageGson.getEvent();
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());
282 logger.debug("not acted on json {}", nhcMessage);
284 } catch (JsonParseException e) {
285 logger.debug("not acted on unsupported json {}", nhcMessage);
289 private void setIfPresent(Map<String, String> data, String key, Consumer<String> consumer) {
290 String val = data.get(key);
292 consumer.accept(val);
296 private synchronized void cmdSystemInfo(Map<String, String> data) {
297 logger.debug("systeminfo");
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);
312 * Return the object with system info as read from the Niko Home Control controller.
314 * @return the systemInfo
316 public synchronized NhcSystemInfo1 getSystemInfo() {
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");
327 logger.debug("error code {} returned on start events", errorCode);
330 logger.debug("could not determine error code returned on start events");
334 private void cmdListLocations(List<Map<String, String>> data) {
335 logger.debug("list locations");
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");
346 NhcLocation1 nhcLocation1 = new NhcLocation1(name);
347 locations.put(id, nhcLocation1);
351 private void cmdListActions(List<Map<String, String>> data) {
352 logger.debug("list actions");
354 for (Map<String, String> action : data) {
355 String id = action.get("id");
357 logger.debug("id not found in action {}", action);
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));
367 if (!actions.containsKey(id)) {
368 // Initial instantiation of NhcAction class for action object
369 String name = action.get("name");
371 logger.debug("name not found in action {}", action);
374 String type = Optional.ofNullable(action.get("type")).orElse("");
375 ActionType actionType = ActionType.GENERIC;
378 actionType = ActionType.TRIGGER;
381 actionType = ActionType.RELAY;
384 actionType = ActionType.DIMMER;
388 actionType = ActionType.ROLLERSHUTTER;
391 logger.debug("unknown action type {} for action {}", type, id);
394 String locationId = action.get("location");
395 String location = "";
396 if (locationId != null && !locationId.isEmpty()) {
397 location = locations.getOrDefault(locationId, new NhcLocation1("")).getName();
399 NhcAction nhcAction = new NhcAction1(id, name, actionType, location, this, scheduler);
400 if (actionType == ActionType.ROLLERSHUTTER) {
401 nhcAction.setShutterTimes(openTime, closeTime);
403 nhcAction.setState(state);
404 actions.put(id, nhcAction);
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);
417 private int parseIntOrThrow(@Nullable String str) throws IllegalArgumentException {
419 throw new IllegalArgumentException("String is null");
422 return Integer.parseInt(str);
423 } catch (NumberFormatException e) {
424 throw new IllegalArgumentException(e);
428 private void cmdListThermostat(List<Map<String, String>> data) {
429 logger.debug("list thermostats");
431 for (Map<String, String> thermostat : data) {
433 String id = thermostat.get("id");
435 logger.debug("skipping thermostat {}, id not found", thermostat);
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]);
449 int ecosave = parseIntOrThrow(thermostat.get("ecosave"));
451 // For parity with NHC II, assume heating/cooling if thermostat is on and setpoint different from
453 int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
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();
467 return new NhcThermostat1(i, name, location, this);
469 throw new IllegalArgumentException();
472 t.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
474 } catch (IllegalArgumentException e) {
480 private void cmdExecuteActions(Map<String, String> data) {
482 int errorCode = parseIntOrThrow(data.get("error"));
483 if (errorCode == 0) {
484 logger.debug("execute action success");
486 logger.debug("error code {} returned on command execution", errorCode);
488 } catch (IllegalArgumentException e) {
489 logger.debug("no error code returned on command execution");
493 private void cmdExecuteThermostat(Map<String, String> data) {
495 int errorCode = parseIntOrThrow(data.get("error"));
496 if (errorCode == 0) {
497 logger.debug("execute thermostats success");
499 logger.debug("error code {} returned on command execution", errorCode);
501 } catch (IllegalArgumentException e) {
502 logger.debug("no error code returned on command execution");
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);
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);
525 private void eventListThermostat(List<Map<String, String>> data) {
526 for (Map<String, String> thermostat : data) {
528 String id = thermostat.get("id");
529 if (!thermostats.containsKey(id)) {
530 logger.warn("thermostat in controller not known {}", id);
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]);
545 int ecosave = parseIntOrThrow(thermostat.get("ecosave"));
547 int demand = (mode != 3) ? (setpoint > measured ? 1 : (setpoint < measured ? -1 : 0)) : 0;
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);
554 t.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
556 } catch (IllegalArgumentException e) {
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);
568 switch (data.getOrDefault("type", "")) {
570 logger.debug("alarm - {}", alarmText);
571 handler.alarmEvent(alarmText);
574 logger.debug("notice - {}", alarmText);
575 handler.noticeEvent(alarmText);
578 logger.debug("unexpected message type {}", data.get("type"));
583 public void executeAction(String actionId, String value) {
584 NhcMessageCmd1 nhcCmd = new NhcMessageCmd1("executeactions", Integer.parseInt(actionId),
585 Integer.parseInt(value));
590 public void executeThermostat(String thermostatId, String mode) {
591 NhcMessageCmd1 nhcCmd = new NhcMessageCmd1("executethermostat", Integer.parseInt(thermostatId))
592 .withMode(Integer.parseInt(mode));
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);