bluetooth-lowenergy - 几秒钟后停止扫描,使用 react-native-ble-plx 进行 BLE 扫描
问题描述
我目前正在使用 polidea 的 react-native-ble-plx 库进行 BLE 扫描。我不想让它继续扫描,我只想在指定的时间限制后捕获那些扫描的。有没有办法做到这一点?
代码:
export const scan = function scan() {
const subscription = DeviceManager.onStateChange((state) => {
if (state === 'PoweredOn') {
DeviceManager.startDeviceScan(null, null, (error, device) => {
if (error) {
console.log('error', error);
}
if (device !== null) {
console.log('device found ----> [id,name]', device.id, device.name);
}
});
subscription.remove();
}
}, true);
};
输出: 输出图像
解决方案
我会简单地通过在这个函数范围之外创建一个计时器变量来做到这一点,扫描回调处理程序的每次迭代都会检查经过了多少时间,如果超过一定时间就停止扫描。
let startTime = new Date();
export const scan = function scan() {
const subscription = DeviceManager.onStateChange((state) => {
if (state === 'PoweredOn') {
DeviceManager.startDeviceScan(null, null, (error, device) => {
endTime = new Date();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
// get seconds
var seconds = Math.round(timeDiff);
if (error) {
console.log('error', error);
}
if (device !== null) {
console.log('device found ----> [id,name]', device.id, device.name);
}
if (seconds > 5) {
DeviceManager.stopDeviceScan(); //stop scanning if more than 5 secs passed
}
});
subscription.remove();
}
}, true);
};
推荐阅读
- discord.js - 尝试获取 SQLite 值时,discord.js 机器人返回未定义
- r - 在Rstudio中省略大于常数值的值时查找向量的平均值
- java - 在执行 .jar 文件时,`scala` 是否不需要 -jar,而 `java` 需要?
- python - Django 3.0.5 到 sql server 2012 的连接问题
- linux - 两个文件之间的 AWK 部分字符串搜索
- java - 在 Java 中执行 /usr/bin/env bash -c "command"
- android - 启动特定的 Flutter 屏幕
- node.js - Docker - 撰写我无法创建 postgress 服务器
- php - Phalcon 3.4: Inject a component in a controller action without using dispatcher events
- postgresql - 如何配置从 Vanilla Postgresql 9.6 DB 到 AWS RDS Postgresql 的流复制