]> git.basschouten.com Git - openhab-addons.git/blob
271b696b29dede0064bc3681603724fceef38c43
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.konnected.internal.handler;
14
15 import static org.openhab.binding.konnected.internal.KonnectedBindingConstants.*;
16
17 import java.util.Map;
18 import java.util.Map.Entry;
19 import java.util.concurrent.TimeUnit;
20
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;
43
44 import com.google.gson.Gson;
45 import com.google.gson.GsonBuilder;
46
47 /**
48  * The {@link KonnectedHandler} is responsible for handling commands, which are
49  * sent to one of the channels.
50  *
51  * @author Zachary Christiansen - Initial contribution
52  */
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;
63
64     /**
65      * This is the constructor of the Konnected Handler.
66      *
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
69      *            Module
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.
72      */
73     public KonnectedHandler(Thing thing, String callbackUrl) {
74         super(thing);
75         this.callbackUrl = callbackUrl;
76         logger.debug("The auto discovered callback URL is: {}", this.callbackUrl);
77         retryCount = 2;
78         thingID = getThing().getThingTypeUID().getId();
79         authToken = getThing().getUID().getAsString();
80     }
81
82     @Override
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");
94             } else {
95                 sendActuatorCommand(onOffCommand, zone, channelUID);
96             }
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);
101             } else {
102                 scheduler.schedule(() -> {
103                     handleCommand(channelUID, command);
104                 }, 1, TimeUnit.MINUTES);
105             }
106         }
107     }
108
109     /**
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
112      *
113      * @param event the {@link KonnectedModuleGson} event that contains the state and pin information to be processed
114      */
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(),
123                 zone);
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)) {
130                 logger.debug(
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);
140                     if (state != null) {
141                         OnOffType onOffType = state == zoneConfig.onValue ? OnOffType.ON : OnOffType.OFF;
142                         updateState(channelId, onOffType);
143                     }
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));
151                     } else {
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());
155
156                         if (event.getAddr().equalsIgnoreCase(zoneConfig.ds18b20Address)) {
157                             updateState(channelId,
158                                     new QuantityType<>(Double.parseDouble(event.getTemp()), SIUnits.CELSIUS));
159                         } else {
160                             logger.debug("The address of {} does not match {} not updating this channel",
161                                     event.getAddr(), zoneConfig.ds18b20Address);
162                         }
163                     }
164                 }
165             } else {
166                 logger.trace(
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());
169             }
170         });
171     }
172
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;
182         } else {
183             getThing().getConfiguration().put(CALLBACK_URL, callbackUrl);
184         }
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);
189         try {
190             this.retryCount = Integer.parseInt(testRetryCount);
191         } catch (NumberFormatException e) {
192             logger.debug(
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",
194                     testRetryCount);
195             this.retryCount = 2;
196         }
197         try {
198             this.http.setRequestTimeout(Integer.parseInt(testRequestTimeout));
199         } catch (NumberFormatException e) {
200             logger.debug(
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",
202                     testRequestTimeout);
203         }
204
205         if ((callbackUrl == null)) {
206             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Unable to obtain callback URL");
207         }
208
209         else {
210             this.config = getConfigAs(KonnectedConfiguration.class);
211         }
212     }
213
214     @Override
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);
221
222             if (value == null) {
223                 continue;
224             }
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(() -> {
232                         try {
233                             http.doGet(baseUrl + "/settings?restart=true", null, retryCount);
234                         } catch (KonnectedHttpRetryExceeded e) {
235                             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
236                         }
237                     });
238                 } else if ("removewifi".equals(cfg[1]) && value instanceof Boolean bool && bool) {
239                     scheduler.execute(() -> {
240                         try {
241                             http.doGet(baseUrl + "/settings?restore=true", null, retryCount);
242                         } catch (KonnectedHttpRetryExceeded e) {
243                             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
244                         }
245                     });
246                 } else if ("sendConfig".equals(cfg[1]) && value instanceof Boolean bool && bool) {
247                     scheduler.execute(() -> {
248                         try {
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.");
255                             } else {
256                                 updateStatus(ThingStatus.ONLINE);
257                             }
258                         } catch (KonnectedHttpRetryExceeded e) {
259                             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
260                         }
261                     });
262                 }
263             }
264         }
265
266         super.handleConfigurationUpdate(configurationParameters);
267         try
268
269         {
270             String response = updateKonnectedModule();
271             logger.trace("The response from the konnected module with thingID {} was {}", getThing().getUID(),
272                     response);
273             if (response == null) {
274                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
275                         "Unable to communicate with Konnected Module confirm settings.");
276             } else {
277                 updateStatus(ThingStatus.ONLINE);
278             }
279         } catch (KonnectedHttpRetryExceeded e) {
280             logger.trace("The number of retries was exceeeded during the HandleConfigurationUpdate(): {}",
281                     e.getMessage());
282             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
283         }
284     }
285
286     @Override
287     public void initialize() {
288         updateStatus(ThingStatus.UNKNOWN);
289         try {
290             checkConfiguration();
291         } catch (ConfigValidationException e) {
292             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
293         }
294         scheduler.execute(() -> {
295             try {
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.");
300                 } else {
301                     updateStatus(ThingStatus.ONLINE);
302                 }
303             } catch (KonnectedHttpRetryExceeded e) {
304                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
305             }
306         });
307     }
308
309     @Override
310     public void dispose() {
311         logger.debug("Running dispose()");
312         super.dispose();
313     }
314
315     /**
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
321      *
322      * @return a json settings payload which can be sent to the Konnected Module based on the Thing
323      */
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
351                 // the temp sensor
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",
355                         channel);
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);
361                     logger.trace(
362                             "Channel {} will be configured on the konnected alarm panel as a DHT22 temperature sensor",
363                             channel);
364                 } else {
365                     // add to payload as a DS18B20 module if the parameter is false
366                     payload.addDs18b20(module);
367                     logger.trace(
368                             "Channel {} will be configured on the konnected alarm panel as a DS18B20 temperature sensor",
369                             channel);
370                 }
371             } else {
372                 logger.debug("Channel {} is of type {} which is not supported by the konnected binding", channel,
373                         channelType);
374             }
375         });
376         // Create Json to Send to Konnected Module
377
378         String payloadString = gson.toJson(payload);
379         logger.debug("The payload is: {}", payloadString);
380         return payloadString;
381     }
382
383     /*
384      * Prepares and sends the {@link KonnectedModulePayload} via the {@link KonnectedHttpUtils}
385      *
386      * @return response obtained from sending the settings payload to Konnected module defined by the thing
387      *
388      * @throws KonnectedHttpRetryExceeded if unable to communicate with the Konnected module defined by the Thing
389      */
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);
394         return response;
395     }
396
397     /**
398      * Sends a command to the module via {@link KonnectedHTTPUtils}
399      *
400      * @param command the state to send to the actuator
401      * @param zone the zone to send the command to on the Konnected Module
402      */
403     private void sendActuatorCommand(OnOffType command, String zone, ChannelUID channelId) {
404         try {
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);
412
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);
418                 } else {
419                     payload.setState(zoneConfig.onValue == 1 ? 0 : 1);
420                 }
421
422                 String payloadString = gson.toJson(payload);
423                 logger.debug("The command payload  is: {}", payloadString);
424                 String path = "";
425                 switch (this.thingID) {
426                     case PRO_MODULE:
427                         path = "/zone";
428                         break;
429                     case WIFI_MODULE:
430                         path = "/device";
431                         break;
432                 }
433                 http.doPut(baseUrl + path, payloadString, retryCount);
434             } else {
435                 logger.debug("The channel {} returned null for channelId.getID(): {}", channelId, channelId.getId());
436             }
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.");
442         }
443     }
444
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);
454             try {
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(() -> {
460                     try {
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());
467                     }
468                 }, 2, TimeUnit.MINUTES);
469             }
470         } else {
471             logger.debug("The channel {} returned null for channelId.getID(): {}", channelId, channelId.getId());
472         }
473     }
474
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);
481         }
482     }
483 }