daily pastebin goal
40%
SHARE
TWEET

Untitled

a guest Apr 15th, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class PlaybulbCandle {
  2.  
  3.   constructor() {
  4.     this.device = null;
  5.     this.onDisconnected = this.onDisconnected.bind(this);
  6.   }
  7.  
  8.   request() {
  9.     let options = {
  10.       "filters": [{
  11.         "name": "PLAYBULB Candle"
  12.       }],
  13.       "optionalServices": [0xFF02]
  14.     };
  15.     return navigator.bluetooth.requestDevice(options)
  16.     .then(device => {
  17.       this.device = device;
  18.       this.device.addEventListener('gattserverdisconnected', this.onDisconnected);
  19.     });
  20.   }
  21.  
  22.   connect() {
  23.     if (!this.device) {
  24.       return Promise.reject('Device is not connected.');
  25.     }
  26.     return this.device.gatt.connect();
  27.   }
  28.  
  29.   writeColor(data) {
  30.     return this.device.gatt.getPrimaryService(0xFF02)
  31.     .then(service => service.getCharacteristic(0xFFFC))
  32.     .then(characteristic => characteristic.writeValue(data));
  33.   }
  34.  
  35.   disconnect() {
  36.     if (!this.device) {
  37.       return Promise.reject('Device is not connected.');
  38.     }
  39.     return this.device.gatt.disconnect();
  40.   }
  41.  
  42.   onDisconnected() {
  43.     console.log('Device is disconnected.');
  44.   }
  45. }
  46.  
  47. var playbulbCandle = new PlaybulbCandle();
  48.  
  49. document.querySelector('button').addEventListener('click', event => {
  50.   playbulbCandle.request()
  51.   .then(_ => playbulbCandle.connect())
  52.   .then(_ => { /* Do something with playbulbCandle... */})
  53.   .catch(error => { console.log(error) });
  54. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top