Sending and receiving data

On the things side, we are going to send the temperature every second. To do so, we will encode it inside a JSONObject, using the same technique as for the REST API. In this case we create a Payload from the bytes of the JSONObject once it is converted to a string and we send that to the connectedEndpoint. Please note that we will only invoke this method if the connectedEndpoint is already set.

private fun sendTemperatureToNearby(temp: Float) {
val json = JSONObject()
json.put("temperature", temp)
val payload = Payload.fromBytes(json.toString().toByteArray())
nearbyConnections.sendPayload(connectedEndpoint!!, payload)
}

And, in a straightforward way, the payload will arrive on the other device via the payloadCallback we passed in when accepting the connection:

private val payloadCallback = object: PayloadCallback() {
override fun onPayloadReceived(p0: String, payload: Payload) {
// Info about the temperature
val json = payload.getAsJson()
runOnUiThread {
val value = json.getDouble("temperature").toString()
findViewById<TextView>(R.id.temperatureValue).setText(value)

}
}

override fun onPayloadTransferUpdate(p0: String, p1: PayloadTransferUpdate) {
// Nothing to do here
}
}

We just convert the payload to JSON, get the right field, and post a runnable to the UI thread to update the UI. Quite simple.

Note that we have created an extension function that gets the payload as a JSONObject. It is just a couple of lines, but makes the code much more readable.

private fun Payload.getAsJson(): JSONObject {
val string = String(this.asBytes()!!)
return JSONObject(string)
}

Similarly to what we just saw, we can send a payload from mobile to things to change the state of the LED. As in the case of the REST API, this is solved in the code samples, but it is left as an exercise for the reader.

Given that Nearby does not require connectivity -it is a mesh network-, it is very handy to communicate with devices that are nearby. The advertising and discovery steps solve the problem of knowing the IP we had on the REST API approach.

However, there are a couple of drawbacks. First, it does have a lot of states and managing all of them properly can be complex, including the case when Bluetooth is not enabled, or if any of the required permissions are not granted.

There is also the lack of structure of the payloads. You can do whatever you want, which is good because it gives you flexibility, but it also requires you to define clearly the states and communications your apps perform.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.189.177