ITPNYU / p5.ble.js

A Javascript library that enables communication between BLE devices and a p5 sketch using Web Bluetooth API. https://itpnyu.github.io/p5ble-website.
MIT License
41 stars 29 forks source link

Options object not working #9

Open bborncr opened 4 years ago

bborncr commented 4 years ago

Thanks for the library! I am using version 0.0.6. (Have also tried 0.0.4 and 0.0.5) Creating an options object and using it directly instead of a serviceUuid is not working.

Any attempt at using an options object give the following errors:

Please pass in a serviceUuid string or option object, e.g. options = { filters: [{ services: [serviceUuid] }]} 
Requesting Bluetooth Device... 
Error: TypeError: Failed to execute 'requestDevice' on 'Bluetooth': Either 'filters' should be present or 'acceptAllDevices' should be true, but not both.
characteristics:  
undefined
There is no device connected.

The options objects I am trying to use have been tested using the Chrome demo page: https://googlechrome.github.io/samples/web-bluetooth/device-info.html For example, the following filter works just fine to scan all the BBC micro:bits in the vicinity using the Chrome demo code but does not work with P5Ble (same error as above): options = {filters:[{namePrefix:"BBC"}]} Also options = {acceptAllDevices: true} works fine on the Chrome demo page.

bborncr commented 4 years ago

Here is the test code. It is based on the P5Ble connect_disconnect test code.

let options = {};

let myBLE;
let isConnected = false;

function setup() {
  options = {
    filters: [{
      namePrefix: ['BBC']
    }]
  };
  // Create a p5ble class
  myBLE = new p5ble();

  createCanvas(200, 200);
  textSize(20);
  textAlign(CENTER, CENTER);

  // Create a 'Connect' button
  const connectButton = createButton('Connect')
  connectButton.mousePressed(connectToBle);

  // Create a 'Disconnect' button
  const disconnectButton = createButton('Disconnect')
  disconnectButton.mousePressed(disconnectToBle);
}

function connectToBle() {
  // Connect to a device by passing the service UUID
  myBLE.connect(options, gotCharacteristics);
}

function disconnectToBle() {
  // Disonnect to the device
  myBLE.disconnect();
  // Check if myBLE is connected
  isConnected = myBLE.isConnected();
}

function onDisconnected() {
  console.log('Device got disconnected.');
  isConnected = false;
}

// A function that will be called once got characteristics
function gotCharacteristics(error, characteristics) {
  if (error) console.log('error: ', error);
  console.log('characteristics: ', characteristics);

  // Check if myBLE is connected
  isConnected = myBLE.isConnected();

  // Add a event handler when the device is disconnected
  myBLE.onDisconnected(onDisconnected)
}

function draw() {
  if (isConnected) {
    background(0, 255, 0);
    text('Connected!', 100, 100);
  } else {
    background(255, 0, 0);
    text('Disconnected :/', 100, 100);
  }
}