Skip to content

Commit

Permalink
Fix: linux ble send message flow
Browse files Browse the repository at this point in the history
Signed-off-by: sukhman <[email protected]>
  • Loading branch information
sukhman-sukh committed Jul 3, 2024
1 parent dc922db commit e6683a4
Show file tree
Hide file tree
Showing 6 changed files with 233 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene
private fun connectDevice(): Boolean {
AppLog.i(TAG, "connectDevice : $bluetoothDevice")
if (bluetoothDevice == null) {
AppLog.e("zzz", "connectDevice : $bluetoothDevice")
AppLog.e(TAG, "connectDevice : $bluetoothDevice")
listener!!.onConnectionFailed(bleScanDevice = bleDevice!!)
}
failTimer = Timer()
Expand Down Expand Up @@ -145,7 +145,7 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene
) {
super.onCharacteristicRead(gatt, characteristic, status)
AppLog.e(
"zzz",
TAG,
"onCharacteristicRead : " + characteristic.uuid.toString() + " , isFromMessage-> $isFromMessage"
)

Expand Down Expand Up @@ -173,12 +173,12 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene
gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int
) {
super.onCharacteristicWrite(gatt, characteristic, status)
// AppLog.e(
// "zzz ",
// "onCharacteristicWrite --------------> $listener $messageId $ : , data : " + BLEUtils.byteToHex(
// characteristic.value
// )
// )
// AppLog.e(
// TAG,
// "onCharacteristicWrite -------------->, data : " + BLEUtils.byteToHex(
// characteristic.value
// )
// )
if (listener != null) {
if (messageId.isEmpty() || messageId.isBlank()) {
listener!!.onCharacteristicWrite(gatt = gatt, characteristic = characteristic)
Expand Down Expand Up @@ -220,6 +220,7 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene
gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int
) {
super.onDescriptorWrite(gatt, descriptor, status)
AppLog.e(TAG, "onDescriptorWrite asked")
if (descriptorWriteQueue != null && descriptorWriteQueue.size > 0) {
descriptorWriteQueue.remove()
if (descriptorWriteQueue.size > 0) writeGattDescriptor(descriptorWriteQueue.element()) else {
Expand Down Expand Up @@ -261,7 +262,7 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene
}

fun send(data: String): Int {
// AppLog.e("zzz", "send data-----------------> isWriting $isWriting data $data")
AppLog.e(TAG, "send data-----------------> isWriting $isWriting data $data")
var data = data
while (data.length > 40) {
sendQueue.add(data.substring(0, 40))
Expand All @@ -277,8 +278,9 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene
AppLog.e("TAG", "_send(): EMPTY QUEUE")
return false
}
// AppLog.e(TAG, "_send(): $attempt Sending: " + sendQueue.peek())
AppLog.e(TAG, "_send(): $attempt Sending: " + sendQueue.peek())
val tx = BLEUtils.hexToByteArray(sendQueue.poll())
// AppLog.e(TAG, "_send(): $attempt Sending: ")
// val tx = sendQueue.poll()?.toByteArray(Charset.forName("UTF-8"))
isWriting = true // Set the write in progress flag
writeServiceData(BleService.SERVICE_UUID, BleService.MSG_CHAR, tx, attempt)
Expand Down Expand Up @@ -346,6 +348,7 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene
* This method is used to write descriptor of gatt
*/
private fun writeGattDescriptor(d: BluetoothGattDescriptor) {
AppLog.e(TAG, "writeGattDescriptor request ")
if (isCharacteristicNotifiable(d.characteristic)) {
d.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
} else {
Expand Down Expand Up @@ -376,7 +379,7 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene
override fun run() {
if (listener != null) {
listener!!.onConnectionFailed(bleDevice!!)
AppLog.e("zzz", "ConnectionFailedTask : $bluetoothDevice")
AppLog.e(TAG, "ConnectionFailedTask : $bluetoothDevice")
disConnectedDevice()
listener!!.onDisconnected(bleDevice!!)
Handler(Looper.getMainLooper()).postDelayed({
Expand Down Expand Up @@ -430,18 +433,17 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene
): Boolean {
if (attempt < 3) {
if (data != null) {
// AppLog.e(
// TAG,
// "writeServiceData -----------> : serUUID : $serUUID, charUUID:$charUUID, data :" + BLEUtils.byteToHex(
// data
// )
// )
// AppLog.e(
// TAG,
// "writeServiceData -----------> : data : ${data}"
// )
if (mBluetoothGatt != null) {
val service = mBluetoothGatt!!.getService(UUID.fromString(serUUID))
if (service != null) {
val characteristic = service.getCharacteristic(UUID.fromString(charUUID))
if (characteristic != null) {
characteristic.value = data
AppLog.e(TAG, "===================Characterstic value = $data")
return mBluetoothGatt!!.writeCharacteristic(characteristic)
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ open class BleWrapperClass(context: Activity) {
}

BleOuterClass.Ble.MessageCase.DIRECT_SEND -> {
AppLog.e("zzz", " DIRECT_SEND ")
AppLog.e(TAG, " DIRECT_SEND ")

val bleDirectSend = bleReq.directSend
if (BleService().isRunning()) {
Expand Down Expand Up @@ -265,16 +265,17 @@ open class BleWrapperClass(context: Activity) {
}

override fun onMessageReceived(bleDevice: BLEScanDevice, message: ByteArray) {
AppLog.e("zzz", "---->onMessageReceived---> ${BLEUtils.byteToHex(message)}")
// AppLog.e(TAG, "---->onMessageReceived---> ${BLEUtils.byteToHex(message)}")
val bleRes = BleOuterClass.Ble.newBuilder()
val directReceived = BleOuterClass.BleDirectReceived.newBuilder()
val msgData = String(message).removeSuffix("$$").removePrefix("$$")
AppLog.e(TAG, "---->onMessageReceived---> " + msgData)
val msgObject = Gson().fromJson(msgData, Message::class.java)
directReceived.from = ByteString.copyFrom(bleDevice.qaulId)
directReceived.data = ByteString.copyFrom(msgObject.message)
// ByteString.copyFrom(msgObject.message, Charset.defaultCharset())
bleRes.directReceived = directReceived.build()
AppLog.e("zzz", "---->onMessageReceived msgObject $msgObject")
// AppLog.e(TAG, "---->onMessageReceived msgObject $msgObject")
sendResponse(bleRes)
}
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -422,9 +422,9 @@ class BleService : LifecycleService() {
super.onCharacteristicWriteRequest(
device, requestId, characteristic, preparedWrite, responseNeeded, offset, value
)
AppLog.e("zzz", "Write Request Received: " + String(value) + " :: " + requestId)
// AppLog.e(TAG, "Write Request Received: " + String(value) + " :: " + requestId)
val s = BLEUtils.byteToHex(value)
// AppLog.e(TAG, "Data in hex:: $s")
AppLog.e(TAG, "Data in hex:: $s")
var bleDevice = ignoreList.find { it.macAddress == device.address }
if (bleDevice == null) {
bleDevice = receiveList.find { it.macAddress == device.address }
Expand All @@ -437,6 +437,8 @@ class BleService : LifecycleService() {
var oldValue = msgMap[device.address]
if (s.endsWith("2424") || (oldValue!!.endsWith("24") && s == "24")) {
//SendResponse of oldValue

AppLog.e(TAG, "onCharacteristicWriteRequest: contain 2424")
oldValue += s
val msgData = String(BLEUtils.hexToByteArray(oldValue)!!).removeSuffix("$$")
.removePrefix("$$")
Expand All @@ -458,6 +460,7 @@ class BleService : LifecycleService() {
Log.e(TAG, "onCharacteristicWriteRequest: contain $$")
}
} else {
AppLog.e(TAG, "onCharacteristicWriteRequest: not contain 2424")
oldValue += s
msgMap[device.address] = oldValue
}
Expand All @@ -466,6 +469,7 @@ class BleService : LifecycleService() {
//Send Response of s
val msgData = String(BLEUtils.hexToByteArray(s)!!).removeSuffix("$$")
.removePrefix("$$")
AppLog.e(TAG, "Got whole message at once $msgData")
val msgObject = Gson().fromJson(msgData, Message::class.java)
if (bleDevice == null) {
bleDevice = BLEScanDevice.getDevice()
Expand Down Expand Up @@ -776,12 +780,12 @@ class BleService : LifecycleService() {
) {
val queue = hashMap[gatt?.device?.address]
if (queue?.isNotEmpty() == true) {
Log.e("zzz", "onMessageSent:SIZE -> queue.isNotEmpty() ")
AppLog.e(TAG, "onMessageSent:SIZE -> queue.isNotEmpty() ")
queue.poll()
hashMap[gatt?.device?.address!!] = queue
}

Log.e("zzz", "onMessageSent:SIZE -> ${queue?.size} ")
AppLog.e(TAG, "onMessageSent:SIZE -> ${queue?.size} ")
bleCallback?.onMessageSent(id = id, success = true, data = value)
sendMessageFromQueu(gatt?.device?.address!!)

Expand All @@ -797,12 +801,12 @@ class BleService : LifecycleService() {

override fun addToBlackList(bleScanDevice: BLEScanDevice) {
blackList.add(bleScanDevice)
AppLog.e(TAG, " addToBlackList : $blackList")
// AppLog.e(TAG, " addToBlackList : $blackList")
}

override fun addToIgnoreList(bleScanDevice: BLEScanDevice) {
ignoreList.add(bleScanDevice)
AppLog.e(TAG, " addToIgnoreList : $ignoreList")
// AppLog.e(TAG, " addToIgnoreList : $ignoreList")
}

}
Expand Down Expand Up @@ -837,9 +841,9 @@ class BleService : LifecycleService() {
}

AppLog.e(
"zzz", "sendMessage ${BLEUtils.byteToHex(message)}"
TAG, "sendMessage ${BLEUtils.byteToHex(message)}"
)
var mainQueue: Queue<Triple<String, ByteArray, ByteArray>>? = null
// var mainQueue: Queue<Triple<String, ByteArray, ByteArray>>? = null
bleDevice?.let {
if (hashMap.containsKey(it.macAddress)) {
var queue = hashMap[it.macAddress!!]
Expand All @@ -849,14 +853,16 @@ class BleService : LifecycleService() {
queue = LinkedList()
}
hashMap[it.macAddress!!] = queue!!
mainQueue = queue
// mainQueue = queue
// AppLog.d(TAG, " Manual send ======= Queue size was already 1 ")
} else {
// AppLog.d(TAG, " Manual send ===== Queue size was empty ")
val queue: Queue<Triple<String, ByteArray, ByteArray>> = LinkedList()
queue.add(Triple(id, from, message))
hashMap[it.macAddress!!] = queue
mainQueue = queue
// mainQueue = queue
}
AppLog.e(TAG, "device--> ${it.macAddress} ${mainQueue?.size}")
// AppLog.e(TAG, "device--> ${it.macAddress} ${mainQueue?.size}")
sendMessageFromQueu(it.macAddress!!, true)

}
Expand All @@ -871,7 +877,7 @@ class BleService : LifecycleService() {
if (!queue.isNullOrEmpty()) {
AppLog.e(
TAG,
"sendMessageFromQueu ${queue.size}"
"sendMessageFromQueu ${queue.size} ${isFromSendMessage}"
)
if (!isFromSendMessage || queue.size == 1) {
var bleDevice = ignoreList.find { it.macAddress.contentEquals(macAddress) }
Expand Down Expand Up @@ -899,14 +905,14 @@ class BleService : LifecycleService() {
delimiter[1] = 36
bleActor.tempData = delimiter + btArray + delimiter
AppLog.e(
"zzz",
TAG,
"data------------>sendMessage ${BLEUtils.byteToHex(bleActor.tempData)}"
)
// },500)

} else {
AppLog.e(
"zzz", "data------------>onMessageSent Failed"
TAG, "data------------>onMessageSent Failed"
)
bleCallback?.onMessageSent(
id = mesTrip.first, success = false, data = ByteArray(0)
Expand Down
2 changes: 2 additions & 0 deletions rust/ble_module/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ futures-concurrency = "7.6.1"
lazy_static = "1.4"
log = "0.4"
prost = "0.12.6"
serde = "1.0.203"
serde_json = "1.0.118"
simplelog = "0.12.2"
state = "0.6.0"
tokio = { version = "1", features = ["full"] }
Loading

0 comments on commit e6683a4

Please sign in to comment.