JuulLabs / koap

Kotlin CoAP encoder/decoder.
https://juullabs.github.io/koap
Apache License 2.0
19 stars 1 forks source link

Example using with BLE #136

Open beriberikix opened 2 years ago

beriberikix commented 2 years ago

Hello! Just discovered this implementation, very cool. I've had the idea to use CoAP over BLE for some time and was wondering if you had any examples of that, perhaps with kable?

twyatt commented 2 years ago

I don't have a full fledged example. From the BLE side, SensorTag sample app shows how to use Kable in a multiplatform way. Since the SensorTag doesn't use CoAP at all (that I'm aware of) there wasn't a need to utilize KoAP for that sample.

I'll share a bit about how we're using KoAP w/ Kable, it won't be an end-to-end sample, but might be enough to get you started? Although, it all depends on how the peripheral (firmware) side implements CoAP as to how you should probably go about it on the central (e.g. phone) side.

CoAP feels very much like HTTP (request then response) style protocol, which differs from BLE a bit (which has a collection of services/characteristics/descriptors that can be written/read/observed).

We bridged the paradigms by having a dedicated "send" characteristic (which we use purely for writing) and a dedicated "response" characteristic (which we "observe" via BLE notifications).

As far as how KoAP builds on Kable for that:

You can have a write function, similar to:

suspend fun send(request: Message.Tcp) {
    peripheral.write(sendCharacteristic, request.encode())
}

Then, for processing responses:

val responses = peripheral.observe(responseCharacteristic)
    .map { bytes -> bytes.decode<Tcp>() }

And, to bring it together for a request+response function:

// note: every CoAP request should have a unique token
suspend fun sendForResponse(request: Message.Tcp): Message.Tcp {
    val response = responses
        .onSubscription { send(request) }
        .first { response.token == request.token }
    check(response.code is Message.Code.Response) { "Received invalid response code: ${response.code}" }
    return response
}

You could additionally have helper functions to emulate an API with a HTTP feel:

suspend fun get(model: YourRequestModel): YourResponseModel {
    // e.g. "POST /example/path"
    val request = Message.Tcp(
        code = POST,
        token = generateRandomToken(),
        options = listOf(
            UriPath("example"), UriPath("path"),
            Accept(CBOR),
        ),
        // e.g. use kotlinx.serialization to encode as CBOR, but other formats should work if your firmware supports it
        payload = Cbor.encodeToByteArray(YourRequestModel.serializer(), model),
    )
    val response = sendForResponse(request)
    // todo: handle `Message.Tcp.option`s that are applicable
    return Cbor.decodeFromByteArray(YourResponseModel.serializer(), response.payload)
}

Note, the above code was written by hand so there could be many compilation or logical errors. Use as psuedo code. 🤷

Best of luck!

beriberikix commented 2 years ago

Thank you writing this up! Hope to play around with this over the weekend.

As a side note, did y'all review the IETF draft https://datatracker.ietf.org/doc/draft-amsuess-core-coap-over-gatt/? It went stale but looks like the author is trying to pick it up again. It follows a similar approach to what we did at a presence company.