]> git.basschouten.com Git - openhab-addons.git/blob
2d605dba427ad89672d16d79835ec11c977e08e5
[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.shelly.internal.api1;
14
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.*;
17 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
18
19 import java.net.SocketException;
20 import java.net.UnknownHostException;
21 import java.util.LinkedHashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.TreeMap;
25
26 import org.eclipse.californium.core.CoapClient;
27 import org.eclipse.californium.core.coap.CoAP.Code;
28 import org.eclipse.californium.core.coap.CoAP.ResponseCode;
29 import org.eclipse.californium.core.coap.CoAP.Type;
30 import org.eclipse.californium.core.coap.MessageObserverAdapter;
31 import org.eclipse.californium.core.coap.Option;
32 import org.eclipse.californium.core.coap.OptionNumberRegistry;
33 import org.eclipse.californium.core.coap.Request;
34 import org.eclipse.californium.core.coap.Response;
35 import org.eclipse.californium.core.network.Endpoint;
36 import org.eclipse.jdt.annotation.NonNullByDefault;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.openhab.binding.shelly.internal.api.ShellyApiException;
39 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
40 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
41 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDescrBlk;
42 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDescrSen;
43 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDevDescrTypeAdapter;
44 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDevDescription;
45 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotGenericSensorList;
46 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotSensor;
47 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotSensorTypeAdapter;
48 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
49 import org.openhab.binding.shelly.internal.handler.ShellyColorUtils;
50 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
51 import org.openhab.core.library.unit.Units;
52 import org.openhab.core.types.State;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 import com.google.gson.Gson;
57 import com.google.gson.GsonBuilder;
58 import com.google.gson.JsonSyntaxException;
59
60 /**
61  * The {@link Shelly1CoapHandler} handles the CoIoT/CoAP registration and events.
62  *
63  * @author Markus Michels - Initial contribution
64  */
65 @NonNullByDefault
66 public class Shelly1CoapHandler implements Shelly1CoapListener {
67     private static final byte[] EMPTY_BYTE = new byte[0];
68
69     private final Logger logger = LoggerFactory.getLogger(Shelly1CoapHandler.class);
70     private final ShellyThingInterface thingHandler;
71     private ShellyThingConfiguration config = new ShellyThingConfiguration();
72     private final GsonBuilder gsonBuilder = new GsonBuilder();
73     private final Gson gson;
74     private String thingName;
75
76     private boolean coiotBound = false;
77     private Shelly1CoIoTInterface coiot;
78     private int coiotVers = -1;
79
80     private final Shelly1CoapServer coapServer;
81     private @Nullable CoapClient statusClient;
82     private Request reqDescription = new Request(Code.GET, Type.CON);
83     private Request reqStatus = new Request(Code.GET, Type.CON);
84     private boolean updatesRequested = false;
85     private int coiotPort = COIOT_PORT;
86
87     private int lastSerial = -1;
88     private String lastPayload = "";
89     private Map<String, CoIotDescrBlk> blkMap = new LinkedHashMap<>();
90     private Map<String, CoIotDescrSen> sensorMap = new LinkedHashMap<>();
91     private ShellyDeviceProfile profile;
92     private ShellyApiInterface api;
93
94     public Shelly1CoapHandler(ShellyThingInterface thingHandler, Shelly1CoapServer coapServer) {
95         this.thingHandler = thingHandler;
96         this.thingName = thingHandler.getThingName();
97         this.profile = thingHandler.getProfile();
98         this.api = thingHandler.getApi();
99         this.coapServer = coapServer;
100         this.coiot = new Shelly1CoIoTVersion2(thingName, thingHandler, blkMap, sensorMap); // Default: V2
101
102         gsonBuilder.registerTypeAdapter(CoIotDevDescription.class, new CoIotDevDescrTypeAdapter());
103         gsonBuilder.registerTypeAdapter(CoIotGenericSensorList.class, new CoIotSensorTypeAdapter());
104         gson = gsonBuilder.create();
105     }
106
107     /**
108      * Initialize CoAP access, send discovery packet and start Status server
109      *
110      * @parm thingName Thing name derived from Thing Type/hostname
111      * @parm config ShellyThingConfiguration
112      * @thows ShellyApiException
113      */
114     public synchronized void start(String thingName, ShellyThingConfiguration config) throws ShellyApiException {
115         try {
116             this.thingName = thingName;
117             this.config = config;
118             this.profile = thingHandler.getProfile();
119             if (isStarted()) {
120                 logger.trace("{}: CoAP Listener was already started", thingName);
121                 stop();
122             }
123
124             logger.debug("{}: Starting CoAP Listener", thingName);
125             if (!profile.coiotEndpoint.isEmpty() && profile.coiotEndpoint.contains(":")) {
126                 String ps = substringAfter(profile.coiotEndpoint, ":");
127                 coiotPort = Integer.parseInt(ps);
128             }
129             coapServer.start(config.localIp, coiotPort, this);
130             statusClient = new CoapClient(completeUrl(config.deviceIp, coiotPort, COLOIT_URI_DEVSTATUS))
131                     .setTimeout((long) SHELLY_API_TIMEOUT_MS).useNONs().setEndpoint(coapServer.getEndpoint());
132             @Nullable
133             Endpoint endpoint = null;
134             CoapClient client = statusClient;
135             if (client != null) {
136                 endpoint = client.getEndpoint();
137             }
138             if ((endpoint == null) || !endpoint.isStarted()) {
139                 logger.warn("{}: Unable to initialize CoAP access (network error)", thingName);
140                 throw new ShellyApiException("Network initialization failed");
141             }
142
143             discover();
144         } catch (SocketException e) {
145             logger.warn("{}: Unable to initialize CoAP access (socket exception) - {}", thingName, e.getMessage());
146             throw new ShellyApiException("Network error", e);
147         } catch (UnknownHostException e) {
148             logger.info("{}: CoAP Exception (Unknown Host)", thingName, e);
149             throw new ShellyApiException("Unknown Host: " + config.deviceIp, e);
150         }
151     }
152
153     public boolean isStarted() {
154         return statusClient != null;
155     }
156
157     /**
158      * Process an inbound Response (or mapped Request): decode CoAP options. handle discovery result or status updates
159      *
160      * @param response The Response packet
161      */
162     @Override
163     public void processResponse(@Nullable Response response) {
164         if (response == null) {
165             thingHandler.incProtErrors();
166             return; // other device instance
167         }
168         ResponseCode code = response.getCode();
169         if (code != ResponseCode.CONTENT) {
170             // error handling
171             logger.debug("{}: Unknown Response Code {} received, payload={}", thingName, code,
172                     response.getPayloadString());
173             thingHandler.incProtErrors();
174             return;
175         }
176
177         List<Option> options = response.getOptions().asSortedList();
178         String ip = response.getSourceContext().getPeerAddress().toString();
179         boolean match = ip.contains(config.deviceIp);
180         if (!match) {
181             // We can't identify device by IP, so we need to check the CoAP header's Global Device ID
182             for (Option opt : options) {
183                 if (opt.getNumber() == COIOT_OPTION_GLOBAL_DEVID) {
184                     String devid = opt.getStringValue();
185                     if (devid.contains("#")) {
186                         // Format: <device type>#<mac address>#<coap version>
187                         String macid = substringBetween(devid, "#", "#");
188                         if (profile.mac.toUpperCase().contains(macid.toUpperCase())) {
189                             match = true;
190                             break;
191                         }
192                     }
193                 }
194             }
195         }
196         if (!match) {
197             // other instance
198             return;
199         }
200
201         String payload = "";
202         String devId = "";
203         String uri = "";
204         int serial = -1;
205         try {
206             thingHandler.incProtMessages();
207             if (logger.isDebugEnabled()) {
208                 logger.debug("{}: CoIoT Message from {} (MID={}): {}", thingName,
209                         response.getSourceContext().getPeerAddress(), response.getMID(), response.getPayloadString());
210             }
211             if (response.isCanceled() || response.isDuplicate() || response.isRejected()) {
212                 logger.debug("{} ({}): Packet was canceled, rejected or is a duplicate -> discard", thingName, devId);
213                 thingHandler.incProtErrors();
214                 return;
215             }
216
217             payload = response.getPayloadString();
218             for (Option opt : options) {
219                 switch (opt.getNumber()) {
220                     case OptionNumberRegistry.URI_PATH:
221                         uri = COLOIT_URI_BASE + opt.getStringValue();
222                         break;
223                     case OptionNumberRegistry.URI_HOST: // ignore
224                         break;
225                     case OptionNumberRegistry.CONTENT_FORMAT: // ignore
226                         break;
227                     case COIOT_OPTION_GLOBAL_DEVID:
228                         devId = opt.getStringValue();
229                         String sVersion = substringAfterLast(devId, "#");
230                         int iVersion = Integer.parseInt(sVersion);
231                         if (coiotBound && (coiotVers != iVersion)) {
232                             logger.debug("{}: CoIoT versopm has changed from {} to {}, maybe the firmware was upgraded",
233                                     thingName, coiotVers, iVersion);
234                             thingHandler.reinitializeThing();
235                             coiotBound = false;
236                         }
237                         if (!coiotBound) {
238                             thingHandler.updateProperties(PROPERTY_COAP_VERSION, sVersion);
239                             logger.debug("{}: CoIoT Version {} detected", thingName, iVersion);
240                             if (iVersion == COIOT_VERSION_1) {
241                                 coiot = new Shelly1CoIoTVersion1(thingName, thingHandler, blkMap, sensorMap);
242                             } else if (iVersion == COIOT_VERSION_2) {
243                                 coiot = new Shelly1CoIoTVersion2(thingName, thingHandler, blkMap, sensorMap);
244                             } else {
245                                 logger.warn("{}: Unsupported CoAP version detected: {}", thingName, sVersion);
246                                 return;
247                             }
248                             coiotVers = iVersion;
249                             coiotBound = true;
250                         }
251                         break;
252                     case COIOT_OPTION_STATUS_VALIDITY:
253                         break;
254                     case COIOT_OPTION_STATUS_SERIAL:
255                         serial = opt.getIntegerValue();
256                         break;
257                     default:
258                         logger.debug("{} ({}): COAP option {} with value {} skipped", thingName, devId, opt.getNumber(),
259                                 opt.getValue());
260                 }
261             }
262
263             // If we received a CoAP message successful the thing must be online
264             thingHandler.setThingOnline();
265
266             // The device changes the serial on every update, receiving a message with the same serial is a
267             // duplicate, excep for battery devices! Those reset the serial every time when they wake-up
268             if ((serial == lastSerial) && payload.equals(lastPayload) && (!profile.hasBattery
269                     || coiot.getLastWakeup().equalsIgnoreCase("ext_power") || ((serial & 0xFF) != 0))) {
270                 logger.debug("{}: Serial {} was already processed, ignore update", thingName, serial);
271                 return;
272             }
273
274             // fixed malformed JSON :-(
275             payload = fixJSON(payload);
276
277             try {
278                 if (uri.equalsIgnoreCase(COLOIT_URI_DEVDESC) || (uri.isEmpty() && payload.contains(COIOT_TAG_BLK))) {
279                     handleDeviceDescription(devId, payload);
280                 } else if (uri.equalsIgnoreCase(COLOIT_URI_DEVSTATUS)
281                         || (uri.isEmpty() && payload.contains(COIOT_TAG_GENERIC))) {
282                     handleStatusUpdate(devId, payload, serial);
283                 }
284             } catch (ShellyApiException e) {
285                 logger.debug("{}: Unable to process CoIoT message: {}", thingName, e.toString());
286                 thingHandler.incProtErrors();
287             }
288
289             if (!updatesRequested) {
290                 // Observe Status Updates
291                 reqStatus = sendRequest(reqStatus, config.deviceIp, COLOIT_URI_DEVSTATUS, Type.NON);
292                 updatesRequested = true;
293             }
294         } catch (JsonSyntaxException | IllegalArgumentException | NullPointerException e) {
295             logger.debug("{}: Unable to process CoIoT Message for payload={}", thingName, payload, e);
296             resetSerial();
297             thingHandler.incProtErrors();
298         }
299     }
300
301     /**
302      * Process a CoIoT device description message. This includes definitions on device units (Relay0, Relay1, Sensors
303      * etc.) as well as a definition of sensors and actors. This information needs to be stored allowing to map ids from
304      * status updates to the device units and matching the correct thing channel.
305      *
306      * @param devId The device id reported in the CoIoT message.
307      * @param payload Device desciption in JSon format, example:
308      *            {"blk":[{"I":0,"D":"Relay0"}],"sen":[{"I":112,"T":"Switch","R":"0/1","L":0}],"act":[{"I":211,"D":"Switch","L":0,"P":[{"I":2011,"D":"ToState","R":"0/1"}]}]}
309      */
310     private void handleDeviceDescription(String devId, String payload) throws ShellyApiException {
311         logger.debug("{}: CoIoT Device Description for {}: {}", thingName, devId, payload);
312
313         try {
314             boolean valid = true;
315
316             // Decode Json
317             CoIotDevDescription descr = fromJson(gson, payload, CoIotDevDescription.class);
318             for (int i = 0; i < descr.blk.size(); i++) {
319                 CoIotDescrBlk blk = descr.blk.get(i);
320                 logger.debug("{}:    id={}: {}", thingName, blk.id, blk.desc);
321                 if (!blkMap.containsKey(blk.id)) {
322                     blkMap.put(blk.id, blk);
323                 } else {
324                     blkMap.replace(blk.id, blk);
325                 }
326                 if ((blk.type != null) && !blk.type.isEmpty()) {
327                     // in fact it is a sen entry - that's vioaling the Spec
328                     logger.trace("{}:    fix: auto-create sensor definition for id {}/{}!", thingName, blk.id,
329                             blk.desc);
330                     CoIotDescrSen sen = new CoIotDescrSen();
331                     sen.id = blk.id;
332                     sen.desc = blk.desc;
333                     sen.type = blk.type;
334                     sen.range = blk.range;
335                     sen.links = blk.links;
336                     valid &= addSensor(sen);
337                 }
338             }
339
340             // Save to thing properties
341             thingHandler.updateProperties(PROPERTY_COAP_DESCR, payload);
342
343             logger.debug("{}: Adding {} sensor definitions", thingName, descr.sen.size());
344             if (descr.sen != null) {
345                 for (int i = 0; i < descr.sen.size(); i++) {
346                     valid &= addSensor(descr.sen.get(i));
347                 }
348             }
349             coiot.completeMissingSensorDefinition(sensorMap);
350
351             if (!valid) {
352                 logger.debug(
353                         "{}: Incompatible device description detected for CoIoT version {} (id length mismatch), discarding!",
354                         thingName, coiot.getVersion());
355
356                 discover();
357                 return;
358             }
359         } catch (JsonSyntaxException e) {
360             logger.warn("{}: Unable to parse CoAP Device Description! JSON={}", thingName, payload);
361         } catch (NullPointerException | IllegalArgumentException e) {
362             logger.warn("{}: Unable to parse CoAP Device Description! JSON={}", thingName, payload, e);
363         }
364     }
365
366     /**
367      * Add a new sensor to the sensor table
368      *
369      * @param sen CoIotDescrSen of the sensor
370      */
371     private synchronized boolean addSensor(CoIotDescrSen sen) {
372         logger.debug("{}:    id {}: {}, Type={}, Range={}, Links={}", thingName, sen.id, sen.desc, sen.type, sen.range,
373                 sen.links);
374         // CoIoT version 2 changes from 3 digit IDs to 4 digit IDs
375         // We need to make sure that the persisted device description matches,
376         // otherwise the stored one is discarded and a new discovery is triggered
377         // This happens on firmware up/downgrades (version 1.8 brings CoIoT v2 with 4 digit IDs)
378         int vers = coiot.getVersion();
379         if (((vers == COIOT_VERSION_1) && (sen.id.length() > 3))
380                 || ((vers >= COIOT_VERSION_2) && (sen.id.length() < 4))) {
381             logger.debug("{}: Invalid format for sensor defition detected, id={}", thingName, sen.id);
382             return false;
383         }
384
385         try {
386             CoIotDescrSen fixed = coiot.fixDescription(sen, blkMap);
387             if (!sensorMap.containsKey(fixed.id)) {
388                 sensorMap.put(sen.id, fixed);
389             } else {
390                 sensorMap.replace(sen.id, fixed);
391             }
392         } catch (NullPointerException | IllegalArgumentException e) { // depending on firmware release the CoAP device
393                                                                       // description is buggy
394             logger.debug("{}: Unable to decode sensor definition -> skip", thingName, e);
395         }
396
397         return true;
398     }
399
400     /**
401      * Process CoIoT status update message. If a status update is received, but the device description has not been
402      * received yet a GET is send to query device description.
403      *
404      * @param devId device id included in the status packet
405      * @param payload CoAP payload (Json format), example: {"G":[[0,112,0]]}
406      * @param serial Serial for this request. If this the the same as last serial
407      *            the update was already sent and processed so this one gets
408      *            ignored.
409      * @throws ShellyApiException
410      */
411     private void handleStatusUpdate(String devId, String payload, int serial) throws ShellyApiException {
412         logger.debug("{}: CoIoT Sensor data {} (serial={})", thingName, payload, serial);
413         if (blkMap.isEmpty()) {
414             // send discovery packet
415             resetSerial();
416             discover();
417
418             // try to uses description from last initialization
419             String savedDescr = thingHandler.getProperty(PROPERTY_COAP_DESCR);
420             if (savedDescr.isEmpty()) {
421                 logger.debug("{}: Device description not yet received, trigger auto-initialization", thingName);
422                 return;
423             }
424
425             // simulate received device description to create element table
426             logger.debug("{}: Device description for {} restored: {}", thingName, devId, savedDescr);
427             handleDeviceDescription(devId, savedDescr);
428         }
429
430         // Parse Json,
431         CoIotGenericSensorList list = fromJson(gson, fixJSON(payload), CoIotGenericSensorList.class);
432         if (list.generic == null) {
433             logger.debug("{}: Sensor list has invalid format! Payload: {}", devId, payload);
434             return;
435         }
436
437         List<CoIotSensor> sensorUpdates = list.generic;
438         Map<String, State> updates = new TreeMap<String, State>();
439         logger.debug("{}: {} CoAP sensor updates received", thingName, sensorUpdates.size());
440         int failed = 0;
441         ShellyColorUtils col = new ShellyColorUtils();
442         for (int i = 0; i < sensorUpdates.size(); i++) {
443             try {
444                 CoIotSensor s = sensorUpdates.get(i);
445                 CoIotDescrSen sen = sensorMap.get(s.id);
446                 if (sen == null) {
447                     logger.debug("{}: Unable to sensor definition for id={}, payload={}", thingName, s.id, payload);
448                     continue;
449                 }
450                 // find matching sensor definition from device description, use the Link ID as index
451                 CoIotDescrBlk element = null;
452                 sen = coiot.fixDescription(sen, blkMap);
453                 element = blkMap.get(sen.links);
454                 if (element == null) {
455                     logger.debug("{}: Unable to find BLK for link {} from sen.id={}, payload={}", thingName, sen.links,
456                             sen.id, payload);
457                     continue;
458                 }
459                 logger.trace("{}:  Sensor value[{}]: id={}, Value={} ({}, Type={}, Range={}, Link={}: {})", thingName,
460                         i, s.id, getString(s.valueStr).isEmpty() ? s.value : s.valueStr, sen.desc, sen.type, sen.range,
461                         sen.links, element.desc);
462
463                 if (!coiot.handleStatusUpdate(sensorUpdates, sen, serial, s, updates, col)) {
464                     logger.debug("{}: CoIoT data for id {}, type {}/{} not processed, value={}; payload={}", thingName,
465                             sen.id, sen.type, sen.desc, s.value, payload);
466                 }
467             } catch (NullPointerException | IllegalArgumentException e) {
468                 // even the processing of one value failed we continue with the next one (sometimes this is caused by
469                 // buggy formats provided by the device
470                 logger.debug("{}: Unable to process data from sensor[{}], devId={}, payload={}", thingName, i, devId,
471                         payload, e);
472             }
473         }
474
475         if (!updates.isEmpty()) {
476             int updated = 0;
477             for (Map.Entry<String, State> u : updates.entrySet()) {
478                 String key = u.getKey();
479                 updated += thingHandler.updateChannel(key, u.getValue(), false) ? 1 : 0;
480             }
481             if (updated > 0) {
482                 logger.debug("{}: {} channels updated from CoIoT status, serial={}", thingName, updated, serial);
483                 if (profile.isSensor || profile.isRoller) {
484                     // CoAP is currently lacking the lastUpdate info, so we use host timestamp
485                     thingHandler.updateChannel(profile.getControlGroup(0), CHANNEL_LAST_UPDATE, getTimestamp());
486                 }
487             }
488
489             if (profile.isLight && profile.inColor && col.isRgbValid()) {
490                 // Update color picker from single values
491                 if (col.isRgbValid()) {
492                     thingHandler.updateChannel(mkChannelId(CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_PICKER),
493                             col.toHSB(), false);
494                 }
495             }
496
497             if ((profile.isRGBW2 && !profile.inColor) || profile.isRoller) {
498                 // Aggregate Meter Data from different Coap updates
499                 int i = 1;
500                 double totalCurrent = 0.0;
501                 @SuppressWarnings("unused")
502                 double totalKWH = 0.0;
503                 boolean updateMeter = false;
504                 while (i <= thingHandler.getProfile().numMeters) {
505                     String meter = CHANNEL_GROUP_METER + i;
506                     double current = thingHandler.getChannelDouble(meter, CHANNEL_METER_CURRENTWATTS);
507                     double total = thingHandler.getChannelDouble(meter, CHANNEL_METER_TOTALKWH);
508                     totalCurrent += current >= 0 ? current : 0;
509                     totalKWH += total >= 0 ? total : 0;
510                     updateMeter |= current >= 0 | total >= 0;
511                     i++;
512                 }
513                 if (updateMeter) {
514                     thingHandler.updateChannel(CHANNEL_GROUP_METER, CHANNEL_METER_CURRENTWATTS,
515                             toQuantityType(totalCurrent, DIGITS_WATT, Units.WATT));
516                     thingHandler.updateChannel(CHANNEL_GROUP_METER, CHANNEL_LAST_UPDATE, getTimestamp());
517                 }
518             }
519
520             // Old firmware release are lacking various status values, which are not updated using CoIoT.
521             // In this case we keep a refresh so it gets polled using REST. Beginning with Firmware 1.6 most
522             // of the values are available
523             thingHandler.triggerUpdateFromCoap();
524         } else {
525             if (failed == sensorUpdates.size()) {
526                 logger.debug("{}: Device description problem detected, re-discover", thingName);
527                 coiotBound = false;
528                 discover();
529             }
530         }
531
532         // Remember serial, new packets with same serial will be ignored
533         lastSerial = serial;
534         lastPayload = payload;
535     }
536
537     private void discover() {
538         if (coiot.getVersion() >= 2) {
539             {
540                 try {
541                     // Try to device description using http request (FW 1.10+)
542                     String payload = api.getCoIoTDescription();
543                     if (!payload.isEmpty()) {
544                         logger.debug("{}: Using CoAP device description from successful HTTP /cit/d", thingName);
545                         handleDeviceDescription(thingName, payload);
546                         return;
547                     }
548                 } catch (ShellyApiException e) {
549                     // ignore if not supported by device
550                 }
551             }
552         }
553         reqDescription = sendRequest(reqDescription, config.deviceIp, COLOIT_URI_DEVDESC, Type.CON);
554     }
555
556     /**
557      * Fix malformed JSON - stupid, but the devices sometimes return malformed JSON with then causes a
558      * JsonSyntaxException
559      *
560      * @param json to be checked/fixed
561      */
562     private static String fixJSON(String payload) {
563         String json = payload;
564         json = json.replace("}{", "},{");
565         json = json.replace("][", "],[");
566         json = json.replace("],,[", "],[");
567         return json;
568     }
569
570     /**
571      * Send a new request (Discovery to get Device Description). Before a pending
572      * request will be canceled.
573      *
574      * @param request The current request (this will be canceled an a new one will
575      *            be created)
576      * @param ipAddress Device's IP address
577      * @param uri The URI we are calling (CoIoT = /cit/d or /cit/s)
578      * @param con true: send as CON, false: send as NON
579      * @return new packet
580      */
581     private Request sendRequest(@Nullable Request request, String ipAddress, String uri, Type con) {
582         if ((request != null) && !request.isCanceled()) {
583             request.cancel();
584         }
585
586         resetSerial();
587         return newRequest(ipAddress, coiotPort, uri, con).send();
588     }
589
590     /**
591      * Allocate a new Request structure. A message observer will be added to get the
592      * callback when a response has been received.
593      *
594      * @param ipAddress IP address of the device
595      * @param uri URI to be addressed
596      * @param uri The URI we are calling (CoIoT = /cit/d or /cit/s)
597      * @param con true: send as CON, false: send as NON
598      * @return new packet
599      */
600
601     private Request newRequest(String ipAddress, int port, String uri, Type con) {
602         // We need to build our own Request to set an empty Token
603         Request request = new Request(Code.GET, con);
604         request.setURI(completeUrl(ipAddress, port, uri));
605         request.setToken(EMPTY_BYTE);
606         request.addMessageObserver(new MessageObserverAdapter() {
607             @Override
608             public void onResponse(@Nullable Response response) {
609                 processResponse(response);
610             }
611
612             @Override
613             public void onCancel() {
614                 logger.debug("{}: CoAP Request was canceled", thingName);
615             }
616
617             @Override
618             public void onTimeout() {
619                 logger.debug("{}: CoAP Request timed out", thingName);
620             }
621         });
622         return request;
623     }
624
625     /**
626      * Reset serial and payload used to detect duplicate messages, which have to be ignored.
627      * We can't rely that the device manages serials correctly all the time. There are firmware releases sending updated
628      * sensor information with the serial from the last packet, which is wrong. We bypass this problem by comparing also
629      * the payload.
630      */
631     private void resetSerial() {
632         lastSerial = -1;
633         lastPayload = "";
634     }
635
636     public int getVersion() {
637         return coiotVers;
638     }
639
640     /**
641      * Cancel pending requests and shutdown the client
642      */
643     public synchronized void stop() {
644         if (isStarted()) {
645             logger.debug("{}: Stopping CoAP Listener", thingName);
646             coapServer.stop(this);
647             CoapClient cclient = statusClient;
648             if (cclient != null) {
649                 cclient.shutdown();
650                 statusClient = null;
651             }
652             Request request = reqDescription;
653             if (!request.isCanceled()) {
654                 request.cancel();
655             }
656             request = reqStatus;
657             if (!request.isCanceled()) {
658                 request.cancel();
659             }
660         }
661         resetSerial();
662         coiotBound = false;
663     }
664
665     public void dispose() {
666         stop();
667     }
668
669     private static String completeUrl(String ipAddress, int port, String uri) {
670         return "coap://" + ipAddress + ":" + port + uri;
671     }
672 }