无法写入特征性WebBLE

时间:2018-09-30 03:26:38

标签: javascript web-bluetooth bleno

我有这个index.html文件,该文件与通过BLE运行bleno应用程序的Raspberry pi 3进行通讯。

<!-- <!DOCTYPE html> -->
<html>
  <head>
    <meta charset="utf-8">
    <title>bluetooth</title>
    <script type="text/javascript">
    var serv;

    var readVal="";

    function onButtonClick() {
      console.log('clciked');
      let filters = [];


      var options1 = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
      };

      let options = {};
        var tem = '00010000-89BD-43C8-9231-40F6E305F96D'.toLowerCase();
        filters.push({services: [tem]});

        options.acceptAllDevices = false;
        options.filters = filters;

      console.log('Requesting Bluetooth Device...');
      console.log('with ' + JSON.stringify(options));
      var listn;
      if(navigator.bluetooth){
        document.getElementById('result').innerHTML = "Bluetooth Supported";
      }
      else{
        document.getElementById('result').innerHTML = "Bluetooth not Supported";
      }



      function success(pos) {
        var crd = pos.coords;

        console.log(crd);
      }

      function error(err) {
        console.warn(`ERROR(${err.code}): ${err.message}`);
      }


      console.log(navigator);

      navigator.geolocation.getCurrentPosition(success, error, options1);
      // navigator.
      let decoder = new TextDecoder('utf-8');

      navigator.bluetooth.requestDevice(options)
      .then(device => {
        console.log('> Name:             ' + device.name);
        console.log('> Id:               ' + device.id);
        console.log('> Connected:        ' + device.gatt.connected);
        return device.gatt.connect();
      })
      .then(server => {

        return server.getPrimaryService(tem);
      })
      .then(service => {
        serv = service;
        console.log(service);
        return service.getCharacteristic('00010010-89bd-43c8-9231-40f6e305f96d');
      })
      .then(characteristic => {
        // console.log(characteristic);
        return characteristic.readValue();
      })
      .then(value => {
        let decoder = new TextDecoder('utf-8');
        var str = decoder.decode(value);
        readVal = str;
        console.log(value);
        console.log(value.toString());
        console.log(str);            
      })
      .catch(error => {
        console.log('Argh! ' + error);
      });
    }





    function onSend() {

      serv.getCharacteristics().then(characteristics =>{
        // console.log(characteristics);
        var charact;
        for(var i = 0; i < characteristics.length; i++){
          var ob = characteristics[i];
          if(ob['properties']['write'] === true){
            charact = ob;
          }
        }
        console.log(charact);
        var Encoder = new TextEncoder("utf-8");
        console.log(readVal);
        var b = Encoder.encode(readVal);
        console.log(b);
        charact.writeValue(b);
      })
      .then(_ => {
        console.log('wrote data');
      })
      .catch(err => {
        console.log(err);
      });
    }



    </script>
  </head>
  <body>
    <button id = "b1" onclick="onButtonClick();">Click</button>
    <h1 id = 'result'></h1>
    <div id = 'networks'></div>
    <button id="send" onclick="onSend();">Send Back</button>
  </body>
</html>

我可以从ble外设读取特征,但是由于index.html第0行未知的原因,我得到DOMException GATToperation失败。

我在Pi上的bleno应用app.js

var bleno = require('bleno');
var fs = require('fs');

var scannedNetworks = [];

const WIFI_SERVICE_UUID = "00010000-89BD-43C8-9231-40F6E305F96D";
const ARGUMENT_1_UUID = "00010001-89BD-43C8-9231-40F6E305F96D";
const RESULT_UUID = "00010010-89BD-43C8-9231-40F6E305F96D";



class ArgumentCharacteristic extends bleno.Characteristic {
    constructor(uuid, name) {
        super({
            uuid: uuid,
            properties: ["write"],
            value: null,
            descriptors: [
                new bleno.Descriptor({
                    uuid: "2901",
                    value: name
                  })
            ]
        });

        this.argument = 0;
        this.name = name;
    }

    onWriteRequest(data, offset, withoutResponse, callback) {
        try {
            if(data.length != 1) {
                callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH);
                return;
            }

            this.argument = data.readUInt8();
        let decoder = new TextDecoder('utf-8');
            var str = decoder.decode(value);
            console.log(`Argument ${this.name} is now ${this.argument}`);
        console.log(str);
            callback(this.RESULT_SUCCESS);

        } catch (err) {
            console.error(err);
            callback(this.RESULT_UNLIKELY_ERROR);
        }
    }
}

class ResultCharacteristic extends bleno.Characteristic {
    constructor() {
        super({
            uuid: RESULT_UUID,
            properties: ["read"],
            value: null,
            descriptors: [
                new bleno.Descriptor({
                    uuid: "2901",
                    value: "Calculation result"
                  })
            ]
        });

        //this.calcResultFunc = calcResultFunc;
    }

    onReadRequest(offset, callback) {
        try {
            fs.readFile('./weights.txt', (err,dat)=>{
                if(!err){
                    var result = dat.toString();
                    console.log(`Returning result: ${result}`);

                    let data = new Buffer(result);
                    //data.writeUInt8(result, 0);
            console.log(data);
                    callback(this.RESULT_SUCCESS, data);
                }
            });
        } catch (err) {
            console.error(err);
            callback(this.RESULT_UNLIKELY_ERROR);
        }
    }
}

console.log("Starting bleno...");

bleno.on("stateChange", state => {

    if (state === "poweredOn") {

        bleno.startAdvertising("Visualizer thresholds", [WIFI_SERVICE_UUID], err => {
            if (err) console.log(err);
        });

    } else {
        console.log("Stopping...");
        bleno.stopAdvertising();
    }
});

bleno.on("advertisingStart", err => {

    console.log("Configuring services...");

    if(err) {
        console.error(err);
        return;
    }

    let argument1 = new ArgumentCharacteristic(ARGUMENT_1_UUID, "Argument 1");
    let result = new ResultCharacteristic();

    let calculator = new bleno.PrimaryService({
        uuid: WIFI_SERVICE_UUID,
        characteristics: [
            result,
            argument1
        ]
    });

    bleno.setServices([calculator], err => {
        if(err)
            console.log(err);
        else
            console.log("Services configured");
    });
});


// some diagnostics
bleno.on("stateChange", state => console.log(`Bleno: Adapter changed state to ${state}`));

bleno.on("advertisingStart", err => console.log("Bleno: advertisingStart"));
bleno.on("advertisingStartError", err => console.log("Bleno: advertisingStartError"));
bleno.on("advertisingStop", err => console.log("Bleno: advertisingStop"));

bleno.on("servicesSet", err => console.log("Bleno: servicesSet"));
bleno.on("servicesSetError", err => console.log("Bleno: servicesSetError"));

bleno.on("accept", clientAddress => console.log(`Bleno: accept ${clientAddress}`));
bleno.on("disconnect", clientAddress => console.log(`Bleno: disconnect ${clientAddress}`));

你们能帮我解决我哪里出问题吗?

谢谢

0 个答案:

没有答案