2 * Copyright (c) 2010-2022 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.boschindego.internal.handler;
15 import static org.openhab.binding.boschindego.internal.BoschIndegoBindingConstants.*;
17 import java.time.Instant;
18 import java.time.ZonedDateTime;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.eclipse.jetty.client.HttpClient;
25 import org.openhab.binding.boschindego.internal.BoschIndegoTranslationProvider;
26 import org.openhab.binding.boschindego.internal.DeviceStatus;
27 import org.openhab.binding.boschindego.internal.IndegoController;
28 import org.openhab.binding.boschindego.internal.config.BoschIndegoConfiguration;
29 import org.openhab.binding.boschindego.internal.dto.DeviceCommand;
30 import org.openhab.binding.boschindego.internal.dto.response.DeviceStateResponse;
31 import org.openhab.binding.boschindego.internal.dto.response.OperatingDataResponse;
32 import org.openhab.binding.boschindego.internal.exceptions.IndegoAuthenticationException;
33 import org.openhab.binding.boschindego.internal.exceptions.IndegoException;
34 import org.openhab.core.i18n.TimeZoneProvider;
35 import org.openhab.core.library.types.DateTimeType;
36 import org.openhab.core.library.types.DecimalType;
37 import org.openhab.core.library.types.OnOffType;
38 import org.openhab.core.library.types.PercentType;
39 import org.openhab.core.library.types.QuantityType;
40 import org.openhab.core.library.types.StringType;
41 import org.openhab.core.library.unit.SIUnits;
42 import org.openhab.core.library.unit.Units;
43 import org.openhab.core.thing.ChannelUID;
44 import org.openhab.core.thing.Thing;
45 import org.openhab.core.thing.ThingStatus;
46 import org.openhab.core.thing.ThingStatusDetail;
47 import org.openhab.core.thing.binding.BaseThingHandler;
48 import org.openhab.core.types.Command;
49 import org.openhab.core.types.RefreshType;
50 import org.openhab.core.types.UnDefType;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * The {@link BoschIndegoHandler} is responsible for handling commands, which are
56 * sent to one of the channels.
58 * @author Jonas Fleck - Initial contribution
59 * @author Jacob Laursen - Refactoring, bugfixing and removal of dependency towards abandoned library
62 public class BoschIndegoHandler extends BaseThingHandler {
64 private final Logger logger = LoggerFactory.getLogger(BoschIndegoHandler.class);
65 private final HttpClient httpClient;
66 private final BoschIndegoTranslationProvider translationProvider;
67 private final TimeZoneProvider timeZoneProvider;
69 private @NonNullByDefault({}) IndegoController controller;
70 private @Nullable ScheduledFuture<?> statePollFuture;
71 private @Nullable ScheduledFuture<?> cuttingTimeMapPollFuture;
72 private boolean propertiesInitialized;
73 private int previousStateCode;
75 public BoschIndegoHandler(Thing thing, HttpClient httpClient, BoschIndegoTranslationProvider translationProvider,
76 TimeZoneProvider timeZoneProvider) {
78 this.httpClient = httpClient;
79 this.translationProvider = translationProvider;
80 this.timeZoneProvider = timeZoneProvider;
84 public void initialize() {
85 logger.debug("Initializing Indego handler");
86 BoschIndegoConfiguration config = getConfigAs(BoschIndegoConfiguration.class);
87 String username = config.username;
88 String password = config.password;
90 if (username == null || username.isBlank()) {
91 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
92 "@text/offline.conf-error.missing-username");
95 if (password == null || password.isBlank()) {
96 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
97 "@text/offline.conf-error.missing-password");
101 controller = new IndegoController(httpClient, username, password);
103 updateStatus(ThingStatus.UNKNOWN);
104 this.statePollFuture = scheduler.scheduleWithFixedDelay(this::refreshStateAndOperatingDataWithExceptionHandling,
105 0, config.refresh, TimeUnit.SECONDS);
106 this.cuttingTimeMapPollFuture = scheduler.scheduleWithFixedDelay(
107 this::refreshCuttingTimesAndMapWithExceptionHandling, 0, config.cuttingTimeMapRefresh,
112 public void dispose() {
113 logger.debug("Disposing Indego handler");
114 ScheduledFuture<?> pollFuture = this.statePollFuture;
115 if (pollFuture != null) {
116 pollFuture.cancel(true);
118 this.statePollFuture = null;
119 pollFuture = this.cuttingTimeMapPollFuture;
120 if (pollFuture != null) {
121 pollFuture.cancel(true);
123 this.cuttingTimeMapPollFuture = null;
125 scheduler.execute(() -> {
127 controller.deauthenticate();
128 } catch (IndegoException e) {
129 logger.debug("Deauthentication failed", e);
135 public void handleCommand(ChannelUID channelUID, Command command) {
136 logger.debug("handleCommand {} for channel {}", command, channelUID);
138 if (command == RefreshType.REFRESH) {
139 handleRefreshCommand(channelUID.getId());
142 if (command instanceof DecimalType && channelUID.getId().equals(STATE)) {
143 sendCommand(((DecimalType) command).intValue());
145 } catch (IndegoAuthenticationException e) {
146 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
147 "@text/offline.comm-error.authentication-failure");
148 } catch (IndegoException e) {
149 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
153 private void handleRefreshCommand(String channelId) throws IndegoAuthenticationException, IndegoException {
165 refreshCuttingTimes();
169 case BATTERY_VOLTAGE:
170 case BATTERY_TEMPERATURE:
172 refreshOperatingData();
180 private void sendCommand(int commandInt) throws IndegoException {
181 DeviceCommand command;
182 switch (commandInt) {
184 command = DeviceCommand.MOW;
187 command = DeviceCommand.RETURN;
190 command = DeviceCommand.PAUSE;
193 logger.warn("Invalid command {}", commandInt);
197 DeviceStateResponse state = controller.getState();
198 DeviceStatus deviceStatus = DeviceStatus.fromCode(state.state);
199 if (!verifyCommand(command, deviceStatus, state.error)) {
202 logger.debug("Sending command {}", command);
203 updateState(TEXTUAL_STATE, UnDefType.UNDEF);
204 controller.sendCommand(command);
208 private void refreshStateAndOperatingDataWithExceptionHandling() {
211 refreshOperatingData();
212 } catch (IndegoAuthenticationException e) {
213 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
214 "@text/offline.comm-error.authentication-failure");
215 } catch (IndegoException e) {
216 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
220 private void refreshState() throws IndegoAuthenticationException, IndegoException {
221 if (!propertiesInitialized) {
222 getThing().setProperty(Thing.PROPERTY_SERIAL_NUMBER, controller.getSerialNumber());
223 propertiesInitialized = true;
226 DeviceStateResponse state = controller.getState();
229 // When state code changed, refresh cutting times immediately.
230 if (state.state != previousStateCode) {
231 refreshCuttingTimes();
232 previousStateCode = state.state;
236 private void refreshOperatingData() throws IndegoAuthenticationException, IndegoException {
237 updateOperatingData(controller.getOperatingData());
238 updateStatus(ThingStatus.ONLINE);
241 private void refreshCuttingTimes() throws IndegoAuthenticationException, IndegoException {
242 if (isLinked(LAST_CUTTING)) {
243 Instant lastCutting = controller.getPredictiveLastCutting();
244 if (lastCutting != null) {
245 updateState(LAST_CUTTING,
246 new DateTimeType(ZonedDateTime.ofInstant(lastCutting, timeZoneProvider.getTimeZone())));
248 updateState(LAST_CUTTING, UnDefType.UNDEF);
252 if (isLinked(NEXT_CUTTING)) {
253 Instant nextCutting = controller.getPredictiveNextCutting();
254 if (nextCutting != null) {
255 updateState(NEXT_CUTTING,
256 new DateTimeType(ZonedDateTime.ofInstant(nextCutting, timeZoneProvider.getTimeZone())));
258 updateState(NEXT_CUTTING, UnDefType.UNDEF);
263 private void refreshCuttingTimesAndMapWithExceptionHandling() {
265 refreshCuttingTimes();
267 } catch (IndegoAuthenticationException e) {
268 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
269 "@text/offline.comm-error.authentication-failure");
270 } catch (IndegoException e) {
271 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
275 private void refreshMap() throws IndegoAuthenticationException, IndegoException {
276 if (isLinked(GARDEN_MAP)) {
277 updateState(GARDEN_MAP, controller.getMap());
281 private void updateState(DeviceStateResponse state) {
282 DeviceStatus deviceStatus = DeviceStatus.fromCode(state.state);
283 int status = getStatusFromCommand(deviceStatus.getAssociatedCommand());
284 int mowed = state.mowed;
285 int error = state.error;
286 int statecode = state.state;
287 boolean ready = isReadyToMow(deviceStatus, state.error);
289 updateState(STATECODE, new DecimalType(statecode));
290 updateState(READY, new DecimalType(ready ? 1 : 0));
291 updateState(ERRORCODE, new DecimalType(error));
292 updateState(MOWED, new PercentType(mowed));
293 updateState(STATE, new DecimalType(status));
294 updateState(TEXTUAL_STATE, new StringType(deviceStatus.getMessage(translationProvider)));
297 private void updateOperatingData(OperatingDataResponse operatingData) {
298 updateState(BATTERY_VOLTAGE, new QuantityType<>(operatingData.battery.voltage, Units.VOLT));
299 updateState(BATTERY_LEVEL, new DecimalType(operatingData.battery.percent));
300 updateState(LOW_BATTERY, OnOffType.from(operatingData.battery.percent < 20));
301 updateState(BATTERY_TEMPERATURE, new QuantityType<>(operatingData.battery.batteryTemperature, SIUnits.CELSIUS));
302 updateState(GARDEN_SIZE, new QuantityType<>(operatingData.garden.size, SIUnits.SQUARE_METRE));
305 private boolean isReadyToMow(DeviceStatus deviceStatus, int error) {
306 return deviceStatus.isReadyToMow() && error == 0;
309 private boolean verifyCommand(DeviceCommand command, DeviceStatus deviceStatus, int errorCode) {
310 // Mower reported an error
311 if (errorCode != 0) {
312 logger.error("The mower reported an error.");
316 // Command is equal to current state
317 if (command == deviceStatus.getAssociatedCommand()) {
318 logger.debug("Command is equal to state");
321 // Can't pause while the mower is docked
322 if (command == DeviceCommand.PAUSE && deviceStatus.getAssociatedCommand() == DeviceCommand.RETURN) {
323 logger.debug("Can't pause the mower while it's docked or docking");
326 // Command means "MOW" but mower is not ready
327 if (command == DeviceCommand.MOW && !isReadyToMow(deviceStatus, errorCode)) {
328 logger.debug("The mower is not ready to mow at the moment");
334 private int getStatusFromCommand(@Nullable DeviceCommand command) {
335 if (command == null) {