如何解决向 BLE 设备发送数据时,桌面和安卓手机上的 chrome 的不同行为
在我的 ESP32 设备上连接到 BLE 服务器时,使用“Web 蓝牙 API”,我遇到了一个奇怪的行为。
我可以使用桌面上的 chrome 浏览器连接和发送/接收数据,但是在我的 android 手机上使用 chrome 浏览器,我无法将数据发送到我设备上的 BLE 服务器。
我想不通是什么原因。桌面和移动浏览器上的编码/解码是否不同,某些权限问题或 json 字符串以某些不同的方式发送,或者 从移动浏览器发送的数据长度是否有一些限制,因为我能够发送简单的“hello world” " 来自移动浏览器的字符串,但我无法发送“hello world hello world hello world hello world”?
我的代码如下:
btnconnect.addEventListener('click',submitted);
var wifissid;
var wifipw;
var myjson;
var decoder = new TextDecoder('utf-8');
var encoder = new TextEncoder('utf-8');
var characteristic1;
async function submitted() {
wifissid = document.getElementById("ssid").value;
wifipw = document.getElementById("pw").value;
xdid = document.getElementById("xdid").value;
var obj = {
ssid: wifissid,
pw: wifipw,
did: xdid,
};
myjson = JSON.stringify(obj);
try {
const device = await navigator.bluetooth.requestDevice({
filters: [{
name: 'DEVICENAME'
}],
optionalServices: [‘xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx’]
});
const server = await device.gatt.connect();
const service = await server.getPrimaryService(‘xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx’);
characteristic1 = await service.getCharacteristic(‘yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy’);
await characteristic1.startNotifications();
characteristic1.addEventListener('characteristicvaluechanged',
handleNotifications);
let valuesent = encoder.encode(myjson);
await characteristic1.writeValue(valuesent);
} catch (error) {
console.log( error);
}
}
async function handleNotifications(event) {
let value = await event.target.value;
let valDecoded = decoder.decode(value);
if (valDecoded.includes("success")) {
// Do something
}
if (valDecoded.includes("failed")) {
// Do something
}}
解决方法
抱歉回复晚了。是的,尺寸很重要。对于移动设备,最大传输单元 (MTU) 有 23 个字节的限制,但实际上您只能发送 20 个字节。有办法解决这个问题。我通过多次写入特征解决了我的问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。