Code Monkey home page Code Monkey logo

angular-web-bluetooth's Introduction

The missing Web Bluetooth module for Angular

Install

npm install -S @manekinekko/angular-web-bluetooth @types/web-bluetooth

Note: Make also sure the @types/web-bluetooth is installed correctly in your node_modules.

Getting started

1) import the WebBluetoothModule module

import { NgModule } from '@angular/core';
import { WebBluetoothModule } from '@manekinekko/angular-web-bluetooth';

@NgModule({
  imports: [
    //...,
    WebBluetoothModule.forRoot({
      enableTracing: true // or false, this will enable logs in the browser's console
    })
  ]
  //...
})
export class AppModule {}

2.a) use it in your service/component (the easiest way)

Here is an annotated example using the BluetoothCore service:

import { Injectable } from '@angular/core';
import { BluetoothCore } from '@manekinekko/angular-web-bluetooth';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class BatteryLevelService {

  constructor(public readonly ble: BluetoothCore) {}

  getDevice() {
    // call this method to get the connected device
    return this.ble.getDevice$();
  }

  stream() {
    // call this method to get a stream of values emitted by the device for a given characteristic
    return this.ble.streamValues$().pipe(
      map((value: DataView) => value.getInt8(0))
    );
  }

  disconnectDevice() {
    // call this method to disconnect from the device. This method will also stop clear all subscribed notifications
    this.ble.disconnectDevice();
  }

  value() {
    console.log('Getting Battery level...');

    return this.ble
      .value$({
        service: 'battery_service',
        characteristic: 'battery_level'
      });
  }

}

2.b) use it in your service/component (the advanced way)

Here is an annotated example using the BluetoothCore service:

import { Injectable } from '@angular/core';
import { map, mergeMap } from 'rxjs/operators';
import { BluetoothCore } from '@manekinekko/angular-web-bluetooth';

@Injectable({
  providedIn: 'root'
})
export class BatteryLevelService {
  static GATT_CHARACTERISTIC_BATTERY_LEVEL = 'battery_level';
  static GATT_PRIMARY_SERVICE = 'battery_service';

  constructor(public ble: BluetoothCore) {}

  getDevice() {
    // call this method to get the connected device
    return this.ble.getDevice$();
  }

  stream() {
    // call this method to get a stream of values emitted by the device
    return this.ble.streamValues$().pipe(map((value: DataView) => value.getUint8(0)));
  }

  disconnectDevice() {
    this.ble.disconnectDevice();
  }

  /**
   * Get Battery Level GATT Characteristic value.
   * This logic is specific to this service, this is why we can't abstract it elsewhere.
   * The developer is free to provide any service, and characteristics they want.
   *
   * @return Emites the value of the requested service read from the device
   */
  value() {
    console.log('Getting Battery level...');

    return this.ble

        // 1) call the discover method will trigger the discovery process (by the browser)
        .discover$({
          acceptAllDevices: true,
          optionalServices: [BatteryLevelService.GATT_PRIMARY_SERVICE]
        })
        .pipe(

          // 2) get that service
          mergeMap((gatt: BluetoothRemoteGATTServer) => {
            return this.ble.getPrimaryService$(gatt, BatteryLevelService.GATT_PRIMARY_SERVICE);
          }),

          // 3) get a specific characteristic on that service
          mergeMap((primaryService: BluetoothRemoteGATTService) => {
            return this.ble.getCharacteristic$(primaryService, BatteryLevelService.GATT_CHARACTERISTIC_BATTERY_LEVEL);
          }),

          // 4) ask for the value of that characteristic (will return a DataView)
          mergeMap((characteristic: BluetoothRemoteGATTCharacteristic) => {
            return this.ble.readValue$(characteristic);
          }),

          // 5) on that DataView, get the right value
          map((value: DataView) => value.getUint8(0))
        )
  }
}

API documentation

The API documentation can be found here: https://manekinekko.github.io/angular-web-bluetooth/

Need a starter?

This project serves also as a starter. Run the following command:

npm start

Blog post

Checkout my full blog post on dev.to about how to use this package in your app.

Have a PR?

All contributions are welcome. Here are few open issues that I need help with ;)

License

The MIT License (MIT) Copyright (c) 2017 - Wassim CHEGHAM

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

angular-web-bluetooth's People

Contributors

bobbyg603 avatar chewiewookie avatar fayway avatar manekinekko avatar msftgits avatar renovate[bot] avatar thanhpd avatar urish avatar vogloblinsky avatar webmaxru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-web-bluetooth's Issues

disconnect event not accessible

I believe that the disconnect event is not accessible from user app.

I've tried to link the disconnect event from the device to a function in my code, but failed.
Either I'm doing something wrong or this part of the code has an issue. device.ongattserverdisconnected is always null.

line 74 bluetoot.servic.ts
if (device.ongattserverdisconnected) {
device.addEventListener('gattserverdisconnected', this.onDeviceDisconnected.bind(this));
}

Hope you can help me.

Add a method that converts a characteristic into an observable of values

sketch for a possible implementation:

  notifications$(char: BluetoothRemoteGATTCharacteristic) {  
    char.startNotifications();
    const disconnected = Observable.fromEvent(char.service.device as any, 'gattserverdisconnected');
    return Observable.fromEvent(char as any, 'characteristicvaluechanged').takeUntil(disconnected).map(event => event.target.value as DataView);
  }

You'd still need to stop the notifications when everybody unsubscribes, but I guess this can be added later.

error TS2451: Cannot redeclare block-scoped variable 'ngDevMode'

I have implemented the web-bluetooth module in same way but getting below error message , please help me to resolve this.

