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.FanModeType;
50 import org.openhab.binding.miio.internal.robot.HistoryRecordDTO;
51 import org.openhab.binding.miio.internal.robot.RRMapDraw;
52 import org.openhab.binding.miio.internal.robot.RRMapDrawOptions;
53 import org.openhab.binding.miio.internal.robot.RobotCababilities;
54 import org.openhab.binding.miio.internal.robot.StatusDTO;
55 import org.openhab.binding.miio.internal.robot.StatusType;
56 import org.openhab.binding.miio.internal.robot.VacuumErrorType;
57 import org.openhab.binding.miio.internal.transport.MiIoAsyncCommunication;
58 import org.openhab.core.cache.ExpiringCache;
59 import org.openhab.core.i18n.LocaleProvider;
60 import org.openhab.core.i18n.TranslationProvider;
61 import org.openhab.core.library.types.DateTimeType;
62 import org.openhab.core.library.types.DecimalType;
63 import org.openhab.core.library.types.OnOffType;
64 import org.openhab.core.library.types.QuantityType;
65 import org.openhab.core.library.types.RawType;
66 import org.openhab.core.library.types.StringType;
67 import org.openhab.core.library.unit.SIUnits;
68 import org.openhab.core.library.unit.Units;
69 import org.openhab.core.thing.Channel;
70 import org.openhab.core.thing.ChannelUID;
71 import org.openhab.core.thing.Thing;
72 import org.openhab.core.thing.ThingStatusDetail;
73 import org.openhab.core.thing.binding.builder.ChannelBuilder;
74 import org.openhab.core.thing.binding.builder.ThingBuilder;
75 import org.openhab.core.thing.type.ChannelType;
76 import org.openhab.core.thing.type.ChannelTypeRegistry;
77 import org.openhab.core.types.Command;
78 import org.openhab.core.types.RefreshType;
79 import org.openhab.core.types.State;
80 import org.openhab.core.types.UnDefType;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
84 import com.google.gson.Gson;
85 import com.google.gson.GsonBuilder;
86 import com.google.gson.JsonArray;
87 import com.google.gson.JsonElement;
88 import com.google.gson.JsonObject;
91 * The {@link MiIoVacuumHandler} is responsible for handling commands, which are
92 * sent to one of the channels.
94 * @author Marcel Verpaalen - Initial contribution
97 public class MiIoVacuumHandler extends MiIoAbstractHandler {
98 private final Logger logger = LoggerFactory.getLogger(MiIoVacuumHandler.class);
99 private static final DateTimeFormatter DATEFORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
100 private static final Gson GSON = new GsonBuilder().serializeNulls().create();
101 private final ChannelUID mapChannelUid;
103 private static final Set<RobotCababilities> FEATURES_CHANNELS = Collections.unmodifiableSet(Stream
104 .of(RobotCababilities.SEGMENT_STATUS, RobotCababilities.MAP_STATUS, RobotCababilities.LED_STATUS,
105 RobotCababilities.CARPET_MODE, RobotCababilities.FW_FEATURES, RobotCababilities.ROOM_MAPPING,
106 RobotCababilities.MULTI_MAP_LIST, RobotCababilities.CUSTOMIZE_CLEAN_MODE)
107 .collect(Collectors.toSet()));
109 private ExpiringCache<String> status;
110 private ExpiringCache<String> consumables;
111 private ExpiringCache<String> dnd;
112 private ExpiringCache<String> history;
114 private ExpiringCache<String> map;
115 private String lastHistoryId = "";
116 private String lastMap = "";
117 private boolean hasChannelStructure;
118 private ConcurrentHashMap<RobotCababilities, Boolean> deviceCapabilities = new ConcurrentHashMap<>();
119 private ChannelTypeRegistry channelTypeRegistry;
120 private RRMapDrawOptions mapDrawOptions = new RRMapDrawOptions();
122 public MiIoVacuumHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService,
123 CloudConnector cloudConnector, ChannelTypeRegistry channelTypeRegistry, TranslationProvider i18nProvider,
124 LocaleProvider localeProvider) {
125 super(thing, miIoDatabaseWatchService, cloudConnector, i18nProvider, localeProvider);
126 this.channelTypeRegistry = channelTypeRegistry;
127 mapChannelUid = new ChannelUID(thing.getUID(), CHANNEL_VACUUM_MAP);
128 status = new ExpiringCache<>(CACHE_EXPIRY, () -> {
130 int ret = sendCommand(MiIoCommand.GET_STATUS);
134 } catch (Exception e) {
135 logger.debug("Error during status refresh: {}", e.getMessage(), e);
139 consumables = new ExpiringCache<>(CACHE_EXPIRY, () -> {
141 int ret = sendCommand(MiIoCommand.CONSUMABLES_GET);
145 } catch (Exception e) {
146 logger.debug("Error during consumables refresh: {}", e.getMessage(), e);
150 dnd = new ExpiringCache<>(CACHE_EXPIRY, () -> {
152 int ret = sendCommand(MiIoCommand.DND_GET);
156 } catch (Exception e) {
157 logger.debug("Error during dnd refresh: {}", e.getMessage(), e);
161 history = new ExpiringCache<>(CACHE_EXPIRY, () -> {
163 int ret = sendCommand(MiIoCommand.CLEAN_SUMMARY_GET);
167 } catch (Exception e) {
168 logger.debug("Error during cleaning data refresh: {}", e.getMessage(), e);
172 map = new ExpiringCache<String>(CACHE_EXPIRY, () -> {
174 int ret = sendCommand(MiIoCommand.GET_MAP);
178 } catch (Exception e) {
179 logger.debug("Error during dnd refresh: {}", e.getMessage(), e);
186 public void handleCommand(ChannelUID channelUID, Command command) {
187 if (getConnection() == null) {
188 logger.debug("Vacuum {} not online. Command {} ignored", getThing().getUID(), command.toString());
191 if (command == RefreshType.REFRESH) {
192 logger.debug("Refreshing {}", channelUID);
195 if (channelUID.getId().equals(CHANNEL_VACUUM_MAP)) {
196 sendCommand(MiIoCommand.GET_MAP);
200 if (handleCommandsChannels(channelUID, command)) {
204 if (channelUID.getId().equals(CHANNEL_VACUUM)) {
205 if (command instanceof OnOffType) {
206 if (command.equals(OnOffType.ON)) {
207 sendCommand(MiIoCommand.START_VACUUM);
211 sendCommand(MiIoCommand.STOP_VACUUM);
212 miIoScheduler.schedule(() -> {
213 sendCommand(MiIoCommand.CHARGE);
215 }, 2000, TimeUnit.MILLISECONDS);
220 if (channelUID.getId().equals(CHANNEL_CONTROL)) {
221 if ("vacuum".equals(command.toString())) {
222 sendCommand(MiIoCommand.START_VACUUM);
223 } else if ("spot".equals(command.toString())) {
224 sendCommand(MiIoCommand.START_SPOT);
225 } else if ("pause".equals(command.toString())) {
226 sendCommand(MiIoCommand.PAUSE);
227 } else if ("dock".equals(command.toString())) {
228 sendCommand(MiIoCommand.STOP_VACUUM);
229 miIoScheduler.schedule(() -> {
230 sendCommand(MiIoCommand.CHARGE);
232 }, 2000, TimeUnit.MILLISECONDS);
235 logger.info("Command {} not recognised", command.toString());
240 if (channelUID.getId().equals(CHANNEL_FAN_POWER)) {
241 sendCommand(MiIoCommand.SET_MODE, "[" + command.toString() + "]");
245 if (channelUID.getId().equals(RobotCababilities.WATERBOX_MODE.getChannel())) {
246 sendCommand(MiIoCommand.SET_WATERBOX_MODE, "[" + command.toString() + "]");
250 if (channelUID.getId().equals(RobotCababilities.SEGMENT_CLEAN.getChannel()) && !command.toString().isEmpty()
251 && !command.toString().contentEquals("-")) {
252 sendCommand(MiIoCommand.START_SEGMENT, "[" + command.toString() + "]");
253 updateState(RobotCababilities.SEGMENT_CLEAN.getChannel(), new StringType("-"));
257 if (channelUID.getId().equals(CHANNEL_FAN_CONTROL)) {
258 if (Integer.valueOf(command.toString()) > 0) {
259 sendCommand(MiIoCommand.SET_MODE, "[" + command.toString() + "]");
264 if (channelUID.getId().equals(CHANNEL_CONSUMABLE_RESET)) {
265 sendCommand(MiIoCommand.CONSUMABLES_RESET, "[" + command.toString() + "]");
266 updateState(CHANNEL_CONSUMABLE_RESET, new StringType("none"));
270 private void forceStatusUpdate() {
271 status.invalidateValue();
272 miIoScheduler.schedule(() -> {
274 }, 3000, TimeUnit.MILLISECONDS);
277 private void safeUpdateState(String channelID, @Nullable Integer state) {
279 updateState(channelID, new DecimalType(state));
281 logger.debug("Channel {} not update. value not available.", channelID);
285 private boolean updateVacuumStatus(JsonObject statusData) {
286 StatusDTO statusInfo = GSON.fromJson(statusData, StatusDTO.class);
287 if (statusInfo == null) {
290 safeUpdateState(CHANNEL_BATTERY, statusInfo.getBattery());
291 if (statusInfo.getCleanArea() != null) {
292 updateState(CHANNEL_CLEAN_AREA,
293 new QuantityType<>(statusInfo.getCleanArea() / 1000000.0, SIUnits.SQUARE_METRE));
295 if (statusInfo.getCleanTime() != null) {
296 updateState(CHANNEL_CLEAN_TIME,
297 new QuantityType<>(TimeUnit.SECONDS.toMinutes(statusInfo.getCleanTime()), Units.MINUTE));
299 safeUpdateState(CHANNEL_DND_ENABLED, statusInfo.getDndEnabled());
301 if (statusInfo.getErrorCode() != null) {
302 updateState(CHANNEL_ERROR_CODE,
303 new StringType(VacuumErrorType.getType(statusInfo.getErrorCode()).getDescription()));
304 safeUpdateState(CHANNEL_ERROR_ID, statusInfo.getErrorCode());
307 if (statusInfo.getFanPower() != null) {
308 updateState(CHANNEL_FAN_POWER, new DecimalType(statusInfo.getFanPower()));
309 updateState(CHANNEL_FAN_CONTROL, new DecimalType(FanModeType.getType(statusInfo.getFanPower()).getId()));
311 safeUpdateState(CHANNEL_IN_CLEANING, statusInfo.getInCleaning());
312 safeUpdateState(CHANNEL_MAP_PRESENT, statusInfo.getMapPresent());
313 if (statusInfo.getState() != null) {
314 stateId = statusInfo.getState();
315 StatusType state = StatusType.getType(statusInfo.getState());
316 updateState(CHANNEL_STATE, new StringType(state.getDescription()));
317 updateState(CHANNEL_STATE_ID, new DecimalType(statusInfo.getState()));
319 State vacuum = OnOffType.OFF;
327 vacuum = OnOffType.ON;
342 vacuum = OnOffType.ON;
348 if ("undef".equals(control)) {
349 updateState(CHANNEL_CONTROL, UnDefType.UNDEF);
351 updateState(CHANNEL_CONTROL, new StringType(control));
353 updateState(CHANNEL_VACUUM, vacuum);
355 if (deviceCapabilities.containsKey(RobotCababilities.WATERBOX_MODE)) {
356 safeUpdateState(RobotCababilities.WATERBOX_MODE.getChannel(), statusInfo.getWaterBoxMode());
358 if (deviceCapabilities.containsKey(RobotCababilities.WATERBOX_STATUS)) {
359 safeUpdateState(RobotCababilities.WATERBOX_STATUS.getChannel(), statusInfo.getWaterBoxStatus());
361 if (deviceCapabilities.containsKey(RobotCababilities.WATERBOX_CARRIAGE)) {
362 safeUpdateState(RobotCababilities.WATERBOX_CARRIAGE.getChannel(), statusInfo.getWaterBoxCarriageStatus());
364 if (deviceCapabilities.containsKey(RobotCababilities.LOCKSTATUS)) {
365 safeUpdateState(RobotCababilities.LOCKSTATUS.getChannel(), statusInfo.getLockStatus());
367 if (deviceCapabilities.containsKey(RobotCababilities.MOP_FORBIDDEN)) {
368 safeUpdateState(RobotCababilities.MOP_FORBIDDEN.getChannel(), statusInfo.getMopForbiddenEnable());
370 if (deviceCapabilities.containsKey(RobotCababilities.LOCATING)) {
371 safeUpdateState(RobotCababilities.LOCATING.getChannel(), statusInfo.getIsLocating());
376 private boolean updateConsumables(JsonObject consumablesData) {
377 int mainBrush = consumablesData.get("main_brush_work_time").getAsInt();
378 int sideBrush = consumablesData.get("side_brush_work_time").getAsInt();
379 int filter = consumablesData.get("filter_work_time").getAsInt();
380 int sensor = consumablesData.get("sensor_dirty_time").getAsInt();
381 updateState(CHANNEL_CONSUMABLE_MAIN_TIME,
382 new QuantityType<>(ConsumablesType.remainingHours(mainBrush, ConsumablesType.MAIN_BRUSH), Units.HOUR));
383 updateState(CHANNEL_CONSUMABLE_MAIN_PERC,
384 new DecimalType(ConsumablesType.remainingPercent(mainBrush, ConsumablesType.MAIN_BRUSH)));
385 updateState(CHANNEL_CONSUMABLE_SIDE_TIME,
386 new QuantityType<>(ConsumablesType.remainingHours(sideBrush, ConsumablesType.SIDE_BRUSH), Units.HOUR));
387 updateState(CHANNEL_CONSUMABLE_SIDE_PERC,
388 new DecimalType(ConsumablesType.remainingPercent(sideBrush, ConsumablesType.SIDE_BRUSH)));
389 updateState(CHANNEL_CONSUMABLE_FILTER_TIME,
390 new QuantityType<>(ConsumablesType.remainingHours(filter, ConsumablesType.FILTER), Units.HOUR));
391 updateState(CHANNEL_CONSUMABLE_FILTER_PERC,
392 new DecimalType(ConsumablesType.remainingPercent(filter, ConsumablesType.FILTER)));
393 updateState(CHANNEL_CONSUMABLE_SENSOR_TIME,
394 new QuantityType<>(ConsumablesType.remainingHours(sensor, ConsumablesType.SENSOR), Units.HOUR));
395 updateState(CHANNEL_CONSUMABLE_SENSOR_PERC,
396 new DecimalType(ConsumablesType.remainingPercent(sensor, ConsumablesType.SENSOR)));
400 private boolean updateDnD(JsonObject dndData) {
401 logger.trace("Do not disturb data: {}", dndData.toString());
402 updateState(CHANNEL_DND_FUNCTION, new DecimalType(dndData.get("enabled").getAsBigDecimal()));
403 updateState(CHANNEL_DND_START, new StringType(String.format("%02d:%02d", dndData.get("start_hour").getAsInt(),
404 dndData.get("start_minute").getAsInt())));
405 updateState(CHANNEL_DND_END, new StringType(
406 String.format("%02d:%02d", dndData.get("end_hour").getAsInt(), dndData.get("end_minute").getAsInt())));
410 private boolean updateHistoryLegacy(JsonArray historyData) {
411 logger.trace("Cleaning history data: {}", historyData.toString());
412 updateState(CHANNEL_HISTORY_TOTALTIME,
413 new QuantityType<>(TimeUnit.SECONDS.toMinutes(historyData.get(0).getAsLong()), Units.MINUTE));
414 updateState(CHANNEL_HISTORY_TOTALAREA,
415 new QuantityType<>(historyData.get(1).getAsDouble() / 1000000D, SIUnits.SQUARE_METRE));
416 updateState(CHANNEL_HISTORY_COUNT, new DecimalType(historyData.get(2).toString()));
417 if (historyData.get(3).getAsJsonArray().size() > 0) {
418 String lastClean = historyData.get(3).getAsJsonArray().get(0).getAsString();
419 if (!lastClean.equals(lastHistoryId)) {
420 lastHistoryId = lastClean;
421 sendCommand(MiIoCommand.CLEAN_RECORD_GET, "[" + lastClean + "]");
427 private boolean updateHistory(JsonObject historyData) {
428 logger.trace("Cleaning history data: {}", historyData);
429 if (historyData.has("clean_time")) {
430 updateState(CHANNEL_HISTORY_TOTALTIME, new QuantityType<>(
431 TimeUnit.SECONDS.toMinutes(historyData.get("clean_time").getAsLong()), Units.MINUTE));
433 if (historyData.has("clean_area")) {
434 updateState(CHANNEL_HISTORY_TOTALAREA,
435 new QuantityType<>(historyData.get("clean_area").getAsDouble() / 1000000D, SIUnits.SQUARE_METRE));
437 if (historyData.has("clean_count")) {
438 updateState(CHANNEL_HISTORY_COUNT, new DecimalType(historyData.get("clean_count").getAsLong()));
440 if (historyData.has("records") & historyData.get("records").isJsonArray()) {
441 JsonArray historyRecords = historyData.get("records").getAsJsonArray();
442 if (!historyRecords.isEmpty()) {
443 String lastClean = historyRecords.get(0).getAsString();
444 if (!lastClean.equals(lastHistoryId)) {
445 lastHistoryId = lastClean;
446 sendCommand(MiIoCommand.CLEAN_RECORD_GET, "[" + lastClean + "]");
453 private void updateHistoryRecordLegacy(JsonArray historyData) {
454 HistoryRecordDTO historyRecord = new HistoryRecordDTO();
455 for (int i = 0; i < historyData.size(); ++i) {
457 BigInteger value = historyData.get(i).getAsBigInteger();
460 historyRecord.setStart(ZonedDateTime
461 .ofInstant(Instant.ofEpochSecond(value.longValue()), ZoneId.systemDefault())
465 historyRecord.setStart(ZonedDateTime
466 .ofInstant(Instant.ofEpochSecond(value.longValue()), ZoneId.systemDefault())
470 historyRecord.setDuration(value.intValue());
473 historyRecord.setArea(new BigDecimal(value).divide(BigDecimal.valueOf(1000000)));
476 historyRecord.setError(value.intValue());
479 historyRecord.setFinished(value.intValue());
482 historyRecord.setStartType(value.intValue());
485 historyRecord.setCleanType(value.intValue());
488 historyRecord.setFinishReason(value.intValue());
491 } catch (ClassCastException | NumberFormatException | IllegalStateException e) {
494 updateHistoryRecord(historyRecord);
497 private void updateHistoryRecord(HistoryRecordDTO historyRecordDTO) {
498 JsonObject historyRecord = new JsonObject();
499 if (historyRecordDTO.getStart() != null) {
500 historyRecord.addProperty("start", historyRecordDTO.getStart().split("\\+")[0]);
501 updateState(CHANNEL_HISTORY_START_TIME, new DateTimeType(historyRecordDTO.getStart().split("\\+")[0]));
503 if (historyRecordDTO.getEnd() != null) {
504 historyRecord.addProperty("end", historyRecordDTO.getEnd().split("\\+")[0]);
505 updateState(CHANNEL_HISTORY_END_TIME, new DateTimeType(historyRecordDTO.getEnd().split("\\+")[0]));
507 if (historyRecordDTO.getDuration() != null) {
508 long duration = TimeUnit.SECONDS.toMinutes(historyRecordDTO.getDuration().longValue());
509 historyRecord.addProperty("duration", duration);
510 updateState(CHANNEL_HISTORY_DURATION, new QuantityType<>(duration, Units.MINUTE));
512 if (historyRecordDTO.getArea() != null) {
513 historyRecord.addProperty("area", historyRecordDTO.getArea());
514 updateState(CHANNEL_HISTORY_AREA, new QuantityType<>(historyRecordDTO.getArea(), SIUnits.SQUARE_METRE));
516 if (historyRecordDTO.getError() != null) {
517 historyRecord.addProperty("error", historyRecordDTO.getError());
518 updateState(CHANNEL_HISTORY_ERROR, new DecimalType(historyRecordDTO.getError()));
520 if (historyRecordDTO.getFinished() != null) {
521 historyRecord.addProperty("finished", historyRecordDTO.getFinished());
522 updateState(CHANNEL_HISTORY_FINISH, new DecimalType(historyRecordDTO.getFinished()));
524 if (historyRecordDTO.getFinishReason() != null) {
525 historyRecord.addProperty("finish_reason", historyRecordDTO.getFinishReason());
526 updateState(CHANNEL_HISTORY_FINISHREASON, new DecimalType(historyRecordDTO.getFinishReason()));
528 if (historyRecordDTO.getDustCollectionStatus() != null) {
529 historyRecord.addProperty("dust_collection_status", historyRecordDTO.getDustCollectionStatus());
530 updateState(CHANNEL_HISTORY_DUSTCOLLECTION, new DecimalType(historyRecordDTO.getDustCollectionStatus()));
532 updateState(CHANNEL_HISTORY_RECORD, new StringType(historyRecord.toString()));
535 private void updateRoomMapping(MiIoSendCommand response) {
536 for (RobotCababilities cmd : FEATURES_CHANNELS) {
537 if (response.getCommand().getCommand().contentEquals(cmd.getCommand())) {
538 if (response.getResult().isJsonArray()) {
539 JsonArray rooms = response.getResult().getAsJsonArray();
540 JsonArray mappedRoom = new JsonArray();
541 for (JsonElement roomE : rooms) {
542 JsonArray room = roomE.getAsJsonArray();
543 HomeRoomDTO name = cloudConnector.getRoom(room.get(1).getAsString());
544 if (name != null && name.getName() != null) {
545 room.add(name.getName());
547 room.add("not found");
549 mappedRoom.add(room);
551 updateState(cmd.getChannel(), new StringType(mappedRoom.toString()));
553 updateState(cmd.getChannel(), new StringType(response.getResult().toString()));
561 protected boolean skipUpdate() {
562 if (!hasConnection()) {
563 logger.debug("Skipping periodic update for '{}'. No Connection", getThing().getUID().toString());
566 if (ThingStatusDetail.CONFIGURATION_ERROR.equals(getThing().getStatusInfo().getStatusDetail())) {
567 logger.debug("Skipping periodic update for '{}' UID '{}'. Thing Status", getThing().getUID().toString(),
568 getThing().getStatusInfo().getStatusDetail());
572 final MiIoAsyncCommunication mc = miioCom;
573 if (mc != null && mc.getQueueLength() > MAX_QUEUE) {
574 logger.debug("Skipping periodic update for '{}'. {} elements in queue.", getThing().getUID().toString(),
575 mc.getQueueLength());
582 protected synchronized void updateData() {
583 if (!hasConnection() || skipUpdate()) {
586 logger.debug("Periodic update for '{}' ({})", getThing().getUID().toString(), getThing().getThingTypeUID());
592 consumables.getValue();
593 if (lastMap.isEmpty() || stateId != 8) {
594 if (isLinked(mapChannelUid)) {
598 for (RobotCababilities cmd : FEATURES_CHANNELS) {
599 if (isLinked(cmd.getChannel())) {
600 sendCommand(cmd.getCommand());
603 } catch (Exception e) {
604 logger.debug("Error while updating '{}': '{}", getThing().getUID().toString(), e.getLocalizedMessage());
609 public void initialize() {
611 hasChannelStructure = false;
612 this.mapDrawOptions = RRMapDrawOptions
613 .getOptionsFromFile(BINDING_USERDATA_PATH + File.separator + "mapConfig.json", logger);
614 updateState(RobotCababilities.SEGMENT_CLEAN.getChannel(), new StringType("-"));
615 cloudConnector.getHomeLists();
619 protected boolean initializeData() {
620 updateState(CHANNEL_CONSUMABLE_RESET, new StringType("none"));
621 return super.initializeData();
625 public void onMessageReceived(MiIoSendCommand response) {
626 super.onMessageReceived(response);
627 if (response.isError()) {
630 switch (response.getCommand()) {
632 if (response.getResult().isJsonArray()) {
633 JsonObject statusResponse = response.getResult().getAsJsonArray().get(0).getAsJsonObject();
634 if (!hasChannelStructure) {
635 setCapabilities(statusResponse);
636 createCapabilityChannels();
638 updateVacuumStatus(statusResponse);
641 case CONSUMABLES_GET:
642 if (response.getResult().isJsonArray()) {
643 updateConsumables(response.getResult().getAsJsonArray().get(0).getAsJsonObject());
647 if (response.getResult().isJsonArray()) {
648 updateDnD(response.getResult().getAsJsonArray().get(0).getAsJsonObject());
651 case CLEAN_SUMMARY_GET:
652 if (response.getResult().isJsonArray()) {
653 updateHistoryLegacy(response.getResult().getAsJsonArray());
654 } else if (response.getResult().isJsonObject()) {
655 updateHistory(response.getResult().getAsJsonObject());
658 case CLEAN_RECORD_GET:
659 if (response.getResult().isJsonArray() && response.getResult().getAsJsonArray().size() > 0
660 && response.getResult().getAsJsonArray().get(0).isJsonArray()) {
661 updateHistoryRecordLegacy(response.getResult().getAsJsonArray().get(0).getAsJsonArray());
662 } else if (response.getResult().isJsonObject()) {
663 final HistoryRecordDTO historyRecordDTO = GSON.fromJson(response.getResult().getAsJsonObject(),
664 HistoryRecordDTO.class);
665 if (historyRecordDTO != null) {
666 updateHistoryRecord(historyRecordDTO);
669 logger.debug("Could not extract cleaning history record from: {}", response);
673 if (response.getResult().isJsonArray()) {
674 String mapresponse = response.getResult().getAsJsonArray().get(0).getAsString();
675 if (!mapresponse.contentEquals("retry") && !mapresponse.contentEquals(lastMap)) {
676 lastMap = mapresponse;
677 miIoScheduler.submit(() -> updateState(CHANNEL_VACUUM_MAP, getMap(mapresponse)));
682 case GET_SEGMENT_STATUS:
684 updateNumericChannel(response);
686 case GET_ROOM_MAPPING:
687 updateRoomMapping(response);
689 case GET_CARPET_MODE:
690 case GET_FW_FEATURES:
691 case GET_CUSTOMIZED_CLEAN_MODE:
692 case GET_MULTI_MAP_LIST:
693 for (RobotCababilities cmd : FEATURES_CHANNELS) {
694 if (response.getCommand().getCommand().contentEquals(cmd.getCommand())) {
695 updateState(cmd.getChannel(), new StringType(response.getResult().toString()));
705 private void updateNumericChannel(MiIoSendCommand response) {
706 RobotCababilities capabilityChannel = null;
707 for (RobotCababilities cmd : FEATURES_CHANNELS) {
708 if (response.getCommand().getCommand().contentEquals(cmd.getCommand())) {
709 capabilityChannel = cmd;
713 if (capabilityChannel != null) {
714 if (response.getResult().isJsonArray() && response.getResult().getAsJsonArray().get(0).isJsonPrimitive()) {
716 Integer stat = response.getResult().getAsJsonArray().get(0).getAsInt();
717 updateState(capabilityChannel.getChannel(), new DecimalType(stat));
719 } catch (ClassCastException | IllegalStateException e) {
720 logger.debug("Could not update numeric channel {} with '{}': {}", capabilityChannel.getChannel(),
721 response.getResult(), e.getMessage());
724 logger.debug("Could not update numeric channel {} with '{}': Not in expected format",
725 capabilityChannel.getChannel(), response.getResult());
727 updateState(capabilityChannel.getChannel(), UnDefType.UNDEF);
731 private void setCapabilities(JsonObject statusResponse) {
732 for (RobotCababilities capability : RobotCababilities.values()) {
733 if (statusResponse.has(capability.getStatusFieldName())) {
734 deviceCapabilities.putIfAbsent(capability, false);
735 logger.debug("Setting additional vacuum {}", capability);
740 private void createCapabilityChannels() {
741 ThingBuilder thingBuilder = editThing();
744 for (Entry<RobotCababilities, Boolean> robotCapability : deviceCapabilities.entrySet()) {
745 RobotCababilities capability = robotCapability.getKey();
746 Boolean channelCreated = robotCapability.getValue();
747 if (!channelCreated) {
748 if (thing.getChannels().stream()
749 .anyMatch(ch -> ch.getUID().getId().equalsIgnoreCase(capability.getChannel()))) {
750 logger.debug("Channel already available...skip creation of channel '{}'.", capability.getChannel());
751 deviceCapabilities.replace(capability, true);
754 logger.debug("Creating dynamic channel for capability {}", capability);
755 ChannelType channelType = channelTypeRegistry.getChannelType(capability.getChannelType());
756 if (channelType != null) {
757 logger.debug("Found channelType '{}' for capability {}", channelType, capability.name());
758 ChannelUID channelUID = new ChannelUID(getThing().getUID(), capability.getChannel());
759 Channel channel = ChannelBuilder.create(channelUID, channelType.getItemType())
760 .withType(capability.getChannelType()).withLabel(channelType.getLabel()).build();
761 thingBuilder.withChannel(channel);
764 logger.debug("ChannelType {} not found (Unexpected). Available types:",
765 capability.getChannelType());
766 for (ChannelType ct : channelTypeRegistry.getChannelTypes()) {
767 logger.debug("Available channelType: '{}' '{}' '{}'", ct.getUID(), ct.toString(),
768 ct.getConfigDescriptionURI());
774 updateThing(thingBuilder.build());
776 hasChannelStructure = true;
779 private State getMap(String map) {
780 final MiIoBindingConfiguration configuration = this.configuration;
781 if (configuration != null && cloudConnector.isConnected()) {
783 final @Nullable RawType mapDl = cloudConnector.getMap(map, configuration.cloudServer);
785 byte[] mapData = mapDl.getBytes();
786 RRMapDraw rrMap = RRMapDraw.loadImage(new ByteArrayInputStream(mapData));
787 rrMap.setDrawOptions(mapDrawOptions);
788 ByteArrayOutputStream baos = new ByteArrayOutputStream();
789 if (logger.isDebugEnabled()) {
790 final String mapPath = BINDING_USERDATA_PATH + File.separator + map
791 + LocalDateTime.now().format(DATEFORMATTER) + ".rrmap";
792 CloudUtil.writeBytesToFileNio(mapData, mapPath);
793 logger.debug("Mapdata saved to {}", mapPath);
795 ImageIO.write(rrMap.getImage(), "jpg", baos);
796 byte[] byteArray = baos.toByteArray();
797 if (byteArray != null && byteArray.length > 0) {
798 return new RawType(byteArray, "image/jpeg");
800 logger.debug("Mapdata empty removing image");
801 return UnDefType.UNDEF;
804 } catch (MiCloudException e) {
805 logger.debug("Error getting data from Xiaomi cloud. Mapdata could not be updated: {}", e.getMessage());
806 } catch (IOException e) {
807 logger.debug("Mapdata could not be updated: {}", e.getMessage());
810 logger.debug("Not connected to Xiaomi cloud. Cannot retreive new map: {}", map);
812 return UnDefType.UNDEF;