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