]> git.basschouten.com Git - openhab-addons.git/blob
83832f3334bdaaa5184e027fc4e51b1163af3128
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.IOException;
18 import java.math.BigDecimal;
19 import java.time.Instant;
20 import java.time.LocalDateTime;
21 import java.util.HashMap;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ScheduledExecutorService;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.ScheduledThreadPoolExecutor;
28 import java.util.concurrent.TimeUnit;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.openhab.binding.miio.internal.Message;
33 import org.openhab.binding.miio.internal.MiIoBindingConfiguration;
34 import org.openhab.binding.miio.internal.MiIoCommand;
35 import org.openhab.binding.miio.internal.MiIoCrypto;
36 import org.openhab.binding.miio.internal.MiIoCryptoException;
37 import org.openhab.binding.miio.internal.MiIoDevices;
38 import org.openhab.binding.miio.internal.MiIoInfoApDTO;
39 import org.openhab.binding.miio.internal.MiIoInfoDTO;
40 import org.openhab.binding.miio.internal.MiIoMessageListener;
41 import org.openhab.binding.miio.internal.MiIoSendCommand;
42 import org.openhab.binding.miio.internal.Utils;
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.transport.MiIoAsyncCommunication;
46 import org.openhab.core.cache.ExpiringCache;
47 import org.openhab.core.common.NamedThreadFactory;
48 import org.openhab.core.config.core.Configuration;
49 import org.openhab.core.library.types.DecimalType;
50 import org.openhab.core.library.types.StringType;
51 import org.openhab.core.thing.ChannelUID;
52 import org.openhab.core.thing.Thing;
53 import org.openhab.core.thing.ThingStatus;
54 import org.openhab.core.thing.ThingStatusDetail;
55 import org.openhab.core.thing.ThingTypeUID;
56 import org.openhab.core.thing.binding.BaseThingHandler;
57 import org.openhab.core.thing.binding.builder.ThingBuilder;
58 import org.openhab.core.types.Command;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 import com.google.gson.Gson;
63 import com.google.gson.GsonBuilder;
64 import com.google.gson.JsonObject;
65 import com.google.gson.JsonPrimitive;
66 import com.google.gson.JsonSyntaxException;
67
68 /**
69  * The {@link MiIoAbstractHandler} is responsible for handling commands, which are
70  * sent to one of the channels.
71  *
72  * @author Marcel Verpaalen - Initial contribution
73  */
74 @NonNullByDefault
75 public abstract class MiIoAbstractHandler extends BaseThingHandler implements MiIoMessageListener {
76     protected static final int MAX_QUEUE = 5;
77     protected static final Gson GSON = new GsonBuilder().create();
78     protected static final String TIMESTAMP = "timestamp";
79
80     protected ScheduledExecutorService miIoScheduler = scheduler;
81     protected @Nullable ScheduledFuture<?> pollingJob;
82     protected MiIoDevices miDevice = MiIoDevices.UNKNOWN;
83     protected boolean isIdentified;
84
85     protected byte[] token = new byte[0];
86
87     protected @Nullable MiIoBindingConfiguration configuration;
88     protected @Nullable MiIoAsyncCommunication miioCom;
89     protected CloudConnector cloudConnector;
90     protected String cloudServer = "";
91     protected int lastId;
92
93     protected Map<Integer, String> cmds = new ConcurrentHashMap<>();
94     protected Map<String, Object> deviceVariables = new HashMap<>();
95     protected final ExpiringCache<String> network = new ExpiringCache<>(CACHE_EXPIRY_NETWORK, () -> {
96         int ret = sendCommand(MiIoCommand.MIIO_INFO);
97         if (ret != 0) {
98             return "id:" + ret;
99         }
100         return "failed";
101     });;
102     protected static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(5);
103     protected static final long CACHE_EXPIRY_NETWORK = TimeUnit.SECONDS.toMillis(60);
104
105     private final Logger logger = LoggerFactory.getLogger(MiIoAbstractHandler.class);
106     protected MiIoDatabaseWatchService miIoDatabaseWatchService;
107
108     public MiIoAbstractHandler(Thing thing, MiIoDatabaseWatchService miIoDatabaseWatchService,
109             CloudConnector cloudConnector) {
110         super(thing);
111         this.miIoDatabaseWatchService = miIoDatabaseWatchService;
112         this.cloudConnector = cloudConnector;
113     }
114
115     @Override
116     public abstract void handleCommand(ChannelUID channelUID, Command command);
117
118     protected boolean handleCommandsChannels(ChannelUID channelUID, Command command) {
119         String cmd = processSubstitutions(command.toString(), deviceVariables);
120         if (channelUID.getId().equals(CHANNEL_COMMAND)) {
121             cmds.put(sendCommand(cmd), channelUID.getId());
122             return true;
123         }
124         if (channelUID.getId().equals(CHANNEL_RPC)) {
125             cmds.put(sendCommand(cmd, cloudServer), channelUID.getId());
126             return true;
127         }
128         return false;
129     }
130
131     @Override
132     public void initialize() {
133         logger.debug("Initializing Mi IO device handler '{}' with thingType {}", getThing().getUID(),
134                 getThing().getThingTypeUID());
135
136         ScheduledThreadPoolExecutor miIoScheduler = new ScheduledThreadPoolExecutor(3,
137                 new NamedThreadFactory(getThing().getUID().getAsString(), true));
138         miIoScheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
139         miIoScheduler.setRemoveOnCancelPolicy(true);
140         this.miIoScheduler = miIoScheduler;
141
142         final MiIoBindingConfiguration configuration = getConfigAs(MiIoBindingConfiguration.class);
143         this.configuration = configuration;
144         if (configuration.host.isEmpty()) {
145             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
146                     "IP address required. Configure IP address");
147             return;
148         }
149         if (!tokenCheckPass(configuration.token)) {
150             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Token required. Configure token");
151             return;
152         }
153         this.cloudServer = configuration.cloudServer;
154         isIdentified = false;
155         deviceVariables.put(TIMESTAMP, Instant.now().getEpochSecond());
156         deviceVariables.put(PROPERTY_DID, configuration.deviceId);
157         miIoScheduler.schedule(this::initializeData, 1, TimeUnit.SECONDS);
158         int pollingPeriod = configuration.refreshInterval;
159         if (pollingPeriod > 0) {
160             pollingJob = miIoScheduler.scheduleWithFixedDelay(() -> {
161                 try {
162                     updateData();
163                 } catch (Exception e) {
164                     logger.debug("Unexpected error during refresh.", e);
165                 }
166             }, 10, pollingPeriod, TimeUnit.SECONDS);
167             logger.debug("Polling job scheduled to run every {} sec. for '{}'", pollingPeriod, getThing().getUID());
168         } else {
169             logger.debug("Polling job disabled. for '{}'", getThing().getUID());
170             miIoScheduler.schedule(this::updateData, 10, TimeUnit.SECONDS);
171         }
172         updateStatus(ThingStatus.OFFLINE);
173     }
174
175     private boolean tokenCheckPass(@Nullable String tokenSting) {
176         if (tokenSting == null) {
177             return false;
178         }
179         switch (tokenSting.length()) {
180             case 16:
181                 token = tokenSting.getBytes();
182                 return true;
183             case 32:
184                 if (!IGNORED_TOKENS.contains(tokenSting)) {
185                     token = Utils.hexStringToByteArray(tokenSting);
186                     return true;
187                 }
188                 return false;
189             case 96:
190                 try {
191                     token = Utils.hexStringToByteArray(MiIoCrypto.decryptToken(Utils.hexStringToByteArray(tokenSting)));
192                     logger.debug("IOS token decrypted to {}", Utils.getHex(token));
193                 } catch (MiIoCryptoException e) {
194                     logger.warn("Could not decrypt token {}{}", tokenSting, e.getMessage());
195                     return false;
196                 }
197                 return true;
198             default:
199                 return false;
200         }
201     }
202
203     @Override
204     public void dispose() {
205         logger.debug("Disposing Xiaomi Mi IO handler '{}'", getThing().getUID());
206         miIoScheduler.shutdown();
207         final ScheduledFuture<?> pollingJob = this.pollingJob;
208         if (pollingJob != null) {
209             pollingJob.cancel(true);
210             this.pollingJob = null;
211         }
212         final @Nullable MiIoAsyncCommunication miioCom = this.miioCom;
213         if (miioCom != null) {
214             lastId = miioCom.getId();
215             miioCom.unregisterListener(this);
216             miioCom.close();
217             this.miioCom = null;
218         }
219         miIoScheduler.shutdownNow();
220     }
221
222     protected int sendCommand(MiIoCommand command) {
223         return sendCommand(command, "[]");
224     }
225
226     protected int sendCommand(MiIoCommand command, String params) {
227         return sendCommand(command.getCommand(), processSubstitutions(params, deviceVariables), getCloudServer(), "");
228     }
229
230     protected int sendCommand(String commandString) {
231         return sendCommand(commandString, getCloudServer());
232     }
233
234     /**
235      * This is used to execute arbitrary commands by sending to the commands channel. Command parameters to be added
236      * between
237      * [] brackets. This to allow for unimplemented commands to be executed (e.g. get detailed historical cleaning
238      * records)
239      *
240      * @param commandString command to be executed
241      * @param cloud server to be used or empty string for direct sending to the device
242      * @return vacuum response
243      */
244     protected int sendCommand(String commandString, String cloudServer) {
245         String command = commandString.trim();
246         command = processSubstitutions(commandString.trim(), deviceVariables);
247         String param = "[]";
248         int sb = command.indexOf("[");
249         int cb = command.indexOf("{");
250         if (Math.max(sb, cb) > 0) {
251             int loc = (Math.min(sb, cb) > 0 ? Math.min(sb, cb) : Math.max(sb, cb));
252             param = command.substring(loc).trim();
253             command = command.substring(0, loc).trim();
254         }
255         return sendCommand(command, param, cloudServer, "");
256     }
257
258     protected int sendCommand(String command, String params, String cloudServer) {
259         return sendCommand(command, processSubstitutions(params, deviceVariables), cloudServer, "");
260     }
261
262     /**
263      * Sends commands to the {@link MiIoAsyncCommunication} for transmission to the Mi devices or cloud
264      *
265      * @param command (method) to be queued for execution
266      * @param parameters to be send with the command
267      * @param cloud server to be used or empty string for direct sending to the device
268      * @param sending subdevice or empty string for regular device
269      * @return message id
270      */
271     protected int sendCommand(String command, String params, String cloudServer, String sender) {
272         try {
273             final MiIoAsyncCommunication connection = getConnection();
274             return (connection != null) ? connection.queueCommand(command, params, cloudServer, sender) : 0;
275         } catch (MiIoCryptoException | IOException e) {
276             logger.debug("Command {} for {} failed (type: {}): {}", command.toString(), getThing().getUID(),
277                     getThing().getThingTypeUID(), e.getLocalizedMessage());
278             disconnected(e.getMessage());
279         }
280         return 0;
281     }
282
283     String getCloudServer() {
284         // This can be improved in the future with additional / more advanced options like e.g. directFirst which would
285         // use direct communications and in case of failures fall back to cloud communication. For now we keep it
286         // simple and only have the option for cloud or direct.
287         final MiIoBindingConfiguration configuration = this.configuration;
288         if (configuration != null) {
289             return configuration.communication.equals("cloud") ? cloudServer : "";
290         }
291         return "";
292     }
293
294     protected boolean skipUpdate() {
295         final MiIoAsyncCommunication miioCom = this.miioCom;
296         if (!hasConnection() || miioCom == null) {
297             logger.debug("Skipping periodic update for '{}'. No Connection", getThing().getUID().toString());
298             return true;
299         }
300         if (getThing().getStatusInfo().getStatusDetail().equals(ThingStatusDetail.CONFIGURATION_ERROR)) {
301             logger.debug("Skipping periodic update for '{}'. Thing Status {}", getThing().getUID().toString(),
302                     getThing().getStatusInfo().getStatusDetail());
303             sendCommand(MiIoCommand.MIIO_INFO);
304             return true;
305         }
306         if (miioCom.getQueueLength() > MAX_QUEUE) {
307             logger.debug("Skipping periodic update for '{}'. {} elements in queue.", getThing().getUID().toString(),
308                     miioCom.getQueueLength());
309             return true;
310         }
311         return false;
312     }
313
314     protected abstract void updateData();
315
316     protected boolean updateNetwork(JsonObject networkData) {
317         try {
318             final MiIoInfoDTO miioInfo = GSON.fromJson(networkData, MiIoInfoDTO.class);
319             final MiIoInfoApDTO ap = miioInfo != null ? miioInfo.ap : null;
320             if (miioInfo != null && ap != null) {
321                 if (ap.getSsid() != null) {
322                     updateState(CHANNEL_SSID, new StringType(ap.getSsid()));
323                 }
324                 if (ap.getBssid() != null) {
325                     updateState(CHANNEL_BSSID, new StringType(ap.getBssid()));
326                 }
327                 if (ap.getRssi() != null) {
328                     updateState(CHANNEL_RSSI, new DecimalType(ap.getRssi()));
329                 } else if (ap.getWifiRssi() != null) {
330                     updateState(CHANNEL_RSSI, new DecimalType(ap.getWifiRssi()));
331                 } else {
332                     logger.debug("No RSSI info in response");
333                 }
334                 if (miioInfo.life != null) {
335                     updateState(CHANNEL_LIFE, new DecimalType(miioInfo.life));
336                 }
337             }
338             return true;
339         } catch (NumberFormatException e) {
340             logger.debug("Could not parse number in network response: {}", networkData);
341         } catch (JsonSyntaxException e) {
342             logger.debug("Could not parse network response: {}", networkData, e);
343         }
344         return false;
345     }
346
347     protected boolean hasConnection() {
348         return getConnection() != null;
349     }
350
351     protected void disconnectedNoResponse() {
352         disconnected("No Response from device");
353     }
354
355     protected void disconnected(@Nullable String message) {
356         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
357                 message != null ? message : "");
358         final MiIoAsyncCommunication miioCom = this.miioCom;
359         if (miioCom != null) {
360             lastId = miioCom.getId();
361             lastId += 10;
362         }
363     }
364
365     protected synchronized @Nullable MiIoAsyncCommunication getConnection() {
366         if (miioCom != null) {
367             return miioCom;
368         }
369         final MiIoBindingConfiguration configuration = getConfigAs(MiIoBindingConfiguration.class);
370         if (configuration.host.isBlank()) {
371             return null;
372         }
373         @Nullable
374         String deviceId = configuration.deviceId;
375         if (deviceId.length() == 8 && deviceId.matches("^.*[a-zA-Z]+.*$")) {
376             logger.warn(
377                     "As per openHAB version 3.2 the deviceId is no longer a string with hexadecimals, instead it is a string with the numeric respresentation of the deviceId. If you continue seeing this message, update deviceId in your thing configuration");
378             deviceId = "";
379         }
380         try {
381             if (!deviceId.isBlank() && tokenCheckPass(configuration.token)) {
382                 final MiIoAsyncCommunication miioCom = new MiIoAsyncCommunication(configuration.host, token, deviceId,
383                         lastId, configuration.timeout, cloudConnector);
384                 if (getCloudServer().isBlank()) {
385                     logger.debug("Ping Mi deviceId '{}' at {}", deviceId, configuration.host);
386                     Message miIoResponse = miioCom.sendPing(configuration.host);
387                     if (miIoResponse != null) {
388                         logger.debug("Ping response from deviceId '{}' at {}. Time stamp: {}, OH time {}, delta {}",
389                                 Utils.fromHEX(Utils.getHex(miIoResponse.getDeviceId())), configuration.host,
390                                 miIoResponse.getTimestamp(), LocalDateTime.now(), miioCom.getTimeDelta());
391                         miioCom.registerListener(this);
392                         this.miioCom = miioCom;
393                         return miioCom;
394                     } else {
395                         miioCom.close();
396                     }
397                 } else {
398                     miioCom.registerListener(this);
399                     this.miioCom = miioCom;
400                     return miioCom;
401                 }
402             } else {
403                 logger.debug("No deviceId defined. Retrieving Mi deviceId");
404                 final MiIoAsyncCommunication miioCom = new MiIoAsyncCommunication(configuration.host, token, "", lastId,
405                         configuration.timeout, cloudConnector);
406                 Message miIoResponse = miioCom.sendPing(configuration.host);
407                 if (miIoResponse != null) {
408                     deviceId = Utils.fromHEX(Utils.getHex(miIoResponse.getDeviceId()));
409                     logger.debug("Ping response from deviceId '{}' at {}. Time stamp: {}, OH time {}, delta {}",
410                             deviceId, configuration.host, miIoResponse.getTimestamp(), LocalDateTime.now(),
411                             miioCom.getTimeDelta());
412                     miioCom.setDeviceId(deviceId);
413                     logger.debug("Using retrieved Mi deviceId: {}", deviceId);
414                     updateDeviceIdConfig(deviceId);
415                     miioCom.registerListener(this);
416                     this.miioCom = miioCom;
417                     return miioCom;
418                 } else {
419                     miioCom.close();
420                 }
421             }
422             logger.debug("Ping response from deviceId '{}' at {} FAILED", configuration.deviceId, configuration.host);
423             disconnectedNoResponse();
424             return null;
425         } catch (IOException e) {
426             logger.debug("Could not connect to {} at {}", getThing().getUID().toString(), configuration.host);
427             disconnected(e.getMessage());
428             return null;
429         }
430     }
431
432     private void updateDeviceIdConfig(String deviceId) {
433         if (!deviceId.isEmpty()) {
434             updateProperty(Thing.PROPERTY_SERIAL_NUMBER, deviceId);
435             Configuration config = editConfiguration();
436             config.put(PROPERTY_DID, deviceId);
437             updateConfiguration(config);
438             deviceVariables.put(PROPERTY_DID, deviceId);
439         } else {
440             logger.debug("Could not update config with deviceId: {}", deviceId);
441         }
442     }
443
444     protected boolean initializeData() {
445         this.miioCom = getConnection();
446         return true;
447     }
448
449     protected void refreshNetwork() {
450         network.getValue();
451     }
452
453     protected void defineDeviceType(JsonObject miioInfo) {
454         updateProperties(miioInfo);
455         isIdentified = updateThingType(miioInfo);
456     }
457
458     private void updateProperties(JsonObject miioInfo) {
459         final MiIoInfoDTO info = GSON.fromJson(miioInfo, MiIoInfoDTO.class);
460         if (info == null) {
461             return;
462         }
463         Map<String, String> properties = editProperties();
464         if (info.model != null) {
465             properties.put(Thing.PROPERTY_MODEL_ID, info.model);
466         }
467         if (info.fwVer != null) {
468             properties.put(Thing.PROPERTY_FIRMWARE_VERSION, info.fwVer);
469         }
470         if (info.hwVer != null) {
471             properties.put(Thing.PROPERTY_HARDWARE_VERSION, info.hwVer);
472         }
473         if (info.wifiFwVer != null) {
474             properties.put("wifiFirmware", info.wifiFwVer);
475         }
476         if (info.mcuFwVer != null) {
477             properties.put("mcuFirmware", info.mcuFwVer);
478         }
479         deviceVariables.putAll(properties);
480         updateProperties(properties);
481     }
482
483     protected String processSubstitutions(String cmd, Map<String, Object> deviceVariables) {
484         if (!cmd.contains("$")) {
485             return cmd;
486         }
487         String returnCmd = cmd.replace("\"$", "$").replace("$\"", "$");
488         String cmdParts[] = cmd.split("\\$");
489         if (logger.isTraceEnabled()) {
490             logger.debug("processSubstitutions {} ", cmd);
491             for (Entry<String, Object> e : deviceVariables.entrySet()) {
492                 logger.debug("key, value:  {}  -> {}", e.getKey(), e.getValue());
493             }
494         }
495         for (String substitute : cmdParts) {
496             if (deviceVariables.containsKey(substitute)) {
497                 String replacementString = "";
498                 Object replacement = deviceVariables.get(substitute);
499                 if (replacement == null) {
500                     logger.debug("Replacement for '{}' is null. skipping replacement", substitute);
501                     continue;
502                 }
503                 if (replacement instanceof Integer || replacement instanceof Long || replacement instanceof Double
504                         || replacement instanceof BigDecimal || replacement instanceof Boolean) {
505                     replacementString = replacement.toString();
506                 } else if (replacement instanceof JsonPrimitive) {
507                     replacementString = ((JsonPrimitive) replacement).getAsString();
508                 } else if (replacement instanceof String) {
509                     replacementString = "\"" + (String) replacement + "\"";
510                 } else {
511                     replacementString = String.valueOf(replacement);
512                 }
513                 returnCmd = returnCmd.replace("$" + substitute + "$", replacementString);
514             }
515         }
516         return returnCmd;
517     }
518
519     protected boolean updateThingType(JsonObject miioInfo) {
520         MiIoBindingConfiguration configuration = getConfigAs(MiIoBindingConfiguration.class);
521         String model = miioInfo.get("model").getAsString();
522         miDevice = MiIoDevices.getType(model);
523         if (configuration.model.isEmpty()) {
524             Configuration config = editConfiguration();
525             config.put(PROPERTY_MODEL, model);
526             updateConfiguration(config);
527             configuration = getConfigAs(MiIoBindingConfiguration.class);
528         }
529         if (!configuration.model.equals(model)) {
530             logger.info("Mi Device model {} has model config: {}. Unexpected unless manual override", model,
531                     configuration.model);
532         }
533         if (miDevice.getThingType().equals(getThing().getThingTypeUID())
534                 && !(miDevice.getThingType().equals(THING_TYPE_UNSUPPORTED)
535                         && miIoDatabaseWatchService.getDatabaseUrl(model) != null)) {
536             logger.debug("Mi Device model {} identified as: {}. Matches thingtype {}", model, miDevice.toString(),
537                     miDevice.getThingType().toString());
538             return true;
539         } else {
540             if (getThing().getThingTypeUID().equals(THING_TYPE_MIIO)
541                     || getThing().getThingTypeUID().equals(THING_TYPE_UNSUPPORTED)) {
542                 changeType(model);
543             } else {
544                 logger.info(
545                         "Mi Device model {} identified as: {}, thingtype {}. Does not matches thingtype {}. Unexpected, unless manual override.",
546                         miDevice.toString(), miDevice.getThingType(), getThing().getThingTypeUID().toString(),
547                         miDevice.getThingType().toString());
548                 return true;
549             }
550         }
551         return false;
552     }
553
554     /**
555      * Changes the {@link org.openhab.core.thing.type.ThingType} to the right type once it is retrieved from
556      * the device.
557      *
558      * @param modelId String with the model id
559      */
560     private void changeType(final String modelId) {
561         final ScheduledFuture<?> pollingJob = this.pollingJob;
562         if (pollingJob != null) {
563             pollingJob.cancel(true);
564             this.pollingJob = null;
565         }
566         miIoScheduler.schedule(() -> {
567             String label = getThing().getLabel();
568             if (label == null || label.startsWith("Xiaomi Mi Device")) {
569                 ThingBuilder thingBuilder = editThing();
570                 thingBuilder.withLabel(miDevice.getDescription());
571                 updateThing(thingBuilder.build());
572             }
573             logger.info("Mi Device model {} identified as: {}. Does not match thingtype {}. Changing thingtype to {}",
574                     modelId, miDevice.toString(), getThing().getThingTypeUID().toString(),
575                     miDevice.getThingType().toString());
576             ThingTypeUID thingTypeUID = MiIoDevices.getType(modelId).getThingType();
577             if (thingTypeUID.equals(THING_TYPE_UNSUPPORTED)
578                     && miIoDatabaseWatchService.getDatabaseUrl(modelId) != null) {
579                 thingTypeUID = THING_TYPE_BASIC;
580             }
581             changeThingType(thingTypeUID, getConfig());
582         }, 10, TimeUnit.SECONDS);
583     }
584
585     @Override
586     public void onStatusUpdated(ThingStatus status, ThingStatusDetail statusDetail) {
587         updateStatus(status, statusDetail);
588     }
589
590     @Override
591     public void onMessageReceived(MiIoSendCommand response) {
592         logger.debug("Received response for device {} type: {}, result: {}, fullresponse: {}",
593                 getThing().getUID().getId(), response.getCommand(), response.getResult(), response.getResponse());
594         if (response.isError()) {
595             logger.debug("Error received for command '{}': {}.", response.getCommandString(),
596                     response.getResponse().get("error"));
597             if (MiIoCommand.MIIO_INFO.equals(response.getCommand())) {
598                 network.invalidateValue();
599             }
600             return;
601         }
602         try {
603             switch (response.getCommand()) {
604                 case MIIO_INFO:
605                     if (!isIdentified) {
606                         defineDeviceType(response.getResult().getAsJsonObject());
607                     }
608                     updateNetwork(response.getResult().getAsJsonObject());
609                     break;
610                 default:
611                     break;
612             }
613             if (cmds.containsKey(response.getId())) {
614                 String channel = cmds.get(response.getId());
615                 if (channel != null && (CHANNEL_COMMAND.contentEquals(channel) || CHANNEL_RPC.contentEquals(channel))) {
616                     updateState(channel, new StringType(response.getResponse().toString()));
617                     cmds.remove(response.getId());
618                 }
619             }
620         } catch (Exception e) {
621             logger.debug("Error while handing message {}", response.getResponse(), e);
622         }
623     }
624 }