CoapClient
A CoAP client on a CoapEndpoint.
Every call suspends until the whole response is there: block-wise transfers are done in both directions (RFC 7959, or Q-Block of RFC 9177 when CoapClientConfig.qBlock turns it on and the server supports it), separate responses are awaited (RFC 7252 §5.2.2), a 4.01 with Echo is answered once with that Echo value (RFC 9175 §2.3), and message security protects each message (CoapClientConfig.security).
Errors. Error codes (4.xx, 5.xx) are returned as responses, not thrown. A call fails with:
CoapException for everything that goes wrong at runtime, whatever the layer; its CoapException.reason says what: the peer did not answer (CoapException.Reason.TRANSMISSION_TIMEOUT, CoapException.Reason.RESPONSE_TIMEOUT) or refused (CoapException.Reason.RESET), the DTLS session or connection ended (CoapException.Reason.SESSION_ENDED, CoapException.Reason.CONNECTION_CLOSED), the response broke the protocol (CoapException.Reason.BAD_RESPONSE, CoapException.Reason.BLOCKWISE_FAILED), message security could not protect the request (CoapException.Reason.SECURITY) or verify its only answer (CoapException.Reason.UNVERIFIED_RESPONSE), the host could not be resolved (CoapException.Reason.UNRESOLVED_HOST), a limit was reached (CoapException.Reason.MESSAGE_TOO_LARGE, CoapException.Reason.IDENTIFIERS_EXHAUSTED), or the endpoint cannot serve it (CoapException.Reason.TRANSPORT_UNAVAILABLE, CoapException.Reason.TRANSPORT_FAILED, CoapException.Reason.CLOSED). Lower layers' exceptions arrive as its cause, never on their own.
IllegalArgumentExceptionorIllegalStateExceptiononly for a mistake of the caller: a URI string that is not a CoAP URI, observing with a method other than GET or FETCH, or a host the configured EndpointResolver cannot resolve by design, such as a name given to EndpointResolver.Default.CancellationExceptiononly when the calling coroutine is cancelled, which cancels the exchange. A lower layer that cancels itself while the caller is still active, as a resolver whose ownwithTimeoutexpires does, fails the call with CoapException like any other failure of that layer.
Every request, ping and discover lists KcoapException, the root of CoapException, and CancellationException in @Throws, so on Apple platforms Swift catches these failures as an NSError, with the Kotlin exception in its userInfo under "KotlinException". A mistake of the caller is not listed and ends the process there, as a failed precondition does in Swift: a Swift caller parses a URI it did not write itself with CoapUri.parse, which lists IllegalArgumentException, and passes the CoapUri.
Under message security the client acts only on responses it verified (ADR 0008). A protected request answered only by an error that came without message security, such as OSCORE's unprotected 4.01 (RFC 8613 §8.2), is not repeated for its Echo option nor continued block-wise: it throws CoapException with CoapException.Reason.UNVERIFIED_RESPONSE, whose CoapException.response is that error. A security layer that cannot protect a request it should, such as kcoap-oscore's without a context for the peer, fails it before anything is sent, with CoapException.Reason.SECURITY and the layer's MessageSecurityException as cause.
Once the endpoint is closed, by close, by its scope or by a failed transport, every call throws CoapException with CoapEndpoint.closeCause's reason, at once and without resolving the host, and every observe flow fails with it. A call racing CoapEndpoint.close fails the same way: whether the endpoint is closed is decided under the lock that registers the exchange, so no request waits for a response after it.
The client is safe to use from any number of coroutines; it runs on the dispatcher of the endpoint's scope, so on Android or iOS give it one such as lifecycleScope + Dispatchers.Default. Creating it does not start the endpoint receiving; its first request or ping does, so on an endpoint shared with a dev.kcoap.coap.server.CoapServer the two may be created in either order.
The URI's scheme picks the transport: coap goes over the endpoint's datagram transport, coap+tcp, coaps+tcp, coap+ws and coaps+ws (RFC 8323 §8) over connections that its connectors open on demand. On connections, message sizes and block sizes follow the server's Max-Message-Size, with BERT blocks when both sides support them (RFC 8323 §6). A coaps URI needs DTLS (RFC 7252 §6.2, §9.1), which kcoap does not have yet, so every call with one fails with CoapException.Reason.TRANSPORT_UNAVAILABLE before its host is resolved: nothing goes out in plaintext. A coaps+tcp or coaps+ws URI needs TLS (RFC 8323 §9) and fails the same way unless a connector or listener of the endpoint serves its scheme, which a transport does only when it runs TLS for it, as kcoap-transport-ktor's KtorTlsConnector (coaps+tcp, on the JVM) and the WebSocket connector (coaps+ws, where its engine authenticates the server: Apple, browsers, Node.js, or an HttpClient the application passes) do.
val client = CoapClient(KtorUdpTransport.bind(), scope)
val response = client.get("coap://192.0.2.1/sensors/temp")
client.put("coap://192.0.2.1/config", "on".encodeToByteArray(), ContentFormat.TEXT_PLAIN)
client.observe("coap://192.0.2.1/time").take(3).collect { println(it.payloadAsText()) }
val tcp = CoapClient(listOf(KtorTcpConnector(), KtorWebSocketConnector()), scope)
tcp.get("coap+tcp://192.0.2.1/sensors/temp")
tcp.get("coap+ws://example.org/sensors/temp")Constructors
A client on an existing endpoint, which a dev.kcoap.coap.server.CoapServer may share.
A client for CoAP over reliable transports (RFC 8323) on a new endpoint: requests to coap+tcp, coaps+tcp, coap+ws or coaps+ws URIs open connections through connectors, reuse them per peer and release them when idle (dev.kcoap.coap.stack.ReliableTransportConfig.idleTimeout). close closes the endpoint and its connections.
Functions
Resource discovery (RFC 6690 §4): GETs /.well-known/core from server (any URI of the server; its path is replaced), with query as RFC 6690 §4.1 filter such as rt=temperature-c, and parses it. The links are the server's input: their targets are text, to be parsed with CoapUri.parseOrNull.
FETCH (RFC 8132 §2): a GET with a request body.
FETCH to the CoAP URI uri.
GET of the CoAP URI uri.
iPATCH (RFC 8132 §3): an idempotent PATCH.
iPATCH to the CoAP URI uri.
Observes request's target (RFC 7641): the flow registers when collected, emits the first response and every fresher notification, and completes after a response that ends the observation (one without Observe, or an error code, which is emitted last). It fails with CoapException when the registration gets no response or a Reset, or, under message security, only a response that could not be verified (CoapException.Reason.UNVERIFIED_RESPONSE). Once established, the observation ignores such responses: they neither end it nor reach the collectors (ADR 0008).
PATCH (RFC 8132 §3).
PATCH to the CoAP URI uri.
POST (RFC 7252 §5.8.2) of payload in contentFormat to uri; large bodies go in Block1 blocks.
POST to the CoAP URI uri.
PUT (RFC 7252 §5.8.3) of payload in contentFormat to uri; large bodies go in Block1 blocks.
PUT to the CoAP URI uri.
Sends request and returns its whole response: with Q-Block (RFC 9177) where CoapClientConfig.qBlock allows it and the server supports it, otherwise with Block1 and Block2 (RFC 7959) where the body needs them.
The peer for uri through this client's CoapClientConfig.resolver, with the resolver's failures translated as the EndpointResolver contract says: a CoapException, such as CoapException.Reason.UNRESOLVED_HOST, and an IllegalArgumentException for a host the resolver cannot resolve by design pass unchanged; any other exception is a lookup that failed at runtime, CoapException.Reason.UNRESOLVED_HOST with it as cause. That includes a cancellation of the resolver's own, such as its withTimeout expiring, while the caller is still active; the caller's cancellation passes unchanged.