2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.miio.internal.handler;
15 import static org.openhab.binding.miio.internal.MiIoBindingConstants.*;
17 import java.io.ByteArrayInputStream;
18 import java.io.ByteArrayOutputStream;
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;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.TimeUnit;
33 import java.util.stream.Collectors;
34 import java.util.stream.Stream;
36 import javax.imageio.ImageIO;
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;
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;
92 * The {@link MiIoVacuumHandler} is responsible for handling commands, which are
93 * sent to one of the channels.
95 * @author Marcel Verpaalen - Initial contribution
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;
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()));
111 private ExpiringCache<String> status;
112 private ExpiringCache<String> consumables;
113 private ExpiringCache<String> dnd;
114 private ExpiringCache<String> history;
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();
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, () -> {
132 int ret = sendCommand(MiIoCommand.GET_STATUS);
136 } catch (Exception e) {
137 logger.debug("Error during status refresh: {}", e.getMessage(), e);
141 consumables = new ExpiringCache<>(CACHE_EXPIRY, () -> {
143 int ret = sendCommand(MiIoCommand.CONSUMABLES_GET);
147 } catch (Exception e) {
148 logger.debug("Error during consumables refresh: {}", e.getMessage(), e);
152 dnd = new ExpiringCache<>(CACHE_EXPIRY, () -> {
154 int ret = sendCommand(MiIoCommand.DND_GET);
158 } catch (Exception e) {
159 logger.debug("Error during dnd refresh: {}", e.getMessage(), e);
163 history = new ExpiringCache<>(CACHE_EXPIRY, () -> {
165 int ret = sendCommand(MiIoCommand.CLEAN_SUMMARY_GET);
169 } catch (Exception e) {
170 logger.debug("Error during cleaning data refresh: {}", e.getMessage(), e);
174 map = new ExpiringCache<String>(CACHE_EXPIRY, () -> {
176 int ret = sendCommand(MiIoCommand.GET_MAP);
180 } catch (Exception e) {
181 logger.debug("Error during dnd refresh: {}", e.getMessage(), e);
188 public void handleCommand(ChannelUID channelUID, Command command) {
189 if (getConnection() == null) {
190 logger.debug("Vacuum {} not online. Command {} ignored", getThing().getUID(), command.toString());
193 if (command == RefreshType.REFRESH) {
194 logger.debug("Refreshing {}", channelUID);
197 if (channelUID.getId().equals(CHANNEL_VACUUM_MAP)) {
198 sendCommand(MiIoCommand.GET_MAP);
202 if (handleCommandsChannels(channelUID, command)) {
206 if (channelUID.getId().equals(CHANNEL_VACUUM)) {
207 if (command instanceof OnOffType) {
208 if (command.equals(OnOffType.ON)) {
209 sendCommand(MiIoCommand.START_VACUUM);
213 sendCommand(MiIoCommand.STOP_VACUUM);
214 miIoScheduler.schedule(() -> {
215 sendCommand(MiIoCommand.CHARGE);
217 }, 2000, TimeUnit.MILLISECONDS);
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);
234 }, 2000, TimeUnit.MILLISECONDS);
237 logger.info("Command {} not recognised", command.toString());
242 if (channelUID.getId().equals(CHANNEL_FAN_POWER)) {
243 sendCommand(MiIoCommand.SET_MODE, "[" + command.toString() + "]");
248 if (channelUID.getId().equals(RobotCababilities.WATERBOX_MODE.getChannel())) {
249 sendCommand(MiIoCommand.SET_WATERBOX_MODE, "[" + command.toString() + "]");
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("-"));
260 if (channelUID.getId().equals(CHANNEL_FAN_CONTROL)) {
261 if (Integer.valueOf(command.toString()) > 0) {
262 sendCommand(MiIoCommand.SET_MODE, "[" + command.toString() + "]");
267 if (channelUID.getId().equals(CHANNEL_CONSUMABLE_RESET)) {
268 sendCommand(MiIoCommand.CONSUMABLES_RESET, "[" + command.toString() + "]");
269 updateState(CHANNEL_CONSUMABLE_RESET, new StringType("none"));
272 if (channelUID.getId().equals(RobotCababilities.COLLECT_DUST.getChannel()) && !command.toString().isEmpty()
273 && !command.toString().contentEquals("-")) {
274 sendCommand(MiIoCommand.SET_COLLECT_DUST);
279 if (channelUID.getId().equals(RobotCababilities.CLEAN_MOP_START.getChannel()) && !command.toString().isEmpty()
280 && !command.toString().contentEquals("-")) {
281 sendCommand(MiIoCommand.SET_CLEAN_MOP_START);
285 if (channelUID.getId().equals(RobotCababilities.CLEAN_MOP_STOP.getChannel()) && !command.toString().isEmpty()
286 && !command.toString().contentEquals("-")) {
287 sendCommand(MiIoCommand.SET_CLEAN_MOP_STOP);
293 private void forceStatusUpdate() {
294 status.invalidateValue();
295 miIoScheduler.schedule(() -> {
297 }, 3000, TimeUnit.MILLISECONDS);
300 private void safeUpdateState(String channelID, @Nullable Integer state) {
302 updateState(channelID, new DecimalType(state));
304 logger.debug("Channel {} not update. value not available.", channelID);
308 private boolean updateVacuumStatus(JsonObject statusData) {
309 StatusDTO statusInfo = GSON.fromJson(statusData, StatusDTO.class);
310 if (statusInfo == null) {
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));
318 if (statusInfo.getCleanTime() != null) {
319 updateState(CHANNEL_CLEAN_TIME,
320 new QuantityType<>(TimeUnit.SECONDS.toMinutes(statusInfo.getCleanTime()), Units.MINUTE));
322 safeUpdateState(CHANNEL_DND_ENABLED, statusInfo.getDndEnabled());
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());
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()));
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()));
342 State vacuum = OnOffType.OFF;
350 vacuum = OnOffType.ON;
365 vacuum = OnOffType.ON;
371 if ("undef".equals(control)) {
372 updateState(CHANNEL_CONTROL, UnDefType.UNDEF);
374 updateState(CHANNEL_CONTROL, new StringType(control));
376 updateState(CHANNEL_VACUUM, vacuum);
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()));
383 if (deviceCapabilities.containsKey(RobotCababilities.WATERBOX_MODE)) {
384 safeUpdateState(RobotCababilities.WATERBOX_MODE.getChannel(), statusInfo.getWaterBoxMode());
386 if (deviceCapabilities.containsKey(RobotCababilities.WATERBOX_STATUS)) {
387 safeUpdateState(RobotCababilities.WATERBOX_STATUS.getChannel(), statusInfo.getWaterBoxStatus());
389 if (deviceCapabilities.containsKey(RobotCababilities.WATERBOX_CARRIAGE)) {
390 safeUpdateState(RobotCababilities.WATERBOX_CARRIAGE.getChannel(), statusInfo.getWaterBoxCarriageStatus());
392 if (deviceCapabilities.containsKey(RobotCababilities.LOCKSTATUS)) {
393 safeUpdateState(RobotCababilities.LOCKSTATUS.getChannel(), statusInfo.getLockStatus());
395 if (deviceCapabilities.containsKey(RobotCababilities.MOP_FORBIDDEN)) {
396 safeUpdateState(RobotCababilities.MOP_FORBIDDEN.getChannel(), statusInfo.getMopForbiddenEnable());
398 if (deviceCapabilities.containsKey(RobotCababilities.LOCATING)) {
399 safeUpdateState(RobotCababilities.LOCATING.getChannel(), statusInfo.getIsLocating());
401 if (deviceCapabilities.containsKey(RobotCababilities.CLEAN_MOP_START)) {
402 safeUpdateState(RobotCababilities.CLEAN_MOP_START.getChannel(), 0);
404 if (deviceCapabilities.containsKey(RobotCababilities.CLEAN_MOP_STOP)) {
405 safeUpdateState(RobotCababilities.CLEAN_MOP_STOP.getChannel(), 0);
407 if (deviceCapabilities.containsKey(RobotCababilities.COLLECT_DUST)) {
408 safeUpdateState(RobotCababilities.COLLECT_DUST.getChannel(), 0);
410 if (deviceCapabilities.containsKey(RobotCababilities.MOP_DRYING)) {
411 safeUpdateState(RobotCababilities.MOP_DRYING.getChannel(), statusInfo.getIsMopDryingActive());
413 if (deviceCapabilities.containsKey(RobotCababilities.MOP_DRYING_REMAINING_TIME)) {
414 updateState(CHANNEL_MOP_TOTALDRYTIME,
415 new QuantityType<>(TimeUnit.SECONDS.toMinutes(statusInfo.getMopDryTime()), Units.MINUTE));
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)));
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())));
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 + "]");
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));
477 if (historyData.has("clean_area")) {
478 updateState(CHANNEL_HISTORY_TOTALAREA,
479 new QuantityType<>(historyData.get("clean_area").getAsDouble() / 1000000D, SIUnits.SQUARE_METRE));
481 if (historyData.has("clean_count")) {
482 updateState(CHANNEL_HISTORY_COUNT, new DecimalType(historyData.get("clean_count").getAsLong()));
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 + "]");
497 private void updateHistoryRecordLegacy(JsonArray historyData) {
498 HistoryRecordDTO historyRecord = new HistoryRecordDTO();
499 for (int i = 0; i < historyData.size(); ++i) {
501 BigInteger value = historyData.get(i).getAsBigInteger();
504 historyRecord.setStart(ZonedDateTime
505 .ofInstant(Instant.ofEpochSecond(value.longValue()), ZoneId.systemDefault())
509 historyRecord.setStart(ZonedDateTime
510 .ofInstant(Instant.ofEpochSecond(value.longValue()), ZoneId.systemDefault())
514 historyRecord.setDuration(value.intValue());
517 historyRecord.setArea(new BigDecimal(value).divide(BigDecimal.valueOf(1000000)));
520 historyRecord.setError(value.intValue());
523 historyRecord.setFinished(value.intValue());
526 historyRecord.setStartType(value.intValue());
529 historyRecord.setCleanType(value.intValue());
532 historyRecord.setFinishReason(value.intValue());
535 } catch (ClassCastException | NumberFormatException | IllegalStateException e) {
538 updateHistoryRecord(historyRecord);
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]));
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]));
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));
556 if (historyRecordDTO.getArea() != null) {
557 historyRecord.addProperty("area", historyRecordDTO.getArea());
558 updateState(CHANNEL_HISTORY_AREA, new QuantityType<>(historyRecordDTO.getArea(), SIUnits.SQUARE_METRE));
560 if (historyRecordDTO.getError() != null) {
561 historyRecord.addProperty("error", historyRecordDTO.getError());
562 updateState(CHANNEL_HISTORY_ERROR, new DecimalType(historyRecordDTO.getError()));
564 if (historyRecordDTO.getFinished() != null) {
565 historyRecord.addProperty("finished", historyRecordDTO.getFinished());
566 updateState(CHANNEL_HISTORY_FINISH, new DecimalType(historyRecordDTO.getFinished()));
568 if (historyRecordDTO.getFinishReason() != null) {
569 historyRecord.addProperty("finish_reason", historyRecordDTO.getFinishReason());
570 updateState(CHANNEL_HISTORY_FINISHREASON, new DecimalType(historyRecordDTO.getFinishReason()));
572 if (historyRecordDTO.getDustCollectionStatus() != null) {
573 historyRecord.addProperty("dust_collection_status", historyRecordDTO.getDustCollectionStatus());
574 updateState(CHANNEL_HISTORY_DUSTCOLLECTION, new DecimalType(historyRecordDTO.getDustCollectionStatus()));
576 updateState(CHANNEL_HISTORY_RECORD, new StringType(historyRecord.toString()));
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());
591 room.add("not found");
593 mappedRoom.add(room);
595 updateState(cmd.getChannel(), new StringType(mappedRoom.toString()));
597 updateState(cmd.getChannel(), new StringType(response.getResult().toString()));
605 protected boolean skipUpdate() {
606 if (!hasConnection()) {
607 logger.debug("Skipping periodic update for '{}'. No Connection", getThing().getUID().toString());
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());
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());
626 protected synchronized void updateData() {
627 if (!hasConnection() || skipUpdate()) {
630 logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
636 consumables.getValue();
637 if (lastMap.isEmpty() || stateId != 8) {
638 if (isLinked(mapChannelUid)) {
642 for (RobotCababilities cmd : FEATURES_CHANNELS) {
643 if (isLinked(cmd.getChannel())) {
644 sendCommand(cmd.getCommand());
647 } catch (Exception e) {
648 logger.debug("Error while updating '{}': '{}", getThing().getUID().toString(), e.getLocalizedMessage());
653 public void 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();
663 protected boolean initializeData() {
664 updateState(CHANNEL_CONSUMABLE_RESET, new StringType("none"));
665 return super.initializeData();
669 public void onMessageReceived(MiIoSendCommand response) {
670 super.onMessageReceived(response);
671 if (response.isError()) {
674 switch (response.getCommand()) {
676 if (response.getResult().isJsonArray()) {
677 JsonObject statusResponse = response.getResult().getAsJsonArray().get(0).getAsJsonObject();
678 if (!hasChannelStructure) {
679 setCapabilities(statusResponse);
680 createCapabilityChannels();
682 updateVacuumStatus(statusResponse);
685 case CONSUMABLES_GET:
686 if (response.getResult().isJsonArray()) {
687 updateConsumables(response.getResult().getAsJsonArray().get(0).getAsJsonObject());
691 if (response.getResult().isJsonArray()) {
692 updateDnD(response.getResult().getAsJsonArray().get(0).getAsJsonObject());
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());
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);
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);
720 logger.debug("Could not extract cleaning history record from: {}", response.getResult());
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)));
733 case GET_SEGMENT_STATUS:
735 updateNumericChannel(response);
737 case GET_ROOM_MAPPING:
738 updateRoomMapping(response);
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()));
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;
767 if (capabilityChannel != null) {
768 if (response.getResult().isJsonArray() && response.getResult().getAsJsonArray().get(0).isJsonPrimitive()) {
770 Integer stat = response.getResult().getAsJsonArray().get(0).getAsInt();
771 updateState(capabilityChannel.getChannel(), new DecimalType(stat));
773 } catch (ClassCastException | IllegalStateException e) {
774 logger.debug("Could not update numeric channel {} with '{}': {}", capabilityChannel.getChannel(),
775 response.getResult(), e.getMessage());
778 logger.debug("Could not update numeric channel {} with '{}': Not in expected format",
779 capabilityChannel.getChannel(), response.getResult());
781 updateState(capabilityChannel.getChannel(), UnDefType.UNDEF);
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);
794 private void createCapabilityChannels() {
795 ThingBuilder thingBuilder = editThing();
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);
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);
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());
828 updateThing(thingBuilder.build());
830 hasChannelStructure = true;
833 private State getMap(String map) {
834 final MiIoBindingConfiguration configuration = this.configuration;
835 if (configuration != null && cloudConnector.isConnected()) {
837 final @Nullable RawType mapDl = cloudConnector.getMap(map, configuration.cloudServer);
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);
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");
854 logger.debug("Mapdata empty removing image");
855 return UnDefType.UNDEF;
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());
864 logger.debug("Not connected to Xiaomi cloud. Cannot retreive new map: {}", map);
866 return UnDefType.UNDEF;