]> git.basschouten.com Git - openhab-addons.git/blob
09e15bd4c79618df592fb34148f8d6c157332bea
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.miio.internal.handler;
14
15 import static org.openhab.binding.miio.internal.MiIoBindingConstants.*;
16
17 import java.io.ByteArrayInputStream;
18 import java.io.ByteArrayOutputStream;
19 import java.io.File;
20 import java.io.IOException;
21 import java.math.BigDecimal;
22 import java.math.BigInteger;
23 import java.time.Instant;
24 import java.time.LocalDateTime;
25 import java.time.ZoneId;
26 import java.time.ZonedDateTime;
27 import java.time.format.DateTimeFormatter;
28 import java.util.Collections;
29 import java.util.Map.Entry;
30 import java.util.Set;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.TimeUnit;
33 import java.util.stream.Collectors;
34 import java.util.stream.Stream;
35
36 import javax.imageio.ImageIO;
37
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.openhab.binding.miio.internal.MiIoBindingConfiguration;
41 import org.openhab.binding.miio.internal.MiIoCommand;
42 import org.openhab.binding.miio.internal.MiIoSendCommand;
43 import org.openhab.binding.miio.internal.basic.MiIoDatabaseWatchService;
44 import org.openhab.binding.miio.internal.cloud.CloudConnector;
45 import org.openhab.binding.miio.internal.cloud.CloudUtil;
46 import org.openhab.binding.miio.internal.cloud.HomeRoomDTO;
47 import org.openhab.binding.miio.internal.cloud.MiCloudException;
48 import org.openhab.binding.miio.internal.robot.ConsumablesType;
49 import org.openhab.binding.miio.internal.robot.DockStatusType;
50 import org.openhab.binding.miio.internal.robot.FanModeType;
51 import org.openhab.binding.miio.internal.robot.HistoryRecordDTO;
52 import org.openhab.binding.miio.internal.robot.RRMapDraw;
53 import org.openhab.binding.miio.internal.robot.RRMapDrawOptions;
54 import org.openhab.binding.miio.internal.robot.RobotCababilities;
55 import org.openhab.binding.miio.internal.robot.StatusDTO;
56 import org.openhab.binding.miio.internal.robot.StatusType;
57 import org.openhab.binding.miio.internal.robot.VacuumErrorType;
58 import org.openhab.binding.miio.internal.transport.MiIoAsyncCommunication;
59 import org.openhab.core.cache.ExpiringCache;
60 import org.openhab.core.i18n.LocaleProvider;
61 import org.openhab.core.i18n.TranslationProvider;
62 import org.openhab.core.library.types.DateTimeType;
63 import org.openhab.core.library.types.DecimalType;
64 import org.openhab.core.library.types.OnOffType;
65 import org.openhab.core.library.types.QuantityType;
66 import org.openhab.core.library.types.RawType;
67 import org.openhab.core.library.types.StringType;
68 import org.openhab.core.library.unit.SIUnits;
69 import org.openhab.core.library.unit.Units;
70 import org.openhab.core.thing.Channel;
71 import org.openhab.core.thing.ChannelUID;
72 import org.openhab.core.thing.Thing;
73 import org.openhab.core.thing.ThingStatusDetail;
74 import org.openhab.core.thing.binding.builder.ChannelBuilder;
75 import org.openhab.core.thing.binding.builder.ThingBuilder;
76 import org.openhab.core.thing.type.ChannelType;
77 import org.openhab.core.thing.type.ChannelTypeRegistry;
78 import org.openhab.core.types.Command;
79 import org.openhab.core.types.RefreshType;
80 import org.openhab.core.types.State;
81 import org.openhab.core.types.UnDefType;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84
85 import com.google.gson.Gson;
86 import com.google.gson.GsonBuilder;
87 import com.google.gson.JsonArray;
88 import com.google.gson.JsonElement;
89 import com.google.gson.JsonObject;
90
91 /**
92  * The {@link MiIoVacuumHandler} is responsible for handling commands, which are
93  * sent to one of the channels.
94  *
95  * @author Marcel Verpaalen - Initial contribution
96  */
97 @NonNullByDefault
98 public class MiIoVacuumHandler extends MiIoAbstractHandler {
99     private final Logger logger = LoggerFactory.getLogger(MiIoVacuumHandler.class);
100     private static final DateTimeFormatter DATEFORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
101     private static final Gson GSON = new GsonBuilder().serializeNulls().create();
102     private final ChannelUID mapChannelUid;
103
104     private static final Set<RobotCababilities> FEATURES_CHANNELS = Collections.unmodifiableSet(Stream.of(
105             RobotCababilities.SEGMENT_STATUS, RobotCababilities.MAP_STATUS, RobotCababilities.LED_STATUS,
106             RobotCababilities.CARPET_MODE, RobotCababilities.FW_FEATURES, RobotCababilities.ROOM_MAPPING,
107             RobotCababilities.MULTI_MAP_LIST, RobotCababilities.CUSTOMIZE_CLEAN_MODE, RobotCababilities.COLLECT_DUST,
108             RobotCababilities.CLEAN_MOP_START, RobotCababilities.CLEAN_MOP_STOP, RobotCababilities.MOP_DRYING,
109             RobotCababilities.MOP_DRYING_REMAINING_TIME, RobotCababilities.DOCK_STATE_ID).collect(Collectors.toSet()));
110
111     private ExpiringCache<String> status;
112     private ExpiringCache<String> consumables;
113     private ExpiringCache<String> dnd;
114     private ExpiringCache<String> history;
115     private int stateId;
116     private ExpiringCache<String> map;
117     private String lastHistoryId = "";
118     private String lastMap = "";
119     private boolean hasChannelStructure;
120     private ConcurrentHashMap<RobotCababilities, Boolean> deviceCapabilities = new ConcurrentHashMap<>();
121     private ChannelTypeRegistry channelTypeRegistry;
122     private RRMapDrawOptions mapDrawOptions = new RRMapDrawOptions();
123
124     public MiIoVacuumHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService,
125             CloudConnector cloudConnector, ChannelTypeRegistry channelTypeRegistry, TranslationProvider i18nProvider,
126             LocaleProvider localeProvider) {
127         super(thing, miIoDatabaseWatchService, cloudConnector, i18nProvider, localeProvider);
128         this.channelTypeRegistry = channelTypeRegistry;
129         mapChannelUid = new ChannelUID(thing.getUID(), CHANNEL_VACUUM_MAP);
130         status = new ExpiringCache<>(CACHE_EXPIRY, () -> {
131             try {
132                 int ret = sendCommand(MiIoCommand.GET_STATUS);
133                 if (ret != 0) {
134                     return "id:" + ret;
135                 }
136             } catch (Exception e) {
137                 logger.debug("Error during status refresh: {}", e.getMessage(), e);
138             }
139             return null;
140         });
141         consumables = new ExpiringCache<>(CACHE_EXPIRY, () -> {
142             try {
143                 int ret = sendCommand(MiIoCommand.CONSUMABLES_GET);
144                 if (ret != 0) {
145                     return "id:" + ret;
146                 }
147             } catch (Exception e) {
148                 logger.debug("Error during consumables refresh: {}", e.getMessage(), e);
149             }
150             return null;
151         });
152         dnd = new ExpiringCache<>(CACHE_EXPIRY, () -> {
153             try {
154                 int ret = sendCommand(MiIoCommand.DND_GET);
155                 if (ret != 0) {
156                     return "id:" + ret;
157                 }
158             } catch (Exception e) {
159                 logger.debug("Error during dnd refresh: {}", e.getMessage(), e);
160             }
161             return null;
162         });
163         history = new ExpiringCache<>(CACHE_EXPIRY, () -> {
164             try {
165                 int ret = sendCommand(MiIoCommand.CLEAN_SUMMARY_GET);
166                 if (ret != 0) {
167                     return "id:" + ret;
168                 }
169             } catch (Exception e) {
170                 logger.debug("Error during cleaning data refresh: {}", e.getMessage(), e);
171             }
172             return null;
173         });
174         map = new ExpiringCache<>(CACHE_EXPIRY, () -> {
175             try {
176                 int ret = sendCommand(MiIoCommand.GET_MAP);
177                 if (ret != 0) {
178                     return "id:" + ret;
179                 }
180             } catch (Exception e) {
181                 logger.debug("Error during dnd refresh: {}", e.getMessage(), e);
182             }
183             return null;
184         });
185     }
186
187     @Override
188     public void handleCommand(ChannelUID channelUID, Command command) {
189         if (getConnection() == null) {
190             logger.debug("Vacuum {} not online. Command {} ignored", getThing().getUID(), command.toString());
191             return;
192         }
193         if (command == RefreshType.REFRESH) {
194             logger.debug("Refreshing {}", channelUID);
195             updateData();
196             lastMap = "";
197             if (channelUID.getId().equals(CHANNEL_VACUUM_MAP)) {
198                 sendCommand(MiIoCommand.GET_MAP);
199             }
200             return;
201         }
202         if (handleCommandsChannels(channelUID, command)) {
203             forceStatusUpdate();
204             return;
205         }
206         if (channelUID.getId().equals(CHANNEL_VACUUM)) {
207             if (command instanceof OnOffType) {
208                 if (command.equals(OnOffType.ON)) {
209                     sendCommand(MiIoCommand.START_VACUUM);
210                     forceStatusUpdate();
211                     return;
212                 } else {
213                     sendCommand(MiIoCommand.STOP_VACUUM);
214                     miIoScheduler.schedule(() -> {
215                         sendCommand(MiIoCommand.CHARGE);
216                         forceStatusUpdate();
217                     }, 2000, TimeUnit.MILLISECONDS);
218                     return;
219                 }
220             }
221         }
222         if (channelUID.getId().equals(CHANNEL_CONTROL)) {
223             if ("vacuum".equals(command.toString())) {
224                 sendCommand(MiIoCommand.START_VACUUM);
225             } else if ("spot".equals(command.toString())) {
226                 sendCommand(MiIoCommand.START_SPOT);
227             } else if ("pause".equals(command.toString())) {
228                 sendCommand(MiIoCommand.PAUSE);
229             } else if ("dock".equals(command.toString())) {
230                 sendCommand(MiIoCommand.STOP_VACUUM);
231                 miIoScheduler.schedule(() -> {
232                     sendCommand(MiIoCommand.CHARGE);
233                     forceStatusUpdate();
234                 }, 2000, TimeUnit.MILLISECONDS);
235                 return;
236             } else {
237                 logger.info("Command {} not recognised", command.toString());
238             }
239             forceStatusUpdate();
240             return;
241         }
242         if (channelUID.getId().equals(CHANNEL_FAN_POWER)) {
243             sendCommand(MiIoCommand.SET_MODE, "[" + command.toString() + "]");
244             forceStatusUpdate();
245             return;
246         }
247
248         if (channelUID.getId().equals(RobotCababilities.WATERBOX_MODE.getChannel())) {
249             sendCommand(MiIoCommand.SET_WATERBOX_MODE, "[" + command.toString() + "]");
250             forceStatusUpdate();
251             return;
252         }
253         if (channelUID.getId().equals(RobotCababilities.SEGMENT_CLEAN.getChannel()) && !command.toString().isEmpty()
254                 && !command.toString().contentEquals("-")) {
255             sendCommand(MiIoCommand.START_SEGMENT, "[" + command.toString() + "]");
256             updateState(RobotCababilities.SEGMENT_CLEAN.getChannel(), new StringType("-"));
257             forceStatusUpdate();
258             return;
259         }
260         if (channelUID.getId().equals(CHANNEL_FAN_CONTROL)) {
261             if (Integer.valueOf(command.toString()) > 0) {
262                 sendCommand(MiIoCommand.SET_MODE, "[" + command.toString() + "]");
263             }
264             forceStatusUpdate();
265             return;
266         }
267         if (channelUID.getId().equals(CHANNEL_CONSUMABLE_RESET)) {
268             sendCommand(MiIoCommand.CONSUMABLES_RESET, "[" + command.toString() + "]");
269             updateState(CHANNEL_CONSUMABLE_RESET, new StringType("none"));
270         }
271
272         if (channelUID.getId().equals(RobotCababilities.COLLECT_DUST.getChannel()) && !command.toString().isEmpty()
273                 && !command.toString().contentEquals("-")) {
274             sendCommand(MiIoCommand.SET_COLLECT_DUST);
275             forceStatusUpdate();
276             return;
277         }
278
279         if (channelUID.getId().equals(RobotCababilities.CLEAN_MOP_START.getChannel()) && !command.toString().isEmpty()
280                 && !command.toString().contentEquals("-")) {
281             sendCommand(MiIoCommand.SET_CLEAN_MOP_START);
282             forceStatusUpdate();
283             return;
284         }
285         if (channelUID.getId().equals(RobotCababilities.CLEAN_MOP_STOP.getChannel()) && !command.toString().isEmpty()
286                 && !command.toString().contentEquals("-")) {
287             sendCommand(MiIoCommand.SET_CLEAN_MOP_STOP);
288             forceStatusUpdate();
289             return;
290         }
291     }
292
293     private void forceStatusUpdate() {
294         status.invalidateValue();
295         miIoScheduler.schedule(() -> {
296             status.getValue();
297         }, 3000, TimeUnit.MILLISECONDS);
298     }
299
300     private void safeUpdateState(String channelID, @Nullable Integer state) {
301         if (state != null) {
302             updateState(channelID, new DecimalType(state));
303         } else {
304             logger.debug("Channel {} not update. value not available.", channelID);
305         }
306     }
307
308     private boolean updateVacuumStatus(JsonObject statusData) {
309         StatusDTO statusInfo = GSON.fromJson(statusData, StatusDTO.class);
310         if (statusInfo == null) {
311             return false;
312         }
313         safeUpdateState(CHANNEL_BATTERY, statusInfo.getBattery());
314         if (statusInfo.getCleanArea() != null) {
315             updateState(CHANNEL_CLEAN_AREA,
316                     new QuantityType<>(statusInfo.getCleanArea() / 1000000.0, SIUnits.SQUARE_METRE));
317         }
318         if (statusInfo.getCleanTime() != null) {
319             updateState(CHANNEL_CLEAN_TIME,
320                     new QuantityType<>(TimeUnit.SECONDS.toMinutes(statusInfo.getCleanTime()), Units.MINUTE));
321         }
322         safeUpdateState(CHANNEL_DND_ENABLED, statusInfo.getDndEnabled());
323
324         if (statusInfo.getErrorCode() != null) {
325             updateState(CHANNEL_ERROR_CODE,
326                     new StringType(VacuumErrorType.getType(statusInfo.getErrorCode()).getDescription()));
327             safeUpdateState(CHANNEL_ERROR_ID, statusInfo.getErrorCode());
328         }
329
330         if (statusInfo.getFanPower() != null) {
331             updateState(CHANNEL_FAN_POWER, new DecimalType(statusInfo.getFanPower()));
332             updateState(CHANNEL_FAN_CONTROL, new DecimalType(FanModeType.getType(statusInfo.getFanPower()).getId()));
333         }
334         safeUpdateState(CHANNEL_IN_CLEANING, statusInfo.getInCleaning());
335         safeUpdateState(CHANNEL_MAP_PRESENT, statusInfo.getMapPresent());
336         if (statusInfo.getState() != null) {
337             stateId = statusInfo.getState();
338             StatusType state = StatusType.getType(statusInfo.getState());
339             updateState(CHANNEL_STATE, new StringType(state.getDescription()));
340             updateState(CHANNEL_STATE_ID, new DecimalType(statusInfo.getState()));
341
342             State vacuum = OnOffType.OFF;
343             String control;
344             switch (state) {
345                 case ZONE:
346                 case ROOM:
347                 case CLEANING:
348                 case RETURNING:
349                     control = "vacuum";
350                     vacuum = OnOffType.ON;
351                     break;
352                 case CHARGING:
353                 case CHARGING_ERROR:
354                 case DOCKING:
355                 case FULL:
356                     control = "dock";
357                     break;
358                 case SLEEPING:
359                 case PAUSED:
360                 case IDLE:
361                     control = "pause";
362                     break;
363                 case SPOTCLEAN:
364                     control = "spot";
365                     vacuum = OnOffType.ON;
366                     break;
367                 default:
368                     control = "undef";
369                     break;
370             }
371             if ("undef".equals(control)) {
372                 updateState(CHANNEL_CONTROL, UnDefType.UNDEF);
373             } else {
374                 updateState(CHANNEL_CONTROL, new StringType(control));
375             }
376             updateState(CHANNEL_VACUUM, vacuum);
377         }
378         if (this.deviceCapabilities.containsKey(RobotCababilities.DOCK_STATE_ID)) {
379             DockStatusType state = DockStatusType.getType(statusInfo.getDockErrorStatus().intValue());
380             updateState(CHANNEL_DOCK_STATE, new StringType(state.getDescription()));
381             updateState(CHANNEL_DOCK_STATE_ID, new DecimalType(state.getId()));
382         }
383         if (deviceCapabilities.containsKey(RobotCababilities.WATERBOX_MODE)) {
384             safeUpdateState(RobotCababilities.WATERBOX_MODE.getChannel(), statusInfo.getWaterBoxMode());
385         }
386         if (deviceCapabilities.containsKey(RobotCababilities.WATERBOX_STATUS)) {
387             safeUpdateState(RobotCababilities.WATERBOX_STATUS.getChannel(), statusInfo.getWaterBoxStatus());
388         }
389         if (deviceCapabilities.containsKey(RobotCababilities.WATERBOX_CARRIAGE)) {
390             safeUpdateState(RobotCababilities.WATERBOX_CARRIAGE.getChannel(), statusInfo.getWaterBoxCarriageStatus());
391         }
392         if (deviceCapabilities.containsKey(RobotCababilities.LOCKSTATUS)) {
393             safeUpdateState(RobotCababilities.LOCKSTATUS.getChannel(), statusInfo.getLockStatus());
394         }
395         if (deviceCapabilities.containsKey(RobotCababilities.MOP_FORBIDDEN)) {
396             safeUpdateState(RobotCababilities.MOP_FORBIDDEN.getChannel(), statusInfo.getMopForbiddenEnable());
397         }
398         if (deviceCapabilities.containsKey(RobotCababilities.LOCATING)) {
399             safeUpdateState(RobotCababilities.LOCATING.getChannel(), statusInfo.getIsLocating());
400         }
401         if (deviceCapabilities.containsKey(RobotCababilities.CLEAN_MOP_START)) {
402             safeUpdateState(RobotCababilities.CLEAN_MOP_START.getChannel(), 0);
403         }
404         if (deviceCapabilities.containsKey(RobotCababilities.CLEAN_MOP_STOP)) {
405             safeUpdateState(RobotCababilities.CLEAN_MOP_STOP.getChannel(), 0);
406         }
407         if (deviceCapabilities.containsKey(RobotCababilities.COLLECT_DUST)) {
408             safeUpdateState(RobotCababilities.COLLECT_DUST.getChannel(), 0);
409         }
410         if (deviceCapabilities.containsKey(RobotCababilities.MOP_DRYING)) {
411             safeUpdateState(RobotCababilities.MOP_DRYING.getChannel(), statusInfo.getIsMopDryingActive());
412         }
413         if (deviceCapabilities.containsKey(RobotCababilities.MOP_DRYING_REMAINING_TIME)) {
414             updateState(CHANNEL_MOP_TOTALDRYTIME,
415                     new QuantityType<>(TimeUnit.SECONDS.toMinutes(statusInfo.getMopDryTime()), Units.MINUTE));
416         }
417         return true;
418     }
419
420     private boolean updateConsumables(JsonObject consumablesData) {
421         int mainBrush = consumablesData.get("main_brush_work_time").getAsInt();
422         int sideBrush = consumablesData.get("side_brush_work_time").getAsInt();
423         int filter = consumablesData.get("filter_work_time").getAsInt();
424         int sensor = consumablesData.get("sensor_dirty_time").getAsInt();
425         updateState(CHANNEL_CONSUMABLE_MAIN_TIME,
426                 new QuantityType<>(ConsumablesType.remainingHours(mainBrush, ConsumablesType.MAIN_BRUSH), Units.HOUR));
427         updateState(CHANNEL_CONSUMABLE_MAIN_PERC,
428                 new DecimalType(ConsumablesType.remainingPercent(mainBrush, ConsumablesType.MAIN_BRUSH)));
429         updateState(CHANNEL_CONSUMABLE_SIDE_TIME,
430                 new QuantityType<>(ConsumablesType.remainingHours(sideBrush, ConsumablesType.SIDE_BRUSH), Units.HOUR));
431         updateState(CHANNEL_CONSUMABLE_SIDE_PERC,
432                 new DecimalType(ConsumablesType.remainingPercent(sideBrush, ConsumablesType.SIDE_BRUSH)));
433         updateState(CHANNEL_CONSUMABLE_FILTER_TIME,
434                 new QuantityType<>(ConsumablesType.remainingHours(filter, ConsumablesType.FILTER), Units.HOUR));
435         updateState(CHANNEL_CONSUMABLE_FILTER_PERC,
436                 new DecimalType(ConsumablesType.remainingPercent(filter, ConsumablesType.FILTER)));
437         updateState(CHANNEL_CONSUMABLE_SENSOR_TIME,
438                 new QuantityType<>(ConsumablesType.remainingHours(sensor, ConsumablesType.SENSOR), Units.HOUR));
439         updateState(CHANNEL_CONSUMABLE_SENSOR_PERC,
440                 new DecimalType(ConsumablesType.remainingPercent(sensor, ConsumablesType.SENSOR)));
441         return true;
442     }
443
444     private boolean updateDnD(JsonObject dndData) {
445         logger.trace("Do not disturb data: {}", dndData.toString());
446         updateState(CHANNEL_DND_FUNCTION, new DecimalType(dndData.get("enabled").getAsBigDecimal()));
447         updateState(CHANNEL_DND_START, new StringType(String.format("%02d:%02d", dndData.get("start_hour").getAsInt(),
448                 dndData.get("start_minute").getAsInt())));
449         updateState(CHANNEL_DND_END, new StringType(
450                 String.format("%02d:%02d", dndData.get("end_hour").getAsInt(), dndData.get("end_minute").getAsInt())));
451         return true;
452     }
453
454     private boolean updateHistoryLegacy(JsonArray historyData) {
455         logger.trace("Cleaning history data: {}", historyData.toString());
456         updateState(CHANNEL_HISTORY_TOTALTIME,
457                 new QuantityType<>(TimeUnit.SECONDS.toMinutes(historyData.get(0).getAsLong()), Units.MINUTE));
458         updateState(CHANNEL_HISTORY_TOTALAREA,
459                 new QuantityType<>(historyData.get(1).getAsDouble() / 1000000D, SIUnits.SQUARE_METRE));
460         updateState(CHANNEL_HISTORY_COUNT, new DecimalType(historyData.get(2).toString()));
461         if (historyData.get(3).getAsJsonArray().size() > 0) {
462             String lastClean = historyData.get(3).getAsJsonArray().get(0).getAsString();
463             if (!lastClean.equals(lastHistoryId)) {
464                 lastHistoryId = lastClean;
465                 sendCommand(MiIoCommand.CLEAN_RECORD_GET, "[" + lastClean + "]");
466             }
467         }
468         return true;
469     }
470
471     private boolean updateHistory(JsonObject historyData) {
472         logger.trace("Cleaning history data: {}", historyData);
473         if (historyData.has("clean_time")) {
474             updateState(CHANNEL_HISTORY_TOTALTIME, new QuantityType<>(
475                     TimeUnit.SECONDS.toMinutes(historyData.get("clean_time").getAsLong()), Units.MINUTE));
476         }
477         if (historyData.has("clean_area")) {
478             updateState(CHANNEL_HISTORY_TOTALAREA,
479                     new QuantityType<>(historyData.get("clean_area").getAsDouble() / 1000000D, SIUnits.SQUARE_METRE));
480         }
481         if (historyData.has("clean_count")) {
482             updateState(CHANNEL_HISTORY_COUNT, new DecimalType(historyData.get("clean_count").getAsLong()));
483         }
484         if (historyData.has("records") & historyData.get("records").isJsonArray()) {
485             JsonArray historyRecords = historyData.get("records").getAsJsonArray();
486             if (!historyRecords.isEmpty()) {
487                 String lastClean = historyRecords.get(0).getAsString();
488                 if (!lastClean.equals(lastHistoryId)) {
489                     lastHistoryId = lastClean;
490                     sendCommand(MiIoCommand.CLEAN_RECORD_GET, "[" + lastClean + "]");
491                 }
492             }
493         }
494         return true;
495     }
496
497     private void updateHistoryRecordLegacy(JsonArray historyData) {
498         HistoryRecordDTO historyRecord = new HistoryRecordDTO();
499         for (int i = 0; i < historyData.size(); ++i) {
500             try {
501                 BigInteger value = historyData.get(i).getAsBigInteger();
502                 switch (i) {
503                     case 0:
504                         historyRecord.setStart(ZonedDateTime
505                                 .ofInstant(Instant.ofEpochSecond(value.longValue()), ZoneId.systemDefault())
506                                 .toString());
507                         break;
508                     case 1:
509                         historyRecord.setStart(ZonedDateTime
510                                 .ofInstant(Instant.ofEpochSecond(value.longValue()), ZoneId.systemDefault())
511                                 .toString());
512                         break;
513                     case 2:
514                         historyRecord.setDuration(value.intValue());
515                         break;
516                     case 3:
517                         historyRecord.setArea(new BigDecimal(value).divide(BigDecimal.valueOf(1000000)));
518                         break;
519                     case 4:
520                         historyRecord.setError(value.intValue());
521                         break;
522                     case 5:
523                         historyRecord.setFinished(value.intValue());
524                         break;
525                     case 6:
526                         historyRecord.setStartType(value.intValue());
527                         break;
528                     case 7:
529                         historyRecord.setCleanType(value.intValue());
530                         break;
531                     case 8:
532                         historyRecord.setFinishReason(value.intValue());
533                         break;
534                 }
535             } catch (ClassCastException | NumberFormatException | IllegalStateException e) {
536             }
537         }
538         updateHistoryRecord(historyRecord);
539     }
540
541     private void updateHistoryRecord(HistoryRecordDTO historyRecordDTO) {
542         JsonObject historyRecord = GSON.toJsonTree(historyRecordDTO).getAsJsonObject();
543         if (historyRecordDTO.getStart() != null) {
544             historyRecord.addProperty("start", historyRecordDTO.getStart().split("\\+")[0].split("\\-")[0]);
545             updateState(CHANNEL_HISTORY_START_TIME,
546                     new DateTimeType(historyRecordDTO.getStart().split("\\+")[0].split("\\-")[0]));
547         }
548         if (historyRecordDTO.getEnd() != null) {
549             historyRecord.addProperty("end", historyRecordDTO.getEnd().split("\\+")[0].split("\\-")[0]);
550             updateState(CHANNEL_HISTORY_END_TIME,
551                     new DateTimeType(historyRecordDTO.getEnd().split("\\+")[0].split("\\-")[0]));
552         }
553         if (historyRecordDTO.getDuration() != null) {
554             long duration = TimeUnit.SECONDS.toMinutes(historyRecordDTO.getDuration().longValue());
555             historyRecord.addProperty("duration", duration);
556             updateState(CHANNEL_HISTORY_DURATION, new QuantityType<>(duration, Units.MINUTE));
557         }
558         if (historyRecordDTO.getArea() != null) {
559             historyRecord.addProperty("area", historyRecordDTO.getArea());
560             updateState(CHANNEL_HISTORY_AREA, new QuantityType<>(historyRecordDTO.getArea(), SIUnits.SQUARE_METRE));
561         }
562         if (historyRecordDTO.getError() != null) {
563             historyRecord.addProperty("error", historyRecordDTO.getError());
564             updateState(CHANNEL_HISTORY_ERROR, new DecimalType(historyRecordDTO.getError()));
565         }
566         if (historyRecordDTO.getFinished() != null) {
567             historyRecord.addProperty("finished", historyRecordDTO.getFinished());
568             updateState(CHANNEL_HISTORY_FINISH, new DecimalType(historyRecordDTO.getFinished()));
569         }
570         if (historyRecordDTO.getFinishReason() != null) {
571             historyRecord.addProperty("finish_reason", historyRecordDTO.getFinishReason());
572             updateState(CHANNEL_HISTORY_FINISHREASON, new DecimalType(historyRecordDTO.getFinishReason()));
573         }
574         if (historyRecordDTO.getDustCollectionStatus() != null) {
575             historyRecord.addProperty("dust_collection_status", historyRecordDTO.getDustCollectionStatus());
576             updateState(CHANNEL_HISTORY_DUSTCOLLECTION, new DecimalType(historyRecordDTO.getDustCollectionStatus()));
577         }
578         updateState(CHANNEL_HISTORY_RECORD, new StringType(historyRecord.toString()));
579     }
580
581     private void updateRoomMapping(MiIoSendCommand response) {
582         for (RobotCababilities cmd : FEATURES_CHANNELS) {
583             if (response.getCommand().getCommand().contentEquals(cmd.getCommand())) {
584                 if (response.getResult().isJsonArray()) {
585                     JsonArray rooms = response.getResult().getAsJsonArray();
586                     JsonArray mappedRoom = new JsonArray();
587                     for (JsonElement roomE : rooms) {
588                         JsonArray room = roomE.getAsJsonArray();
589                         HomeRoomDTO name = cloudConnector.getRoom(room.get(1).getAsString());
590                         if (name != null && name.getName() != null) {
591                             room.add(name.getName());
592                         } else {
593                             room.add("not found");
594                         }
595                         mappedRoom.add(room);
596                     }
597                     updateState(cmd.getChannel(), new StringType(mappedRoom.toString()));
598                 } else {
599                     updateState(cmd.getChannel(), new StringType(response.getResult().toString()));
600                 }
601                 break;
602             }
603         }
604     }
605
606     @Override
607     protected boolean skipUpdate() {
608         if (!hasConnection()) {
609             logger.debug("Skipping periodic update for '{}'. No Connection", getThing().getUID().toString());
610             return true;
611         }
612         if (ThingStatusDetail.CONFIGURATION_ERROR.equals(getThing().getStatusInfo().getStatusDetail())) {
613             logger.debug("Skipping periodic update for '{}' UID '{}'. Thing Status", getThing().getUID().toString(),
614                     getThing().getStatusInfo().getStatusDetail());
615             refreshNetwork();
616             return true;
617         }
618         final MiIoAsyncCommunication mc = miioCom;
619         if (mc != null && mc.getQueueLength() > MAX_QUEUE) {
620             logger.debug("Skipping periodic update for '{}'. {} elements in queue.", getThing().getUID().toString(),
621                     mc.getQueueLength());
622             return true;
623         }
624         return false;
625     }
626
627     @Override
628     protected synchronized void updateData() {
629         if (!hasConnection() || skipUpdate()) {
630             return;
631         }
632         logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
633         try {
634             dnd.getValue();
635             history.getValue();
636             status.getValue();
637             refreshNetwork();
638             consumables.getValue();
639             if (lastMap.isEmpty() || stateId != 8) {
640                 if (isLinked(mapChannelUid)) {
641                     map.getValue();
642                 }
643             }
644             for (RobotCababilities cmd : FEATURES_CHANNELS) {
645                 if (isLinked(cmd.getChannel()) && !cmd.getCommand().isBlank()) {
646                     sendCommand(cmd.getCommand());
647                 }
648             }
649         } catch (Exception e) {
650             logger.debug("Error while updating '{}': '{}", getThing().getUID().toString(), e.getLocalizedMessage());
651         }
652     }
653
654     @Override
655     public void initialize() {
656         super.initialize();
657         hasChannelStructure = false;
658         this.mapDrawOptions = RRMapDrawOptions
659                 .getOptionsFromFile(BINDING_USERDATA_PATH + File.separator + "mapConfig.json", logger);
660         updateState(RobotCababilities.SEGMENT_CLEAN.getChannel(), new StringType("-"));
661         cloudConnector.getHomeLists();
662     }
663
664     @Override
665     protected boolean initializeData() {
666         updateState(CHANNEL_CONSUMABLE_RESET, new StringType("none"));
667         return super.initializeData();
668     }
669
670     @Override
671     public void onMessageReceived(MiIoSendCommand response) {
672         super.onMessageReceived(response);
673         if (response.isError()) {
674             return;
675         }
676         switch (response.getCommand()) {
677             case GET_STATUS:
678                 if (response.getResult().isJsonArray()) {
679                     JsonObject statusResponse = response.getResult().getAsJsonArray().get(0).getAsJsonObject();
680                     if (!hasChannelStructure) {
681                         setCapabilities(statusResponse);
682                         createCapabilityChannels();
683                     }
684                     updateVacuumStatus(statusResponse);
685                 }
686                 break;
687             case CONSUMABLES_GET:
688                 if (response.getResult().isJsonArray()) {
689                     updateConsumables(response.getResult().getAsJsonArray().get(0).getAsJsonObject());
690                 }
691                 break;
692             case DND_GET:
693                 if (response.getResult().isJsonArray()) {
694                     updateDnD(response.getResult().getAsJsonArray().get(0).getAsJsonObject());
695                 }
696                 break;
697             case CLEAN_SUMMARY_GET:
698                 if (response.getResult().isJsonArray()) {
699                     updateHistoryLegacy(response.getResult().getAsJsonArray());
700                 } else if (response.getResult().isJsonObject()) {
701                     updateHistory(response.getResult().getAsJsonObject());
702                 }
703                 break;
704             case CLEAN_RECORD_GET:
705                 if (response.getResult().isJsonArray() && response.getResult().getAsJsonArray().size() > 0
706                         && response.getResult().getAsJsonArray().get(0).isJsonArray()) {
707                     updateHistoryRecordLegacy(response.getResult().getAsJsonArray().get(0).getAsJsonArray());
708                 } else if (response.getResult().isJsonArray() && response.getResult().getAsJsonArray().size() > 0
709                         && response.getResult().getAsJsonArray().get(0).isJsonObject()) {
710                     final HistoryRecordDTO historyRecordDTO = GSON.fromJson(
711                             response.getResult().getAsJsonArray().get(0).getAsJsonObject(), HistoryRecordDTO.class);
712                     if (historyRecordDTO != null) {
713                         updateHistoryRecord(historyRecordDTO);
714                     }
715                 } else if (response.getResult().isJsonObject()) {
716                     final HistoryRecordDTO historyRecordDTO = GSON.fromJson(response.getResult().getAsJsonObject(),
717                             HistoryRecordDTO.class);
718                     if (historyRecordDTO != null) {
719                         updateHistoryRecord(historyRecordDTO);
720                     }
721                 } else {
722                     logger.debug("Could not extract cleaning history record from: {}", response.getResult());
723                 }
724                 break;
725             case GET_MAP:
726                 if (response.getResult().isJsonArray()) {
727                     String mapresponse = response.getResult().getAsJsonArray().get(0).getAsString();
728                     if (!mapresponse.contentEquals("retry") && !mapresponse.contentEquals(lastMap)) {
729                         lastMap = mapresponse;
730                         miIoScheduler.submit(() -> updateState(CHANNEL_VACUUM_MAP, getMap(mapresponse)));
731                     }
732                 }
733                 break;
734             case GET_MAP_STATUS:
735             case GET_SEGMENT_STATUS:
736             case GET_LED_STATUS:
737                 updateNumericChannel(response);
738                 break;
739             case GET_ROOM_MAPPING:
740                 updateRoomMapping(response);
741                 break;
742             case GET_CARPET_MODE:
743             case GET_FW_FEATURES:
744             case GET_CUSTOMIZED_CLEAN_MODE:
745             case GET_MULTI_MAP_LIST:
746             case SET_COLLECT_DUST:
747             case SET_CLEAN_MOP_START:
748             case SET_CLEAN_MOP_STOP:
749                 for (RobotCababilities cmd : FEATURES_CHANNELS) {
750                     if (response.getCommand().getCommand().contentEquals(cmd.getCommand())) {
751                         updateState(cmd.getChannel(), new StringType(response.getResult().toString()));
752                         break;
753                     }
754                 }
755                 break;
756             default:
757                 break;
758         }
759     }
760
761     private void updateNumericChannel(MiIoSendCommand response) {
762         RobotCababilities capabilityChannel = null;
763         for (RobotCababilities cmd : FEATURES_CHANNELS) {
764             if (response.getCommand().getCommand().contentEquals(cmd.getCommand())) {
765                 capabilityChannel = cmd;
766                 break;
767             }
768         }
769         if (capabilityChannel != null) {
770             if (response.getResult().isJsonArray() && response.getResult().getAsJsonArray().get(0).isJsonPrimitive()) {
771                 try {
772                     Integer stat = response.getResult().getAsJsonArray().get(0).getAsInt();
773                     updateState(capabilityChannel.getChannel(), new DecimalType(stat));
774                     return;
775                 } catch (ClassCastException | IllegalStateException e) {
776                     logger.debug("Could not update numeric channel {} with '{}': {}", capabilityChannel.getChannel(),
777                             response.getResult(), e.getMessage());
778                 }
779             } else {
780                 logger.debug("Could not update numeric channel {} with '{}': Not in expected format",
781                         capabilityChannel.getChannel(), response.getResult());
782             }
783             updateState(capabilityChannel.getChannel(), UnDefType.UNDEF);
784         }
785     }
786
787     private void setCapabilities(JsonObject statusResponse) {
788         for (RobotCababilities capability : RobotCababilities.values()) {
789             if (statusResponse.has(capability.getStatusFieldName())) {
790                 deviceCapabilities.putIfAbsent(capability, false);
791                 logger.debug("Setting additional vacuum {}", capability);
792             }
793         }
794     }
795
796     private void createCapabilityChannels() {
797         ThingBuilder thingBuilder = editThing();
798         int cnt = 0;
799
800         for (Entry<RobotCababilities, Boolean> robotCapability : deviceCapabilities.entrySet()) {
801             RobotCababilities capability = robotCapability.getKey();
802             Boolean channelCreated = robotCapability.getValue();
803             if (!channelCreated) {
804                 if (thing.getChannels().stream()
805                         .anyMatch(ch -> ch.getUID().getId().equalsIgnoreCase(capability.getChannel()))) {
806                     logger.debug("Channel already available...skip creation of channel '{}'.", capability.getChannel());
807                     deviceCapabilities.replace(capability, true);
808                     continue;
809                 }
810                 logger.debug("Creating dynamic channel for capability {}", capability);
811                 ChannelType channelType = channelTypeRegistry.getChannelType(capability.getChannelType());
812                 if (channelType != null) {
813                     logger.debug("Found channelType '{}' for capability {}", channelType, capability.name());
814                     ChannelUID channelUID = new ChannelUID(getThing().getUID(), capability.getChannel());
815                     Channel channel = ChannelBuilder.create(channelUID, channelType.getItemType())
816                             .withType(capability.getChannelType()).withLabel(channelType.getLabel()).build();
817                     thingBuilder.withChannel(channel);
818                     cnt++;
819                 } else {
820                     logger.debug("ChannelType {} not found (Unexpected). Available types:",
821                             capability.getChannelType());
822                     for (ChannelType ct : channelTypeRegistry.getChannelTypes()) {
823                         logger.debug("Available channelType: '{}' '{}' '{}'", ct.getUID(), ct.toString(),
824                                 ct.getConfigDescriptionURI());
825                     }
826                 }
827             }
828         }
829         if (cnt > 0) {
830             updateThing(thingBuilder.build());
831         }
832         hasChannelStructure = true;
833     }
834
835     private State getMap(String map) {
836         final MiIoBindingConfiguration configuration = this.configuration;
837         if (configuration != null && cloudConnector.isConnected()) {
838             try {
839                 final @Nullable RawType mapDl = cloudConnector.getMap(map, configuration.cloudServer);
840                 if (mapDl != null) {
841                     byte[] mapData = mapDl.getBytes();
842                     RRMapDraw rrMap = RRMapDraw.loadImage(new ByteArrayInputStream(mapData));
843                     rrMap.setDrawOptions(mapDrawOptions);
844                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
845                     if (logger.isDebugEnabled()) {
846                         final String mapPath = BINDING_USERDATA_PATH + File.separator + map
847                                 + LocalDateTime.now().format(DATEFORMATTER) + ".rrmap";
848                         CloudUtil.writeBytesToFileNio(mapData, mapPath);
849                         logger.debug("Mapdata saved to {}", mapPath);
850                     }
851                     ImageIO.write(rrMap.getImage(), "jpg", baos);
852                     byte[] byteArray = baos.toByteArray();
853                     if (byteArray != null && byteArray.length > 0) {
854                         return new RawType(byteArray, "image/jpeg");
855                     } else {
856                         logger.debug("Mapdata empty removing image");
857                         return UnDefType.UNDEF;
858                     }
859                 }
860             } catch (MiCloudException e) {
861                 logger.debug("Error getting data from Xiaomi cloud. Mapdata could not be updated: {}", e.getMessage());
862             } catch (IOException e) {
863                 logger.debug("Mapdata could not be updated: {}", e.getMessage());
864             }
865         } else {
866             logger.debug("Not connected to Xiaomi cloud. Cannot retreive new map: {}", map);
867         }
868         return UnDefType.UNDEF;
869     }
870 }