manniru
3/28/2018 - 12:53 PM

ReactJS_Web_Bluetooth_BatteryLevel.js

import React, { Component } from "react";

var faker = require('faker');

let printCharacteristic;

class App extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    this.sendPrint = this.sendPrint.bind(this);
  }
  
  sendPrint = () => {
    navigator.bluetooth.requestDevice({
        filters: [{
            services: ['000018f0-0000-1000-8000-00805f9b34fb']
        }]
    })
        .then(device => {
            console.log('> Found ' + device.name);
            console.log('Connecting to GATT Server...');
            return device.gatt.connect();
        })
        .then(server => server.getPrimaryService("000018f0-0000-1000-8000-00805f9b34fb"))
        .then(service => service.getCharacteristic("00002af1-0000-1000-8000-00805f9b34fb"))
        .then(characteristic => {
          
            printCharacteristic = characteristic;
            console.log(printCharacteristic); // printCharacteristic.writeValueで書き込めるっぽい
            //let text1 = new Uint8Array([1]);
            //printCharacteristic.writeValue(text);

            let encoder = new TextEncoder("utf-8");
          // Add line feed + carriage return chars to text
          var millis = +new Date();
          var pin = faker.finance.amount(100000000000,999999999999);
          let text = encoder.encode(millis + '=' + pin + '\u000A\u000D');
          return printCharacteristic.writeValue(text).then(() => {
            console.log('Print Sent!');
            
            
            //let resetEnergyExpended = new Uint8Array([1]);
            //return characteristic.writeValue(resetEnergyExpended);

        });

        })
        .catch(error => console.log(error));
            console.log('BLEConnect')
  }
  /*
  async function onButtonClick() {
  try {
    log('Requesting Bluetooth Device...');
    const device = await navigator.bluetooth.requestDevice({
        filters: [{services: ['battery_service']}]});

    log('Connecting to GATT Server...');
    const server = await device.gatt.connect();

    log('Getting Battery Service...');
    const service = await server.getPrimaryService('battery_service');

    log('Getting Battery Level Characteristic...');
    const characteristic = await service.getCharacteristic('battery_level');

    log('Reading Battery Level...');
    const value = await characteristic.readValue();

    log('> Battery Level is ' + value.getUint8(0) + '%');
  } catch(error) {
    log('Argh! ' + error);
  }
}
*/

onButtonClick = async() => {
  /*
    try {
      const res = await fetch('https://time.jsontest.com/')
      const time = await res.json()
      //this.setState({ user })
      console.log(time)
    } catch (e) {
      this.setState({ err: e.message })
    } 
    */
    
    try {
      console.log('Requesting Bluetooth Device...');
      const device = await navigator.bluetooth.requestDevice({
          filters: [{services: ['battery_service']}]});

      console.log('Connecting to GATT Server...');
      const server = await device.gatt.connect();

      console.log('Getting Battery Service...');
      const service = await server.getPrimaryService('battery_service');

      console.log('Getting Battery Level Characteristic...');
      const characteristic = await service.getCharacteristic('battery_level');

      console.log('Reading Battery Level...');
      const value = await characteristic.readValue();

      console.log('> Battery Level is ' + value.getUint8(0) + '%');
    } catch(error) {
      console.log('Argh! ' + error);
    }
    
  }
  
  render() {
    return (
      <div>
      <button onClick={this.sendPrint}>Print</button>
      <br />
      <button onClick={this.onButtonClick}>Button2</button>
      </div>
    );
  }
}

export default App;