ERROR in node_modules/@angular/core/src/render3/ng_dev_mode.d.ts(9,11): error TS2451: Cannot redeclare block-scoped variable 'ngDevMode'.
node_modules/@manekinekko/angular-web-bluetooth/node_modules/@angular/core/src/render3/ng_dev_mode.d.ts(9,11): error TS2451: Cannot redeclare block-scoped variable 'ngDevMode'.

Request: Make the service reusable for multiple components

Is your feature request related to a problem? Please describe.

I have a custom device that communicates over multiple BLE characteristics (approx. 10).

The communications are mainly one way (read only) from the device to the web webapp. One exception is a "command" characteristic that is used to send a set of pre-defined commands to the device.

The whole application will use multiple Angular components on a certain number of pages.

As of now, I have to create an instance of the Angular-Web-Bluetooth Service for each component/characteristic. This is not practical and surely not scalable.

Describe the solution you'd like

What I would like, is the service to be centralized to the main app.component and be shared throughout all the components.
A suggestion would be to implement a getCharacteristics (note the S) in the bluetooth.service.ts

The resulting collection of characteristics could be saved or cached for later reuse. The library user could then subscribe to observables events of one or many characteristics for notifications.

Here is a sample of what it could look like from
https://googlechrome.github.io/samples/web-bluetooth/discover-services-and-characteristics-async-await.html

try {
    log('Requesting any Bluetooth Device...');
    const device = await navigator.bluetooth.requestDevice({
     // filters: [...] <- Prefer filters to save energy & show relevant devices.
        acceptAllDevices: true,
        optionalServices: optionalServices});

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

    // Note that we could also get all services that match a specific UUID by
    // passing it to getPrimaryServices().
    log('Getting Services...');
    const services = await server.getPrimaryServices();

    log('Getting Characteristics...');
    for (const service of services) {
      log('> Service: ' + service.uuid);
      const characteristics = await service.getCharacteristics();   //  <==== This =====

      characteristics.forEach(characteristic => {      
        log('>> Characteristic: ' + characteristic.uuid + ' ' +
            getSupportedProperties(characteristic));
      });
    }

I am still a newby related to Angular, Rx.js and observable. So it is outside of my league currently. But I am learning fast :-)

Additional context
You can see a sample of my application here on github pages: https://intensite.github.io/morgan-app/

The source code of the web-app is here: https://github.com/intensite/morgan-app

Thanks for this great library by the way!

Where is disconnect device function

Hi manekinekko,

I want to add a disconnect button in my project. However, I could not find the disconnect device function in the the module. Could yo please tell me where is disconnect function?

Thanks

Error with Angular 4

after installing the backage -> found version number error as the following:
image
I fix it manually edit version number in "manekinekko-angular-web-bluetooth.metadata.json" file from "4" to "3"

after that there runtime error with angular 4 project
image

Function calls are not supported in [email protected]

A new project bootstrap + ng serve gives following:

`ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 18:23 in the original .ts file), resolving symbol WebBluetoothModule.forRoot in /Users/.../node_modules/@manekinekko/angular-web-bluetooth/dist/lib/bluetooth.module.d.ts, resolving symbol AppModule in /Users/.../bt-test/src/app/app.module.ts, resolving symbol AppModule in /Users/.../bt-test/src/app/app.module.ts

ERROR in ./src/app/app.module.ts
Module not found: Error: Can't resolve '@manekinekko/angular-web-bluetooth' in '/Users/.../bt-test/src/app'
@ ./src/app/app.module.ts 14:0-72
@ ./src/main.ts
@ multi main`

This is because of angular/angular-cli#3707
PR is on the way :)

Cannot find type definition file for 'web-bluetooth'

Describe the bug

Compilation fails with following errors


