You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Angular Web Bluetooth模块写入与通知功能示例

Hey there! I’ve worked with Angular’s web bluetooth module before, so I can share some concrete examples for writing to a characteristic and setting up notifications—both should work with the same module you’re using for reading battery level.

Writing to a Bluetooth Characteristic

Here’s how you can implement a write function, structured similarly to your getBatteryLevel() method:

async writeToCharacteristic(device: BluetoothDevice, serviceUuid: string, charUuid: string, data: string) {
  try {
    // Ensure the device is connected (reconnect if needed)
    if (!device.gatt?.connected) {
      await device.gatt.connect();
    }

    // Fetch the target service and characteristic
    const service = await device.gatt.getPrimaryService(serviceUuid);
    const characteristic = await service.getCharacteristic(charUuid);

    // Convert your data to an ArrayBuffer (adjust encoding for your device's requirements)
    const encoder = new TextEncoder();
    const buffer = encoder.encode(data);

    // Write the value to the characteristic
    await characteristic.writeValue(buffer);
    console.log('Data written successfully!');
  } catch (error) {
    console.error('Error writing to characteristic:', error);
    throw error;
  }
}

Key notes:

  • The TextEncoder converts strings to an ArrayBuffer—if your device expects binary data, create the buffer manually (e.g., new Uint8Array([0x01, 0x02]).buffer)
  • writeValue is the core method exposed by the Angular module, wrapping the native Web Bluetooth API
Setting Up Notifications for a Characteristic

To listen for real-time updates from a Bluetooth device, use this notification setup example:

async setupNotifications(device: BluetoothDevice, serviceUuid: string, charUuid: string, callback: (value: string) => void) {
  try {
    if (!device.gatt?.connected) {
      await device.gatt.connect();
    }

    const service = await device.gatt.getPrimaryService(serviceUuid);
    const characteristic = await service.getCharacteristic(charUuid);

    // Enable notifications from the characteristic
    await characteristic.startNotifications();

    // Listen for incoming value changes
    characteristic.addEventListener('characteristicvaluechanged', (event) => {
      const value = event.target as BluetoothRemoteGATTCharacteristic;
      const decoder = new TextDecoder();
      const decodedValue = decoder.decode(value.value);
      callback(decodedValue);
      console.log('Received notification:', decodedValue);
    });

    console.log('Notifications enabled successfully');
  } catch (error) {
    console.error('Error setting up notifications:', error);
    throw error;
  }
}

Key notes:

  • startNotifications() triggers the device to send updates whenever the characteristic’s value changes
  • The characteristicvaluechanged event fires on each update—use TextDecoder to convert the raw ArrayBuffer back to a readable format (adjust for binary data if needed)
  • Pass a callback to handle the received data (e.g., update your component’s UI state)

Example Usage

Call these methods from your component just like your battery level function:

// Write a command to a device
await this.writeToCharacteristic(connectedDevice, '0000ffe0-0000-1000-8000-00805f9b34fb', '0000ffe1-0000-1000-8000-00805f9b34fb', 'TurnOnLED');

// Set up notifications for a sensor
this.setupNotifications(connectedDevice, '0000ffe0-0000-1000-8000-00805f9b34fb', '0000ffe1-0000-1000-8000-00805f9b34fb', (value) => {
  this.sensorReading = value;
});

内容的提问来源于stack exchange,提问作者Avionic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:54:14