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.konnected.internal.handler;
15 import static org.openhab.binding.konnected.internal.KonnectedBindingConstants.*;
17 import java.math.BigDecimal;
19 import java.util.Map.Entry;
20 import java.util.concurrent.TimeUnit;
22 import org.openhab.binding.konnected.internal.KonnectedConfiguration;
23 import org.openhab.binding.konnected.internal.KonnectedHTTPUtils;
24 import org.openhab.binding.konnected.internal.KonnectedHttpRetryExceeded;
25 import org.openhab.binding.konnected.internal.gson.KonnectedModuleGson;
26 import org.openhab.binding.konnected.internal.gson.KonnectedModulePayload;
27 import org.openhab.core.config.core.Configuration;
28 import org.openhab.core.config.core.validation.ConfigValidationException;
29 import org.openhab.core.library.types.OnOffType;
30 import org.openhab.core.library.types.QuantityType;
31 import org.openhab.core.library.unit.SIUnits;
32 import org.openhab.core.library.unit.Units;
33 import org.openhab.core.thing.Channel;
34 import org.openhab.core.thing.ChannelUID;
35 import org.openhab.core.thing.Thing;
36 import org.openhab.core.thing.ThingStatus;
37 import org.openhab.core.thing.ThingStatusDetail;
38 import org.openhab.core.thing.binding.BaseThingHandler;
39 import org.openhab.core.types.Command;
40 import org.openhab.core.types.RefreshType;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
44 import com.google.gson.Gson;
45 import com.google.gson.GsonBuilder;
48 * The {@link KonnectedHandler} is responsible for handling commands, which are
49 * sent to one of the channels.
51 * @author Zachary Christiansen - Initial contribution
53 public class KonnectedHandler extends BaseThingHandler {
54 private final Logger logger = LoggerFactory.getLogger(KonnectedHandler.class);
55 private KonnectedConfiguration config;
56 private final String konnectedServletPath;
57 private final KonnectedHTTPUtils http = new KonnectedHTTPUtils(30);
58 private String callbackIpAddress = null;
59 private String moduleIpAddress;
60 private final Gson gson = new GsonBuilder().create();
61 private int retryCount;
62 private final String thingID;
63 public String authToken;
66 * This is the constructor of the Konnected Handler.
68 * @param thing the instance of the Konnected thing
69 * @param webHookServlet the instance of the callback servlet that is running for communication with the Konnected
71 * @param hostAddress the webaddress of the openHAB server instance obtained by the runtime
72 * @param port the port on which the openHAB instance is running that was obtained by the runtime.
74 public KonnectedHandler(Thing thing, String path, String hostAddress, String port) {
76 this.konnectedServletPath = path;
77 callbackIpAddress = hostAddress + ":" + port;
78 logger.debug("The callback ip address is: {}", callbackIpAddress);
80 thingID = getThing().getThingTypeUID().getId();
81 authToken = getThing().getUID().getAsString();
85 public void handleCommand(ChannelUID channelUID, Command command) {
86 // get the zone number in integer form
87 Channel channel = this.getThing().getChannel(channelUID.getId());
88 String channelType = channel.getChannelTypeUID().getAsString();
89 String zone = (String) channel.getConfiguration().get(CHANNEL_ZONE);
90 logger.debug("The channelUID is: {} and the zone is : {}", channelUID.getAsString(), zone);
91 // if the command is OnOfftype
92 if (command instanceof OnOffType) {
93 if (channelType.contains(CHANNEL_SWITCH)) {
94 logger.debug("A command was sent to a sensor type so we are ignoring the command");
96 int sendCommand = (OnOffType.OFF.compareTo((OnOffType) command));
97 logger.debug("The command being sent to zone {} for channel:{} is {}", zone, channelUID.getAsString(),
99 sendActuatorCommand(Integer.toString(sendCommand), zone, channelUID);
101 } else if (command instanceof RefreshType) {
102 // check to see if handler has been initialized before attempting to get state of pin, else wait one minute
103 if (this.isInitialized()) {
104 getSwitchState(zone, channelUID);
106 scheduler.schedule(() -> {
107 handleCommand(channelUID, command);
108 }, 1, TimeUnit.MINUTES);
114 * Process a {@link WebHookEvent} that has been received by the Servlet from a Konnected module with respect to a
115 * sensor event or status update request
117 * @param event the {@link KonnectedModuleGson} event that contains the state and pin information to be processed
119 public void handleWebHookEvent(KonnectedModuleGson event) {
120 // if we receive a command update the thing status to being online
121 updateStatus(ThingStatus.ONLINE);
122 // get the zone number based off of the index location of the pin value
123 // String sentZone = Integer.toString(Arrays.asList(PIN_TO_ZONE).indexOf(event.getPin()));
124 String zone = event.getZone(thingID);
125 // check that the zone number is in one of the channelUID definitions
126 logger.debug("Looping Through all channels on thing: {} to find a match for {}", thing.getUID().getAsString(),
128 getThing().getChannels().forEach(channel -> {
129 ChannelUID channelId = channel.getUID();
130 String zoneNumber = (String) channel.getConfiguration().get(CHANNEL_ZONE);
131 // if the string zone that was sent equals the last digit of the channelId found process it as the
132 // channelId else do nothing
133 if (zone.equalsIgnoreCase(zoneNumber)) {
135 "The configrued zone of channelID: {} was a match for the zone sent by the alarm panel: {} on thing: {}",
136 channelId, zone, this.getThing().getUID().getId());
137 String channelType = channel.getChannelTypeUID().getAsString();
138 logger.debug("The channeltypeID is: {}", channelType);
139 // check if the itemType has been defined for the zone received
140 // check the itemType of the Zone, if Contact, send the State if Temp send Temp, etc.
141 if (channelType.contains(CHANNEL_SWITCH) || channelType.contains(CHANNEL_ACTUATOR)) {
142 OnOffType onOffType = event.getState().equalsIgnoreCase(getOnState(channel)) ? OnOffType.ON
144 updateState(channelId, onOffType);
145 } else if (channelType.contains(CHANNEL_HUMIDITY)) {
146 // if the state is of type number then this means it is the humidity channel of the dht22
147 updateState(channelId, new QuantityType<>(Double.parseDouble(event.getHumi()), Units.PERCENT));
148 } else if (channelType.contains(CHANNEL_TEMPERATURE)) {
149 Configuration configuration = channel.getConfiguration();
150 if (((Boolean) configuration.get(CHANNEL_TEMPERATURE_TYPE))) {
151 updateState(channelId,
152 new QuantityType<>(Double.parseDouble(event.getTemp()), SIUnits.CELSIUS));
154 // need to check to make sure right dsb1820 address
155 logger.debug("The address of the DSB1820 sensor received from modeule {} is: {}",
156 this.thing.getUID(), event.getAddr());
158 .equalsIgnoreCase((String) (configuration.get(CHANNEL_TEMPERATURE_DS18B20_ADDRESS)))) {
159 updateState(channelId,
160 new QuantityType<>(Double.parseDouble(event.getTemp()), SIUnits.CELSIUS));
162 logger.debug("The address of {} does not match {} not updating this channel",
163 event.getAddr(), (configuration.get(CHANNEL_TEMPERATURE_DS18B20_ADDRESS)));
169 "The zone number sent by the alarm panel: {} was not a match the configured zone for channelId: {} for thing {}",
170 zone, channelId, getThing().getThingTypeUID().toString());
175 private void checkConfiguration() throws ConfigValidationException {
176 logger.debug("Checking configuration on thing {}", this.getThing().getUID().getAsString());
177 Configuration testConfig = this.getConfig();
178 String testRetryCount = testConfig.get(RETRY_COUNT).toString();
179 String testRequestTimeout = testConfig.get(REQUEST_TIMEOUT).toString();
180 logger.debug("The RequestTimeout Parameter is Configured as: {}", testRequestTimeout);
181 logger.debug("The Retry Count Parameter is Configured as: {}", testRetryCount);
183 this.retryCount = Integer.parseInt(testRetryCount);
184 } catch (NumberFormatException e) {
186 "Please check your configuration of the Retry Count as it is not an Integer. It is configured as: {}, will contintue to configure the binding with the default of 2",
191 this.http.setRequestTimeout(Integer.parseInt(testRequestTimeout));
192 } catch (NumberFormatException e) {
194 "Please check your configuration of the Request Timeout as it is not an Integer. It is configured as: {}, will contintue to configure the binding with the default of 30",
198 if ((callbackIpAddress == null)) {
199 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
200 "Unable to obtain hostaddress from OSGI service, please configure hostaddress");
204 this.config = getConfigAs(KonnectedConfiguration.class);
209 public void handleConfigurationUpdate(Map<String, Object> configurationParameters)
210 throws ConfigValidationException {
211 this.validateConfigurationParameters(configurationParameters);
212 for (Entry<String, Object> configurationParameter : configurationParameters.entrySet()) {
213 Object value = configurationParameter.getValue();
214 logger.debug("Controller Configuration update {} to {}", configurationParameter.getKey(), value);
219 // this is a nonstandard implementation to to address the configuration of the konnected alarm panel (as
220 // opposed to the handler) until
221 // https://github.com/eclipse/smarthome/issues/3484 has been implemented in the framework
222 String[] cfg = configurationParameter.getKey().split("_");
223 if ("controller".equals(cfg[0])) {
224 if (cfg[1].equals("softreset") && value instanceof Boolean && (Boolean) value) {
225 scheduler.execute(() -> {
227 http.doGet(moduleIpAddress + "/settings?restart=true", null, retryCount);
228 } catch (KonnectedHttpRetryExceeded e) {
229 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
233 } else if (cfg[1].equals("removewifi") && value instanceof Boolean && (Boolean) value) {
234 scheduler.execute(() -> {
236 http.doGet(moduleIpAddress + "/settings?restore=true", null, retryCount);
237 } catch (KonnectedHttpRetryExceeded e) {
238 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
242 } else if (cfg[1].equals("sendConfig") && value instanceof Boolean && (Boolean) value) {
243 scheduler.execute(() -> {
245 String response = updateKonnectedModule();
246 logger.trace("The response from the konnected module with thingID {} was {}",
247 getThing().getUID().toString(), response);
248 if (response == null) {
249 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
250 "Unable to communicate with Konnected Module.");
252 updateStatus(ThingStatus.ONLINE);
254 } catch (KonnectedHttpRetryExceeded e) {
255 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
263 super.handleConfigurationUpdate(configurationParameters);
267 String response = updateKonnectedModule();
268 logger.trace("The response from the konnected module with thingID {} was {}",
269 getThing().getUID().toString(), response);
270 if (response == null) {
271 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
272 "Unable to communicate with Konnected Module confirm settings.");
274 updateStatus(ThingStatus.ONLINE);
276 } catch (KonnectedHttpRetryExceeded e) {
277 logger.trace("The number of retries was exceeeded during the HandleConfigurationUpdate(): {}",
279 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
284 public void initialize() {
285 updateStatus(ThingStatus.UNKNOWN);
287 checkConfiguration();
288 } catch (ConfigValidationException e) {
289 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
291 this.moduleIpAddress = this.getThing().getProperties().get(HOST).toString();
292 scheduler.execute(() -> {
294 String response = updateKonnectedModule();
295 if (response == null) {
296 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
297 "Unable to communicate with Konnected Module confirm settings or readd thing.");
299 updateStatus(ThingStatus.ONLINE);
301 } catch (KonnectedHttpRetryExceeded e) {
302 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
308 public void dispose() {
309 logger.debug("Running dispose()");
314 * This method constructs the payload that will be sent
315 * to the Konnected module via the put request
316 * it adds the appropriate sensors and actuators to the {@link KonnectedModulePayload}
317 * as well as the location of the callback {@link KonnectedJTTPServlet}
318 * and auth_token which can be used for validation
320 * @return a json settings payload which can be sent to the Konnected Module based on the Thing
322 private String constructSettingsPayload() {
323 String apiUrl = (String) getThing().getConfiguration().get(CALLBACK_URI);
324 if (apiUrl == null) {
325 apiUrl = "http://" + callbackIpAddress + this.konnectedServletPath;
328 logger.debug("The Auth_Token is: {}", authToken);
329 KonnectedModulePayload payload = new KonnectedModulePayload(authToken, apiUrl);
330 payload.setBlink(config.blink);
331 payload.setDiscovery(config.discovery);
332 this.getThing().getChannels().forEach(channel -> {
333 // ChannelUID channelId = channel.getUID();
334 if (isLinked(channel.getUID())) {
335 // adds linked channels to list based on last value of Channel ID
336 // which is set to a number
337 // get the zone number in integer form
338 String zone = (String) channel.getConfiguration().get(CHANNEL_ZONE);
339 // if the pin is an actuator add to actuator string
340 // else add to sensor string
341 // This is determined based off of the accepted item type, contact types are sensors
342 // switch types are actuators
343 String channelType = channel.getChannelTypeUID().getAsString();
344 logger.debug("The channeltypeID is: {}", channelType);
345 KonnectedModuleGson module = new KonnectedModuleGson();
346 module.setZone(thingID, zone);
347 if (channelType.contains(CHANNEL_SWITCH)) {
348 payload.addSensor(module);
349 logger.trace("Channel {} will be configured on the konnected alarm panel as a switch",
351 } else if (channelType.contains(CHANNEL_ACTUATOR)) {
352 payload.addActuators(module);
353 logger.trace("Channel {} will be configured on the konnected alarm panel as an actuator",
355 } else if (channelType.contains(CHANNEL_HUMIDITY)) {
356 // the humidity channels do not need to be added because the supported sensor (dht22) is added under
358 logger.trace("Channel {} is a humidity channel.", channel.toString());
359 } else if (channelType.contains(CHANNEL_TEMPERATURE)) {
360 logger.trace("Channel {} will be configured on the konnected alarm panel as a temperature sensor",
362 Configuration configuration = channel.getConfiguration();
363 if (configuration.get(CHANNEL_TEMPERATRUE_POLL) == null) {
364 module.setPollInterval(3);
366 module.setPollInterval(((BigDecimal) configuration.get(CHANNEL_TEMPERATRUE_POLL)).intValue());
368 logger.trace("The Temperature Sensor Type is: {} ",
369 configuration.get(CHANNEL_TEMPERATURE_TYPE).toString());
370 if ((boolean) configuration.get(CHANNEL_TEMPERATURE_TYPE)) {
371 // add it as a dht22 module
372 payload.addDht22(module);
374 "Channel {} will be configured on the konnected alarm panel as a DHT22 temperature sensor",
377 // add to payload as a DS18B20 module if the parameter is false
378 payload.addDs18b20(module);
380 "Channel {} will be configured on the konnected alarm panel as a DS18B20 temperature sensor",
384 logger.debug("Channel {} is of type {} which is not supported by the konnected binding",
385 channel.toString(), channelType);
388 logger.debug("The Channel {} is not linked to an item", channel.getUID());
391 // Create Json to Send to Konnected Module
393 String payloadString = gson.toJson(payload);
394 logger.debug("The payload is: {}", payloadString);
395 return payloadString;
399 * Prepares and sends the {@link KonnectedModulePayload} via the {@link KonnectedHttpUtils}
401 * @return response obtained from sending the settings payload to Konnected module defined by the thing
403 * @throws KonnectedHttpRetryExceeded if unable to communicate with the Konnected module defined by the Thing
405 private String updateKonnectedModule() throws KonnectedHttpRetryExceeded {
406 String payload = constructSettingsPayload();
407 String response = http.doPut(moduleIpAddress + "/settings", payload, retryCount);
408 logger.debug("The response of the put request was: {}", response);
413 * Sends a command to the module via {@link KonnectedHTTPUtils}
415 * @param scommand the string command, either 0 or 1 to send to the actutor pin on the Konnected module
416 * @param zone the zone to send the command to on the Konnected Module
418 private void sendActuatorCommand(String scommand, String zone, ChannelUID channelId) {
420 Channel channel = getThing().getChannel(channelId.getId());
421 if (!(channel == null)) {
422 logger.debug("getasstring: {} getID: {} getGroupId: {} toString:{}", channelId.getAsString(),
423 channelId.getId(), channelId.getGroupId(), channelId.toString());
424 Configuration configuration = channel.getConfiguration();
425 KonnectedModuleGson payload = new KonnectedModuleGson();
426 payload.setState(scommand);
428 payload.setZone(thingID, zone);
430 // check to see if this is an On Command type, if so add the momentary, pause, times to the payload if
431 // they exist on the configuration.
432 if (scommand.equals(getOnState(channel))) {
433 if (configuration.get(CHANNEL_ACTUATOR_TIMES) == null) {
435 "The times configuration was not set for channelID: {}, not adding it to the payload.",
436 channelId.toString());
438 payload.setTimes(configuration.get(CHANNEL_ACTUATOR_TIMES).toString());
439 logger.debug("The times configuration was set to: {} for channelID: {}.",
440 configuration.get(CHANNEL_ACTUATOR_TIMES).toString(), channelId.toString());
442 if (configuration.get(CHANNEL_ACTUATOR_MOMENTARY) == null) {
444 "The momentary configuration was not set for channelID: {}, not adding it to the payload.",
445 channelId.toString());
447 payload.setMomentary(configuration.get(CHANNEL_ACTUATOR_MOMENTARY).toString());
448 logger.debug("The momentary configuration set to: {} channelID: {}.",
449 configuration.get(CHANNEL_ACTUATOR_MOMENTARY).toString(), channelId.toString());
451 if (configuration.get(CHANNEL_ACTUATOR_PAUSE) == null) {
453 "The pause configuration was not set for channelID: {}, not adding it to the payload.",
454 channelId.toString());
456 payload.setPause(configuration.get(CHANNEL_ACTUATOR_PAUSE).toString());
457 logger.debug("The pause configuration was set to: {} for channelID: {}.",
458 configuration.get(CHANNEL_ACTUATOR_PAUSE).toString(), channelId.toString());
461 String payloadString = gson.toJson(payload);
462 logger.debug("The command payload is: {}", payloadString);
464 switch (this.thingID) {
472 http.doPut(moduleIpAddress + path, payloadString, retryCount);
474 logger.debug("The channel {} returned null for channelId.getID(): {}", channelId.toString(),
477 } catch (KonnectedHttpRetryExceeded e) {
478 logger.debug("Attempting to set the state of the actuator on thing {} failed: {}",
479 this.thing.getUID().getId(), e.getMessage());
480 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
481 "Unable to communicate with Konnected Alarm Panel confirm settings, and that module is online.");
485 private void getSwitchState(String zone, ChannelUID channelId) {
486 Channel channel = getThing().getChannel(channelId.getId());
487 if (!(channel == null)) {
488 logger.debug("getasstring: {} getID: {} getGroupId: {} toString:{}", channelId.getAsString(),
489 channelId.getId(), channelId.getGroupId(), channelId.toString());
490 KonnectedModuleGson payload = new KonnectedModuleGson();
491 payload.setZone(thingID, zone);
492 String payloadString = gson.toJson(payload);
493 logger.debug("The command payload is: {}", payloadString);
495 sendSetSwitchState(thingID, payloadString);
496 } catch (KonnectedHttpRetryExceeded e) {
497 // try to get the state of the device one more time 30 seconds later. This way it can be confirmed if
498 // the device was simply in a reboot loop when device state was attempted the first time
499 scheduler.schedule(() -> {
501 sendSetSwitchState(thingID, payloadString);
502 } catch (KonnectedHttpRetryExceeded ex) {
503 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
504 "Unable to communicate with Konnected Alarm Panel confirm settings, and that module is online.");
505 logger.debug("Attempting to get the state of the zone on thing {} failed for channel: {} : {}",
506 this.thing.getUID().getId(), channelId.getAsString(), ex.getMessage());
508 }, 2, TimeUnit.MINUTES);
511 logger.debug("The channel {} returned null for channelId.getID(): {}", channelId.toString(),
516 private void sendSetSwitchState(String thingId, String payloadString) throws KonnectedHttpRetryExceeded {
517 String path = thingId.equals(WIFI_MODULE) ? "/device" : "/zone";
518 String response = http.doGet(moduleIpAddress + path, payloadString, retryCount);
519 KonnectedModuleGson[] events = gson.fromJson(response, KonnectedModuleGson[].class);
520 for (KonnectedModuleGson event : events) {
521 this.handleWebHookEvent(event);
525 private String getOnState(Channel channel) {
526 String config = (String) channel.getConfiguration().get(CHANNEL_ONVALUE);
527 if (config == null) {