Date: 2018-06-01T12:33:15.846Z
Hash: a9e8058741d47076abd3
Time: 5944ms
chunk {main} main.js, main.js.map (main) 1.87 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 654 bytes [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 5.4 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 15.6 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 325 kB [initial] [rendered]

ERROR in node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(1,23): error TS2688: Cannot find type definition file for 'web-bluetooth'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(9,28): error TS2304: Cannot find name 'BluetoothDevice'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(10,26): error TS2304: Cannot find name 'BluetoothRemoteGATTServer'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(12,18): error TS2304: Cannot find name 'BluetoothRemoteGATTServer'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(14,30): error TS2304: Cannot find name 'BluetoothDevice'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(15,28): error TS2304: Cannot find name 'BluetoothRemoteGATTServer'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(23,24): error TS2304: Cannot find name 'RequestDeviceOptions'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(23,55): error TS2304: Cannot find name 'BluetoothDevice'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(34,25): error TS2304: Cannot find name 'RequestDeviceOptions'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(34,66): error TS2304: Cannot find name 'BluetoothRemoteGATTServer'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(40,27): error TS2304: Cannot find name 'BluetoothDevice'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(40,53): error TS2304: Cannot find name 'BluetoothRemoteGATTServer'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(46,28): error TS2304: Cannot find name 'BluetoothDevice'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(46,57): error TS2304: Cannot find name 'BluetoothRemoteGATTServer'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(52,30): error TS2304: Cannot find name 'BluetoothRemoteGATTServer'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(52,66): error TS2304: Cannot find name 'BluetoothServiceUUID'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(52,100): error TS2304: Cannot find name 'BluetoothRemoteGATTService'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(58,40): error TS2304: Cannot find name 'BluetoothRemoteGATTService'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(58,84): error TS2304: Cannot find name 'BluetoothCharacteristicUUID'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(58,132): error TS2304: Cannot find name 'BluetoothRemoteGATTCharacteristic'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(65,37): error TS2304: Cannot find name 'BluetoothServiceUUID'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(65,75): error TS2304: Cannot find name 'BluetoothCharacteristicUUID'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(65,136): error TS2304: Cannot find name 'BluetoothRemoteGATTService'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(71,35): error TS2304: Cannot find name 'BluetoothServiceUUID'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(71,73): error TS2304: Cannot find name 'BluetoothCharacteristicUUID'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(71,127): error TS2304: Cannot find name 'BluetoothRemoteGATTService'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(77,36): error TS2304: Cannot find name 'BluetoothServiceUUID'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(77,74): error TS2304: Cannot find name 'BluetoothCharacteristicUUID'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(77,128): error TS2304: Cannot find name 'BluetoothRemoteGATTService'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(91,32): error TS2304: Cannot find name 'BluetoothRemoteGATTCharacteristic'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(97,33): error TS2304: Cannot find name 'BluetoothRemoteGATTCharacteristic'.
node_modules/@manekinekko/angular-web-bluetooth/lib/bluetooth.service.d.ts(102,35): error TS2304: Cannot find name 'BluetoothRemoteGATTCharacteristic'.
node_modules/@manekinekko/angular-web-bluetooth/lib/platform/browser.d.ts(1,23): error TS2688: Cannot find type definition file for 'web-bluetooth'.
node_modules/@manekinekko/angular-web-bluetooth/lib/platform/browser.d.ts(5,28): error TS2304: Cannot find name 'RequestDeviceOptions'.
node_modules/@manekinekko/angular-web-bluetooth/lib/platform/browser.d.ts(5,59): error TS2304: Cannot find name 'BluetoothDevice'.

i 「wdm」: Failed to compile.

To Reproduce
Steps to reproduce the behavior:

  1. ng new mybluetoothapp
  2. Follow tutorial on https://manekinekko.github.io/angular-web-bluetooth/index.html
  3. ng serve

Expected behavior
Compilation should be successful.

Desktop (please complete the following information):

Angular CLI: 6.1.0-beta.0
Node: 8.11.2
OS: win32 x64
Angular: 6.0.3
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.7.0-beta.1
@angular-devkit/build-angular     0.7.0-beta.1
@angular-devkit/build-optimizer   0.7.0-beta.1
@angular-devkit/core              0.7.0-beta.1
@angular-devkit/schematics        0.7.0-beta.0
@angular/cli                      6.1.0-beta.0
@ngtools/webpack                  6.1.0-beta.1
@schematics/angular               0.7.0-beta.0
@schematics/update                0.7.0-beta.0
rxjs                              6.2.0
typescript                        2.7.2
webpack                           4.6.0

Can't start project

I'm trying to start the project, but I've gotten several errors. After running npm install, got the following:

Time Elapsed 00:00:34.88
gyp ERR! build error 
gyp ERR! stack Error: `C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Projects\angular-web-bluetooth\node_modules\node-gyp\lib\build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (events.js:209:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)
gyp ERR! System Windows_NT 10.0.18362
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Projects\\angular-web-bluetooth\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:\Projects\angular-web-bluetooth\node_modules\node-sass
gyp ERR! node -v v12.9.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
Build failed with error code: 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\snguyen\AppData\Roaming\npm-cache\_logs\2020-02-28T17_33_54_255Z-debug.log

After running npm run build:

Cannot find module 'ng-packagr'
Require stack:
- C:\Projects\angular-web-bluetooth\node_modules\@angular-devkit\build-ng-packagr\src\build\index.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\node_modules\@angular-devkit\architect\src\architect.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\node_modules\@angular-devkit\architect\src\index.js    
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\models\architect-command.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\commands\build-impl.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular-devkit\schematics\tools\export-ref.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular-devkit\schematics\tools\index.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\utilities\json-schema.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\models\command-runner.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\lib\cli\index.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\lib\init.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\bin\ng
Error: Cannot find module 'ng-packagr'
Require stack:
- C:\Projects\angular-web-bluetooth\node_modules\@angular-devkit\build-ng-packagr\src\build\index.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\node_modules\@angular-devkit\architect\src\architect.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\node_modules\@angular-devkit\architect\src\index.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\models\architect-command.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\commands\build-impl.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular-devkit\schematics\tools\export-ref.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular-devkit\schematics\tools\index.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\utilities\json-schema.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\models\command-runner.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\lib\cli\index.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\lib\init.js
- C:\Projects\angular-web-bluetooth\node_modules\@angular\cli\bin\ng
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:772:15)
    at Function.resolve (internal/modules/cjs/helpers.js:74:19)
    at requireProjectModule (C:\Projects\angular-web-bluetooth\node_modules\@angular-devkit\build-ng-packagr\src\build\index.js:19:28)
    at Observable._subscribe (C:\Projects\angular-web-bluetooth\node_modules\@angular-devkit\build-ng-packagr\src\build\index.js:57:38)
    at Observable._trySubscribe (C:\Projects\angular-web-bluetooth\node_modules\rxjs\internal\Observable.js:44:25)
    at Observable.subscribe (C:\Projects\angular-web-bluetooth\node_modules\rxjs\internal\Observable.js:30:22)
    at C:\Projects\angular-web-bluetooth\node_modules\rxjs\internal\util\subscribeTo.js:22:31
    at Object.subscribeToResult (C:\Projects\angular-web-bluetooth\node_modules\rxjs\internal\util\subscribeToResult.js:10:45)
    at MergeMapSubscriber._innerSub (C:\Projects\angular-web-bluetooth\node_modules\rxjs\internal\operators\mergeMap.js:82:29)
    at MergeMapSubscriber._tryNext (C:\Projects\angular-web-bluetooth\node_modules\rxjs\internal\operators\mergeMap.js:76:14)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] prebuild: `ng build @manekinekko/angular-web-bluetooth`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] prebuild script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\snguyen\AppData\Roaming\npm-cache\_logs\2020-02-28T17_35_39_492Z-debug.log

Compile error report

I downloaded angular-web-bluetooth.
But when I run ng serve --open command, there is a error as below:

ERROR in ./src/app/app.module.ts
Module not found: Error: Can't resolve 'C:\Users\angular-web-bluetooth-master\dist\angular-web-bluetooth' in 'C:\Users\angular-web-bluetooth-master\src\app'
ERROR in ./src/app/battery-level/battery-level.service.ts
Module not found: Error: Can't resolve 'C:\Users\angular-web-bluetooth-master\dist\angular-web-bluetooth' in 'C:\Users\angular-web-bluetooth-master\src\app\battery-level'

Could you please check whey this error happens?

Thanks

AOT compile Error

Hi, I just followed the given example in the readme to include it to my angular 5 application and while the normal build works ok, the AOT build gives the following error.

ERROR in ../@manekinekko/angular-web-bluetooth/dist/lib/bluetooth.module.ts(29,2): Error during template compile of 'WebBluetoothModule'
Function expressions are not supported in decorators in 'NgModule'
'NgModule' contains the error at ../@angular/core/core.ts(194,31)
Consider changing the function expression into an exported function.

Failed to execute 'requestDevice' on 'Bluetooth': Either 'filters' should be present or 'acceptAllDevices' should be true, but not both.

chrome: Version 60.0.3112.101 (Official Build) (64-bit)
npm: 5.3.0
angular-cli: 1.0.0-beta.24
node: 8.4.0
os: darwin x64
angular/common: 2.4.7
angular/compiler: 2.4.7
angular/compiler-cli: 2.4.7
angular/core: 2.4.7
angular/forms: 2.4.7
angular/http: 2.4.7
angular/platform-browser: 2.4.7
angular/platform-browser-dynamic: 2.4.7
angular/router: 3.4.7
ngtools/webpack: 1.2.4

error_handler.js:60 TypeError: Failed to execute 'requestDevice' on 'Bluetooth': Either 'filters' should be present or 'acceptAllDevices' should be true, but not both.
at BrowserWebBluetooth.requestDevice (browser.js:11)
at BluetoothCore.discover (bluetooth.service.js:62)
at BluetoothCore.discover$ (bluetooth.service.js:87)
at BatteryLevelService.getBatteryLevel (battery-level.service.ts:48)
at DeviceComponent.getBatteryLevel (device.component.ts:60)
at CompiledTemplate.proxyViewClass.View_DeviceComponent0.handleEvent_24 (/DeviceModule/DeviceComponent/component.ngfactory.js:108)
at HTMLAnchorElement. (dom_renderer.js:490)
at ZoneDelegate.invokeTask (zone.js:363)
at Object.onInvokeTask (ng_zone.js:264)
at ZoneDelegate.invokeTask (zone.js:362)
at Zone.runTask (zone.js:166)
at HTMLAnchorElement.ZoneTask.invoke (zone.js:416)

Cannot find module '@manekinekko/angular-web-bluetooth'

Hi,

I follow the instruction for installing the package, but I get this error
Cannot find module '@manekinekko/angular-web-bluetooth'
As well the package @types/web-bluetooth is missing
I use npm 6.14.4 and angular 9.1 (ubuntu)

EDIT:
Just tried with Windows 10/Angular 8.3.26 (same errors).

Module is not Found

Describe the bug
After installing it using npm i -S @manekinekko/angular-web-bluetooth @types/web-bluetooth, when I try to import the web module it is not found.

To Reproduce
Steps to reproduce the behavior:

  1. Install the Web Bluetooth Module
  2. Go to App.module.ts
  3. Try to import WebBluetoothModule from @manekinekko/angular-web-bluetooth
  4. See error

Expected behavior
No error when I import the Module, so I can use it.

Screenshots
Screenshot (181)

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: chrome

Comments
Angular Version:
Screenshot (182)

Cannot upgrade to 11.2.1 "error TS2307: Cannot find module '@manekinekko/angular-web-bluetooth' or its corresponding type declarations."

Describe the bug
Upgrading the version from 9.1.1 to 11.2.1.

To Reproduce
Steps to reproduce the behavior:

  1. Update package.json dependency: "@manekinekko/angular-web-bluetooth": "^11.2.1"
  2. Npm install
  3. Ng build
  4. See error

Error: src/app/device-management/comms/ferit-config-bluetooth.service.ts:3:31 - error TS2307: Cannot find module '@manekinekko/angular-web-bluetooth' or its corresponding type declarations.

Expected behavior
A clean compile, no errors.

Desktop (please complete the following information):

  • OS: Windows 10
  • Npm 6.4.1
  • Node: 10.15.3
  • Angular: 11.0.2

Also tried a fresh project checkout, removing bluetooth dependency completely from package.json and run:
npm install -S @manekinekko/angular-web-bluetooth @types/web-bluetooth
Checked node modules and found the packages in both types and @manekinekko/angular-web-bluetooth directory.
run ng build. Same build error and not bluetooth types found. If I revert the project to 9.1.1 all is well again.

Feat: better exception handling

nice to see @types/web-bluetooth release. 👍

  1. please include types for BluetoothUUID so that we could use static GATT_PRIMARY_SERVICE = BluetoothUUID.getService('heart_rate')
  2. throwing error when browser doesn't support bluetooth causing the entire Angular app to crash. If you simply console.log or propagate error through discover$ Observable , then at least non-bluetooth part of the page will render. Developers can gracefully show the error message.
  3. it would nice if we have auto bluetooth disconnect/ auto unsubscribe capability for discover$ when developer call discover$.first() or discover$.take(1) similarly for observeValue$

How can I send print job to bluetooth connected printer?

Hi there,

I am trying to achieve the same as this example: https://github.com/WebBluetoothCG/demos/tree/gh-pages/bluetooth-printer

Would like to send print jobs to the connected printer. I tested the example above and that is printing for me. Would like to print receipts in my webapp :)

Also in this function:
requestValue() { this.valuesSubscription = this.bluetoothService.value().subscribe( () => null, (error) => console.log(error) ); }

I get this error:

No Services matching UUID 0000180f-0000-1000-8000-00805f9b34fb found in Device. (battery_service) at BluetoothCore.<anonymous> (manekinekko-angular-web-bluetooth.js:310)

feat(error): handle errors

The current implementation does not handle ALL errors. It'd be nice to be able to catch the errors. For instance, if the use cancels the requestDevice() chooser, the exception is thrown in the console.

error: property 'map' and 'mergeMap' does not exist...

I integrated bluetooth component and battery level service into my angular project. When I run ng serve --open, I get below errors. Could you please give some comments for the root causes?

ERROR in src/app/bluetooth.service.ts(24,37): error TS2339: Property 'map' does not exist on type 'Observable'.
src/app/bluetooth.service.ts(43,10): error TS2339: Property 'mergeMap' does not exist on type 'Observable<void | BluetoothRemoteGATTServer>'.

Feat: auto disconnect

@xmlking has submitted this feature:

it would nice if we have auto bluetooth disconnect/ auto unsubscribe capability for discover$ when developer call discover$.first() or discover$.take(1) similarly for observeValue$

Not get informations of device

  • No call api request
  • No getting informations of device bluetooth in function getDevice$()

Screenshots
image

// Versions
Angular CLI: 6.0.8
Node: 8.11.3
OS: linux x64
Angular: 6.0.9
@manekinekko/angular-web-bluetooth: 3.0.0

How can I subscribe to multiple services (via notify) ble simultaneously with a single click on the button?

Is your feature request related to a problem? Please describe.
I created a common service ble like this:

`import { Injectable } from '@angular/core';
import { BluetoothCore } from '@manekinekko/angular-web-bluetooth';
import { map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class BatteryLevelService {

  constructor(public readonly ble: BluetoothCore) {}

  getDevice() {
    // call this method to get the connected device
    return this.ble.getDevice$();
  }

  stream() {
    // call this method to get a stream of values emitted by the device for a given characteristic
    return this.ble.streamValues$().pipe(
      map((value: DataView) => value.getInt8(0))
    );
  }

  disconnectDevice() {
    // call this method to disconnect from the device. This method will also stop clear all subscribed notifications
    this.ble.disconnectDevice();
  }

  value() {
    console.log('Getting Battery level...');

    return this.ble
      .value$({
        service: 'battery_service',
        characteristic: 'battery_level'
      });
  }}`

and i try to use it on 2 components but i want just to click one time to read 2 values from 2 different charateristics of 2 services of ble.
Thanks in advance for the reply.

No devices detected

I used the starter, to try out connecting my BLE device over Chrome, but no device was detected (not my device, but also no other when trying to figure out if the device was the problem).

The chrome flag #enable-experimental-web-platform-features is enabled, and according to different documentations, this should be enough to work.

Am I missing something? Is there anything else I need to change?

Specifications:

  • OS: Windows 10
  • Browser: Chrome, Version 70
  • Device: BLE Robot

Thank you for any help! I would really appreciate it.

How to use custom service

hi,

i want to communicate by device with hm10 (BLE module). it use service 0xFFE0 and characteristics 0xFFE1 for send and receive data. how can i communicate to this device it's show me an error

manekinekko-angular-web-bluetooth.js:95 TypeError: Failed to execute 'requestDevice' on 'Bluetooth': Invalid Service name: 'ffe0'. It must be a valid UUID alias (e.g. 0x1234), UUID (lowercase hex characters e.g. '00001234-0000-1000-8000-00805f9b34fb'), or recognized standard name from https://www.bluetooth.com/specifications/gatt/services e.g. 'alert_notification'.
at BrowserWebBluetooth.push../dist/manekinekko/angular-web-bluetooth/fesm5/manekinekko-angular-web-bluetooth.js.BrowserWebBluetooth.requestDevice (manekinekko-angular-web-bluetooth.js:27)

Please help me as soon as possible

Reading characteristic value failing intermittently after device discovery.

I am trying to build one application for a MI smart band. This application reads the pedometer data. Now, after pairing devices, it fails to read the characteristics value. Post that, once it dispatches notifications of value changed, characteristic values starts to flow in.

Further, this failure is happening only in 90%cases. Once in a while, failure does not happen. It works perfectly fine the very first time.

Now, what i feel is, when we read the characteristics by calling ble.getCharacteristic$(), it returns the promise which generally gets settled before starting the notification on that characteristics. In such case, when we try to read value out of this characteristics, it fails.

Now, in 10 % case, char.startNotifications() gets settled before the above mentioned promise. Hence, the issue do not come while reading the value.

Logs in 10% cases where it works fine.

manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Connecting to GATT Server of BluetoothDevice {id: "gUkAd5nZjn8yRumfGRtIJQ==", name: "Mi Band HRX", gatt: BluetoothRemoteGATTServer, ongattserverdisconnected: null}
manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Getting primary service "0000fee0-0000-1000-8000-00805f9b34fb" (if available) of BluetoothRemoteGATTServer {device: BluetoothDevice, connected: true}
manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Getting Characteristic "00000007-0000-3512-2118-0009af100700" of BluetoothRemoteGATTService {device: BluetoothDevice, uuid: "0000fee0-0000-1000-8000-00805f9b34fb", isPrimary: true}
manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Reading Characteristic BluetoothRemoteGATTCharacteristic {service: BluetoothRemoteGATTService, uuid: "00000007-0000-3512-2118-0009af100700", properties: BluetoothCharacteristicProperties, value: null, oncharacteristicvaluechanged: null}
manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Starting notifications of "00000007-0000-3512-2118-0009af100700"
manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Dispatching new characteristic value Event {isTrusted: true, type: "characteristicvaluechanged", target: BluetoothRemoteGATTCharacteristic, currentTarget: BluetoothRemoteGATTCharacteristic, eventPhase: 2, …}
display-mi-band-stats.component.ts:53 Reading pedometer results 

Logs in 90% cases when it fails

manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Connecting to GATT Server of BluetoothDevice {id: "gUkAd5nZjn8yRumfGRtIJQ==", name: "Mi Band HRX", gatt: BluetoothRemoteGATTServer, ongattserverdisconnected: null}
manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Getting primary service "0000fee0-0000-1000-8000-00805f9b34fb" (if available) of BluetoothRemoteGATTServer {device: BluetoothDevice, connected: true}
manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Getting Characteristic "00000007-0000-3512-2118-0009af100700" of BluetoothRemoteGATTService {device: BluetoothDevice, uuid: "0000fee0-0000-1000-8000-00805f9b34fb", isPrimary: true}
manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Reading Characteristic BluetoothRemoteGATTCharacteristic {service: BluetoothRemoteGATTService, uuid: "00000007-0000-3512-2118-0009af100700", properties: BluetoothCharacteristicProperties, value: null, oncharacteristicvaluechanged: null}
core.js:1542 ERROR GATT operation failed for unknown reason.
......
manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Starting notifications of "00000007-0000-3512-2118-0009af100700"
manekinekko-angular-web-bluetooth.js:80 [BLE::Info] Dispatching new characteristic value Event {isTrusted: true, type: "characteristicvaluechanged", target: BluetoothRemoteGATTCharacteristic, currentTarget: BluetoothRemoteGATTCharacteristic, eventPhase: 2, …}
display-mi-band-stats.component.ts:53 Reading pedometer results 

Are multiple services per connection and characteristics per service supported?

Thanks for the awesome project :)

I'm interested in supporting Nordic UART Service and battery level service at the same time. I'd need to share the connection between different characteristics and services at the same time.

After a quick exploration of the project it seems that currently I'd need to disconnect from one characteristic before connecting to next, is this the case or did I miss something?

Unexpected value '[object Object]' imported by the module 'AppModule' error

Hi, I am getting this error

Uncaught Error: Unexpected value '[object Object]' imported by the module 'AppModule'
    Zone.runTask @ zone.js:170
    ZoneTask.invoke @ zone.js:420

after I add

WebBluetoothModule.forRoot({
  enableTracing: true
}),

to the imports section of AppModule.

Do you have any suggestion on how to avoid that?
Thanks a lot

Number format from BLE scale

I have a scale that I'm trying to read from. When connecting to it via nrfConnect, and reading the value from the device's weight service/characteristic, I get this in the log:


V	19:03:51.236	Reading descriptor 00002904-0000-1000-8000-00805f9b34fb
D	19:03:51.236	gatt.readDescriptor(00002904-0000-1000-8000-00805f9b34fb)
I	19:03:51.612	Read Response received from descr. 00002904-0000-1000-8000-00805f9b34fb, value: (0x) 10-FA-02-27-00-00-00
A	19:03:51.612	"Format: signed 32-bit integer
Exponent: -6
Unit: mass (kilogram)
Namespace: Reserved for future use (0)
Description: 0" received

This somehow tells nrfConnect that the values in characteristic 1bc50002 are to be interpreted as kG, in the format of a Int32 with an exponent of -6
Then, if I read the weight, I get:

V	19:05:48.854	Reading characteristic 1bc50002-0200-0aa5-e311-24cb004a98c5
D	19:05:48.854	gatt.readCharacteristic(1bc50002-0200-0aa5-e311-24cb004a98c5)
I	19:05:49.112	Read Response received from 1bc50002-0200-0aa5-e311-24cb004a98c5, value: (0x) E3-2C-00-00
A	19:05:49.112	"0.011491 kg" received

V	19:06:34.036	Reading characteristic 1bc50002-0200-0aa5-e311-24cb004a98c5
D	19:06:34.036	gatt.readCharacteristic(1bc50002-0200-0aa5-e311-24cb004a98c5)
I	19:06:34.287	Read Response received from 1bc50002-0200-0aa5-e311-24cb004a98c5, value: (0x) 75-E8-FF-FF
A	19:06:34.287	"-0.006027 kg" received

So, I used the battery level example, and put together this code to read from the scale:

static GATT_PRIMARY_SERVICE = '1bc50001-0200-0aa5-e311-24cb004a98c5';
static GATT_CHARACTERISTIC_WEIGHT = '1bc50002-0200-0aa5-e311-24cb004a98c5';

value() {
      return this.ble.discover$({
        acceptAllDevices: true,
        optionalServices: [WeightService.GATT_PRIMARY_SERVICE]
      })
      .pipe(

        // 2) get that service
        mergeMap((gatt: BluetoothRemoteGATTServer) => {
          // gatt.connect();
          return this.ble.getPrimaryService$(gatt, WeightService.GATT_PRIMARY_SERVICE);
        }),

        // 3) get a specific characteristic on that service
        mergeMap((primaryService: BluetoothRemoteGATTService) => {
          return this.ble.getCharacteristic$(primaryService, WeightService.GATT_CHARACTERISTIC_WEIGHT);
        }),

        // 4) ask for the value of that characteristic (will return a DataView)
        mergeMap((characteristic: BluetoothRemoteGATTCharacteristic) => {
          return this.ble.readValue$(characteristic);
        }),

        // 5) on that DataView, get the right value
        map((value: DataView) => {

          console.log(value);
          return value.getInt32(0);
        }
        )
      );
  }

and in the DataView, I get values like:
Uint8[35, 234, 255, 255]

Which correspond with the same values from nrfConnect when the scale is empty.

My question is how do I convert this data into a weight using the information from the device that the values are '32 bit integer with an exponent of -6 and the format is mass (kg)'
I played around with the data from nRFConnect
(0x) 75-E8-FF-FF === -0.006027kg and am unable to figure anything out.

Unsupported device error

I wrote a small demo program to test this lib. I mainly used the code from the starter project for my service and my component.

And I setup a GATT-server with a battery service and a battery level characteristic on my phone.

When I call getBatteryLevel() I can choose my device but I can not retrieve the data. I get the debug message ERROR Error: Uncaught (in promise): Unsupported device. followed by ERROR TypeError: Cannot read property 'getPrimaryService' of undefined.

I am not sure if this is a general web bluetooth problem or a problem with this library.

Error in find type definition file for 'web-bluetooth'

Describe the bug
No Running in angular 6, error in serve application

Screenshots
image
image

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: Dell Inspiron 15 and Xioami Mi5
  • OS: Linux and Android
  • Browser Chromium and Chrome
  • Version 67

Does not support on mac Chrome build 76.

Describe the bug
Although this chrome (76) browser supports WebBluetoothAPI, it throws me an error

To Reproduce

  1. from the mac connect to remote server.

Expected behavior
Works. I tried looking that the source code and compared it with other web bluetooth api services' source code, but it does not differ at all. Could not pinpoint where the problem is coming from.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: MacOS
  • Browser Google Chrome
  • Version 76

Additional context
DashboardComponent.html:32 ERROR Error: Your browser does not support Smart Bluetooth. See http://caniuse.com/#search=Bluetooth for more details.
at new BrowserWebBluetooth (manekinekko-angular-web-bluetooth.js:15)
at browserWebBluetooth (manekinekko-angular-web-bluetooth.js:803)
at callFactory (core.js:19825)
at createProviderInstance (core.js:19783)
at resolveNgModuleDep (core.js:19744)
at NgModuleRef
.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef
.get (core.js:20452)
at resolveDep (core.js:20823)
at callFactory (core.js:20716)
at createProviderInstance$1 (core.js:20682)
at createProviderInstance (core.js:20557)
View_DashboardComponent_0 @ DashboardComponent.html:32
proxyClass @ compiler.js:17945
push../node_modules/@angular/core/fesm5/core.js.DebugContext
.logError @ core.js:22708
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:14624
(anonymous) @ core.js:16706
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:16094
(anonymous) @ core.js:16706
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
onInvoke @ core.js:16135
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
(anonymous) @ zone.js:872
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
onInvokeTask @ core.js:16126
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:420
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
drainMicroTaskQueue @ zone.js:595
Promise.then (async)
scheduleMicroTask @ zone.js:578
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:410
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:252
scheduleResolveOrReject @ zone.js:862
ZoneAwarePromise.then @ zone.js:962
push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @ core.js:16639
./src/main.ts @ main.ts:12
webpack_require @ bootstrap:78
0 @ main.ts:13
webpack_require @ bootstrap:78
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
DashboardComponent.html:32 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 43, nodeDef: {…}, elDef: {…}, elView: {…}}
View_DashboardComponent_0 @ DashboardComponent.html:32
proxyClass @ compiler.js:17945
push../node_modules/@angular/core/fesm5/core.js.DebugContext_.logError @ core.js:22708
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:14629
(anonymous) @ core.js:16706
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:16094
(anonymous) @ core.js:16706
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
onInvoke @ core.js:16135
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
(anonymous) @ zone.js:872
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
onInvokeTask @ core.js:16126
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:420
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
drainMicroTaskQueue @ zone.js:595
Promise.then (async)
scheduleMicroTask @ zone.js:578
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:410
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:252
scheduleResolveOrReject @ zone.js:862
ZoneAwarePromise.then @ zone.js:962
push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @ core.js:16639
./src/main.ts @ main.ts:12
webpack_require @ bootstrap:78
0 @ main.ts:13
webpack_require @ bootstrap:78
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.js:1
main.ts:13 Error: Your browser does not support Smart Bluetooth. See http://caniuse.com/#search=Bluetooth for more details.
at new BrowserWebBluetooth (manekinekko-angular-web-bluetooth.js:15)
at browserWebBluetooth (manekinekko-angular-web-bluetooth.js:803)
at callFactory (core.js:19825)
at createProviderInstance (core.js:19783)
at resolveNgModuleDep (core.js:19744)
at NgModuleRef
.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef
.get (core.js:20452)
at resolveDep (core.js:20823)
at callFactory (core.js:20716)
at _createProviderInstance$1 (core.js:20682)
at createProviderInstance (core.js:20557)

app won't launch

after installing packages, and doing npm start, getting this error:
ERROR in node_modules/@manekinekko/angular-web-bluetooth/node_modules/rxjs/observable/FromEventObservable.d.ts(23,22): error TS2415: Class 'FromEventObservable' incorrectly extends base class 'Observable'.
Types of property '_subscribe' are incompatible.
Type '(subscriber: Subscriber) => void' is not assignable to type '(subscriber: Subscriber) => TeardownLogic'.
Types of parameters 'subscriber' and 'subscriber' are incompatible.
Type 'Subscriber' is not assignable to type 'Subscriber'.
Property 'isStopped' is protected but type 'Subscriber' is not a class derived from 'Subscriber'.
node_modules/@manekinekko/angular-web-bluetooth/node_modules/rxjs/observable/PromiseObservable.d.ts(10,22): error TS2415: Class 'PromiseObservable' incorrectly extends base class 'Observable'.
Types of property '_subscribe' are incompatible.
Type '(subscriber: Subscriber) => TeardownLogic' is not assignable to type '(subscriber: Subscriber) => TeardownLogic'.
Types of parameters 'subscriber' and 'subscriber' are incompatible.
Type 'Subscriber' is not assignable to type 'Subscriber'.
Property 'isStopped' is protected but type 'Subscriber' is not a class derived from 'Subscriber'.

please make your dependencies as devDependencies in package.json

please make your dependencies as devDependencies in package.json
lib users may be using newer versions of angular/core-js and it is unnecessary to force them to download them when then run yarn add @manekinekko/angular-web-bluetooth

    "dependencies": {
        "@angular/common": "^2.4.1",
        "@angular/core": "^2.4.1",
        "@angular/compiler": "^2.4.1",
        "@angular/platform-browser": "^2.4.1",
        "core-js": "2.4.1",
        "rxjs": "5.0.2",
        "zone.js": "0.7.4",
        "typescript": "2.0.10"
    },

Fail to build... ng build --prod

I am trying to build my Angular project using the CLI with the production flag, but I'm getting the following error.

ERROR in ..\@manekinekko\angular-web-bluetooth\dist\lib\platform\browser.ts(3,2): Error during template compile of 'BrowserWebBluetooth'
Function calls are not supported in decorators but 'ɵmakeDecorator' was called in 'Injectable'
'Injectable' calls 'ɵmakeDecorator'.

Some info...
Angular Core: 5.2.0
Angular CLI: 1.6.8
Node: 8.9.1
OS: Windows 10 x64

Any assistance would be greatly appreciated.

Reconnection failed but success callback was executed

Hi :)

Describe the bug
When I try to reconnect to previously connected device and this reconnection failed because the device is no longer available ( turned off bluetooth ), success callback is called instead of error.

To Reproduce
Steps to reproduce the behavior:

  1. Connect to device
  2. Turn off the device's bluetooth
  3. Wait for a reconnection try
  4. See that the success callback is executed

Expected behavior
Method connectDevice$() should give an observable that in case of every failure in connecting a device will execute error callback

Code
Invoking Reconnection

private reconnect() {
        console.info('Reconnecting');
        this.tryReconnect(3, 2,
            () => {
                return this.ble.connectDevice$(this.bluetoothDevice);
            },
            (server: BluetoothRemoteGATTServer) => {
                console.info('Reconnection success');
            },
            (error) => {
                console.error(error);
                throw error;
            }
        );
    }

Subscribing to Observable

tryReconnect(retries: number, delay: number, toTry:() => Observable<any>, success: (obj:any) => void, fail: (text: any) => void){
        console.info('Try count: ' + retries);
        toTry().subscribe(
                result => success(result),
                error => {
                    if(retries == 0){
                        return fail(error);
                    }
                    console.info('Retry: ' + retries);
                    setTimeout(() => {
                        this.tryReconnect(--retries, delay,toTry,success,fail);
                    }, delay * 1000);
                }
            )
    }

Here the error callback with console.info('Retry'.... ) newer actually logs that message.
Instead console.info('Reconnection success') is logged.

Performance improvement

Is your feature request related to a problem? Please describe.
We are seeing very slow response times using the library to write to a NUS serial service tx characteristic. For example, using python with the bleak BLE library we are seeing around 7-10ms response times. For the same request using angular-web-bluetooth library we are seeing on average 300 - 400ms response times. Our application requires many requests to load data from our devices so we would love to see similar performance to the python script.

Describe the solution you'd like
An improvement in the amount of time for the write subscription to return. Here is an example of a request we are making:
this.bluetooth.writeValue$(this.feritConnection.rx, slice)
.subscribe(() => { console.log("This on average takes around 300 - 400ms to return");};

Additional context
Cleaner screenshot of code we are using to write to the NUS serial service tx characteristic:

angularBluetoothWriteRequestCode

Definition of the NUS serial service:
nusSerialSerrvice

Streaming of values stops working when the parameter enableTracing is set to false

Describe the bug
Streaming of values stops working when the parameter enableTracing is set to false.

I created one application which reads pedeometer stats from smart band (BLE) and then display on the screen. Further, the values get refreshed when the someone wears the band and move. This functionality has been enabled by calling below function as described in ReadME.md

streamValues() {
    // call this method to get a stream of values emitted by the device
    return this.ble.streamValues$();//.pipe(map((value: DataView) => value.getUint8(0)));
  }

This works absolutely fine when enableTracing parameter is set to true inside the module configuration. However, it stops working when same is set to false.

To Reproduce
NA

Expected behavior
By setting enableTracing to false should not impact any functionality.

Screenshots
NA
Desktop (please complete the following information):
NA

Smartphone (please complete the following information):

  • Device: Moto G4+
  • OS: Android 7
  • Browser Chrome
  • Version 67

Additional context
NA

Support batch mode.

Describe the solution you'd like
We need to support requesting multiple services and characteristics at once.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.