]> git.basschouten.com Git - openhab-addons.git/blob
61d407f29ba0eb82d003bbcaf433494f8876420d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.nhc2;
14
15 import static org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlConstants.*;
16
17 import java.lang.reflect.Type;
18 import java.net.InetAddress;
19 import java.security.cert.CertificateException;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.NoSuchElementException;
23 import java.util.Objects;
24 import java.util.Optional;
25 import java.util.concurrent.CompletableFuture;
26 import java.util.concurrent.CopyOnWriteArrayList;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.ScheduledExecutorService;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.TimeoutException;
31 import java.util.stream.Collectors;
32 import java.util.stream.IntStream;
33
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcAction;
37 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcControllerEvent;
38 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcEnergyMeter;
39 import org.openhab.binding.nikohomecontrol.internal.protocol.NhcThermostat;
40 import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlCommunication;
41 import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlConstants.ActionType;
42 import org.openhab.binding.nikohomecontrol.internal.protocol.nhc2.NhcDevice2.NhcProperty;
43 import org.openhab.binding.nikohomecontrol.internal.protocol.nhc2.NhcMessage2.NhcMessageParam;
44 import org.openhab.core.io.transport.mqtt.MqttConnectionObserver;
45 import org.openhab.core.io.transport.mqtt.MqttConnectionState;
46 import org.openhab.core.io.transport.mqtt.MqttException;
47 import org.openhab.core.io.transport.mqtt.MqttMessageSubscriber;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 import com.google.gson.FieldNamingPolicy;
52 import com.google.gson.Gson;
53 import com.google.gson.GsonBuilder;
54 import com.google.gson.JsonSyntaxException;
55 import com.google.gson.reflect.TypeToken;
56
57 /**
58  * The {@link NikoHomeControlCommunication2} class is able to do the following tasks with Niko Home Control II
59  * systems:
60  * <ul>
61  * <li>Start and stop MQTT connection with Niko Home Control II Connected Controller.
62  * <li>Read all setup and status information from the Niko Home Control Controller.
63  * <li>Execute Niko Home Control commands.
64  * <li>Listen for events from Niko Home Control.
65  * </ul>
66  *
67  * @author Mark Herwege - Initial Contribution
68  */
69 @NonNullByDefault
70 public class NikoHomeControlCommunication2 extends NikoHomeControlCommunication
71         implements MqttMessageSubscriber, MqttConnectionObserver {
72
73     private final Logger logger = LoggerFactory.getLogger(NikoHomeControlCommunication2.class);
74
75     private final NhcMqttConnection2 mqttConnection;
76
77     private final List<NhcService2> services = new CopyOnWriteArrayList<>();
78
79     private volatile String profile = "";
80
81     private volatile @Nullable NhcSystemInfo2 nhcSystemInfo;
82     private volatile @Nullable NhcTimeInfo2 nhcTimeInfo;
83
84     private volatile @Nullable CompletableFuture<Boolean> communicationStarted;
85
86     private ScheduledExecutorService scheduler;
87
88     private final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
89
90     /**
91      * Constructor for Niko Home Control communication object, manages communication with
92      * Niko Home Control II Connected Controller.
93      *
94      * @throws CertificateException when the SSL context for MQTT communication cannot be created
95      * @throws UnknownHostException when the IP address is not provided
96      *
97      */
98     public NikoHomeControlCommunication2(NhcControllerEvent handler, String clientId,
99             ScheduledExecutorService scheduler) throws CertificateException {
100         super(handler);
101         mqttConnection = new NhcMqttConnection2(clientId, this, this);
102         this.scheduler = scheduler;
103     }
104
105     @Override
106     public synchronized void startCommunication() {
107         communicationStarted = new CompletableFuture<>();
108
109         InetAddress addr = handler.getAddr();
110         if (addr == null) {
111             logger.warn("IP address cannot be empty");
112             stopCommunication();
113             return;
114         }
115         String addrString = addr.getHostAddress();
116         int port = handler.getPort();
117         logger.debug("initializing for mqtt connection to CoCo on {}:{}", addrString, port);
118
119         profile = handler.getProfile();
120
121         String token = handler.getToken();
122         if (token.isEmpty()) {
123             logger.warn("JWT token cannot be empty");
124             stopCommunication();
125             return;
126         }
127
128         try {
129             mqttConnection.startConnection(addrString, port, profile, token);
130             initialize();
131         } catch (MqttException e) {
132             logger.debug("error in mqtt communication");
133             stopCommunication();
134         }
135     }
136
137     @Override
138     public synchronized void stopCommunication() {
139         CompletableFuture<Boolean> started = communicationStarted;
140         if (started != null) {
141             started.complete(false);
142         }
143         communicationStarted = null;
144         mqttConnection.stopConnection();
145     }
146
147     @Override
148     public boolean communicationActive() {
149         CompletableFuture<Boolean> started = communicationStarted;
150         if (started == null) {
151             return false;
152         }
153         try {
154             // Wait until we received all devices info to confirm we are active.
155             return started.get(5000, TimeUnit.MILLISECONDS);
156         } catch (InterruptedException | ExecutionException | TimeoutException e) {
157             logger.debug("exception waiting for connection start");
158             return false;
159         }
160     }
161
162     /**
163      * After setting up the communication with the Niko Home Control Connected Controller, send all initialization
164      * messages.
165      *
166      */
167     private void initialize() throws MqttException {
168         NhcMessage2 message = new NhcMessage2();
169
170         message.method = "systeminfo.publish";
171         mqttConnection.connectionPublish(profile + "/system/cmd", gson.toJson(message));
172
173         message.method = "services.list";
174         mqttConnection.connectionPublish(profile + "/authentication/cmd", gson.toJson(message));
175
176         message.method = "devices.list";
177         mqttConnection.connectionPublish(profile + "/control/devices/cmd", gson.toJson(message));
178
179         message.method = "notifications.list";
180         mqttConnection.connectionPublish(profile + "/notification/cmd", gson.toJson(message));
181     }
182
183     private void connectionLost(String message) {
184         logger.debug("connection lost");
185         stopCommunication();
186         handler.controllerOffline(message);
187     }
188
189     private void systemEvt(String response) {
190         Type messageType = new TypeToken<NhcMessage2>() {
191         }.getType();
192         List<NhcTimeInfo2> timeInfo = null;
193         List<NhcSystemInfo2> systemInfo = null;
194         try {
195             NhcMessage2 message = gson.fromJson(response, messageType);
196             List<NhcMessageParam> messageParams = (message != null) ? message.params : null;
197             if (messageParams != null) {
198                 timeInfo = messageParams.stream().filter(p -> (p.timeInfo != null)).findFirst().get().timeInfo;
199                 systemInfo = messageParams.stream().filter(p -> (p.systemInfo != null)).findFirst().get().systemInfo;
200             }
201         } catch (JsonSyntaxException e) {
202             logger.debug("unexpected json {}", response);
203         } catch (NoSuchElementException ignore) {
204             // Ignore if timeInfo not present in response, this should not happen in a timeInfo response
205         }
206         if (timeInfo != null) {
207             nhcTimeInfo = timeInfo.get(0);
208         }
209         if (systemInfo != null) {
210             nhcSystemInfo = systemInfo.get(0);
211             handler.updatePropertiesEvent();
212         }
213     }
214
215     private void systeminfoPublishRsp(String response) {
216         Type messageType = new TypeToken<NhcMessage2>() {
217         }.getType();
218         List<NhcSystemInfo2> systemInfo = null;
219         try {
220             NhcMessage2 message = gson.fromJson(response, messageType);
221             List<NhcMessageParam> messageParams = (message != null) ? message.params : null;
222             if (messageParams != null) {
223                 systemInfo = messageParams.stream().filter(p -> (p.systemInfo != null)).findFirst().get().systemInfo;
224             }
225         } catch (JsonSyntaxException e) {
226             logger.debug("unexpected json {}", response);
227         } catch (NoSuchElementException ignore) {
228             // Ignore if systemInfo not present in response, this should not happen in a systemInfo response
229         }
230         if (systemInfo != null) {
231             nhcSystemInfo = systemInfo.get(0);
232         }
233     }
234
235     private void servicesListRsp(String response) {
236         Type messageType = new TypeToken<NhcMessage2>() {
237         }.getType();
238         List<NhcService2> serviceList = null;
239         try {
240             NhcMessage2 message = gson.fromJson(response, messageType);
241             List<NhcMessageParam> messageParams = (message != null) ? message.params : null;
242             if (messageParams != null) {
243                 serviceList = messageParams.stream().filter(p -> (p.services != null)).findFirst().get().services;
244             }
245         } catch (JsonSyntaxException e) {
246             logger.debug("unexpected json {}", response);
247         } catch (NoSuchElementException ignore) {
248             // Ignore if services not present in response, this should not happen in a services response
249         }
250         services.clear();
251         if (serviceList != null) {
252             services.addAll(serviceList);
253         }
254     }
255
256     private void devicesListRsp(String response) {
257         Type messageType = new TypeToken<NhcMessage2>() {
258         }.getType();
259         List<NhcDevice2> deviceList = null;
260         try {
261             NhcMessage2 message = gson.fromJson(response, messageType);
262             List<NhcMessageParam> messageParams = (message != null) ? message.params : null;
263             if (messageParams != null) {
264                 deviceList = messageParams.stream().filter(p -> (p.devices != null)).findFirst().get().devices;
265             }
266         } catch (JsonSyntaxException e) {
267             logger.debug("unexpected json {}", response);
268         } catch (NoSuchElementException ignore) {
269             // Ignore if devices not present in response, this should not happen in a devices response
270         }
271         if (deviceList == null) {
272             return;
273         }
274
275         for (NhcDevice2 device : deviceList) {
276             addDevice(device);
277             updateState(device);
278         }
279
280         // Once a devices list response is received, we know the communication is fully started.
281         logger.debug("Communication start complete.");
282         handler.controllerOnline();
283         CompletableFuture<Boolean> future = communicationStarted;
284         if (future != null) {
285             future.complete(true);
286         }
287     }
288
289     private void devicesEvt(String response) {
290         Type messageType = new TypeToken<NhcMessage2>() {
291         }.getType();
292         List<NhcDevice2> deviceList = null;
293         String method = null;
294         try {
295             NhcMessage2 message = gson.fromJson(response, messageType);
296             method = (message != null) ? message.method : null;
297             List<NhcMessageParam> messageParams = (message != null) ? message.params : null;
298             if (messageParams != null) {
299                 deviceList = messageParams.stream().filter(p -> (p.devices != null)).findFirst().get().devices;
300             }
301         } catch (JsonSyntaxException e) {
302             logger.debug("unexpected json {}", response);
303         } catch (NoSuchElementException ignore) {
304             // Ignore if devices not present in response, this should not happen in a devices event
305         }
306         if (deviceList == null) {
307             return;
308         }
309
310         if ("devices.removed".equals(method)) {
311             deviceList.forEach(this::removeDevice);
312             return;
313         } else if ("devices.added".equals(method)) {
314             deviceList.forEach(this::addDevice);
315         }
316
317         deviceList.forEach(this::updateState);
318     }
319
320     private void notificationEvt(String response) {
321         Type messageType = new TypeToken<NhcMessage2>() {
322         }.getType();
323         List<NhcNotification2> notificationList = null;
324         try {
325             NhcMessage2 message = gson.fromJson(response, messageType);
326             List<NhcMessageParam> messageParams = (message != null) ? message.params : null;
327             if (messageParams != null) {
328                 notificationList = messageParams.stream().filter(p -> (p.notifications != null)).findFirst()
329                         .get().notifications;
330             }
331         } catch (JsonSyntaxException e) {
332             logger.debug("unexpected json {}", response);
333         } catch (NoSuchElementException ignore) {
334             // Ignore if notifications not present in response, this should not happen in a notifications event
335         }
336         logger.debug("notifications {}", notificationList);
337         if (notificationList == null) {
338             return;
339         }
340
341         for (NhcNotification2 notification : notificationList) {
342             if ("new".equals(notification.status)) {
343                 String alarmText = notification.text;
344                 switch (notification.type) {
345                     case "alarm":
346                         handler.alarmEvent(alarmText);
347                         break;
348                     case "notification":
349                         handler.noticeEvent(alarmText);
350                         break;
351                     default:
352                         logger.debug("unexpected message type {}", notification.type);
353                 }
354             }
355         }
356     }
357
358     private void addDevice(NhcDevice2 device) {
359         String location = null;
360         if (device.parameters != null) {
361             location = device.parameters.stream().map(p -> p.locationName).filter(Objects::nonNull).findFirst()
362                     .orElse(null);
363         }
364
365         if ("action".equals(device.type)) {
366             if (!actions.containsKey(device.uuid)) {
367                 logger.debug("adding action device {}, {}", device.uuid, device.name);
368
369                 ActionType actionType;
370                 switch (device.model) {
371                     case "generic":
372                     case "pir":
373                     case "simulation":
374                     case "comfort":
375                     case "alarms":
376                     case "alloff":
377                     case "overallcomfort":
378                     case "garagedoor":
379                         actionType = ActionType.TRIGGER;
380                         break;
381                     case "light":
382                     case "socket":
383                     case "switched-generic":
384                     case "switched-fan":
385                         actionType = ActionType.RELAY;
386                         break;
387                     case "dimmer":
388                         actionType = ActionType.DIMMER;
389                         break;
390                     case "rolldownshutter":
391                     case "sunblind":
392                     case "venetianblind":
393                     case "gate":
394                         actionType = ActionType.ROLLERSHUTTER;
395                         break;
396                     default:
397                         actionType = ActionType.GENERIC;
398                         logger.debug("device model {} not recognised, default to GENERIC action", device.model);
399                 }
400
401                 NhcAction2 nhcAction = new NhcAction2(device.uuid, device.name, device.model, device.technology,
402                         actionType, location, this);
403                 actions.put(device.uuid, nhcAction);
404             }
405         } else if ("thermostat".equals(device.type)) {
406             if (!thermostats.containsKey(device.uuid)) {
407                 logger.debug("adding thermostat device {}, {}", device.uuid, device.name);
408
409                 NhcThermostat2 nhcThermostat = new NhcThermostat2(device.uuid, device.name, device.model,
410                         device.technology, location, this);
411                 thermostats.put(device.uuid, nhcThermostat);
412             }
413         } else if ("centralmeter".equals(device.type)) {
414             if (!energyMeters.containsKey(device.uuid)) {
415                 logger.debug("adding centralmeter device {}, {}", device.uuid, device.name);
416                 NhcEnergyMeter2 nhcEnergyMeter = new NhcEnergyMeter2(device.uuid, device.name, device.model,
417                         device.technology, this, scheduler);
418                 energyMeters.put(device.uuid, nhcEnergyMeter);
419             }
420         } else {
421             logger.debug("device type {} not supported for {}, {}", device.type, device.uuid, device.name);
422         }
423     }
424
425     private void removeDevice(NhcDevice2 device) {
426         NhcAction action = actions.get(device.uuid);
427         NhcThermostat thermostat = thermostats.get(device.uuid);
428         NhcEnergyMeter energyMeter = energyMeters.get(device.uuid);
429         if (action != null) {
430             action.actionRemoved();
431             actions.remove(device.uuid);
432         } else if (thermostat != null) {
433             thermostat.thermostatRemoved();
434             thermostats.remove(device.uuid);
435         } else if (energyMeter != null) {
436             energyMeter.energyMeterRemoved();
437             energyMeters.remove(device.uuid);
438         }
439     }
440
441     private void updateState(NhcDevice2 device) {
442         List<NhcProperty> deviceProperties = device.properties;
443         if (deviceProperties == null) {
444             logger.debug("Cannot Update state for {} as no properties defined in device message", device.uuid);
445             return;
446         }
447
448         NhcAction action = actions.get(device.uuid);
449         NhcThermostat thermostat = thermostats.get(device.uuid);
450         NhcEnergyMeter energyMeter = energyMeters.get(device.uuid);
451
452         if (action != null) {
453             updateActionState((NhcAction2) action, deviceProperties);
454         } else if (thermostat != null) {
455             updateThermostatState((NhcThermostat2) thermostat, deviceProperties);
456         } else if (energyMeter != null) {
457             updateEnergyMeterState((NhcEnergyMeter2) energyMeter, deviceProperties);
458         }
459     }
460
461     private void updateActionState(NhcAction2 action, List<NhcProperty> deviceProperties) {
462         if (action.getType() == ActionType.ROLLERSHUTTER) {
463             updateRollershutterState(action, deviceProperties);
464         } else {
465             updateLightState(action, deviceProperties);
466         }
467     }
468
469     private void updateLightState(NhcAction2 action, List<NhcProperty> deviceProperties) {
470         Optional<NhcProperty> statusProperty = deviceProperties.stream().filter(p -> (p.status != null)).findFirst();
471         Optional<NhcProperty> dimmerProperty = deviceProperties.stream().filter(p -> (p.brightness != null))
472                 .findFirst();
473         Optional<NhcProperty> basicStateProperty = deviceProperties.stream().filter(p -> (p.basicState != null))
474                 .findFirst();
475
476         String booleanState = null;
477         if (statusProperty.isPresent()) {
478             booleanState = statusProperty.get().status;
479         } else if (basicStateProperty.isPresent()) {
480             booleanState = basicStateProperty.get().basicState;
481         }
482
483         if (NHCOFF.equals(booleanState)) {
484             action.setBooleanState(false);
485             logger.debug("setting action {} internally to OFF", action.getId());
486         }
487
488         if (dimmerProperty.isPresent()) {
489             String brightness = dimmerProperty.get().brightness;
490             if (brightness != null) {
491                 try {
492                     action.setState(Integer.parseInt(brightness));
493                     logger.debug("setting action {} internally to {}", action.getId(), dimmerProperty.get().brightness);
494                 } catch (NumberFormatException e) {
495                     logger.debug("received invalid brightness value {} for dimmer {}", brightness, action.getId());
496                 }
497             }
498         }
499
500         if (NHCON.equals(booleanState)) {
501             action.setBooleanState(true);
502             logger.debug("setting action {} internally to ON", action.getId());
503         }
504     }
505
506     private void updateRollershutterState(NhcAction2 action, List<NhcProperty> deviceProperties) {
507         deviceProperties.stream().map(p -> p.position).filter(Objects::nonNull).findFirst().ifPresent(position -> {
508             try {
509                 action.setState(Integer.parseInt(position));
510                 logger.debug("setting action {} internally to {}", action.getId(), position);
511             } catch (NumberFormatException e) {
512                 logger.trace("received empty or invalid rollershutter {} position info {}", action.getId(), position);
513             }
514         });
515     }
516
517     private void updateThermostatState(NhcThermostat2 thermostat, List<NhcProperty> deviceProperties) {
518         Optional<Boolean> overruleActiveProperty = deviceProperties.stream().map(p -> p.overruleActive)
519                 .filter(Objects::nonNull).map(t -> Boolean.parseBoolean(t)).findFirst();
520         Optional<Integer> overruleSetpointProperty = deviceProperties.stream().map(p -> p.overruleSetpoint)
521                 .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s) * 10) : null)
522                 .filter(Objects::nonNull).findFirst();
523         Optional<Integer> overruleTimeProperty = deviceProperties.stream().map(p -> p.overruleTime)
524                 .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s)) : null)
525                 .filter(Objects::nonNull).findFirst();
526         Optional<Integer> setpointTemperatureProperty = deviceProperties.stream().map(p -> p.setpointTemperature)
527                 .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s) * 10) : null)
528                 .filter(Objects::nonNull).findFirst();
529         Optional<Boolean> ecoSaveProperty = deviceProperties.stream().map(p -> p.ecoSave)
530                 .map(s -> s != null ? Boolean.parseBoolean(s) : null).filter(Objects::nonNull).findFirst();
531         Optional<Integer> ambientTemperatureProperty = deviceProperties.stream().map(p -> p.ambientTemperature)
532                 .map(s -> (!((s == null) || s.isEmpty())) ? Math.round(Float.parseFloat(s) * 10) : null)
533                 .filter(Objects::nonNull).findFirst();
534         Optional<@Nullable String> demandProperty = deviceProperties.stream().map(p -> p.demand)
535                 .filter(Objects::nonNull).findFirst();
536         Optional<@Nullable String> operationModeProperty = deviceProperties.stream().map(p -> p.operationMode)
537                 .filter(Objects::nonNull).findFirst();
538
539         String modeString = deviceProperties.stream().map(p -> p.program).filter(Objects::nonNull).findFirst()
540                 .orElse("");
541         int mode = IntStream.range(0, THERMOSTATMODES.length).filter(i -> THERMOSTATMODES[i].equals(modeString))
542                 .findFirst().orElse(thermostat.getMode());
543
544         int measured = ambientTemperatureProperty.orElse(thermostat.getMeasured());
545         int setpoint = setpointTemperatureProperty.orElse(thermostat.getSetpoint());
546
547         int overrule = thermostat.getOverrule();
548         int overruletime = thermostat.getRemainingOverruletime();
549         if (overruleActiveProperty.orElse(false)) {
550             overrule = overruleSetpointProperty.orElse(0);
551             overruletime = overruleTimeProperty.orElse(0);
552         }
553
554         int ecosave = thermostat.getEcosave();
555         if (ecoSaveProperty.orElse(false)) {
556             ecosave = 1;
557         }
558
559         int demand = thermostat.getDemand();
560         String demandString = demandProperty.orElse(operationModeProperty.orElse(""));
561         demandString = demandString == null ? "" : demandString;
562         switch (demandString) {
563             case "None":
564                 demand = 0;
565                 break;
566             case "Heating":
567                 demand = 1;
568                 break;
569             case "Cooling":
570                 demand = -1;
571                 break;
572         }
573
574         logger.debug(
575                 "Niko Home Control: setting thermostat {} with measured {}, setpoint {}, mode {}, overrule {}, overruletime {}, ecosave {}, demand {}",
576                 thermostat.getId(), measured, setpoint, mode, overrule, overruletime, ecosave, demand);
577         thermostat.updateState(measured, setpoint, mode, overrule, overruletime, ecosave, demand);
578     }
579
580     private void updateEnergyMeterState(NhcEnergyMeter2 energyMeter, List<NhcProperty> deviceProperties) {
581         deviceProperties.stream().map(p -> p.electricalPower).filter(Objects::nonNull).findFirst()
582                 .ifPresent(electricalPower -> {
583                     try {
584                         // Sometimes API sends a fractional part, although API should only send whole units in W,
585                         // therefore drop fractional part
586                         energyMeter.setPower((int) Double.parseDouble(electricalPower));
587                         logger.trace("setting energy meter {} power to {}", energyMeter.getId(), electricalPower);
588                     } catch (NumberFormatException e) {
589                         energyMeter.setPower(null);
590                         logger.trace("received empty energy meter {} power reading", energyMeter.getId());
591                     }
592                 });
593     }
594
595     @Override
596     public void executeAction(String actionId, String value) {
597         NhcMessage2 message = new NhcMessage2();
598
599         message.method = "devices.control";
600         ArrayList<NhcMessageParam> params = new ArrayList<>();
601         NhcMessageParam param = new NhcMessageParam();
602         params.add(param);
603         message.params = params;
604         ArrayList<NhcDevice2> devices = new ArrayList<>();
605         NhcDevice2 device = new NhcDevice2();
606         devices.add(device);
607         param.devices = devices;
608         device.uuid = actionId;
609         ArrayList<NhcProperty> deviceProperties = new ArrayList<>();
610         NhcProperty property = new NhcProperty();
611         deviceProperties.add(property);
612         device.properties = deviceProperties;
613
614         NhcAction2 action = (NhcAction2) actions.get(actionId);
615         if (action == null) {
616             return;
617         }
618
619         switch (action.getType()) {
620             case GENERIC:
621             case TRIGGER:
622                 if (!NHCON.equals(value)) {
623                     // Only trigger for ON
624                     return;
625                 }
626                 property.basicState = NHCTRIGGERED;
627                 break;
628             case RELAY:
629                 property.status = value;
630                 break;
631             case DIMMER:
632                 if (NHCON.equals(value)) {
633                     action.setBooleanState(true); // this will trigger sending the stored brightness value event out
634                     property.status = value;
635                 } else if (NHCOFF.equals(value)) {
636                     property.status = value;
637                 } else {
638                     try {
639                         action.setState(Integer.parseInt(value)); // set cached state to new brightness value to avoid
640                                                                   // switching on with old brightness value before
641                                                                   // updating
642                                                                   // to new value
643                     } catch (NumberFormatException e) {
644                         logger.debug("internal error, trying to set invalid brightness value {} for dimmer {}", value,
645                                 action.getId());
646                         return;
647                     }
648
649                     // If the light is off, turn the light on before sending the brightness value, needs to happen
650                     // in 2 separate messages.
651                     if (!action.booleanState()) {
652                         executeAction(actionId, NHCON);
653                     }
654                     property.brightness = value;
655                 }
656                 break;
657             case ROLLERSHUTTER:
658                 if (NHCSTOP.equals(value)) {
659                     property.action = value;
660                 } else if (NHCUP.equals(value)) {
661                     property.position = "100";
662                 } else if (NHCDOWN.equals(value)) {
663                     property.position = "0";
664                 } else {
665                     property.position = value;
666                 }
667                 break;
668         }
669
670         String topic = profile + "/control/devices/cmd";
671         String gsonMessage = gson.toJson(message);
672         sendDeviceMessage(topic, gsonMessage);
673     }
674
675     @Override
676     public void executeThermostat(String thermostatId, String mode) {
677         NhcMessage2 message = new NhcMessage2();
678
679         message.method = "devices.control";
680         ArrayList<NhcMessageParam> params = new ArrayList<>();
681         NhcMessageParam param = new NhcMessageParam();
682         params.add(param);
683         message.params = params;
684         ArrayList<NhcDevice2> devices = new ArrayList<>();
685         NhcDevice2 device = new NhcDevice2();
686         devices.add(device);
687         param.devices = devices;
688         device.uuid = thermostatId;
689         ArrayList<NhcProperty> deviceProperties = new ArrayList<>();
690
691         NhcProperty overruleActiveProp = new NhcProperty();
692         deviceProperties.add(overruleActiveProp);
693         overruleActiveProp.overruleActive = "False";
694
695         NhcProperty program = new NhcProperty();
696         deviceProperties.add(program);
697         program.program = mode;
698
699         device.properties = deviceProperties;
700
701         String topic = profile + "/control/devices/cmd";
702         String gsonMessage = gson.toJson(message);
703         sendDeviceMessage(topic, gsonMessage);
704     }
705
706     @Override
707     public void executeThermostat(String thermostatId, int overruleTemp, int overruleTime) {
708         NhcMessage2 message = new NhcMessage2();
709
710         message.method = "devices.control";
711         ArrayList<NhcMessageParam> params = new ArrayList<>();
712         NhcMessageParam param = new NhcMessageParam();
713         params.add(param);
714         message.params = params;
715         ArrayList<NhcDevice2> devices = new ArrayList<>();
716         NhcDevice2 device = new NhcDevice2();
717         devices.add(device);
718         param.devices = devices;
719         device.uuid = thermostatId;
720         ArrayList<NhcProperty> deviceProperties = new ArrayList<>();
721
722         if (overruleTime > 0) {
723             NhcProperty overruleActiveProp = new NhcProperty();
724             overruleActiveProp.overruleActive = "True";
725             deviceProperties.add(overruleActiveProp);
726
727             NhcProperty overruleSetpointProp = new NhcProperty();
728             overruleSetpointProp.overruleSetpoint = String.valueOf(overruleTemp / 10.0);
729             deviceProperties.add(overruleSetpointProp);
730
731             NhcProperty overruleTimeProp = new NhcProperty();
732             overruleTimeProp.overruleTime = String.valueOf(overruleTime);
733             deviceProperties.add(overruleTimeProp);
734         } else {
735             NhcProperty overruleActiveProp = new NhcProperty();
736             overruleActiveProp.overruleActive = "False";
737             deviceProperties.add(overruleActiveProp);
738         }
739         device.properties = deviceProperties;
740
741         String topic = profile + "/control/devices/cmd";
742         String gsonMessage = gson.toJson(message);
743         sendDeviceMessage(topic, gsonMessage);
744     }
745
746     @Override
747     public void startEnergyMeter(String energyMeterId) {
748         NhcMessage2 message = new NhcMessage2();
749
750         message.method = "devices.control";
751         ArrayList<NhcMessageParam> params = new ArrayList<>();
752         NhcMessageParam param = new NhcMessageParam();
753         params.add(param);
754         message.params = params;
755         ArrayList<NhcDevice2> devices = new ArrayList<>();
756         NhcDevice2 device = new NhcDevice2();
757         devices.add(device);
758         param.devices = devices;
759         device.uuid = energyMeterId;
760         ArrayList<NhcProperty> deviceProperties = new ArrayList<>();
761
762         NhcProperty reportInstantUsageProp = new NhcProperty();
763         deviceProperties.add(reportInstantUsageProp);
764         reportInstantUsageProp.reportInstantUsage = "True";
765         device.properties = deviceProperties;
766
767         String topic = profile + "/control/devices/cmd";
768         String gsonMessage = gson.toJson(message);
769
770         NhcEnergyMeter2 energyMeter = (NhcEnergyMeter2) energyMeters.get(energyMeterId);
771         if (energyMeter != null) {
772             energyMeter.startEnergyMeter(topic, gsonMessage);
773         }
774     }
775
776     @Override
777     public void stopEnergyMeter(String energyMeterId) {
778         NhcEnergyMeter2 energyMeter = (NhcEnergyMeter2) energyMeters.get(energyMeterId);
779         if (energyMeter != null) {
780             energyMeter.stopEnergyMeter();
781         }
782     }
783
784     /**
785      * Method called from the {@link NhcEnergyMeter2} object to send message to Niko Home Control.
786      *
787      * @param topic
788      * @param gsonMessage
789      */
790     public void executeEnergyMeter(String topic, String gsonMessage) {
791         sendDeviceMessage(topic, gsonMessage);
792     }
793
794     private void sendDeviceMessage(String topic, String gsonMessage) {
795         try {
796             mqttConnection.connectionPublish(topic, gsonMessage);
797
798         } catch (MqttException e) {
799             String message = e.getLocalizedMessage();
800
801             logger.debug("sending command failed, trying to restart communication");
802             restartCommunication();
803             // retry sending after restart
804             try {
805                 if (communicationActive()) {
806                     mqttConnection.connectionPublish(topic, gsonMessage);
807                 } else {
808                     logger.debug("failed to restart communication");
809                 }
810             } catch (MqttException e1) {
811                 message = e1.getLocalizedMessage();
812
813                 logger.debug("error resending device command");
814             }
815             if (!communicationActive()) {
816                 message = (message != null) ? message : "@text/offline.communication-error";
817                 connectionLost(message);
818             }
819         }
820     }
821
822     @Override
823     public void processMessage(String topic, byte[] payload) {
824         String message = new String(payload);
825         if ((profile + "/system/evt").equals(topic)) {
826             systemEvt(message);
827         } else if ((profile + "/system/rsp").equals(topic)) {
828             logger.debug("received topic {}, payload {}", topic, message);
829             systeminfoPublishRsp(message);
830         } else if ((profile + "/notification/evt").equals(topic)) {
831             logger.debug("received topic {}, payload {}", topic, message);
832             notificationEvt(message);
833         } else if ((profile + "/control/devices/evt").equals(topic)) {
834             logger.trace("received topic {}, payload {}", topic, message);
835             devicesEvt(message);
836         } else if ((profile + "/control/devices/rsp").equals(topic)) {
837             logger.debug("received topic {}, payload {}", topic, message);
838             devicesListRsp(message);
839         } else if ((profile + "/authentication/rsp").equals(topic)) {
840             logger.debug("received topic {}, payload {}", topic, message);
841             servicesListRsp(message);
842         } else if ((profile + "/control/devices.error").equals(topic)) {
843             logger.warn("received error {}", message);
844         } else {
845             logger.trace("not acted on received message topic {}, payload {}", topic, message);
846         }
847     }
848
849     /**
850      * @return system info retrieved from Connected Controller
851      */
852     public NhcSystemInfo2 getSystemInfo() {
853         NhcSystemInfo2 systemInfo = nhcSystemInfo;
854         if (systemInfo == null) {
855             systemInfo = new NhcSystemInfo2();
856         }
857         return systemInfo;
858     }
859
860     /**
861      * @return time info retrieved from Connected Controller
862      */
863     public NhcTimeInfo2 getTimeInfo() {
864         NhcTimeInfo2 timeInfo = nhcTimeInfo;
865         if (timeInfo == null) {
866             timeInfo = new NhcTimeInfo2();
867         }
868         return timeInfo;
869     }
870
871     /**
872      * @return comma separated list of services retrieved from Connected Controller
873      */
874     public String getServices() {
875         return services.stream().map(NhcService2::name).collect(Collectors.joining(", "));
876     }
877
878     @Override
879     public void connectionStateChanged(MqttConnectionState state, @Nullable Throwable error) {
880         if (error != null) {
881             logger.debug("Connection state: {}", state, error);
882             String message = error.getLocalizedMessage();
883             message = (message != null) ? message : "@text/offline.communication-error";
884             if (!MqttConnectionState.CONNECTING.equals(state)) {
885                 // This is a connection loss, try to restart
886                 restartCommunication();
887             }
888             if (!communicationActive()) {
889                 connectionLost(message);
890             }
891         } else {
892             logger.trace("Connection state: {}", state);
893         }
894     }
895 }