]> git.basschouten.com Git - openhab-addons.git/blob
b1223159c34e28de6bfae855c10cac32044777ca
[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.tasmotaplug.internal.handler;
14
15 import static org.eclipse.jetty.http.HttpStatus.OK_200;
16 import static org.openhab.binding.tasmotaplug.internal.TasmotaPlugBindingConstants.*;
17
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
24 import java.util.stream.IntStream;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.eclipse.jetty.client.HttpClient;
29 import org.eclipse.jetty.client.api.ContentResponse;
30 import org.openhab.binding.tasmotaplug.internal.TasmotaPlugConfiguration;
31 import org.openhab.core.library.types.OnOffType;
32 import org.openhab.core.thing.Channel;
33 import org.openhab.core.thing.ChannelUID;
34 import org.openhab.core.thing.Thing;
35 import org.openhab.core.thing.ThingStatus;
36 import org.openhab.core.thing.ThingStatusDetail;
37 import org.openhab.core.thing.binding.BaseThingHandler;
38 import org.openhab.core.types.Command;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * The {@link TasmotaPlugHandler} is responsible for handling commands, which are
44  * sent to one of the channels.
45  *
46  * @author Michael Lobstein - Initial contribution
47  */
48 @NonNullByDefault
49 public class TasmotaPlugHandler extends BaseThingHandler {
50     private static final String PASSWORD_REGEX = "&password=(.*)&";
51     private static final String PASSWORD_MASK = "&password=xxxx&";
52
53     private final Logger logger = LoggerFactory.getLogger(TasmotaPlugHandler.class);
54     private final HttpClient httpClient;
55
56     private @Nullable ScheduledFuture<?> refreshJob;
57
58     private String plugHost = BLANK;
59     private int refreshPeriod = DEFAULT_REFRESH_PERIOD_SEC;
60     private int numChannels = DEFAULT_NUM_CHANNELS;
61     private boolean isAuth = false;
62     private String user = BLANK;
63     private String pass = BLANK;
64
65     public TasmotaPlugHandler(Thing thing, HttpClient httpClient) {
66         super(thing);
67         this.httpClient = httpClient;
68     }
69
70     @Override
71     public void initialize() {
72         logger.debug("Initializing TasmotaPlug handler.");
73         TasmotaPlugConfiguration config = getConfigAs(TasmotaPlugConfiguration.class);
74
75         final String hostName = config.hostName;
76         final String username = config.username;
77         final String password = config.password;
78         refreshPeriod = config.refresh;
79         numChannels = config.numChannels;
80
81         if (hostName.isBlank()) {
82             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
83                     "@text/offline.configuration-error-hostname");
84             return;
85         }
86
87         if (!username.isBlank() && !password.isBlank()) {
88             isAuth = true;
89             user = username;
90             pass = password;
91         }
92
93         plugHost = "http://" + hostName;
94
95         // remove the channels we are not using
96         if (this.numChannels < SUPPORTED_CHANNEL_IDS.size()) {
97             List<Channel> channels = new ArrayList<>(this.getThing().getChannels());
98
99             List<Integer> channelsToRemove = IntStream.range(this.numChannels + 1, SUPPORTED_CHANNEL_IDS.size() + 1)
100                     .boxed().toList();
101
102             channelsToRemove.forEach(channel -> {
103                 channels.removeIf(c -> (c.getUID().getId().equals(POWER + channel)));
104             });
105             updateThing(editThing().withChannels(channels).build());
106         }
107
108         updateStatus(ThingStatus.UNKNOWN);
109         startAutomaticRefresh();
110     }
111
112     @Override
113     public void dispose() {
114         logger.debug("Disposing the TasmotaPlug handler.");
115
116         ScheduledFuture<?> refreshJob = this.refreshJob;
117         if (refreshJob != null) {
118             refreshJob.cancel(true);
119             this.refreshJob = null;
120         }
121     }
122
123     @Override
124     public void handleCommand(ChannelUID channelUID, Command command) {
125         if (channelUID.getId().contains(POWER)) {
126             if (command instanceof OnOffType) {
127                 getCommand(channelUID.getId(), command);
128             } else {
129                 updateChannelState(channelUID.getId());
130             }
131         } else {
132             logger.warn("Unsupported command: {}", command.toString());
133         }
134     }
135
136     /**
137      * Start the job to periodically update the state of the plug
138      */
139     private void startAutomaticRefresh() {
140         ScheduledFuture<?> refreshJob = this.refreshJob;
141         if (refreshJob == null || refreshJob.isCancelled()) {
142             refreshJob = null;
143             this.refreshJob = scheduler.scheduleWithFixedDelay(() -> {
144                 SUPPORTED_CHANNEL_IDS.stream().limit(numChannels).forEach(channelId -> {
145                     updateChannelState(channelId);
146                 });
147             }, 0, refreshPeriod, TimeUnit.SECONDS);
148         }
149     }
150
151     private void updateChannelState(String channelId) {
152         final String plugState = getCommand(channelId, null);
153         if (plugState.contains(ON)) {
154             updateState(channelId, OnOffType.ON);
155         } else if (plugState.contains(OFF)) {
156             updateState(channelId, OnOffType.OFF);
157         }
158     }
159
160     private String getCommand(String channelId, @Nullable Command command) {
161         final String plugChannel = channelId.substring(0, 1).toUpperCase() + channelId.substring(1);
162         String url;
163
164         if (isAuth) {
165             url = String.format(CMD_URI_AUTH, user, pass, plugChannel);
166         } else {
167             url = String.format(CMD_URI, plugChannel);
168         }
169
170         if (command != null) {
171             url += "%20" + command;
172         }
173
174         try {
175             logger.trace("Sending GET request to {}{}", plugHost, maskPassword(url));
176             ContentResponse contentResponse = httpClient.GET(plugHost + url);
177             logger.trace("Response: {}", contentResponse.getContentAsString());
178
179             if (contentResponse.getStatus() != OK_200) {
180                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
181                         "@text/offline.communication-error.http-failure [\"" + contentResponse.getStatus() + "\"]");
182                 return BLANK;
183             }
184
185             updateStatus(ThingStatus.ONLINE);
186             return contentResponse.getContentAsString();
187         } catch (TimeoutException | ExecutionException e) {
188             logger.debug("Error executing Tasmota GET request: '{}{}', {}", plugHost, maskPassword(url),
189                     e.getMessage());
190             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
191         } catch (InterruptedException e) {
192             logger.debug("InterruptedException executing Tasmota GET request: '{}{}', {}", plugHost, maskPassword(url),
193                     e.getMessage());
194             Thread.currentThread().interrupt();
195         }
196         return BLANK;
197     }
198
199     private String maskPassword(String input) {
200         return isAuth ? input.replaceAll(PASSWORD_REGEX, PASSWORD_MASK) : input;
201     }
202 }