]> git.basschouten.com Git - openhab-addons.git/blob
672a9756cd75745c6fb0a659a2bedd3d0c6cab82
[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.boschindego.internal.handler;
14
15 import static org.openhab.binding.boschindego.internal.BoschIndegoBindingConstants.*;
16
17 import java.nio.charset.StandardCharsets;
18 import java.time.Duration;
19 import java.time.Instant;
20 import java.time.LocalDateTime;
21 import java.time.ZonedDateTime;
22 import java.time.temporal.ChronoUnit;
23 import java.util.Map;
24 import java.util.Optional;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
27
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.eclipse.jetty.client.HttpClient;
31 import org.openhab.binding.boschindego.internal.BoschIndegoTranslationProvider;
32 import org.openhab.binding.boschindego.internal.DeviceStatus;
33 import org.openhab.binding.boschindego.internal.IndegoDeviceController;
34 import org.openhab.binding.boschindego.internal.IndegoTypeDatabase;
35 import org.openhab.binding.boschindego.internal.config.BoschIndegoConfiguration;
36 import org.openhab.binding.boschindego.internal.dto.DeviceCommand;
37 import org.openhab.binding.boschindego.internal.dto.response.DevicePropertiesResponse;
38 import org.openhab.binding.boschindego.internal.dto.response.DeviceStateResponse;
39 import org.openhab.binding.boschindego.internal.dto.response.OperatingDataResponse;
40 import org.openhab.binding.boschindego.internal.exceptions.IndegoAuthenticationException;
41 import org.openhab.binding.boschindego.internal.exceptions.IndegoException;
42 import org.openhab.binding.boschindego.internal.exceptions.IndegoInvalidCommandException;
43 import org.openhab.binding.boschindego.internal.exceptions.IndegoTimeoutException;
44 import org.openhab.core.auth.client.oauth2.OAuthClientService;
45 import org.openhab.core.i18n.TimeZoneProvider;
46 import org.openhab.core.library.types.DateTimeType;
47 import org.openhab.core.library.types.DecimalType;
48 import org.openhab.core.library.types.OnOffType;
49 import org.openhab.core.library.types.PercentType;
50 import org.openhab.core.library.types.QuantityType;
51 import org.openhab.core.library.types.RawType;
52 import org.openhab.core.library.types.StringType;
53 import org.openhab.core.library.unit.SIUnits;
54 import org.openhab.core.library.unit.Units;
55 import org.openhab.core.thing.Bridge;
56 import org.openhab.core.thing.ChannelUID;
57 import org.openhab.core.thing.Thing;
58 import org.openhab.core.thing.ThingStatus;
59 import org.openhab.core.thing.ThingStatusDetail;
60 import org.openhab.core.thing.ThingStatusInfo;
61 import org.openhab.core.thing.binding.BaseThingHandler;
62 import org.openhab.core.thing.binding.ThingHandler;
63 import org.openhab.core.types.Command;
64 import org.openhab.core.types.RefreshType;
65 import org.openhab.core.types.UnDefType;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 /**
70  * The {@link BoschIndegoHandler} is responsible for handling commands, which are
71  * sent to one of the channels.
72  *
73  * @author Jonas Fleck - Initial contribution
74  * @author Jacob Laursen - Refactoring, bugfixing and removal of dependency towards abandoned library
75  */
76 @NonNullByDefault
77 public class BoschIndegoHandler extends BaseThingHandler {
78
79     private static final String MAP_POSITION_STROKE_COLOR = "#8c8b6d";
80     private static final String MAP_POSITION_FILL_COLOR = "#fff701";
81     private static final int MAP_POSITION_RADIUS = 10;
82     private static final Duration DEVICE_PROPERTIES_VALIDITY_PERIOD = Duration.ofDays(1);
83
84     private static final Duration MAP_REFRESH_INTERVAL = Duration.ofDays(1);
85     private static final Duration OPERATING_DATA_INACTIVE_REFRESH_INTERVAL = Duration.ofHours(6);
86     private static final Duration OPERATING_DATA_OFFLINE_REFRESH_INTERVAL = Duration.ofMinutes(30);
87     private static final Duration OPERATING_DATA_ACTIVE_REFRESH_INTERVAL = Duration.ofMinutes(2);
88     private static final Duration MAP_REFRESH_SESSION_DURATION = Duration.ofMinutes(5);
89     private static final Duration COMMAND_STATE_REFRESH_TIMEOUT = Duration.ofSeconds(10);
90
91     private final Logger logger = LoggerFactory.getLogger(BoschIndegoHandler.class);
92     private final HttpClient httpClient;
93     private final BoschIndegoTranslationProvider translationProvider;
94     private final TimeZoneProvider timeZoneProvider;
95     private Instant devicePropertiesUpdated = Instant.MIN;
96
97     private @NonNullByDefault({}) OAuthClientService oAuthClientService;
98     private @NonNullByDefault({}) IndegoDeviceController controller;
99     private @Nullable ScheduledFuture<?> statePollFuture;
100     private @Nullable ScheduledFuture<?> cuttingTimePollFuture;
101     private @Nullable ScheduledFuture<?> cuttingTimeFuture;
102     private Optional<Integer> previousStateCode = Optional.empty();
103     private @Nullable RawType cachedMap;
104     private Instant cachedMapTimestamp = Instant.MIN;
105     private Instant operatingDataTimestamp = Instant.MIN;
106     private Instant mapRefreshStartedTimestamp = Instant.MIN;
107     private ThingStatus lastOperatingDataStatus = ThingStatus.UNINITIALIZED;
108     private int stateInactiveRefreshIntervalSeconds;
109     private int stateActiveRefreshIntervalSeconds;
110     private int currentRefreshIntervalSeconds;
111
112     public BoschIndegoHandler(Thing thing, HttpClient httpClient, BoschIndegoTranslationProvider translationProvider,
113             TimeZoneProvider timeZoneProvider) {
114         super(thing);
115         this.httpClient = httpClient;
116         this.translationProvider = translationProvider;
117         this.timeZoneProvider = timeZoneProvider;
118     }
119
120     @Override
121     public void initialize() {
122         BoschIndegoConfiguration config = getConfigAs(BoschIndegoConfiguration.class);
123         stateInactiveRefreshIntervalSeconds = (int) config.refresh;
124         stateActiveRefreshIntervalSeconds = (int) config.stateActiveRefresh;
125
126         Bridge bridge = getBridge();
127         if (bridge == null) {
128             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
129                     "@text/offline.conf-error.missing-bridge");
130             return;
131         }
132
133         ThingHandler handler = bridge.getHandler();
134         if (handler instanceof BoschAccountHandler accountHandler) {
135             this.oAuthClientService = accountHandler.getOAuthClientService();
136         } else {
137             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
138                     "@text/offline.conf-error.missing-bridge");
139             return;
140         }
141
142         devicePropertiesUpdated = Instant.MIN;
143         updateProperty(Thing.PROPERTY_SERIAL_NUMBER, config.serialNumber);
144
145         controller = new IndegoDeviceController(httpClient, oAuthClientService, config.serialNumber);
146
147         updateStatus(ThingStatus.UNKNOWN);
148         previousStateCode = Optional.empty();
149         rescheduleStatePoll(0, stateInactiveRefreshIntervalSeconds, false);
150         this.cuttingTimePollFuture = scheduler.scheduleWithFixedDelay(this::refreshCuttingTimesWithExceptionHandling, 0,
151                 config.cuttingTimeRefresh, TimeUnit.MINUTES);
152     }
153
154     @Override
155     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
156         if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE
157                 && getThing().getStatusInfo().getStatus() == ThingStatus.OFFLINE) {
158             // Trigger immediate state refresh upon authorization success.
159             rescheduleStatePoll(0, stateInactiveRefreshIntervalSeconds, true);
160         } else if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
161             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
162         }
163     }
164
165     private boolean rescheduleStatePoll(int delaySeconds, int refreshIntervalSeconds, boolean force) {
166         ScheduledFuture<?> statePollFuture = this.statePollFuture;
167         if (statePollFuture != null) {
168             if (!force && refreshIntervalSeconds == currentRefreshIntervalSeconds) {
169                 // No change.
170                 return false;
171             }
172             statePollFuture.cancel(force);
173         }
174         logger.debug("Scheduling state refresh job with {}s interval and {}s delay", refreshIntervalSeconds,
175                 delaySeconds);
176         this.statePollFuture = scheduler.scheduleWithFixedDelay(this::refreshStateWithExceptionHandling, delaySeconds,
177                 refreshIntervalSeconds, TimeUnit.SECONDS);
178         currentRefreshIntervalSeconds = refreshIntervalSeconds;
179
180         return true;
181     }
182
183     @Override
184     public void dispose() {
185         ScheduledFuture<?> pollFuture = this.statePollFuture;
186         if (pollFuture != null) {
187             pollFuture.cancel(true);
188         }
189         this.statePollFuture = null;
190         pollFuture = this.cuttingTimePollFuture;
191         if (pollFuture != null) {
192             pollFuture.cancel(true);
193         }
194         this.cuttingTimePollFuture = null;
195         pollFuture = this.cuttingTimeFuture;
196         if (pollFuture != null) {
197             pollFuture.cancel(true);
198         }
199         this.cuttingTimeFuture = null;
200     }
201
202     @Override
203     public void handleCommand(ChannelUID channelUID, Command command) {
204         logger.debug("handleCommand {} for channel {}", command, channelUID);
205         try {
206             if (command == RefreshType.REFRESH) {
207                 handleRefreshCommand(channelUID.getId());
208                 return;
209             }
210             if (command instanceof DecimalType && channelUID.getId().equals(STATE)) {
211                 sendCommand(((DecimalType) command).intValue());
212             }
213         } catch (IndegoAuthenticationException e) {
214             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
215                     "@text/offline.comm-error.authentication-failure");
216         } catch (IndegoTimeoutException e) {
217             updateStatus(lastOperatingDataStatus = ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
218                     "@text/offline.comm-error.unreachable");
219         } catch (IndegoInvalidCommandException e) {
220             logger.warn("Invalid command: {}", e.getMessage());
221             if (e.hasErrorCode()) {
222                 updateState(ERRORCODE, new DecimalType(e.getErrorCode()));
223             }
224         } catch (IndegoException e) {
225             logger.warn("Command failed: {}", e.getMessage());
226         }
227     }
228
229     private void handleRefreshCommand(String channelId)
230             throws IndegoAuthenticationException, IndegoTimeoutException, IndegoException {
231         switch (channelId) {
232             case GARDEN_MAP:
233                 // Force map refresh and fall through to state update.
234                 cachedMapTimestamp = Instant.MIN;
235             case STATE:
236             case TEXTUAL_STATE:
237             case MOWED:
238             case ERRORCODE:
239             case STATECODE:
240             case READY:
241                 refreshState();
242                 break;
243             case LAST_CUTTING:
244                 refreshLastCuttingTime();
245                 break;
246             case NEXT_CUTTING:
247                 refreshNextCuttingTime();
248                 break;
249             case BATTERY_LEVEL:
250             case LOW_BATTERY:
251             case BATTERY_VOLTAGE:
252             case BATTERY_TEMPERATURE:
253             case GARDEN_SIZE:
254                 refreshOperatingData();
255                 break;
256         }
257     }
258
259     private void sendCommand(int commandInt) throws IndegoException {
260         DeviceCommand command;
261         switch (commandInt) {
262             case 1:
263                 command = DeviceCommand.MOW;
264                 break;
265             case 2:
266                 command = DeviceCommand.RETURN;
267                 break;
268             case 3:
269                 command = DeviceCommand.PAUSE;
270                 break;
271             default:
272                 logger.warn("Invalid command {}", commandInt);
273                 return;
274         }
275
276         DeviceStateResponse state = controller.getState();
277         DeviceStatus deviceStatus = DeviceStatus.fromCode(state.state);
278         if (!verifyCommand(command, deviceStatus, state.error)) {
279             return;
280         }
281         logger.debug("Sending command {}", command);
282         controller.sendCommand(command);
283
284         // State is not updated immediately, so await new state for some seconds.
285         // For command MOW, state will shortly be updated to 262 (docked, loading map).
286         // This is considered "active", so after this state change, polling frequency will
287         // be increased for faster updates.
288         DeviceStateResponse stateResponse = controller.getState(COMMAND_STATE_REFRESH_TIMEOUT);
289         if (stateResponse.state != 0) {
290             updateState(stateResponse);
291             deviceStatus = DeviceStatus.fromCode(stateResponse.state);
292             rescheduleStatePollAccordingToState(deviceStatus);
293         }
294     }
295
296     private void refreshStateWithExceptionHandling() {
297         try {
298             refreshState();
299         } catch (IndegoAuthenticationException e) {
300             logger.warn("Failed to authenticate: {}", e.getMessage());
301             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
302                     "@text/offline.comm-error.authentication-failure");
303         } catch (IndegoTimeoutException e) {
304             updateStatus(lastOperatingDataStatus = ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
305                     "@text/offline.comm-error.unreachable");
306         } catch (IndegoException e) {
307             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
308         }
309     }
310
311     private void refreshState() throws IndegoAuthenticationException, IndegoException {
312         DeviceStateResponse state = controller.getState();
313         DeviceStatus deviceStatus = DeviceStatus.fromCode(state.state);
314         updateState(state);
315
316         if (devicePropertiesUpdated.isBefore(Instant.now().minus(DEVICE_PROPERTIES_VALIDITY_PERIOD))) {
317             refreshDeviceProperties();
318         }
319
320         // Update map and start tracking positions if mower is active.
321         if (state.mapUpdateAvailable) {
322             cachedMapTimestamp = Instant.MIN;
323         }
324         refreshMap(state.svgXPos, state.svgYPos);
325         if (deviceStatus.isActive()) {
326             trackPosition();
327         }
328
329         int previousState;
330         DeviceStatus previousDeviceStatus;
331         if (previousStateCode.isPresent()) {
332             previousState = previousStateCode.get();
333             previousDeviceStatus = DeviceStatus.fromCode(previousState);
334             if (state.state != previousState
335                     && ((!previousDeviceStatus.isDocked() && deviceStatus.isDocked()) || deviceStatus.isCompleted())) {
336                 // When returning to dock or on its way after completing lawn, refresh last cutting time immediately.
337                 // We cannot fully rely on completed lawn state since active polling refresh interval is configurable
338                 // and we might miss the state if mower returns before next poll.
339                 refreshLastCuttingTime();
340             }
341         } else {
342             previousState = state.state;
343             previousDeviceStatus = DeviceStatus.fromCode(previousState);
344         }
345         previousStateCode = Optional.of(state.state);
346
347         refreshOperatingDataConditionally(
348                 previousDeviceStatus.isCharging() || deviceStatus.isCharging() || deviceStatus.isActive());
349
350         if (lastOperatingDataStatus == ThingStatus.ONLINE && thing.getStatus() != ThingStatus.ONLINE) {
351             // Revert temporary offline status caused by disruptions other than unreachable device.
352             updateStatus(ThingStatus.ONLINE);
353         } else if (lastOperatingDataStatus == ThingStatus.OFFLINE) {
354             // Update description to reflect why thing is still offline.
355             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
356                     "@text/offline.comm-error.unreachable");
357         }
358
359         rescheduleStatePollAccordingToState(deviceStatus);
360     }
361
362     private void refreshDeviceProperties() throws IndegoAuthenticationException, IndegoException {
363         DevicePropertiesResponse deviceProperties = controller.getDeviceProperties();
364         Map<String, String> properties = editProperties();
365         if (deviceProperties.firmwareVersion != null) {
366             properties.put(Thing.PROPERTY_FIRMWARE_VERSION, deviceProperties.firmwareVersion);
367         }
368         if (deviceProperties.bareToolNumber != null) {
369             properties.put(Thing.PROPERTY_MODEL_ID,
370                     IndegoTypeDatabase.nameFromTypeNumber(deviceProperties.bareToolNumber));
371             properties.put(PROPERTY_BARE_TOOL_NUMBER, deviceProperties.bareToolNumber);
372         }
373         properties.put(PROPERTY_SERVICE_COUNTER, String.valueOf(deviceProperties.serviceCounter));
374         properties.put(PROPERTY_NEEDS_SERVICE, String.valueOf(deviceProperties.needsService));
375         properties.put(PROPERTY_RENEW_DATE,
376                 LocalDateTime.ofInstant(deviceProperties.renewDate, timeZoneProvider.getTimeZone()).toString());
377
378         updateProperties(properties);
379         devicePropertiesUpdated = Instant.now();
380     }
381
382     private void rescheduleStatePollAccordingToState(DeviceStatus deviceStatus) {
383         int refreshIntervalSeconds;
384         if (deviceStatus.isActive()) {
385             refreshIntervalSeconds = stateActiveRefreshIntervalSeconds;
386         } else if (deviceStatus.isCharging()) {
387             refreshIntervalSeconds = (int) OPERATING_DATA_ACTIVE_REFRESH_INTERVAL.getSeconds();
388         } else {
389             refreshIntervalSeconds = stateInactiveRefreshIntervalSeconds;
390         }
391         if (rescheduleStatePoll(refreshIntervalSeconds, refreshIntervalSeconds, false)) {
392             // After job has been rescheduled, request operating data one last time on next poll.
393             // This is needed to update battery values after a charging cycle has completed.
394             operatingDataTimestamp = Instant.MIN;
395         }
396     }
397
398     private void refreshOperatingDataConditionally(boolean isActive)
399             throws IndegoAuthenticationException, IndegoTimeoutException, IndegoException {
400         // Refresh operating data only occationally or when robot is active/charging.
401         // This will contact the robot directly through cellular network and wake it up
402         // when sleeping. Additionally, refresh more often after being offline to try to get
403         // back online as soon as possible without putting too much stress on the service.
404         if ((isActive && operatingDataTimestamp.isBefore(Instant.now().minus(OPERATING_DATA_ACTIVE_REFRESH_INTERVAL)))
405                 || (lastOperatingDataStatus != ThingStatus.ONLINE && operatingDataTimestamp
406                         .isBefore(Instant.now().minus(OPERATING_DATA_OFFLINE_REFRESH_INTERVAL)))
407                 || operatingDataTimestamp.isBefore(Instant.now().minus(OPERATING_DATA_INACTIVE_REFRESH_INTERVAL))) {
408             refreshOperatingData();
409         }
410     }
411
412     private void refreshOperatingData() throws IndegoAuthenticationException, IndegoTimeoutException, IndegoException {
413         updateOperatingData(controller.getOperatingData());
414         operatingDataTimestamp = Instant.now();
415         updateStatus(lastOperatingDataStatus = ThingStatus.ONLINE);
416     }
417
418     private void refreshCuttingTimesWithExceptionHandling() {
419         try {
420             refreshLastCuttingTime();
421             refreshNextCuttingTime();
422         } catch (IndegoAuthenticationException e) {
423             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
424                     "@text/offline.comm-error.authentication-failure");
425         } catch (IndegoException e) {
426             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
427         }
428     }
429
430     private void refreshLastCuttingTime() throws IndegoAuthenticationException, IndegoException {
431         if (isLinked(LAST_CUTTING)) {
432             Instant lastCutting = controller.getPredictiveLastCutting();
433             if (lastCutting != null) {
434                 updateState(LAST_CUTTING,
435                         new DateTimeType(ZonedDateTime.ofInstant(lastCutting, timeZoneProvider.getTimeZone())));
436             } else {
437                 updateState(LAST_CUTTING, UnDefType.UNDEF);
438             }
439         }
440     }
441
442     private void refreshNextCuttingTimeWithExceptionHandling() {
443         try {
444             refreshNextCuttingTime();
445         } catch (IndegoAuthenticationException e) {
446             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
447                     "@text/offline.comm-error.authentication-failure");
448         } catch (IndegoException e) {
449             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
450         }
451     }
452
453     private void refreshNextCuttingTime() throws IndegoAuthenticationException, IndegoException {
454         cancelCuttingTimeRefresh();
455         if (isLinked(NEXT_CUTTING)) {
456             Instant nextCutting = controller.getPredictiveNextCutting();
457             if (nextCutting != null) {
458                 updateState(NEXT_CUTTING,
459                         new DateTimeType(ZonedDateTime.ofInstant(nextCutting, timeZoneProvider.getTimeZone())));
460                 scheduleCuttingTimesRefresh(nextCutting);
461             } else {
462                 updateState(NEXT_CUTTING, UnDefType.UNDEF);
463             }
464         }
465     }
466
467     private void cancelCuttingTimeRefresh() {
468         ScheduledFuture<?> cuttingTimeFuture = this.cuttingTimeFuture;
469         if (cuttingTimeFuture != null) {
470             // Do not interrupt as we might be running within that job.
471             cuttingTimeFuture.cancel(false);
472             this.cuttingTimeFuture = null;
473         }
474     }
475
476     private void scheduleCuttingTimesRefresh(Instant nextCutting) {
477         // Schedule additional update right after next planned cutting. This ensures a faster update.
478         long secondsUntilNextCutting = Instant.now().until(nextCutting, ChronoUnit.SECONDS) + 2;
479         if (secondsUntilNextCutting > 0) {
480             logger.debug("Scheduling fetching of next cutting time in {} seconds", secondsUntilNextCutting);
481             this.cuttingTimeFuture = scheduler.schedule(this::refreshNextCuttingTimeWithExceptionHandling,
482                     secondsUntilNextCutting, TimeUnit.SECONDS);
483         }
484     }
485
486     private void refreshMap(int xPos, int yPos) throws IndegoAuthenticationException, IndegoException {
487         if (!isLinked(GARDEN_MAP)) {
488             return;
489         }
490         RawType cachedMap = this.cachedMap;
491         boolean mapRefreshed;
492         if (cachedMap == null || cachedMapTimestamp.isBefore(Instant.now().minus(MAP_REFRESH_INTERVAL))) {
493             this.cachedMap = cachedMap = controller.getMap();
494             cachedMapTimestamp = Instant.now();
495             mapRefreshed = true;
496         } else {
497             mapRefreshed = false;
498         }
499         String svgMap = new String(cachedMap.getBytes(), StandardCharsets.UTF_8);
500         if (!svgMap.endsWith("</svg>")) {
501             if (mapRefreshed) {
502                 logger.warn("Unexpected map format, unable to plot location");
503                 logger.trace("Received map: {}", svgMap);
504                 updateState(GARDEN_MAP, cachedMap);
505             }
506             return;
507         }
508         svgMap = svgMap.substring(0, svgMap.length() - 6) + "<circle cx=\"" + xPos + "\" cy=\"" + yPos + "\" r=\""
509                 + MAP_POSITION_RADIUS + "\" stroke=\"" + MAP_POSITION_STROKE_COLOR + "\" fill=\""
510                 + MAP_POSITION_FILL_COLOR + "\" />\n</svg>";
511         updateState(GARDEN_MAP, new RawType(svgMap.getBytes(), cachedMap.getMimeType()));
512     }
513
514     private void trackPosition() throws IndegoAuthenticationException, IndegoException {
515         if (!isLinked(GARDEN_MAP)) {
516             return;
517         }
518         if (mapRefreshStartedTimestamp.isBefore(Instant.now().minus(MAP_REFRESH_SESSION_DURATION))) {
519             int count = (int) MAP_REFRESH_SESSION_DURATION.getSeconds() / stateActiveRefreshIntervalSeconds + 1;
520             logger.debug("Requesting position updates (count: {}; interval: {}s), previously triggered {}", count,
521                     stateActiveRefreshIntervalSeconds, mapRefreshStartedTimestamp);
522             controller.requestPosition(count, stateActiveRefreshIntervalSeconds);
523             mapRefreshStartedTimestamp = Instant.now();
524         }
525     }
526
527     private void updateState(DeviceStateResponse state) {
528         DeviceStatus deviceStatus = DeviceStatus.fromCode(state.state);
529         DeviceCommand associatedCommand = deviceStatus.getAssociatedCommand();
530         int status = associatedCommand != null ? getStatusFromCommand(associatedCommand) : 0;
531         int mowed = state.mowed;
532         int error = state.error;
533         int statecode = state.state;
534         boolean ready = isReadyToMow(deviceStatus, state.error);
535
536         updateState(STATECODE, new DecimalType(statecode));
537         updateState(READY, new DecimalType(ready ? 1 : 0));
538         updateState(ERRORCODE, new DecimalType(error));
539         updateState(MOWED, new PercentType(mowed));
540         updateState(STATE, new DecimalType(status));
541         updateState(TEXTUAL_STATE, new StringType(deviceStatus.getMessage(translationProvider)));
542     }
543
544     private void updateOperatingData(OperatingDataResponse operatingData) {
545         updateState(BATTERY_VOLTAGE, new QuantityType<>(operatingData.battery.voltage, Units.VOLT));
546         updateState(BATTERY_LEVEL, new DecimalType(operatingData.battery.percent));
547         updateState(LOW_BATTERY, OnOffType.from(operatingData.battery.percent < 20));
548         updateState(BATTERY_TEMPERATURE, new QuantityType<>(operatingData.battery.batteryTemperature, SIUnits.CELSIUS));
549         updateState(GARDEN_SIZE, new QuantityType<>(operatingData.garden.size, SIUnits.SQUARE_METRE));
550     }
551
552     private boolean isReadyToMow(DeviceStatus deviceStatus, int error) {
553         return deviceStatus.isReadyToMow() && error == 0;
554     }
555
556     private boolean verifyCommand(DeviceCommand command, DeviceStatus deviceStatus, int errorCode) {
557         // Mower reported an error
558         if (errorCode != 0) {
559             logger.warn("The mower reported an error.");
560             return false;
561         }
562
563         // Command is equal to current state
564         if (command == deviceStatus.getAssociatedCommand()) {
565             logger.debug("Command is equal to state");
566             return false;
567         }
568         // Can't pause while the mower is docked
569         if (command == DeviceCommand.PAUSE && deviceStatus.getAssociatedCommand() == DeviceCommand.RETURN) {
570             logger.info("Can't pause the mower while it's docked or docking");
571             return false;
572         }
573         // Command means "MOW" but mower is not ready
574         if (command == DeviceCommand.MOW && !isReadyToMow(deviceStatus, errorCode)) {
575             logger.info("The mower is not ready to mow at the moment");
576             return false;
577         }
578         return true;
579     }
580
581     private int getStatusFromCommand(DeviceCommand command) {
582         switch (command) {
583             case MOW:
584                 return 1;
585             case RETURN:
586                 return 2;
587             case PAUSE:
588                 return 3;
589             default:
590                 return 0;
591         }
592     }
593 }