Different behavior of chrome on desktop and android mobile while sending data to BLE device

254 Views Asked by At

While connecting to BLE server on my ESP32 device, using ‘Web Bluetooth API’, I am experiencing a ‎strange behavior. ‎
I can connect and send/receive data using chrome browser on my desktop, but with chrome browser ‎on my android phone I cannot send data to BLE server on my device. ‎
I could not figure out what is the reason. Is Encoding/Decoding different on desktop and mobile ‎browser, some permission problem or json string is sent in some different ways, or is there some limit of data length sent from mobile browser as I am able to send simple "hello world" string from mobile browser but I cannot send "hello world hello world hello world hello world" ?‎
My code is as below:‎

    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
    ‎  }}‎
1

There are 1 best solutions below

2
Zeni On

Sorry for late response. Yes the size matters. For mobile devices Maximum Transmission Unit (MTU) has limit of 23 bytes, but practically you can send only 20 bytes. There are ways to tackle this. I solved my problem by writing to the characteristic multiple times.