2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.shelly.internal.coap;
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.*;
19 import java.net.SocketException;
20 import java.net.UnknownHostException;
21 import java.util.LinkedHashMap;
22 import java.util.List;
24 import java.util.TreeMap;
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;
56 import com.google.gson.Gson;
57 import com.google.gson.GsonBuilder;
58 import com.google.gson.JsonSyntaxException;
61 * The {@link ShellyCoapHandler} handles the CoIoT/CoAP registration and events.
63 * @author Markus Michels - Initial contribution
66 public class ShellyCoapHandler implements ShellyCoapListener {
67 private static final byte[] EMPTY_BYTE = new byte[0];
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;
76 private boolean coiotBound = false;
77 private ShellyCoIoTInterface coiot;
78 private int coiotVers = -1;
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;
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;
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
104 gsonBuilder.registerTypeAdapter(CoIotDevDescription.class, new CoIotDevDescrTypeAdapter());
105 gsonBuilder.registerTypeAdapter(CoIotGenericSensorList.class, new CoIotSensorTypeAdapter());
106 gson = gsonBuilder.create();
110 * Initialize CoAP access, send discovery packet and start Status server
112 * @parm thingName Thing name derived from Thing Type/hostname
113 * @parm config ShellyThingConfiguration
114 * @thows ShellyApiException
116 public synchronized void start(String thingName, ShellyThingConfiguration config) throws ShellyApiException {
118 this.thingName = thingName;
119 this.config = config;
120 this.profile = thingHandler.getProfile();
122 logger.trace("{}: CoAP Listener was already started", thingName);
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);
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());
135 Endpoint endpoint = null;
136 if (statusClient != null) {
137 endpoint = statusClient.getEndpoint();
139 if ((endpoint == null) || !endpoint.isStarted()) {
140 logger.warn("{}: Unable to initialize CoAP access (network error)", thingName);
141 throw new ShellyApiException("Network initialization failed");
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);
154 public boolean isStarted() {
155 return statusClient != null;
159 * Process an inbound Response (or mapped Request): decode CoAP options. handle discovery result or status updates
161 * @param response The Response packet
164 public void processResponse(@Nullable Response response) {
165 if (response == null) {
167 return; // other device instance
169 ResponseCode code = response.getCode();
170 if (code != ResponseCode.CONTENT) {
172 logger.debug("{}: Unknown Response Code {} received, payload={}", thingName, code,
173 response.getPayloadString());
178 List<Option> options = response.getOptions().asSortedList();
179 String ip = response.getSourceContext().getPeerAddress().toString();
180 boolean match = ip.contains(config.deviceIp);
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())) {
208 if (logger.isDebugEnabled()) {
209 logger.debug("{}: CoIoT Message from {} (MID={}): {}", thingName,
210 response.getSourceContext().getPeerAddress(), response.getMID(), response.getPayloadString());
212 if (response.isCanceled() || response.isDuplicate() || response.isRejected()) {
213 logger.debug("{} ({}): Packet was canceled, rejected or is a duplicate -> discard", thingName, devId);
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();
224 case OptionNumberRegistry.URI_HOST: // ignore
226 case OptionNumberRegistry.CONTENT_FORMAT: // ignore
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();
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);
246 logger.warn("{}: Unsupported CoAP version detected: {}", thingName, sVersion);
249 coiotVers = iVersion;
253 case COIOT_OPTION_STATUS_VALIDITY:
255 case COIOT_OPTION_STATUS_SERIAL:
256 serial = opt.getIntegerValue();
259 logger.debug("{} ({}): COAP option {} with value {} skipped", thingName, devId, opt.getNumber(),
264 // If we received a CoAP message successful the thing must be online
265 thingHandler.setThingOnline();
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);
275 // fixed malformed JSON :-(
276 payload = fixJSON(payload);
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);
285 } catch (ShellyApiException e) {
286 logger.debug("{}: Unable to process CoIoT message: {}", thingName, e.toString());
290 if (!updatesRequested) {
291 // Observe Status Updates
292 reqStatus = sendRequest(reqStatus, config.deviceIp, COLOIT_URI_DEVSTATUS, Type.NON);
293 updatesRequested = true;
295 } catch (JsonSyntaxException | IllegalArgumentException | NullPointerException e) {
296 logger.debug("{}: Unable to process CoIoT Message for payload={}", thingName, payload, e);
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.
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"}]}]}
311 private void handleDeviceDescription(String devId, String payload) throws ShellyApiException {
312 logger.debug("{}: CoIoT Device Description for {}: {}", thingName, devId, payload);
315 boolean valid = true;
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);
325 blkMap.replace(blk.id, blk);
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,
331 CoIotDescrSen sen = new CoIotDescrSen();
335 sen.range = blk.range;
336 sen.links = blk.links;
337 valid &= addSensor(sen);
341 // Save to thing properties
342 thingHandler.updateProperties(PROPERTY_COAP_DESCR, payload);
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));
350 coiot.completeMissingSensorDefinition(sensorMap);
354 "{}: Incompatible device description detected for CoIoT version {} (id length mismatch), discarding!",
355 thingName, coiot.getVersion());
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);
368 * Add a new sensor to the sensor table
370 * @param sen CoIotDescrSen of the sensor
372 private synchronized boolean addSensor(CoIotDescrSen sen) {
373 logger.debug("{}: id {}: {}, Type={}, Range={}, Links={}", thingName, sen.id, sen.desc, sen.type, sen.range,
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);
387 CoIotDescrSen fixed = coiot.fixDescription(sen, blkMap);
388 if (!sensorMap.containsKey(fixed.id)) {
389 sensorMap.put(sen.id, fixed);
391 sensorMap.replace(sen.id, fixed);
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);
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.
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
410 * @throws ShellyApiException
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
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);
426 // simulate received device description to create element table
427 logger.debug("{}: Device description for {} restored: {}", thingName, devId, savedDescr);
428 handleDeviceDescription(devId, savedDescr);
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);
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());
442 ShellyColorUtils col = new ShellyColorUtils();
443 for (int i = 0; i < sensorUpdates.size(); i++) {
445 CoIotSensor s = sensorUpdates.get(i);
446 CoIotDescrSen sen = sensorMap.get(s.id);
448 logger.debug("{}: Unable to sensor definition for id={}, payload={}", thingName, s.id, payload);
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,
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);
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);
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,
476 if (!updates.isEmpty()) {
478 for (Map.Entry<String, State> u : updates.entrySet()) {
479 String key = u.getKey();
480 updated += thingHandler.updateChannel(key, u.getValue(), false) ? 1 : 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());
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),
498 if ((profile.isRGBW2 && !profile.inColor) || profile.isRoller) {
499 // Aggregate Meter Data from different Coap updates
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,
510 totalCurrent += current >= 0 ? current : 0;
511 totalKWH += total >= 0 ? total : 0;
512 updateMeter |= current >= 0 | total >= 0;
515 logger.debug("{}: totalCurrent={}, totalKWH={}, update={}", thingName, totalCurrent, totalKWH,
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());
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);
532 if (failed == sensorUpdates.size()) {
533 logger.debug("{}: Device description problem detected, re-discover", thingName);
539 // Remember serial, new packets with same serial will be ignored
541 lastPayload = payload;
544 private void discover() {
545 if (coiot.getVersion() >= 2) {
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);
555 } catch (ShellyApiException e) {
556 // ignore if not supported by device
560 reqDescription = sendRequest(reqDescription, config.deviceIp, COLOIT_URI_DEVDESC, Type.CON);
564 * Fix malformed JSON - stupid, but the devices sometimes return malformed JSON with then causes a
565 * JsonSyntaxException
567 * @param json to be checked/fixed
569 private static String fixJSON(String payload) {
570 String json = payload;
571 json = json.replace("}{", "},{");
572 json = json.replace("][", "],[");
573 json = json.replace("],,[", "],[");
578 * Send a new request (Discovery to get Device Description). Before a pending
579 * request will be canceled.
581 * @param request The current request (this will be canceled an a new one will
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
588 private Request sendRequest(@Nullable Request request, String ipAddress, String uri, Type con) {
589 if ((request != null) && !request.isCanceled()) {
594 return newRequest(ipAddress, coiotPort, uri, con).send();
598 * Allocate a new Request structure. A message observer will be added to get the
599 * callback when a response has been received.
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
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() {
615 public void onResponse(@Nullable Response response) {
616 processResponse(response);
620 public void onCancel() {
621 logger.debug("{}: CoAP Request was canceled", thingName);
625 public void onTimeout() {
626 logger.debug("{}: CoAP Request timed out", thingName);
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
638 private void resetSerial() {
643 public int getVersion() {
648 * Cancel pending requests and shutdown the client
650 public synchronized void stop() {
652 logger.debug("{}: Stopping CoAP Listener", thingName);
653 coapServer.stop(this);
654 CoapClient cclient = statusClient;
655 if (cclient != null) {
659 Request request = reqDescription;
660 if (!request.isCanceled()) {
664 if (!request.isCanceled()) {
672 public long getMessageCount() {
673 return coiotMessages;
676 public long getErrorCount() {
680 public void dispose() {
684 private static String completeUrl(String ipAddress, int port, String uri) {
685 return "coap://" + ipAddress + ":" + port + uri;