2 * Copyright (c) 2010-2023 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.*;
18 import java.util.Map.Entry;
19 import java.util.concurrent.TimeUnit;
21 import org.openhab.binding.konnected.internal.KonnectedConfiguration;
22 import org.openhab.binding.konnected.internal.KonnectedHTTPUtils;
23 import org.openhab.binding.konnected.internal.KonnectedHttpRetryExceeded;
24 import org.openhab.binding.konnected.internal.ZoneConfiguration;
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 KonnectedHTTPUtils http = new KonnectedHTTPUtils(30);
57 private String callbackUrl;
58 private String baseUrl;
59 private final Gson gson = new GsonBuilder().create();
60 private int retryCount;
61 private final String thingID;
62 public String authToken;
65 * This is the constructor of the Konnected Handler.
67 * @param thing the instance of the Konnected thing
68 * @param webHookServlet the instance of the callback servlet that is running for communication with the Konnected
70 * @param hostAddress the webaddress of the openHAB server instance obtained by the runtime
71 * @param port the port on which the openHAB instance is running that was obtained by the runtime.
73 public KonnectedHandler(Thing thing, String callbackUrl) {
75 this.callbackUrl = callbackUrl;
76 logger.debug("The auto discovered callback URL is: {}", this.callbackUrl);
78 thingID = getThing().getThingTypeUID().getId();
79 authToken = getThing().getUID().getAsString();
83 public void handleCommand(ChannelUID channelUID, Command command) {
84 // get the zone number in integer form
85 Channel channel = this.getThing().getChannel(channelUID.getId());
86 String channelType = channel.getChannelTypeUID().getAsString();
87 ZoneConfiguration zoneConfig = channel.getConfiguration().as(ZoneConfiguration.class);
88 String zone = zoneConfig.zone;
89 logger.debug("The channelUID is: {} and the zone is : {}", channelUID.getAsString(), zone);
90 // if the command is OnOfftype
91 if (command instanceof OnOffType onOffCommand) {
92 if (channelType.contains(CHANNEL_SWITCH)) {
93 logger.debug("A command was sent to a sensor type so we are ignoring the command");
95 sendActuatorCommand(onOffCommand, zone, channelUID);
97 } else if (command instanceof RefreshType) {
98 // check to see if handler has been initialized before attempting to get state of pin, else wait one minute
99 if (this.isInitialized()) {
100 getSwitchState(zone, channelUID);
102 scheduler.schedule(() -> {
103 handleCommand(channelUID, command);
104 }, 1, TimeUnit.MINUTES);
110 * Process a {@link WebHookEvent} that has been received by the Servlet from a Konnected module with respect to a
111 * sensor event or status update request
113 * @param event the {@link KonnectedModuleGson} event that contains the state and pin information to be processed
115 public void handleWebHookEvent(KonnectedModuleGson event) {
116 // if we receive a command update the thing status to being online
117 updateStatus(ThingStatus.ONLINE);
118 // get the zone number based off of the index location of the pin value
119 // String sentZone = Integer.toString(Arrays.asList(PIN_TO_ZONE).indexOf(event.getPin()));
120 String zone = event.getZone(thingID);
121 // check that the zone number is in one of the channelUID definitions
122 logger.debug("Looping Through all channels on thing: {} to find a match for {}", thing.getUID().getAsString(),
124 getThing().getChannels().forEach(channel -> {
125 ChannelUID channelId = channel.getUID();
126 ZoneConfiguration zoneConfig = channel.getConfiguration().as(ZoneConfiguration.class);
127 // if the string zone that was sent equals the last digit of the channelId found process it as the
128 // channelId else do nothing
129 if (zone.equalsIgnoreCase(zoneConfig.zone)) {
131 "The configrued zone of channelID: {} was a match for the zone sent by the alarm panel: {} on thing: {}",
132 channelId, zone, this.getThing().getUID().getId());
133 String channelType = channel.getChannelTypeUID().getAsString();
134 logger.debug("The channeltypeID is: {}", channelType);
135 // check if the itemType has been defined for the zone received
136 // check the itemType of the Zone, if Contact, send the State if Temp send Temp, etc.
137 if (channelType.contains(CHANNEL_SWITCH) || channelType.contains(CHANNEL_ACTUATOR)) {
138 Integer state = event.getState();
139 logger.debug("The event state is: {}", state);
141 OnOffType onOffType = state == zoneConfig.onValue ? OnOffType.ON : OnOffType.OFF;
142 updateState(channelId, onOffType);
144 } else if (channelType.contains(CHANNEL_HUMIDITY)) {
145 // if the state is of type number then this means it is the humidity channel of the dht22
146 updateState(channelId, new QuantityType<>(Double.parseDouble(event.getHumi()), Units.PERCENT));
147 } else if (channelType.contains(CHANNEL_TEMPERATURE)) {
148 if (zoneConfig.dht22) {
149 updateState(channelId,
150 new QuantityType<>(Double.parseDouble(event.getTemp()), SIUnits.CELSIUS));
152 // need to check to make sure right dsb1820 address
153 logger.debug("The address of the DSB1820 sensor received from module {} is: {}",
154 this.thing.getUID(), event.getAddr());
156 if (event.getAddr().equalsIgnoreCase(zoneConfig.ds18b20Address)) {
157 updateState(channelId,
158 new QuantityType<>(Double.parseDouble(event.getTemp()), SIUnits.CELSIUS));
160 logger.debug("The address of {} does not match {} not updating this channel",
161 event.getAddr(), zoneConfig.ds18b20Address);
167 "The zone number sent by the alarm panel: {} was not a match the configured zone for channelId: {} for thing {}",
168 zone, channelId, getThing().getThingTypeUID());
173 private void checkConfiguration() throws ConfigValidationException {
174 logger.debug("Checking configuration on thing {}", this.getThing().getUID().getAsString());
175 Configuration testConfig = this.getConfig();
176 String testRetryCount = testConfig.get(RETRY_COUNT).toString();
177 String testRequestTimeout = testConfig.get(REQUEST_TIMEOUT).toString();
178 baseUrl = testConfig.get(BASE_URL).toString();
179 String configuredCallbackUrl = (String) getThing().getConfiguration().get(CALLBACK_URL);
180 if (configuredCallbackUrl != null) {
181 callbackUrl = configuredCallbackUrl;
183 getThing().getConfiguration().put(CALLBACK_URL, callbackUrl);
185 logger.debug("The RequestTimeout Parameter is Configured as: {}", testRequestTimeout);
186 logger.debug("The Retry Count Parameter is Configured as: {}", testRetryCount);
187 logger.debug("Base URL is Configured as: {}", baseUrl);
188 logger.debug("The callback URL is: {}", callbackUrl);
190 this.retryCount = Integer.parseInt(testRetryCount);
191 } catch (NumberFormatException e) {
193 "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",
198 this.http.setRequestTimeout(Integer.parseInt(testRequestTimeout));
199 } catch (NumberFormatException e) {
201 "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",
205 if ((callbackUrl == null)) {
206 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Unable to obtain callback URL");
210 this.config = getConfigAs(KonnectedConfiguration.class);
215 public void handleConfigurationUpdate(Map<String, Object> configurationParameters)
216 throws ConfigValidationException {
217 this.validateConfigurationParameters(configurationParameters);
218 for (Entry<String, Object> configurationParameter : configurationParameters.entrySet()) {
219 Object value = configurationParameter.getValue();
220 logger.debug("Controller Configuration update {} to {}", configurationParameter.getKey(), value);
225 // this is a nonstandard implementation to to address the configuration of the konnected alarm panel (as
226 // opposed to the handler) until
227 // https://github.com/eclipse/smarthome/issues/3484 has been implemented in the framework
228 String[] cfg = configurationParameter.getKey().split("_");
229 if ("controller".equals(cfg[0])) {
230 if ("softreset".equals(cfg[1]) && value instanceof Boolean bool && bool) {
231 scheduler.execute(() -> {
233 http.doGet(baseUrl + "/settings?restart=true", null, retryCount);
234 } catch (KonnectedHttpRetryExceeded e) {
235 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
238 } else if ("removewifi".equals(cfg[1]) && value instanceof Boolean bool && bool) {
239 scheduler.execute(() -> {
241 http.doGet(baseUrl + "/settings?restore=true", null, retryCount);
242 } catch (KonnectedHttpRetryExceeded e) {
243 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
246 } else if ("sendConfig".equals(cfg[1]) && value instanceof Boolean bool && bool) {
247 scheduler.execute(() -> {
249 String response = updateKonnectedModule();
250 logger.trace("The response from the konnected module with thingID {} was {}",
251 getThing().getUID(), response);
252 if (response == null) {
253 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
254 "Unable to communicate with Konnected Module.");
256 updateStatus(ThingStatus.ONLINE);
258 } catch (KonnectedHttpRetryExceeded e) {
259 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
266 super.handleConfigurationUpdate(configurationParameters);
270 String response = updateKonnectedModule();
271 logger.trace("The response from the konnected module with thingID {} was {}", getThing().getUID(),
273 if (response == null) {
274 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
275 "Unable to communicate with Konnected Module confirm settings.");
277 updateStatus(ThingStatus.ONLINE);
279 } catch (KonnectedHttpRetryExceeded e) {
280 logger.trace("The number of retries was exceeeded during the HandleConfigurationUpdate(): {}",
282 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
287 public void initialize() {
288 updateStatus(ThingStatus.UNKNOWN);
290 checkConfiguration();
291 } catch (ConfigValidationException e) {
292 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
294 scheduler.execute(() -> {
296 String response = updateKonnectedModule();
297 if (response == null) {
298 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
299 "Unable to communicate with Konnected Module confirm settings or readd thing.");
301 updateStatus(ThingStatus.ONLINE);
303 } catch (KonnectedHttpRetryExceeded e) {
304 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
310 public void dispose() {
311 logger.debug("Running dispose()");
316 * This method constructs the payload that will be sent
317 * to the Konnected module via the put request
318 * it adds the appropriate sensors and actuators to the {@link KonnectedModulePayload}
319 * as well as the location of the callback {@link KonnectedJTTPServlet}
320 * and auth_token which can be used for validation
322 * @return a json settings payload which can be sent to the Konnected Module based on the Thing
324 private String constructSettingsPayload() {
325 logger.debug("The Auth_Token is: {}", authToken);
326 KonnectedModulePayload payload = new KonnectedModulePayload(authToken, callbackUrl);
327 payload.setBlink(config.blink);
328 payload.setDiscovery(config.discovery);
329 this.getThing().getChannels().forEach(channel -> {
330 // ChannelUID channelId = channel.getUID();
331 // adds channels to list based on last value of Channel ID
332 // which is set to a number
333 // get the zone number in integer form
334 ZoneConfiguration zoneConfig = channel.getConfiguration().as(ZoneConfiguration.class);
335 // if the pin is an actuator add to actuator string
336 // else add to sensor string
337 // This is determined based off of the accepted item type, contact types are sensors
338 // switch types are actuators
339 String channelType = channel.getChannelTypeUID().getAsString();
340 logger.debug("The channeltypeID is: {}", channelType);
341 KonnectedModuleGson module = new KonnectedModuleGson();
342 module.setZone(thingID, zoneConfig.zone);
343 if (channelType.contains(CHANNEL_SWITCH)) {
344 payload.addSensor(module);
345 logger.trace("Channel {} will be configured on the konnected alarm panel as a switch", channel);
346 } else if (channelType.contains(CHANNEL_ACTUATOR)) {
347 payload.addActuators(module);
348 logger.trace("Channel {} will be configured on the konnected alarm panel as an actuator", channel);
349 } else if (channelType.contains(CHANNEL_HUMIDITY)) {
350 // the humidity channels do not need to be added because the supported sensor (dht22) is added under
352 logger.trace("Channel {} is a humidity channel.", channel);
353 } else if (channelType.contains(CHANNEL_TEMPERATURE)) {
354 logger.trace("Channel {} will be configured on the konnected alarm panel as a temperature sensor",
356 module.setPollInterval(zoneConfig.pollInterval);
357 logger.trace("The Temperature Sensor Type is: {} ", zoneConfig.dht22);
358 if (zoneConfig.dht22) {
359 // add it as a dht22 module
360 payload.addDht22(module);
362 "Channel {} will be configured on the konnected alarm panel as a DHT22 temperature sensor",
365 // add to payload as a DS18B20 module if the parameter is false
366 payload.addDs18b20(module);
368 "Channel {} will be configured on the konnected alarm panel as a DS18B20 temperature sensor",
372 logger.debug("Channel {} is of type {} which is not supported by the konnected binding", channel,
376 // Create Json to Send to Konnected Module
378 String payloadString = gson.toJson(payload);
379 logger.debug("The payload is: {}", payloadString);
380 return payloadString;
384 * Prepares and sends the {@link KonnectedModulePayload} via the {@link KonnectedHttpUtils}
386 * @return response obtained from sending the settings payload to Konnected module defined by the thing
388 * @throws KonnectedHttpRetryExceeded if unable to communicate with the Konnected module defined by the Thing
390 private String updateKonnectedModule() throws KonnectedHttpRetryExceeded {
391 String payload = constructSettingsPayload();
392 String response = http.doPut(baseUrl + "/settings", payload, retryCount);
393 logger.debug("The response of the put request was: {}", response);
398 * Sends a command to the module via {@link KonnectedHTTPUtils}
400 * @param command the state to send to the actuator
401 * @param zone the zone to send the command to on the Konnected Module
403 private void sendActuatorCommand(OnOffType command, String zone, ChannelUID channelId) {
405 Channel channel = getThing().getChannel(channelId.getId());
406 if (channel != null) {
407 logger.debug("getasstring: {} getID: {} getGroupId: {} toString:{}", channelId.getAsString(),
408 channelId.getId(), channelId.getGroupId(), channelId);
409 ZoneConfiguration zoneConfig = channel.getConfiguration().as(ZoneConfiguration.class);
410 KonnectedModuleGson payload = new KonnectedModuleGson();
411 payload.setZone(thingID, zone);
413 if (command == OnOffType.ON) {
414 payload.setState(zoneConfig.onValue);
415 payload.setTimes(zoneConfig.times);
416 payload.setMomentary(zoneConfig.momentary);
417 payload.setPause(zoneConfig.pause);
419 payload.setState(zoneConfig.onValue == 1 ? 0 : 1);
422 String payloadString = gson.toJson(payload);
423 logger.debug("The command payload is: {}", payloadString);
425 switch (this.thingID) {
433 http.doPut(baseUrl + path, payloadString, retryCount);
435 logger.debug("The channel {} returned null for channelId.getID(): {}", channelId, channelId.getId());
437 } catch (KonnectedHttpRetryExceeded e) {
438 logger.debug("Attempting to set the state of the actuator on thing {} failed: {}",
439 this.thing.getUID().getId(), e.getMessage());
440 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
441 "Unable to communicate with Konnected Alarm Panel confirm settings, and that module is online.");
445 private void getSwitchState(String zone, ChannelUID channelId) {
446 Channel channel = getThing().getChannel(channelId.getId());
447 if (channel != null) {
448 logger.debug("getasstring: {} getID: {} getGroupId: {} toString:{}", channelId.getAsString(),
449 channelId.getId(), channelId.getGroupId(), channelId);
450 KonnectedModuleGson payload = new KonnectedModuleGson();
451 payload.setZone(thingID, zone);
452 String payloadString = gson.toJson(payload);
453 logger.debug("The command payload is: {}", payloadString);
455 sendSetSwitchState(thingID, payloadString);
456 } catch (KonnectedHttpRetryExceeded e) {
457 // try to get the state of the device one more time 30 seconds later. This way it can be confirmed if
458 // the device was simply in a reboot loop when device state was attempted the first time
459 scheduler.schedule(() -> {
461 sendSetSwitchState(thingID, payloadString);
462 } catch (KonnectedHttpRetryExceeded ex) {
463 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
464 "Unable to communicate with Konnected Alarm Panel confirm settings, and that module is online.");
465 logger.debug("Attempting to get the state of the zone on thing {} failed for channel: {} : {}",
466 this.thing.getUID().getId(), channelId.getAsString(), ex.getMessage());
468 }, 2, TimeUnit.MINUTES);
471 logger.debug("The channel {} returned null for channelId.getID(): {}", channelId, channelId.getId());
475 private void sendSetSwitchState(String thingId, String payloadString) throws KonnectedHttpRetryExceeded {
476 String path = thingId.equals(WIFI_MODULE) ? "/device" : "/zone";
477 String response = http.doGet(baseUrl + path, payloadString, retryCount);
478 KonnectedModuleGson[] events = gson.fromJson(response, KonnectedModuleGson[].class);
479 for (KonnectedModuleGson event : events) {
480 this.handleWebHookEvent(event);