]> git.basschouten.com Git - openhab-addons.git/blob
df76917b550c82a26b8b9a8cd370c5e06ac594b7
[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.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<String>(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]);
545             updateState(CHANNEL_HISTORY_START_TIME, new DateTimeType(historyRecordDTO.getStart().split("\\+")[0]));
546         }
547         if (historyRecordDTO.getEnd() != null) {
548             historyRecord.addProperty("end", historyRecordDTO.getEnd().split("\\+")[0]);
549             updateState(CHANNEL_HISTORY_END_TIME, new DateTimeType(historyRecordDTO.getEnd().split("\\+")[0]));
550         }
551         if (historyRecordDTO.getDuration() != null) {
552             long duration = TimeUnit.SECONDS.toMinutes(historyRecordDTO.getDuration().longValue());
553             historyRecord.addProperty("duration", duration);
554             updateState(CHANNEL_HISTORY_DURATION, new QuantityType<>(duration, Units.MINUTE));
555         }
556         if (historyRecordDTO.getArea() != null) {
557             historyRecord.addProperty("area", historyRecordDTO.getArea());
558             updateState(CHANNEL_HISTORY_AREA, new QuantityType<>(historyRecordDTO.getArea(), SIUnits.SQUARE_METRE));
559         }
560         if (historyRecordDTO.getError() != null) {
561             historyRecord.addProperty("error", historyRecordDTO.getError());
562             updateState(CHANNEL_HISTORY_ERROR, new DecimalType(historyRecordDTO.getError()));
563         }
564         if (historyRecordDTO.getFinished() != null) {
565             historyRecord.addProperty("finished", historyRecordDTO.getFinished());
566             updateState(CHANNEL_HISTORY_FINISH, new DecimalType(historyRecordDTO.getFinished()));
567         }
568         if (historyRecordDTO.getFinishReason() != null) {
569             historyRecord.addProperty("finish_reason", historyRecordDTO.getFinishReason());
570             updateState(CHANNEL_HISTORY_FINISHREASON, new DecimalType(historyRecordDTO.getFinishReason()));
571         }
572         if (historyRecordDTO.getDustCollectionStatus() != null) {
573             historyRecord.addProperty("dust_collection_status", historyRecordDTO.getDustCollectionStatus());
574             updateState(CHANNEL_HISTORY_DUSTCOLLECTION, new DecimalType(historyRecordDTO.getDustCollectionStatus()));
575         }
576         updateState(CHANNEL_HISTORY_RECORD, new StringType(historyRecord.toString()));
577     }
578
579     private void updateRoomMapping(MiIoSendCommand response) {
580         for (RobotCababilities cmd : FEATURES_CHANNELS) {
581             if (response.getCommand().getCommand().contentEquals(cmd.getCommand())) {
582                 if (response.getResult().isJsonArray()) {
583                     JsonArray rooms = response.getResult().getAsJsonArray();
584                     JsonArray mappedRoom = new JsonArray();
585                     for (JsonElement roomE : rooms) {
586                         JsonArray room = roomE.getAsJsonArray();
587                         HomeRoomDTO name = cloudConnector.getRoom(room.get(1).getAsString());
588                         if (name != null && name.getName() != null) {
589                             room.add(name.getName());
590                         } else {
591                             room.add("not found");
592                         }
593                         mappedRoom.add(room);
594                     }
595                     updateState(cmd.getChannel(), new StringType(mappedRoom.toString()));
596                 } else {
597                     updateState(cmd.getChannel(), new StringType(response.getResult().toString()));
598                 }
599                 break;
600             }
601         }
602     }
603
604     @Override
605     protected boolean skipUpdate() {
606         if (!hasConnection()) {
607             logger.debug("Skipping periodic update for '{}'. No Connection", getThing().getUID().toString());
608             return true;
609         }
610         if (ThingStatusDetail.CONFIGURATION_ERROR.equals(getThing().getStatusInfo().getStatusDetail())) {
611             logger.debug("Skipping periodic update for '{}' UID '{}'. Thing Status", getThing().getUID().toString(),
612                     getThing().getStatusInfo().getStatusDetail());
613             refreshNetwork();
614             return true;
615         }
616         final MiIoAsyncCommunication mc = miioCom;
617         if (mc != null && mc.getQueueLength() > MAX_QUEUE) {
618             logger.debug("Skipping periodic update for '{}'. {} elements in queue.", getThing().getUID().toString(),
619                     mc.getQueueLength());
620             return true;
621         }
622         return false;
623     }
624
625     @Override
626     protected synchronized void updateData() {
627         if (!hasConnection() || skipUpdate()) {
628             return;
629         }
630         logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
631         try {
632             dnd.getValue();
633             history.getValue();
634             status.getValue();
635             refreshNetwork();
636             consumables.getValue();
637             if (lastMap.isEmpty() || stateId != 8) {
638                 if (isLinked(mapChannelUid)) {
639                     map.getValue();
640                 }
641             }
642             for (RobotCababilities cmd : FEATURES_CHANNELS) {
643                 if (isLinked(cmd.getChannel())) {
644                     sendCommand(cmd.getCommand());
645                 }
646             }
647         } catch (Exception e) {
648             logger.debug("Error while updating '{}': '{}", getThing().getUID().toString(), e.getLocalizedMessage());
649         }
650     }
651
652     @Override
653     public void initialize() {
654         super.initialize();
655         hasChannelStructure = false;
656         this.mapDrawOptions = RRMapDrawOptions
657                 .getOptionsFromFile(BINDING_USERDATA_PATH + File.separator + "mapConfig.json", logger);
658         updateState(RobotCababilities.SEGMENT_CLEAN.getChannel(), new StringType("-"));
659         cloudConnector.getHomeLists();
660     }
661
662     @Override
663     protected boolean initializeData() {
664         updateState(CHANNEL_CONSUMABLE_RESET, new StringType("none"));
665         return super.initializeData();
666     }
667
668     @Override
669     public void onMessageReceived(MiIoSendCommand response) {
670         super.onMessageReceived(response);
671         if (response.isError()) {
672             return;
673         }
674         switch (response.getCommand()) {
675             case GET_STATUS:
676                 if (response.getResult().isJsonArray()) {
677                     JsonObject statusResponse = response.getResult().getAsJsonArray().get(0).getAsJsonObject();
678                     if (!hasChannelStructure) {
679                         setCapabilities(statusResponse);
680                         createCapabilityChannels();
681                     }
682                     updateVacuumStatus(statusResponse);
683                 }
684                 break;
685             case CONSUMABLES_GET:
686                 if (response.getResult().isJsonArray()) {
687                     updateConsumables(response.getResult().getAsJsonArray().get(0).getAsJsonObject());
688                 }
689                 break;
690             case DND_GET:
691                 if (response.getResult().isJsonArray()) {
692                     updateDnD(response.getResult().getAsJsonArray().get(0).getAsJsonObject());
693                 }
694                 break;
695             case CLEAN_SUMMARY_GET:
696                 if (response.getResult().isJsonArray()) {
697                     updateHistoryLegacy(response.getResult().getAsJsonArray());
698                 } else if (response.getResult().isJsonObject()) {
699                     updateHistory(response.getResult().getAsJsonObject());
700                 }
701                 break;
702             case CLEAN_RECORD_GET:
703                 if (response.getResult().isJsonArray() && response.getResult().getAsJsonArray().size() > 0
704                         && response.getResult().getAsJsonArray().get(0).isJsonArray()) {
705                     updateHistoryRecordLegacy(response.getResult().getAsJsonArray().get(0).getAsJsonArray());
706                 } else if (response.getResult().isJsonArray() && response.getResult().getAsJsonArray().size() > 0
707                         && response.getResult().getAsJsonArray().get(0).isJsonObject()) {
708                     final HistoryRecordDTO historyRecordDTO = GSON.fromJson(
709                             response.getResult().getAsJsonArray().get(0).getAsJsonObject(), HistoryRecordDTO.class);
710                     if (historyRecordDTO != null) {
711                         updateHistoryRecord(historyRecordDTO);
712                     }
713                 } else if (response.getResult().isJsonObject()) {
714                     final HistoryRecordDTO historyRecordDTO = GSON.fromJson(response.getResult().getAsJsonObject(),
715                             HistoryRecordDTO.class);
716                     if (historyRecordDTO != null) {
717                         updateHistoryRecord(historyRecordDTO);
718                     }
719                 } else {
720                     logger.debug("Could not extract cleaning history record from: {}", response.getResult());
721                 }
722                 break;
723             case GET_MAP:
724                 if (response.getResult().isJsonArray()) {
725                     String mapresponse = response.getResult().getAsJsonArray().get(0).getAsString();
726                     if (!mapresponse.contentEquals("retry") && !mapresponse.contentEquals(lastMap)) {
727                         lastMap = mapresponse;
728                         miIoScheduler.submit(() -> updateState(CHANNEL_VACUUM_MAP, getMap(mapresponse)));
729                     }
730                 }
731                 break;
732             case GET_MAP_STATUS:
733             case GET_SEGMENT_STATUS:
734             case GET_LED_STATUS:
735                 updateNumericChannel(response);
736                 break;
737             case GET_ROOM_MAPPING:
738                 updateRoomMapping(response);
739                 break;
740             case GET_CARPET_MODE:
741             case GET_FW_FEATURES:
742             case GET_CUSTOMIZED_CLEAN_MODE:
743             case GET_MULTI_MAP_LIST:
744             case SET_COLLECT_DUST:
745             case SET_CLEAN_MOP_START:
746             case SET_CLEAN_MOP_STOP:
747                 for (RobotCababilities cmd : FEATURES_CHANNELS) {
748                     if (response.getCommand().getCommand().contentEquals(cmd.getCommand())) {
749                         updateState(cmd.getChannel(), new StringType(response.getResult().toString()));
750                         break;
751                     }
752                 }
753                 break;
754             default:
755                 break;
756         }
757     }
758
759     private void updateNumericChannel(MiIoSendCommand response) {
760         RobotCababilities capabilityChannel = null;
761         for (RobotCababilities cmd : FEATURES_CHANNELS) {
762             if (response.getCommand().getCommand().contentEquals(cmd.getCommand())) {
763                 capabilityChannel = cmd;
764                 break;
765             }
766         }
767         if (capabilityChannel != null) {
768             if (response.getResult().isJsonArray() && response.getResult().getAsJsonArray().get(0).isJsonPrimitive()) {
769                 try {
770                     Integer stat = response.getResult().getAsJsonArray().get(0).getAsInt();
771                     updateState(capabilityChannel.getChannel(), new DecimalType(stat));
772                     return;
773                 } catch (ClassCastException | IllegalStateException e) {
774                     logger.debug("Could not update numeric channel {} with '{}': {}", capabilityChannel.getChannel(),
775                             response.getResult(), e.getMessage());
776                 }
777             } else {
778                 logger.debug("Could not update numeric channel {} with '{}': Not in expected format",
779                         capabilityChannel.getChannel(), response.getResult());
780             }
781             updateState(capabilityChannel.getChannel(), UnDefType.UNDEF);
782         }
783     }
784
785     private void setCapabilities(JsonObject statusResponse) {
786         for (RobotCababilities capability : RobotCababilities.values()) {
787             if (statusResponse.has(capability.getStatusFieldName())) {
788                 deviceCapabilities.putIfAbsent(capability, false);
789                 logger.debug("Setting additional vacuum {}", capability);
790             }
791         }
792     }
793
794     private void createCapabilityChannels() {
795         ThingBuilder thingBuilder = editThing();
796         int cnt = 0;
797
798         for (Entry<RobotCababilities, Boolean> robotCapability : deviceCapabilities.entrySet()) {
799             RobotCababilities capability = robotCapability.getKey();
800             Boolean channelCreated = robotCapability.getValue();
801             if (!channelCreated) {
802                 if (thing.getChannels().stream()
803                         .anyMatch(ch -> ch.getUID().getId().equalsIgnoreCase(capability.getChannel()))) {
804                     logger.debug("Channel already available...skip creation of channel '{}'.", capability.getChannel());
805                     deviceCapabilities.replace(capability, true);
806                     continue;
807                 }
808                 logger.debug("Creating dynamic channel for capability {}", capability);
809                 ChannelType channelType = channelTypeRegistry.getChannelType(capability.getChannelType());
810                 if (channelType != null) {
811                     logger.debug("Found channelType '{}' for capability {}", channelType, capability.name());
812                     ChannelUID channelUID = new ChannelUID(getThing().getUID(), capability.getChannel());
813                     Channel channel = ChannelBuilder.create(channelUID, channelType.getItemType())
814                             .withType(capability.getChannelType()).withLabel(channelType.getLabel()).build();
815                     thingBuilder.withChannel(channel);
816                     cnt++;
817                 } else {
818                     logger.debug("ChannelType {} not found (Unexpected). Available types:",
819                             capability.getChannelType());
820                     for (ChannelType ct : channelTypeRegistry.getChannelTypes()) {
821                         logger.debug("Available channelType: '{}' '{}' '{}'", ct.getUID(), ct.toString(),
822                                 ct.getConfigDescriptionURI());
823                     }
824                 }
825             }
826         }
827         if (cnt > 0) {
828             updateThing(thingBuilder.build());
829         }
830         hasChannelStructure = true;
831     }
832
833     private State getMap(String map) {
834         final MiIoBindingConfiguration configuration = this.configuration;
835         if (configuration != null && cloudConnector.isConnected()) {
836             try {
837                 final @Nullable RawType mapDl = cloudConnector.getMap(map, configuration.cloudServer);
838                 if (mapDl != null) {
839                     byte[] mapData = mapDl.getBytes();
840                     RRMapDraw rrMap = RRMapDraw.loadImage(new ByteArrayInputStream(mapData));
841                     rrMap.setDrawOptions(mapDrawOptions);
842                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
843                     if (logger.isDebugEnabled()) {
844                         final String mapPath = BINDING_USERDATA_PATH + File.separator + map
845                                 + LocalDateTime.now().format(DATEFORMATTER) + ".rrmap";
846                         CloudUtil.writeBytesToFileNio(mapData, mapPath);
847                         logger.debug("Mapdata saved to {}", mapPath);
848                     }
849                     ImageIO.write(rrMap.getImage(), "jpg", baos);
850                     byte[] byteArray = baos.toByteArray();
851                     if (byteArray != null && byteArray.length > 0) {
852                         return new RawType(byteArray, "image/jpeg");
853                     } else {
854                         logger.debug("Mapdata empty removing image");
855                         return UnDefType.UNDEF;
856                     }
857                 }
858             } catch (MiCloudException e) {
859                 logger.debug("Error getting data from Xiaomi cloud. Mapdata could not be updated: {}", e.getMessage());
860             } catch (IOException e) {
861                 logger.debug("Mapdata could not be updated: {}", e.getMessage());
862             }
863         } else {
864             logger.debug("Not connected to Xiaomi cloud. Cannot retreive new map: {}", map);
865         }
866         return UnDefType.UNDEF;
867     }
868 }