2 * Copyright (c) 2010-2024 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.tasmotaplug.internal.handler;
15 import static org.eclipse.jetty.http.HttpStatus.OK_200;
16 import static org.openhab.binding.tasmotaplug.internal.TasmotaPlugBindingConstants.*;
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;
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;
43 * The {@link TasmotaPlugHandler} is responsible for handling commands, which are
44 * sent to one of the channels.
46 * @author Michael Lobstein - Initial contribution
49 public class TasmotaPlugHandler extends BaseThingHandler {
50 private static final String PASSWORD_REGEX = "&password=(.*)&";
51 private static final String PASSWORD_MASK = "&password=xxxx&";
53 private final Logger logger = LoggerFactory.getLogger(TasmotaPlugHandler.class);
54 private final HttpClient httpClient;
56 private @Nullable ScheduledFuture<?> refreshJob;
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;
65 public TasmotaPlugHandler(Thing thing, HttpClient httpClient) {
67 this.httpClient = httpClient;
71 public void initialize() {
72 logger.debug("Initializing TasmotaPlug handler.");
73 TasmotaPlugConfiguration config = getConfigAs(TasmotaPlugConfiguration.class);
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;
81 if (hostName.isBlank()) {
82 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
83 "@text/offline.configuration-error-hostname");
87 if (!username.isBlank() && !password.isBlank()) {
93 plugHost = "http://" + hostName;
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());
99 List<Integer> channelsToRemove = IntStream.range(this.numChannels + 1, SUPPORTED_CHANNEL_IDS.size() + 1)
102 channelsToRemove.forEach(channel -> {
103 channels.removeIf(c -> (c.getUID().getId().equals(POWER + channel)));
105 updateThing(editThing().withChannels(channels).build());
108 updateStatus(ThingStatus.UNKNOWN);
109 startAutomaticRefresh();
113 public void dispose() {
114 logger.debug("Disposing the TasmotaPlug handler.");
116 ScheduledFuture<?> refreshJob = this.refreshJob;
117 if (refreshJob != null) {
118 refreshJob.cancel(true);
119 this.refreshJob = null;
124 public void handleCommand(ChannelUID channelUID, Command command) {
125 if (channelUID.getId().contains(POWER)) {
126 if (command instanceof OnOffType) {
127 getCommand(channelUID.getId(), command);
129 updateChannelState(channelUID.getId());
132 logger.warn("Unsupported command: {}", command.toString());
137 * Start the job to periodically update the state of the plug
139 private void startAutomaticRefresh() {
140 ScheduledFuture<?> refreshJob = this.refreshJob;
141 if (refreshJob == null || refreshJob.isCancelled()) {
143 this.refreshJob = scheduler.scheduleWithFixedDelay(() -> {
144 SUPPORTED_CHANNEL_IDS.stream().limit(numChannels).forEach(channelId -> {
145 updateChannelState(channelId);
147 }, 0, refreshPeriod, TimeUnit.SECONDS);
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);
160 private String getCommand(String channelId, @Nullable Command command) {
161 final String plugChannel = channelId.substring(0, 1).toUpperCase() + channelId.substring(1);
165 url = String.format(CMD_URI_AUTH, user, pass, plugChannel);
167 url = String.format(CMD_URI, plugChannel);
170 if (command != null) {
171 url += "%20" + command;
175 logger.trace("Sending GET request to {}{}", plugHost, maskPassword(url));
176 ContentResponse contentResponse = httpClient.GET(plugHost + url);
177 logger.trace("Response: {}", contentResponse.getContentAsString());
179 if (contentResponse.getStatus() != OK_200) {
180 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
181 "@text/offline.communication-error.http-failure [\"" + contentResponse.getStatus() + "\"]");
185 updateStatus(ThingStatus.ONLINE);
186 return contentResponse.getContentAsString();
187 } catch (TimeoutException | ExecutionException e) {
188 logger.debug("Error executing Tasmota GET request: '{}{}', {}", plugHost, maskPassword(url),
190 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
191 } catch (InterruptedException e) {
192 logger.debug("InterruptedException executing Tasmota GET request: '{}{}', {}", plugHost, maskPassword(url),
194 Thread.currentThread().interrupt();
199 private String maskPassword(String input) {
200 return isAuth ? input.replaceAll(PASSWORD_REGEX, PASSWORD_MASK) : input;