arlyxiao / best-practice

1 stars 0 forks source link

Web bluetooth api demo #94

Open arlyxiao opened 1 year ago

arlyxiao commented 1 year ago

According to some resources

Service connection example

https://stackoverflow.com/questions/56013832/gatt-error-not-paired-with-web-bluetooth-when-device-shows-as-connected
https://github.com/atharvadeosthale/web-bluetooth-phone.git
https://googlechrome.github.io/samples/web-bluetooth/device-information-characteristics.html
https://googlechrome.github.io/samples/web-bluetooth/link-loss.html

script.js

const button = document.getElementById("getDetails");
const details = document.getElementById("details");

// Device UUID
let targetService = 'xxx';
let txCharacteristicId = 'xxx';
let rxCharacteristicId = 'xxx';

async function handleNotifications(event) {
  let value = event.target.value;
  console.log('service: ')
  console.log(event.target.service)
  console.log('---')
  let a = [];
  // Convert raw data bytes to hex values just for the sake of showing something.
  // In the "real" world, you'd use data.getUint8, data.getUint16 or even
  // TextDecoder to process raw data bytes.
  for (let i = 0; i < value.byteLength; i++) {
    // a.push('0x' + ('00' + value.getUint8(i).toString(16)).slice(-2));
    a.push(('00' + value.getUint8(i).toString(16)).slice(-2));
  }
  console.log('> ' + a.join(''));
}

button.addEventListener("click", async () => {

  try {

    // Find bluetooth device
    console.log('Requesting Bluetooth Device...');
    const device = await navigator.bluetooth.requestDevice({
      // acceptAllDevices: true,
      filters: [
        { services: [targetService] },
        // { name: "ExampleName" },
        // { namePrefix: "Prefix" },
      ],
      optionalServices: [targetService, 'device_information']
    })
    const server = await device.gatt.connect()

    console.log('Getting UART transparent service...');
    const service = await server.getPrimaryService(targetService);
    let characteristic = await service.getCharacteristic(txCharacteristicId)
    console.dir(characteristic.service.device);

    const descriptors = await characteristic.getDescriptors()
    console.log(descriptors)

    const notifications = await characteristic.startNotifications()
    console.log('notification done: ')
    console.log(notifications)

    characteristic.addEventListener('characteristicvaluechanged',
        handleNotifications);

    // 80000B000400A32003D2AF
    const data = new Uint8Array([0x80, 0x00, 0x0B, 0x00, 0x04, 0x00, 0xA3, 0x20, 0x03, 0xD2, 0xAF]);
    const writeHandler = await service.getCharacteristic(rxCharacteristicId)
    console.log(writeHandler)
    const result = await writeHandler.writeValueWithResponse(data)
    console.log(`result value: ${result}`)

    const notifyValue = characteristic.value
    console.log('notify result: ')
    console.log(notifyValue)

  } catch (error) {
    console.log(JSON.stringify(error, null, 2))
    console.log(error);
    console.log(error.code);
    console.log(error.message); 
    console.log(error.name); 
  }
});

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="getDetails">Get device details</button>
    <div id="details"></div>

    <script src="script.js"></script>
  </body>
</html>