From 439daabcee57e95653397c0e7f8bc68ea4b1fab7 Mon Sep 17 00:00:00 2001 From: sukhman Date: Thu, 4 Jul 2024 02:34:11 +0530 Subject: [PATCH] Refactor the rust ble_module --- .vscode/settings.json | 3 +- .../main/java/net/qaul/ble/core/BleActor.kt | 13 +- .../java/net/qaul/ble/core/BleWrapperClass.kt | 2 - .../java/net/qaul/ble/service/BleService.kt | 13 +- qaul_ui/lib/screens/home/tabs/users_tab.dart | 2 +- rust/ble_module/src/ble/ble_service.rs | 186 +++++++----------- rust/ble_module/src/ble/utils.rs | 40 ++-- rust/ble_module/src/rpc/msg_loop.rs | 9 +- 8 files changed, 107 insertions(+), 161 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 4cca570df..c11669d57 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -29,6 +29,5 @@ "[proto3]": { "editor.defaultFormatter": "xaver.clang-format", "editor.formatOnSave": true - }, - "cmake.sourceDirectory": "/home/death/Desktop/linux_backup/openSource/gsoc/qaul.net/qaul_ui/linux" + } } \ No newline at end of file diff --git a/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/core/BleActor.kt b/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/core/BleActor.kt index 1fd3867e5..ffa7d8144 100644 --- a/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/core/BleActor.kt +++ b/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/core/BleActor.kt @@ -220,7 +220,6 @@ 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 { @@ -230,7 +229,8 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene } } // if (isReconnect && isFromMessage) { -// writeServiceData(BleService.SERVICE_UUID, BleService.MSG_CHAR, tempData, attempt) +// AppLog.e(TAG, "onDescriptorWrite asked") + writeServiceData(BleService.SERVICE_UUID, BleService.MSG_CHAR, tempData, attempt) // attempt = 0 // tempData = ByteArray(0) // isReconnect = false @@ -262,7 +262,7 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene } fun send(data: String): Int { - AppLog.e(TAG, "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)) @@ -278,10 +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")) + // 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) return true @@ -348,7 +347,6 @@ 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 { @@ -443,7 +441,6 @@ class BleActor(private val mContext: Context, var listener: BleConnectionListene val characteristic = service.getCharacteristic(UUID.fromString(charUUID)) if (characteristic != null) { characteristic.value = data - AppLog.e(TAG, "===================Characterstic value = $data") return mBluetoothGatt!!.writeCharacteristic(characteristic) } } else { diff --git a/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/core/BleWrapperClass.kt b/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/core/BleWrapperClass.kt index 7a000f47f..e5ef3ff1c 100644 --- a/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/core/BleWrapperClass.kt +++ b/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/core/BleWrapperClass.kt @@ -269,7 +269,6 @@ open class BleWrapperClass(context: Activity) { 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) @@ -428,7 +427,6 @@ open class BleWrapperClass(context: Activity) { Class.forName(className) true } catch (e: ClassNotFoundException) { - e.printStackTrace() false } } diff --git a/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/service/BleService.kt b/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/service/BleService.kt index 75bc52494..e32fc52b3 100644 --- a/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/service/BleService.kt +++ b/qaul_ui/android/blemodule/src/main/java/net/qaul/ble/service/BleService.kt @@ -424,7 +424,7 @@ class BleService : LifecycleService() { ) // 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 } @@ -437,12 +437,9 @@ 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("$$") - Log.e(TAG, "Msg Data:: $msgData") if (!msgData.contains("$$")) { val msgObject = Gson().fromJson(msgData, Message::class.java) if (bleDevice == null) { @@ -460,7 +457,6 @@ class BleService : LifecycleService() { Log.e(TAG, "onCharacteristicWriteRequest: contain $$") } } else { - AppLog.e(TAG, "onCharacteristicWriteRequest: not contain 2424") oldValue += s msgMap[device.address] = oldValue } @@ -469,7 +465,6 @@ 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() @@ -843,7 +838,7 @@ class BleService : LifecycleService() { AppLog.e( TAG, "sendMessage ${BLEUtils.byteToHex(message)}" ) - // var mainQueue: Queue>? = null + var mainQueue: Queue>? = null bleDevice?.let { if (hashMap.containsKey(it.macAddress)) { var queue = hashMap[it.macAddress!!] @@ -853,14 +848,14 @@ 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> = LinkedList() queue.add(Triple(id, from, message)) hashMap[it.macAddress!!] = queue - // mainQueue = queue + mainQueue = queue } // AppLog.e(TAG, "device--> ${it.macAddress} ${mainQueue?.size}") sendMessageFromQueu(it.macAddress!!, true) diff --git a/qaul_ui/lib/screens/home/tabs/users_tab.dart b/qaul_ui/lib/screens/home/tabs/users_tab.dart index 88db1dc31..ce7115bd9 100644 --- a/qaul_ui/lib/screens/home/tabs/users_tab.dart +++ b/qaul_ui/lib/screens/home/tabs/users_tab.dart @@ -96,7 +96,7 @@ class _AvailableConnections extends StatelessWidget { if (_hasInternet) ...[const Icon(CupertinoIcons.globe), space], if (_hasLan) ...[const Icon(Icons.wifi), space], if (_hasLocal) ...[const Icon(Icons.cable), space], - if (_hasBluetooth) const Icon(Icons.bluetooth), + if (_hasBluetooth) ...[const Icon(Icons.bluetooth)], ], ), ); diff --git a/rust/ble_module/src/ble/ble_service.rs b/rust/ble_module/src/ble/ble_service.rs index 02c138a97..3fb1b0d0b 100644 --- a/rust/ble_module/src/ble/ble_service.rs +++ b/rust/ble_module/src/ble/ble_service.rs @@ -1,7 +1,4 @@ -use crate::ble::ble_uuids::msg_char; -use crate::ble::ble_uuids::msg_service_uuid; -use crate::ble::ble_uuids::read_char; -use crate::ble::{ble_uuids::main_service_uuid, utils::hex_to_bytes}; +use crate::ble::ble_uuids::{main_service_uuid, msg_char, msg_service_uuid, read_char}; use crate::{ ble::utils, rpc::{proto_sys::*, utils::*}, @@ -18,7 +15,6 @@ use futures_concurrency::stream::Merge; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serde_json; -use std::string; use std::{ cell::RefCell, collections::HashMap, collections::HashSet, collections::VecDeque, error::Error, sync::Mutex, @@ -76,6 +72,7 @@ impl IdleBleService { let session = bluer::Session::new().await?; let adapter = session.default_adapter().await?; adapter.set_powered(true).await?; + adapter.set_discoverable(true).await?; Ok(QaulBleService::Idle(IdleBleService { ble_handles: vec![], adapter, @@ -85,11 +82,8 @@ impl IdleBleService { })) } - // pub fn adapter_channel_handles() -> (Sender, Receiver){ - // let (adp_send, adp_recv) = async_std::channel::unbounded::(); - // (adp_send, adp_recv) - // } - + ///Starts BLE advertisement, scan, and listen. + /// Manages streams for BLE events and messages. pub async fn advertise_scan_listen( mut self, qaul_id: Bytes, @@ -124,11 +118,15 @@ impl IdleBleService { return QaulBleService::Idle(self); } }; - - log::debug!( - "Advertising qaul main BLE service at UUID {}", - main_service_uuid() - ); + let (adp_send, adp_recv) = async_std::channel::unbounded::(); + match adp_send.try_send(self.adapter.clone()) { + Ok(_) => { + log::debug!("Sent adapter to channel"); + } + Err(err) => { + log::error!("{:#?}", err); + } + } // ================================================================================== // ------------------------- SET UP APPLICATION ------------------------------------- @@ -194,15 +192,7 @@ impl IdleBleService { return QaulBleService::Idle(self); } }; - let (adp_send, adp_recv) = async_std::channel::unbounded::(); - match adp_send.try_send(self.adapter.clone()) { - Ok(_) => { - log::debug!("Sent adapter to channel"); - } - Err(err) => { - log::error!("{:#?}", err); - } - } + let (cmd_tx, cmd_rx) = async_std::channel::bounded::(8); let join_handle = async_std::task::Builder::new() @@ -213,15 +203,14 @@ impl IdleBleService { let adapter: Adapter; match adp_recv.recv().await { Ok(adp) => { - log::info!("Received adapter from channel"); adapter = adp; } - Err(err) => { - log::error!("Failed to receive adapter from channel: {:#?}", err); + Err(_) => { return self; } }; + // Set up discovery filter and start streaming the discovered devices adn out of range checker. let _ = adapter.set_discovery_filter(get_filter()).await; let device_stream = match adapter.discover_devices().await { Ok(addr_stream) => addr_stream.filter_map(|evt| match evt { @@ -245,7 +234,6 @@ impl IdleBleService { name: "".to_string(), // TODO: get device name is_connected: false, }); - println!("{:?}", device); Some(BleMainLoopEvent::DeviceDiscovered(device)) } Err(_) => None, @@ -260,6 +248,7 @@ impl IdleBleService { } }; utils::out_of_range_checker(internal_sender.clone()); + // ================================================================================== // --------------------------------- MAIN BLE LOOP ---------------------------------- // ================================================================================== @@ -290,39 +279,29 @@ impl IdleBleService { receiver_id, sender_id, data, - )) => { - println!("===============Sending message to {:?}", receiver_id); - match utils::bytes_to_str(&message_id) { - Ok(msg_id) => { - log::info!("Message ID: {:?}", msg_id); - match self - .send_direct_message( - msg_id.to_string(), - receiver_id, - sender_id, - data, - ) - .await - { - Ok(_) => { - todo!() - } - Err(err) => { - log::error!( - "Error sending direct BLE message: {:#?}", - err - ) - } + )) => match utils::bytes_to_str(&message_id) { + Ok(msg_id) => { + match self + .send_direct_message( + msg_id.to_string(), + receiver_id, + sender_id, + data, + ) + .await + { + Ok(_) => { + todo!() + } + Err(err) => { + log::error!("Error sending direct BLE message: {:#?}", err) } - } - Err(err) => { - log::error!( - "Error converting message ID to string: {:#?}", - err - ); } } - } + Err(err) => { + log::error!("Error converting message ID to string: {:#?}", err); + } + }, BleMainLoopEvent::MessageReceived(e) => { log::info!( "Received {} bytes of data from {}", @@ -336,6 +315,10 @@ impl IdleBleService { } BleMainLoopEvent::MsgCharEvent(e) => match e { CharacteristicControlEvent::Write(write) => { + log::debug!( + "Recieved char write request from {:?}", + write.device_address() + ); let mac_address = write.device_address(); if let Ok(reader) = write.accept() { let message_tx = message_tx.clone(); @@ -351,19 +334,16 @@ impl IdleBleService { .await { Ok(msg_receivers) => { - log::debug!( - "================== Device discovered {:?}", - device.name().await - ); - let message_tx = message_tx.clone(); - // let _ = self.spawn_msg_listener(main_chara_ctrl, message_tx); - for rec in msg_receivers { - let message_tx = message_tx.clone(); - // let _ = self.spawn_msg_listener(rec, message_tx); - } + // Was present in kotlin code but no need for the snippet below + + // log::debug!("Device discovered {:?}", device.name().await); + // let message_tx = message_tx.clone(); + // for rec in msg_receivers { + // let message_tx = message_tx.clone(); + // } } Err(err) => { - log::error!("===={:#?}", err); + log::error!("{:#?}", err); } } } @@ -383,6 +363,7 @@ impl IdleBleService { }) } + /// Handles device discovery and validates the qaul uuids. async fn on_device_discovered( &self, device: &Device, @@ -398,14 +379,13 @@ impl IdleBleService { &stringified_addr, &uuids ); - // let connection_status = ; let mut retries = 2; loop { match device.connect().await { Ok(()) => break, Err(err) => { if retries > 0 { - println!(" Connect error: {}", &err); + log::error!(" Connect error: {}", &err); retries -= 1; } else { return Err("Connection retries timeout.".into()); @@ -439,11 +419,16 @@ impl IdleBleService { mac_address: device.address(), device: device.clone(), last_found_time: 0, - name: device.name().await.unwrap().expect("name not set."), // TODO: get device name + name: device.name().await.unwrap().expect("name not set."), is_connected: false, }); read_char_uuid_found = true; let remote_qaul_id = char.read().await?; + log::info!( + "Read characteristic found for device {} with qaul ID {:?}", + &stringified_addr, + &remote_qaul_id + ); self.address_lookup .borrow_mut() .insert(remote_qaul_id.clone(), device.address()); @@ -460,10 +445,11 @@ impl IdleBleService { return Err("UUIDs not found".into()); } Ok(msg_receivers) - // } else { - // Err("Device RSSI less than 0".into()) } + /// Async message listner which is spawned every time a new device tries to write to the msg_char(). + /// The messages are streamed in chunks of 40 or less bytes. + /// The function handles maintains a message map for each nearby users to separate sending queues. async fn spawn_msg_listener( &self, reader: CharacteristicReader, @@ -472,14 +458,12 @@ impl IdleBleService { ) { async_std::task::spawn(async move { while let Some(msg) = reader.recv().await.ok() { - if message_tx.receiver_count() != 0 { - break; - } + // if message_tx.receiver_count() != 0 { + // break; + // } let mut hex_msg = utils::bytes_to_hex(&msg); - log::debug!("Received message: {:?} ", hex_msg); + log::info!("Received message: {:?} ", hex_msg); let stringified_addr = utils::mac_to_string(&mac_address); - // let device = utils::find_device_by_mac(mac_address).unwrap(); - // let mut msg_map = MSG_MAP.lock().unwrap(); match utils::find_msg_map_by_mac(stringified_addr.clone()) { Some(old_value) => { let mut old_value = old_value.clone(); @@ -491,27 +475,21 @@ impl IdleBleService { if !trim_old_value.contains("$$") { hex_msg = trim_old_value.to_string(); utils::remove_msg_map_by_mac(stringified_addr); - // msg_map.remove(&stringified_addr); } } else { old_value += &hex_msg; utils::add_msg_map(stringified_addr, old_value.clone()); - // msg_map.insert(stringified_addr.clone(), old_value.clone()); } } None => { if hex_msg.starts_with("2424") && hex_msg.ends_with("2424") { - // Nothing to do here for now } else if hex_msg.starts_with("2424") { utils::add_msg_map(stringified_addr, hex_msg.clone()); - // msg_map.insert(stringified_addr.clone(), hex_msg.clone()); } else { // Error handling } } } - // let old_value_hex = utils::hex_to_bytes(&hex_msg.clone()); - // let mut msg_data = utils::bytes_to_str(&old_value_hex).unwrap(); let mut data = if let Some(stripped) = hex_msg.strip_prefix("$$") { stripped.to_string() } else { @@ -524,19 +502,16 @@ impl IdleBleService { data.to_string() }; let msg_object: Message = serde_json::from_str(&data).unwrap(); - let message = msg_object.message.clone().unwrap(); + let message = msg_object.message.unwrap(); let _ = message_tx - .send(BleMainLoopEvent::MessageReceived(( - // hex_to_bytes(&message), - message, - mac_address, - ))) + .send(BleMainLoopEvent::MessageReceived((message, mac_address))) .await .map_err(|err| log::error!("{:#?}", err)); } }); } + /// Sends a serialized version of message to remote device in chunks of 40 bytes or less. async fn send_direct_message( &self, message_id: String, @@ -544,19 +519,12 @@ impl IdleBleService { sender_id: Vec, data: Vec, ) -> Result> { - println!( - "=============Sending direct message again to {:?}", - receiver_id - ); - let addr_loopup = self.address_lookup.borrow(); let mac_address = addr_loopup .get(&receiver_id) .ok_or("Could not find a device address for the given qaul ID!")?; let stringified_addr = utils::mac_to_string(mac_address); - // let device = self.adapter.device(recipient.to_owned())?; - // let device = utils::find_ignore_device_by_mac(*recipient); match utils::find_ignore_device_by_mac(*mac_address) { Some(ble_device) => { let device = ble_device.device.clone(); @@ -579,7 +547,7 @@ impl IdleBleService { hash_map.insert(stringified_addr.clone(), queue); } } - + log::info!("Message added to queue -- > {:?}", &data); let extracted_queue = hash_map.get(&stringified_addr).clone(); let mut message_id: String = "".to_string(); let mut send_queue: VecDeque = VecDeque::new(); @@ -639,19 +607,14 @@ impl IdleBleService { impl StartedBleService { pub async fn spawn_handles(self) { - // let handle = async_std::task::spawn(async move { match self.join_handle { Some(join_handles) => { - println!("Spawning handles"); - println!("id = {}", join_handles.task().id()); join_handles.await; } None => { - println!("No handle to spawn"); + log::error!("No handle to spawn"); } } - // }); - // handle.await; } pub async fn direct_send( @@ -675,17 +638,6 @@ impl StartedBleService { sender.send_stop_unsuccessful(err.to_string()); return QaulBleService::Started(self); } - - // let ble_service: IdleBleService; - // match self.join_handle { - // Some(join_handles) => { - // println!("Spawning handles"); - // ble_service = join_handles.await; - // } - // None => { - // println!("No handle to spawn"); - // } - // } sender.send_stop_successful(); QaulBleService::Idle(self.join_handle.unwrap().await) diff --git a/rust/ble_module/src/ble/utils.rs b/rust/ble_module/src/ble/utils.rs index 6e4a5d83b..29d757c42 100644 --- a/rust/ble_module/src/ble/utils.rs +++ b/rust/ble_module/src/ble/utils.rs @@ -1,10 +1,10 @@ -use bluer::Address; use crate::rpc::utils::*; +use bluer::Address; use lazy_static::lazy_static; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::collections::HashMap; use std::sync::Mutex; -use std:: {string, collections::HashMap}; -// use std::string; +use std::time::{SystemTime, UNIX_EPOCH}; + #[derive(Debug, Clone)] pub struct BleScanDevice { pub qaul_id: Vec, @@ -18,14 +18,11 @@ pub struct BleScanDevice { lazy_static! { static ref IGNORE_LIST: Mutex> = Mutex::new(Vec::new()); -} -lazy_static! { static ref DEVICE_LIST: Mutex> = Mutex::new(Vec::new()); -} -lazy_static! { static ref MSG_MAP: Mutex> = Mutex::new(HashMap::new()); } +/// Convert a MAC address to a stringified version. pub fn mac_to_string(addr: &Address) -> String { addr.map(|octet| format!("{:02x?}", octet)).join(":") } @@ -43,11 +40,13 @@ mod tests { } } +/// Add a new device to list of all previously discovered devices. pub fn add_device(device: BleScanDevice) { let mut devices = DEVICE_LIST.lock().unwrap(); devices.push(device); } +/// Key value lookup for previously discovered. pub fn find_device_by_mac(mac_address: Address) -> Option { let devices = DEVICE_LIST.lock().unwrap(); match devices @@ -59,31 +58,37 @@ pub fn find_device_by_mac(mac_address: Address) -> Option { } } +/// Remove a device from the list of previously discovered devices. pub fn remove_device_by_mac(mac_address: Address) { let mut devices = DEVICE_LIST.lock().unwrap(); devices.retain(|device| device.mac_address != mac_address); } +/// Add a new message to the message map maintained by ble listner. pub fn add_msg_map(stringified_addr: String, hex_msg: String) { let mut msg_map = MSG_MAP.lock().unwrap(); msg_map.insert(stringified_addr.clone(), hex_msg.clone()); } +/// Key value lookup for message map maintained by ble listner. pub fn find_msg_map_by_mac(stringified_addr: String) -> Option { let msg_map = MSG_MAP.lock().unwrap(); msg_map.get(&stringified_addr).cloned() } +/// Remove a message from the message map maintained by ble listner. pub fn remove_msg_map_by_mac(stringified_addr: String) { let mut msg_map = MSG_MAP.lock().unwrap(); msg_map.remove(&stringified_addr); } +/// Add a new device to list of devices present nearby and maintain their last found time. pub fn add_ignore_device(device: BleScanDevice) { let mut ignore_devices = IGNORE_LIST.lock().unwrap(); ignore_devices.push(device); } +/// Key value lookup for devices present nearby. pub fn find_ignore_device_by_mac(mac_address: Address) -> Option { let devices = IGNORE_LIST.lock().unwrap(); match devices @@ -95,6 +100,7 @@ pub fn find_ignore_device_by_mac(mac_address: Address) -> Option } } +/// Update the last found time of a device present nearby. pub fn update_last_found(mac_address: Address) { let mut devices = IGNORE_LIST.lock().unwrap(); for device in devices.iter_mut() { @@ -104,11 +110,13 @@ pub fn update_last_found(mac_address: Address) { } } +/// Remove a device from the list of devices present nearby. pub fn remove_ignore_device_by_mac(mac_address: Address) { let mut devices = DEVICE_LIST.lock().unwrap(); devices.retain(|device| device.mac_address != mac_address); } +/// Get the current time in milliseconds since UNIX_EPOCH. pub fn current_time_millis() -> i64 { let start = SystemTime::now(); let since_the_epoch = start @@ -117,7 +125,8 @@ pub fn current_time_millis() -> i64 { since_the_epoch.as_millis().try_into().unwrap() } -pub fn out_of_range_checker(mut internal_sender :BleResultSender) { +/// Check if a device is out of range and remove it from the list of devices present nearby or Update the last found time of the device. +pub fn out_of_range_checker(mut internal_sender: BleResultSender) { async_std::task::spawn(async move { loop { async_std::task::sleep(std::time::Duration::from_secs(2)).await; @@ -130,27 +139,28 @@ pub fn out_of_range_checker(mut internal_sender :BleResultSender) { if device.last_found_time != 0 && device.last_found_time < current_time - 5000 { log::error!("Device out of range: {:?}", device.mac_address); internal_sender.send_device_unavailable(device.qaul_id.clone()); - let mac_address :Address = device.mac_address; + let mac_address: Address = device.mac_address; remove_device_by_mac(mac_address); remove_ignore_device_by_mac(mac_address); - } + } } } }); } +/// Byte to Hex conversion. pub fn bytes_to_hex(bytes: &[u8]) -> String { - let hex_chars: Vec = bytes.iter() - .map(|byte| format!("{:02x}", byte)) - .collect(); + let hex_chars: Vec = bytes.iter().map(|byte| format!("{:02x}", byte)).collect(); hex_chars.join("") } +/// Bytes to String conversion. pub fn bytes_to_str(bytes: &[u8]) -> Result<&str, std::str::Utf8Error> { std::str::from_utf8(bytes) } +/// Hex to Byte conversion. pub fn hex_to_bytes(hex: &str) -> Vec { let mut bytes = Vec::new(); for i in 0..hex.len() / 2 { @@ -158,4 +168,4 @@ pub fn hex_to_bytes(hex: &str) -> Vec { bytes.push(byte); } bytes -} \ No newline at end of file +} diff --git a/rust/ble_module/src/rpc/msg_loop.rs b/rust/ble_module/src/rpc/msg_loop.rs index 64446cfe3..cad2f33a5 100644 --- a/rust/ble_module/src/rpc/msg_loop.rs +++ b/rust/ble_module/src/rpc/msg_loop.rs @@ -1,8 +1,6 @@ -// use std::{borrow::Borrow, error::Error}; -use std::error::Error; - use async_std::task::spawn; use bytes::Bytes; +use std::error::Error; use crate::{ ble::ble_service::{get_device_info, QaulBleService}, @@ -11,6 +9,7 @@ use crate::{ use super::BleRpc; +/// Manages all sys messages defined in the 'ble.proto' file. pub async fn listen_for_sys_msgs( mut rpc_receiver: BleRpc, mut ble_service: QaulBleService, @@ -37,10 +36,6 @@ pub async fn listen_for_sys_msgs( let ble_service = svc .advertise_scan_listen(qaul_id, None, internal_sender.clone()) .await; - - log::debug!( - "Set up advertisement and scan filter, entering BLE main loop." - ); match ble_service { QaulBleService::Idle(_) => { log::error!("Error occured in configuring BLE module");