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:

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

Link copied to clipboard
constructor(endpoint: CoapEndpoint, config: CoapClientConfig = CoapClientConfig.Default)

A client on an existing endpoint, which a dev.kcoap.coap.server.CoapServer may share.

constructor(transport: DatagramTransport, scope: CoroutineScope, config: CoapClientConfig = CoapClientConfig.Default, endpointConfig: CoapEndpointConfig = CoapEndpointConfig.Default)

A client on a new endpoint over transport; close closes both.

constructor(connectors: List<Connector>, scope: CoroutineScope, config: CoapClientConfig = CoapClientConfig.Default, endpointConfig: CoapEndpointConfig = CoapEndpointConfig.Default)

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.

Properties

Link copied to clipboard
Link copied to clipboard

Functions

Link copied to clipboard
suspend fun close()

Closes the endpoint if the client created it.

Link copied to clipboard
suspend fun delete(uri: CoapUri, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

DELETE (RFC 7252 §5.8.4) of uri.

suspend fun delete(uri: String, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

DELETE of the CoAP URI uri.

Link copied to clipboard
suspend fun discover(server: CoapUri, query: String? = null): List<WebLink>

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.

suspend fun discover(server: String, query: String? = null): List<WebLink>

Resource discovery at the server of the CoAP URI server; see discover.

Link copied to clipboard
suspend fun fetch(uri: CoapUri, payload: ByteArray = ByteArray(0), contentFormat: Int? = null, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

FETCH (RFC 8132 §2): a GET with a request body.

suspend fun fetch(uri: String, payload: ByteArray = ByteArray(0), contentFormat: Int? = null, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

FETCH to the CoAP URI uri.

Link copied to clipboard
suspend fun get(uri: CoapUri, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

GET (RFC 7252 §5.8.1) of uri; configure adds options or makes it Non-confirmable.

suspend fun get(uri: String, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

GET of the CoAP URI uri.

Link copied to clipboard
suspend fun ipatch(uri: CoapUri, payload: ByteArray = ByteArray(0), contentFormat: Int? = null, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

iPATCH (RFC 8132 §3): an idempotent PATCH.

suspend fun ipatch(uri: String, payload: ByteArray = ByteArray(0), contentFormat: Int? = null, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

iPATCH to the CoAP URI uri.

Link copied to clipboard
fun observe(request: CoapRequest): Flow<CoapResponse>

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).

fun observe(uri: CoapUri, configure: CoapRequest.Builder.() -> Unit = {}): Flow<CoapResponse>

Observes uri with GET; see observe.

fun observe(uri: String, configure: CoapRequest.Builder.() -> Unit = {}): Flow<CoapResponse>

Observes the CoAP URI uri with GET; see observe.

Link copied to clipboard
suspend fun patch(uri: CoapUri, payload: ByteArray = ByteArray(0), contentFormat: Int? = null, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

PATCH (RFC 8132 §3).

suspend fun patch(uri: String, payload: ByteArray = ByteArray(0), contentFormat: Int? = null, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

PATCH to the CoAP URI uri.

Link copied to clipboard
suspend fun ping(uri: CoapUri): Boolean

CoAP ping of the server at uri: an Empty Confirmable message over UDP (RFC 7252 §4.3), true if it answered with a Reset (or ACK); a Ping over a reliable transport (RFC 8323 §5.4), true if the Pong came.

suspend fun ping(uri: String): Boolean

CoAP ping of the server at the CoAP URI uri.

Link copied to clipboard
suspend fun post(uri: CoapUri, payload: ByteArray = ByteArray(0), contentFormat: Int? = null, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

POST (RFC 7252 §5.8.2) of payload in contentFormat to uri; large bodies go in Block1 blocks.

suspend fun post(uri: String, payload: ByteArray = ByteArray(0), contentFormat: Int? = null, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

POST to the CoAP URI uri.

Link copied to clipboard
suspend fun put(uri: CoapUri, payload: ByteArray = ByteArray(0), contentFormat: Int? = null, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

PUT (RFC 7252 §5.8.3) of payload in contentFormat to uri; large bodies go in Block1 blocks.

suspend fun put(uri: String, payload: ByteArray = ByteArray(0), contentFormat: Int? = null, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

PUT to the CoAP URI uri.

Link copied to clipboard
suspend fun request(request: CoapRequest): CoapResponse

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.

suspend fun request(method: CoapCode, uri: CoapUri, configure: CoapRequest.Builder.() -> Unit = {}): CoapResponse

Sends a method request to uri, set up by configure.

Link copied to clipboard

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.

Link copied to clipboard
open override fun toString(): String