-
Notifications
You must be signed in to change notification settings - Fork 12
Description
Hi, I'm fairly new to Kotlin and Android so this might end up being a silly mistake.
I'm trying to design an app which will connect to two XBee3 modules at once via Bluetooth and continuously receive User Data Relay messages from them. I also use Kotlin coroutines to help with threading and preventing the app from being blocked.
I define both device variables and two IUserDataRelayReceiveListeners like this:
@Volatile var xBeeDevice1: XBeeBLEDevice? = null
@Volatile var xBeeDevice2: XBeeBLEDevice? = null
private val xBeeUserDataListener1 = IUserDataRelayReceiveListener {
GlobalScope.launch {
//receive and process User Data Relay string
}
}
private val xBeeUserDataListener2 = IUserDataRelayReceiveListener {
GlobalScope.launch {
//receive and process User Data Relay string
}
}
I then created two functions which connect to each XBee in the background (I'm just showing the connect function for xBeeDevice1):
private fun xBee1Connect() {
val device = XBeeBLEDevice(this, xBee1MacAddress, xBeePassword)
xBeeConnectJob = GlobalScope.launch(Dispatchers.IO){
//try connecting to the XBee
try {
// Open the connection with the device.
device.open()
// If the open method did not throw an exception, the connection is open.
runOnUiThread {
Toast.makeText(applicationContext, "XBEE connection successful!", Toast.LENGTH_SHORT).show()
xBeeDevice1 = device
//if thread finished successfully then send the connected device to the main UI
xBeeDevice1!!.addUserDataRelayListener(xBeeUserDataListener1)
}
} catch (e: BluetoothAuthenticationException) {
// There was a problem in the Bluetooth authentication process, so ask for the password again.
e.printStackTrace()
} catch (e: XBeeException) {
e.printStackTrace()
}
if (!device.isOpen) {
}
}
}
Everything works great, and both Listener functions receive and process the data concurrently. I also have a Broadcast Receiver which will detect when they disconnect, and it will run the disconnect() function on the proper XBee device.
I believe I have discovered a bug when I turn off one of the XBees while they are both actively connected. Sometimes (not all the time) the Listener for the other XBee will stop receiving data and not work, so then I'll have to reconnect to get it working again.
So, for example, if I shut power off of xBeeDevice1 then xBeeUserDataListener2 will sometimes stop receiving data, even though xBeeDevice2 is still active.
Do you have any idea how this might be happening? Are the two separate UserDataRelayListeners somehow linked together?