- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个蓝牙服务器,它使用 bleno 并向客户端返回可用 Wifi 网络的列表。 readCharacteristic
的代码基本上如下所示:
class ReadCharacteristic extends bleno.Characteristic {
constructor(uuid, name, action) {
super({
uuid: uuid,
properties: ["read"],
value: null,
descriptors: [
new bleno.Descriptor({
uuid: "2901",
value: name
})
]
});
this.actionFunction = action;
}
onReadRequest(offset, callback) {
console.log("Offset: " + offset);
if(offset === 0) {
const result = this.actionFunction();
result.then(value => {
this.actionFunctionResult = value;
const data = new Buffer.from(value).slice(0,bleno.mtu);
console.log("onReadRequest: " + data.toString('utf-8'));
callback(this.RESULT_SUCCESS, data);
}, err => {
console.log("onReadRequest error: " + err);
callback(this.RESULT_UNLIKELY_ERROR);
}).catch( err => {
console.log("onReadRequest error: " + err);
callback(this.RESULT_UNLIKELY_ERROR);
});
}
else {
let data = new Buffer.from(this.actionFunctionResult);
if(offset > data.length) {
callback(this.RESULT_INVALID_OFFSET, null);
}
data = data.slice(offset+1, offset+bleno.mtu);
console.log(data.toString('utf-8'));
callback(this.RESULT_SUCCESS, data);
}
}
}
(我已经尝试过 data = data.slice(offset+1, offset+bleno.mtu);
并像这样 data = data.slice(offset+1);
)
客户端是一个读取该特征的 Android 应用。
用于阅读的 Android 部分如下所示:
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
gatt.requestMtu(256);
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i(TAG, "Disconnected from GATT server.");
mFancyShowCaseView.show();
gatt.close();
scanForBluetoothDevices();
}
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
if (status != BluetoothGatt.GATT_SUCCESS) {
Log.e(TAG, "Can't set mtu to: " + mtu);
} else {
Log.i(TAG, "Connected to GATT server. MTU: " + mtu);
Log.i(TAG, "Attempting to start service discovery:" +
mWifiProvisioningService.discoverServices());
}
}
@Override
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.d(TAG, "ACTION_GATT_SERVICES_DISCOVERED");
BluetoothGattService wifiProvisioningService = gatt.getService(WIFI_PROVISIONING_SERVICE_UUID);
BluetoothGattCharacteristic currentConnectedWifiCharacteristic = wifiProvisioningService.getCharacteristic(WIFI_ID_UUID);
BluetoothGattCharacteristic availableWifiCharacteristic = wifiProvisioningService.getCharacteristic(WIFI_SCAN_UUID);
// Only read the first characteristic and add the 2nd one to a list as we have to wait
// for the read return before we read the 2nd one.
if (!gatt.readCharacteristic(currentConnectedWifiCharacteristic)) {
Log.e(TAG, "Error while reading current connected wifi name.");
}
readCharacteristics.add(availableWifiCharacteristic);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
UUID characteristicUUID = characteristic.getUuid();
if (WIFI_ID_UUID.equals(characteristicUUID)) {
Log.d(TAG, "HEUREKA we found the current wifi name: " + new String(characteristic.getValue()));
final String currentWifiName = new String(characteristic.getValue());
runOnUiThread(new Runnable() {
@Override
public void run() {
((TextView) findViewById(R.id.currentWifiTxt)).setText(currentWifiName);
findViewById(R.id.currentWifiTxtProgress).setVisibility(View.GONE);
}
});
} else if (WIFI_SCAN_UUID.equals(characteristicUUID)) {
Log.d(TAG, "HEUREKA we found the wifi list: " + new String(characteristic.getValue()));
List<String> wifiListArrayList = new ArrayList<>();
try {
JSONObject wifiListRoot = new JSONObject(characteristic.getStringValue(0));
JSONArray wifiListJson = wifiListRoot.getJSONArray("list");
for (int i = 0; i < wifiListJson.length(); i++) {
wifiListArrayList.add(wifiListJson.get(i).toString());
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
return;
}
final String[] wifiList = new String[wifiListArrayList.size()];
wifiListArrayList.toArray(wifiList);
runOnUiThread(new Runnable() {
@Override
public void run() {
((ListView) findViewById(R.id.availableWifiList)).setAdapter(new ArrayAdapter<String>(mContext, R.layout.wifi_name_list_item, wifiList));
findViewById(R.id.currentWifiTxtProgress).setVisibility(View.GONE);
}
});
} else {
Log.i(TAG, "Unexpected Gatt vale: " + new String(characteristic.getValue()));
}
if (readCharacteristics.size() > 0) {
BluetoothGattCharacteristic readCharacteristic = readCharacteristics.get(0);
if (!gatt.readCharacteristic(readCharacteristic)) {
Log.e(TAG, "Error while writing descriptor for connected wifi");
}
readCharacteristics.remove(readCharacteristic);
}
}
}
MTU调整为256字节。我在阅读列表时反射(reflect)在服务器上。调用本身工作正常并返回列表,但如果列表包含超过 600 字节,则只有 600 字节在 Android 上可用。我以某种方式确定 JS 服务器发送了所有数据,但出于某种原因,Android 客户端仅接收或缓存 600 字节,这似乎不正确。
我找到了这篇文章:Android BLE - Peripheral | onCharacteristicRead return wrong value or part of it (but repeated)
还有这个: Android BLE - How is large characteristic value read in chunks (using an offset)?
但是两者都没有解决我的问题。我知道在开始下一次读取之前我需要等待一次读取返回,并且我需要等到 MTU 写入后再继续读取数据。据我所知,这反射(reflect)在您在上面看到的来源中。我有点迷路了。
任何想法都会受到高度赞赏。
非常感谢
最佳答案
对于看到这篇文章的任何人也想知道为什么 Android 似乎只返回 600 字节的长 GATT 特性,就像这个问题所询问的那样,这一切都归结为 Bluedroid(Android 的蓝牙堆栈)如何实现他们的 GATT 客户端及其如何超出规范。就我而言,我使用基于 ESP32 的物联网设备作为我的 GATT 服务器和 Android (SDK 24) 作为 GATT 客户端。
根据规范(蓝牙核心 4.2;第 3 卷,F 部分:3.2.9),特征值(继承自 ATT 的属性值)的最大大小为 512 字节。然而,出于某种原因,Bluedroid 并没有尝试强制执行此要求,而是决定将最大大小设置为 600;如果您深入研究 Bluedroid 源代码并找到设置为 600 的宏 GATT_MAX_ATTR_LEN
(stack/include/gatt_api.h:125
),就可以看到这一点。因为在我的情况下(和你的情况一样)我正在实现读取请求响应代码,所以我也没有看到对特征的读取强制执行 512 字节的限制。
现在,重要的是要了解 Bluedroid 的读取特性,以及它与 MTU 大小、读取的最大大小(应为 512,但 Bluedroid 为 600)以及如何处理超过最大尺寸。 MTU 大小是您可以使用的 ATT 级别的最大数据包大小。因此,对于每次调用 BluetoothGatt.readCharacteristic
,您可能会向服务器发送一个或多个读取请求,具体取决于 Bluedroid 是否认为特征大小超过 MTU 大小。在低级别上,Bluedroid 将首先发送一个 ATT 读取请求(0x0a
),如果数据包的长度为 MTU 字节,它将跟进一个 ATT 读取 Blob 请求(0x0c
) code>) 并将偏移量设置为 MTU 大小。它将继续发送 ATT 读取 Blob 请求,直到 ATT 读取 Blob 响应的长度小于 MTU 字节或直到达到最大特征大小(即 Bluedroid 为 600)。重要的是要注意,如果对于超过 600 字节的数据,MTU 大小不是 600 的完美倍数,则剩余字节将被丢弃(因为 Bluedroid 实际上从未期望读取 600 字节,因为它认为 GATT 服务器将强制执行 512 字节特征尺寸的限制)。因此,如果您的数据超过 600 字节限制(或 512 安全限制),您应该多次调用 BluetoothGatt.readCharacteristic
。这是一个在 Android 端读取大量数据的简单示例(抱歉,我没有使用 bleno,所以无法为您提供修复该端的代码),它依赖于首先将数据长度作为无符号 32 位整数发送,然后如果数据超过 600 字节,则通过重复调用 BluetoothGatt.readCharacteristic
来读出数据:
private int readLength;
private StringBuilder packet; // In my case, Im building a string out of the data
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
gatt.requestMtu(201); // NOTE: If you are going to read a long piece of data, its best to make this value a factor of 600 + 1, like 51, 61, 101, 151, etc due to the risk of data loss if the last packet contains more than 600 bytes of cumulative data
}
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
gatt.discoverServices();
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
// Kick off a read
BluetoothGattCharacteristic characteristic = gatt.getService(UUID.fromString(SERVICE_UUID)).getCharacteristic(UUID.fromString(CHAR_UUID));
readLength = 0;
gatt.readCharacteristic(characteristic);
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (readLength == 0) {
readLength = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 0);
packet = new StringBuilder();
gatt.readCharacteristic(characteristic);
} else {
byte[] data = charactertic.getValue();
packet.append(new String(data));
readLength -= data.length;
if (readLength == 0) {
// Got all data this time; you can now process the data however you want
} else {
gatt.readCharacteristic(characteristic);
}
}
}
关于javascript - Android BLE 客户端在 onCharacteristicRead 中只返回 600 字节的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741196/
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
在编码时,我问了自己这个问题: 这样更快吗: if(false) return true; else return false; 比这个? if(false) return true; return
如何在逻辑条件下进行“返回”? 在这样的情况下这会很有用 checkConfig() || return false; var iNeedThis=doSomething() || return fa
这是我的正则表达式 demo 如问题所述: 如果第一个数字是 1 则返回 1 但如果是 145 则返回 145 但如果是 133 则返回 133 样本数据a: K'8134567 K'81345678
在代码高尔夫问答部分查看谜题和答案时,我遇到了 this solution返回 1 的最长和最晦涩的方法 引用答案, int foo(void) { return! 0; } int bar(
我想在下面返回 JSON。 { "name": "jackie" } postman 给我错误。说明 Unexpected 'n' 这里是 Spring Boot 的新手。 1日龄。有没有正确的方法来
只要“is”返回 True,“==”不应该返回 True 吗? In [101]: np.NAN is np.nan is np.NaN Out[101]: True In [102]: np.NAN
我需要获取所有在 6 号或 7 号房间或根本不在任何房间的学生的详细信息。如果他们在其他房间,简单地说,我不希望有那个记录。 我的架构是: students(roll_no, name,class,.
我有一个表单,我将它发送到 php 以通过 ajax 插入到 mysql 数据库中。一切顺利,php 返回 "true" 值,但在 ajax 中它显示 false 消息。 在这里你可以查看php代码:
我在 Kotlin 中遇到了一个非常奇怪的无法解释的值比较问题,以下代码打印 假 data class Foo ( val a: Byte ) fun main() { val NUM
请注意,这并非特定于 Protractor。问题在于 Angular 2 的内置 Testability service Protractor 碰巧使用。 Protractor 调用 Testabil
在调试窗口中,以下表达式均返回 1。 Application.WorksheetFunction.CountA(Cells(4 + (i - 1) * rows_per_record, 28) & "
我在本地使用 jsonplaceholder ( http://jsonplaceholder.typicode.com/)。我正在通过 extjs rest 代理测试我的 GET 和 POST 调用
这是 Postman 为成功调用我的页面而提供的(修改后的)代码段。 var client = new RestClient("http://sub.example.com/wp-json/wp/v2
这个问题在这里已经有了答案: What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must
我想我对 C 命令行参数有点生疏。我查看了我的一些旧代码,但无论这个版本是什么,都会出现段错误。 运行方式是 ./foo -n num(其中 num 是用户在命令行中输入的数字) 但不知何故它不起作用
我已经编写了一个类来处理命名管道连接,如果我创建了一个实例,关闭它,然后尝试创建另一个实例,调用 CreateFile() 返回 INVALID_HANDLE_VALUE,并且 GetLastErro
即使 is_writable() 返回 true,我也无法写入文件。当然,该文件存在并且显然是可读的。这是代码: $file = "data"; echo file_get_contents($fil
下面代码中的变量 $response 为 NULL,尽管它应该是 SOAP 请求的值。 (潮汐列表)。当我调用 $client->__getLastResponse() 时,我从 SOAP 服务获得了
我一直在网上的不同论坛上搜索答案,但似乎没有与我的情况相符的... 我正在使用 Windows 7,VS2010。 我有一个使用定时器来调用任务栏刷新功能的应用程序。在该任务栏函数中包含对 LoadI
我是一名优秀的程序员,十分优秀!