]> git.basschouten.com Git - openhab-addons.git/blob
1a2fc024c7bc61341abb54e0fe990e73e3429e91
[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.opensprinkler.internal.discovery;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.openhab.binding.opensprinkler.internal.api.exception.CommunicationApiException;
17 import org.openhab.binding.opensprinkler.internal.api.exception.GeneralApiException;
18 import org.openhab.binding.opensprinkler.internal.api.exception.UnauthorizedApiException;
19 import org.openhab.binding.opensprinkler.internal.config.OpenSprinklerHttpInterfaceConfig;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 /**
24  * The {@link OpenSprinklerDiscoveryJob} class allow manual discovery of
25  * OpenSprinkler devices for a single IP address. This is used
26  * for threading to make discovery faster.
27  *
28  * @author Chris Graham - Initial contribution
29  */
30 @NonNullByDefault
31 public class OpenSprinklerDiscoveryJob implements Runnable {
32     private final Logger logger = LoggerFactory.getLogger(OpenSprinklerDiscoveryJob.class);
33     private OpenSprinklerDiscoveryService discoveryClass;
34     private String ipAddress;
35
36     public OpenSprinklerDiscoveryJob(OpenSprinklerDiscoveryService service, String ip) {
37         this.discoveryClass = service;
38         this.ipAddress = ip;
39     }
40
41     @Override
42     public void run() {
43         if (hasOpenSprinklerDevice(this.ipAddress)) {
44             discoveryClass.submitDiscoveryResults(this.ipAddress);
45         }
46     }
47
48     /**
49      * Determines if an OpenSprinkler device is available at a given IP address.
50      *
51      * @param ip IP address of the OpenSprinkler device as a string.
52      * @return True if a device is found, false if not.
53      */
54     private boolean hasOpenSprinklerDevice(String ip) {
55         try {
56             OpenSprinklerHttpInterfaceConfig config = new OpenSprinklerHttpInterfaceConfig();
57             config.hostname = ip;
58             discoveryClass.getApiFactory().getHttpApi(config);
59         } catch (UnauthorizedApiException e) {
60             return true;
61         } catch (CommunicationApiException | GeneralApiException exp) {
62             logger.debug("No OpenSprinkler device found at IP address ({}) because of error: {}", ip, exp.getMessage());
63             return false;
64         }
65         return true;
66     }
67 }