Coder Social home page Coder Social logo

ionic-ble-examples's Introduction

Ionic Bluetooth Low Energy Examples

Demonstrate cordova-plugin-ble-central with Ionic.

These were examples written for an Ionic Bluetooth presentation given at the Ionic Philadelphia Meetup and the Ionic Madison Meetup. The presentation slides are available online.

Projects

  • Scan - Scan for Bluetooth LE devices
  • Connect - Connect to a Bluetooth LE device and show services
  • Light - Control a Bluetooth LE lightbulb
  • Button - Receive notifications from a TI CC2650 SensorTag button
  • Thermometer - Receive temperature notifications from Bluetooth LE thermometer
  • NeoPixel - Control NeoPixel lights with Bluetooth LE

The arduino directory has programs and wiring diagrams for building Bluetooth LE peripherals with the Arduino 101.

ionic-ble-examples's People

Contributors

don 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  avatar  avatar  avatar  avatar  avatar  avatar

ionic-ble-examples's Issues

scan filtered by services seems not to work?

Hi there,

I am developing a simple app to connect to a BLE device. My first approach worked like a charm:

  • Scan all (without any "services" filter) BLE devices and list them.
  • Select one device and show the peripheral data.

The code except would be like this

this.ble.scan([], 5)
    .subscribe(
        device => { devices.push(device); console.log('New device discovered: ' + device); },
        error => { console.log('Error scanning: ' + error); });

Here the problem comes when I add a service filter in order to list only certain devices. This service UUID is "0003cdd0-0000-1000-8000-00805f9b0131" so, as API explains, I was supposed to do the following

var myService = '0003cdd0-0000-1000-8000-00805f9b0131';

this.ble.scan([myService], 5)
    .subscribe(
        device => { devices.push(device); console.log('New device discovered: ' + device); },
        error => { console.log('Error scanning: ' + error); });

It simply does not discover any device, even when I have 2 of them in my desktop.

What am I doing wrong? Any help would be very appreciated.

Notes: I have already checked the communication (read and write) with such service+characteristic in both devices.

scan example won't run on Ionic 5

I can't think of anything more I can do to troubleshoot this. What could I do for this?

`$ ionic cordova run android --device --confirm
√ Creating .\www directory for you - done!

cordova.cmd platform add android --save
Using cordova-fetch for cordova-android@~6.3.0
Adding android project...
Creating Cordova project for the Android platform:
Path: platforms\android
Package: com.example.ble.scan
Name: Scan
Activity: MainActivity
Android target: android-26
Subproject Path: CordovaLib
Android project created with [email protected]
Discovered saved plugin "cordova-plugin-ble-central". Adding it to the project
Installing "cordova-plugin-ble-central" for android
Adding cordova-plugin-ble-central to package.json
Discovered saved plugin "cordova-plugin-console". Adding it to the project
Installing "cordova-plugin-console" for android
Adding cordova-plugin-console to package.json
Discovered saved plugin "cordova-plugin-device". Adding it to the project
Installing "cordova-plugin-device" for android
Adding cordova-plugin-device to package.json
Discovered saved plugin "cordova-plugin-splashscreen". Adding it to the project
Installing "cordova-plugin-splashscreen" for android
Adding cordova-plugin-splashscreen to package.json
Discovered saved plugin "cordova-plugin-statusbar". Adding it to the project
Installing "cordova-plugin-statusbar" for android
Adding cordova-plugin-statusbar to package.json
Discovered saved plugin "cordova-plugin-whitelist". Adding it to the project
Installing "cordova-plugin-whitelist" for android
Adding cordova-plugin-whitelist to package.json
Discovered saved plugin "ionic-plugin-keyboard". Adding it to the project
Installing "ionic-plugin-keyboard" for android
Adding ionic-plugin-keyboard to package.json
Discovered saved plugin "cordova-plugin-ionic-webview". Adding it to the project
Installing "cordova-plugin-ionic-webview" for android
Adding cordova-plugin-ionic-webview to package.json
ionic-app-scripts build --target cordova --platform android
'ionic-app-scripts' is not recognized as an internal or external command,
operable program or batch file.

[INFO] Looks like @ionic/app-scripts isn't installed in this project.

   This package is required for this command to work properly.

--confirm: Install @ionic/app-scripts? Yes

npm.cmd i -D -E @ionic/app-scripts
npm WARN deprecated [email protected]: babili has been renamed to babel-minify. Please update to babel-minify
npm WARN deprecated [email protected]: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated [email protected]: This module has been deprecated and is no longer maintained. Please use @rollup/plugin-json.
npm WARN deprecated [email protected]: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-commonjs.
npm WARN deprecated [email protected]: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-node-resolve.
npm WARN deprecated [email protected]: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm WARN deprecated [email protected]: babili has been renamed to babel-minify. Please update to babel-preset-minify
npm WARN deprecated [email protected]: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN deprecated [email protected]: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated [email protected]: request has been deprecated, see request/request#3142
npm WARN deprecated [email protected]: Please update to the latest object-keys

[email protected] install C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\node-sass
node scripts/install.js

Downloading binary from https://github.com/sass/node-sass/releases/download/v4.5.3/win32-x64-72_binding.node
Cannot download "https://github.com/sass/node-sass/releases/download/v4.5.3/win32-x64-72_binding.node":

HTTP error 404 Not Found

Hint: If github.com is not accessible in your location
try setting a proxy via HTTP_PROXY, e.g.

  export HTTP_PROXY=http://example.com:1234

or configure npm proxy via

  npm config set proxy http://example.com:8080

[email protected] postinstall C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\core-js
node -e "try{require('./postinstall')}catch(e){}"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:

https://opencollective.com/core-js
https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

[email protected] postinstall C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\uglifyjs-webpack-plugin
node lib/post_install.js

[email protected] postinstall C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\node-sass
node scripts/build.js

Building: C:\Program Files\nodejs\node.exe C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
gyp info it worked if it ends with ok
gyp verb cli [
gyp verb cli 'C:\Program Files\nodejs\node.exe',
gyp verb cli 'C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\node-gyp\bin\node-gyp.js',
gyp verb cli 'rebuild',
gyp verb cli '--verbose',
gyp verb cli '--libsass_ext=',
gyp verb cli '--libsass_cflags=',
gyp verb cli '--libsass_ldflags=',
gyp verb cli '--libsass_library='
gyp verb cli ]
gyp info using [email protected]
gyp info using [email protected] | win32 | x64
gyp verb command rebuild []
gyp verb command clean []
gyp verb clean removing "build" directory
gyp verb command configure []
gyp verb check python checking for Python executable "python2" in the PATH
gyp verb which failed Error: not found: python2
gyp verb which failed at getNotFoundError (C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\which\which.js:13:12)
gyp verb which failed at F (C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\which\which.js:68:19)
gyp verb which failed at E (C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\which\which.js:80:29)
gyp verb which failed at C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\which\which.js:89:16
gyp verb which failed at C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\isexe\index.js:42:5
gyp verb which failed at C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\isexe\windows.js:36:5
gyp verb which failed at FSReqCallback.oncomplete (fs.js:167:21)
gyp verb which failed python2 Error: not found: python2
gyp verb which failed at getNotFoundError (C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\which\which.js:13:12)
gyp verb which failed at F (C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\which\which.js:68:19)
gyp verb which failed at E (C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\which\which.js:80:29)
gyp verb which failed at C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\which\which.js:89:16
gyp verb which failed at C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\isexe\index.js:42:5
gyp verb which failed at C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\isexe\windows.js:36:5
gyp verb which failed at FSReqCallback.oncomplete (fs.js:167:21) {
gyp verb which failed code: 'ENOENT'
gyp verb which failed }
gyp verb check python checking for Python executable "python" in the PATH
gyp verb which succeeded python C:\Python38\python.EXE
gyp ERR! configure error
gyp ERR! stack Error: Command failed: C:\Python38\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack File "", line 1
gyp ERR! stack import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack at ChildProcess.exithandler (child_process.js:303:12)
gyp ERR! stack at ChildProcess.emit (events.js:315:20)
gyp ERR! stack at maybeClose (internal/child_process.js:1021:16)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
gyp ERR! System Windows_NT 10.0.18363
gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\node-gyp\bin\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:\cygwin64\home\CBdeV\ionic-ble-examples-master\scan\node_modules\node-sass
gyp ERR! node -v v12.18.1
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
Build failed with error code: 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\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 WARN notsup Unsupported engine for [email protected]: wanted: {"node":"<8.10.0"} (current: {"node":"12.18.1","npm":"6.14.5"})
npm WARN notsup Not compatible with your version of node/npm: [email protected]
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.1.2 (node_modules\watchpack\node_modules\chokidar\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 WARN [email protected] requires a peer of typescript@>=2.0.0 || >=2.0.0-dev || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >= 2.4.0-dev but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of typescript@>=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >=3.0.0-dev || >= 3.1.0-dev || >= 3.2.0-dev but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of typescript@>=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >= 3.0.0-dev || >= 3.1.0-dev but none is installed. You must install peer dependencies yourself.

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\CBdeV\AppData\Roaming\npm-cache_logs\2020-07-06T20_26_41_142Z-debug.log
[ERROR] An error occurred while running subprocess npm.

    npm.cmd i -D -E @ionic/app-scripts exited with exit code 1.

    Re-running this command with the --verbose flag may provide more information.

$
`

How to display Subscribe data in HTML which is continuous change every second in Angular 4

i m working BLE native library in ionic. I m try to display heartbeat on screen. Here,i m able to get heartrate value on console.log() which is continuously change. what i want is to show heartrate value in html page live.

{{ heartrate }}

Where heartrate:number = 0;global variable.

This is my code


this.ble.startNotification("EB:53:D1:0A:A0:78", "180D", "2A37").subscribe((buffer)=>{

  this.getHeartRateNotifications(buffer);

  console.log(buffer);

},(err)=>{
  console.log('aa',JSON.stringify(err))
})
getHeartRateNotifications(buffer){
  console.log(buffer);
  console.log('array : ', String.fromCharCode.apply(null, new Uint8Array(buffer)));
  const value = new DataView(buffer);

  console.log("I am value: ", JSON.stringify(value));

  const flags = value.getUint8(0);

  console.log('FLAGS', flags);


 if(this.session.isEven(flags)){

   this.heartRate = value.getUint8(1);
   console.log('HEART RATE 8 bit: ', this.heartRate);

 }else if(this.session.isOdd(flags)){
   this.heartRate = value.getUint16(2);
   console.log('HEART RATE 16 bit: ', this.heartRate);
 }
}
```

it's not working with ionic viewer application

i compile the source code using ionic dashboard to view in ionic viewer. But scanning is not working and no device listed in the application. Are these examples work with ionic viewer ?

Not triggering subscribe in scan function

@tearforfear007
Thanks for this,

Subscribe is not triggering in scan function. can any body help me on this.
Using Angular 7 and ionic 4
Kindly find the below code

import { Component, NgZone } from '@angular/core';
import { BLE } from '@ionic-native/ble/ngx';
import { Observable } from "rxjs"
// import { NavController } from 'ionic-angular';
// import { ToastController } from 'ionic-angular';

@component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {

devices: any[] = [];
statusMessage: string;

constructor(
// public navCtrl: NavController,
// private toastCtrl: ToastController,
private ble: BLE,
private ngZone: NgZone) {
}

ionViewDidEnter() {
console.log('ionViewDidEnter');
this.scan();
}

onDeviceDiscovered(device) {
console.log('Discovered ' + JSON.stringify(device, null, 2));
this.ngZone.run(() => {
  this.devices.push(device);
});

}

scan() {
this.setStatus('Scanning for Bluetooth LE Devices');
this.devices = []; // clear list

this.ble.scan([], 5).subscribe(
  
  // device => this.onDeviceDiscovered(device), 
  (device) => {
    console.log("inside subscribe")
    this.onDeviceDiscovered(device)}, 
  (error) => {this.scanError(error)}
);

// setTimeout(this.setStatus.bind(this), 5000, 'Scan complete');

}

// If location permission is denied, you'll end up here
scanError(error) {
this.setStatus('Error ' + error);
// let toast = this.toastCtrl.create({
// message: 'Error scanning for Bluetooth low energy devices',
// position: 'middle',
// duration: 5000
// });
// toast.present();
}

setStatus(message) {
console.log(message);
this.ngZone.run(() => {
this.statusMessage = message;
});
}

}

Object(...) is not a function

Hi,

Sorry if my question doesn't make sense I new with angular and ionic
I tried the Scan example and when I launch the ionic serve it returns this error:

PairPage.html:31 ERROR TypeError: Object(...) is not a function
at BLE.scan (index.js:28)
at PairPage.webpackJsonp.73.PairPage.scan (pair.ts:79)
at Object.eval [as handleEvent] (PairPage.html:31)
at handleEvent (core.js:13589)
at callWithDebugContext (core.js:15098)
at Object.debugHandleEvent [as handleEvent] (core.js:14685)
at dispatchEvent (core.js:10004)
at core.js:10629
at HTMLButtonElement. (platform-browser.js:2628)
at t.invokeTask (polyfills.js:3)

Are we taking device and error as function when they are objects?

The only thing that is different is the import:
import { BLE } from '@ionic-native/ble/ngx';

Ionic 3 Native BLE doesn't return anything

Hello,

I tried to use your examples but the BLE functions don't return nothing, not even errors. I am using an Android 7.0 device to test. I didn't forget to turn on location on the device.

This code:

let result = this.ble.enable(); console.log(result)

Returns this:

t = {__zone_symbol__state: null, __zone_symbol__value: Array(0)}; __zone_symbol__state: null; __zone_symbol__value: []; __proto__: Object

I have tested my BLE module using Evothings in the same device and it worked very well.
You can find my main project here and the specific codes related to BLE can be found here. As you can see it is exactly like your example.

I don't know what I am doing wrong and I have tried a lot of things.
Thank you for your attention.

how to read multiple times

Hi,

I want to read a characteritic UUID that change really often.
I can read only the first message. The others are not read.

Any idea ?

couldn't write data after start notification

hi don, recently i had working on a BLE light APP, i found i can't start Notificaiton

this.ble.startNotification(this.peripheral.id, TELINK_SERVICE, TELINK_CHARACTERISTIC_NOTIFY).subscribe(
  buffer => {
     var data = new Uint8Array(buffer);
     console.log('Received Notification:   = ' + data);

    let iv = this.getSecIVS();
    this.copyarray(data, 0, iv, 3, 5);
    let ret = this.mydecryptCmd(this.sessionkey, iv, data);

    this.setStatus('Received Notification:   = ' + ret)
  }, () => this.showAlert('Unexpected Error', 'enable notify failed')
);

Can't connect to my RPI

Hi,

I'm trying ton compile your code with my android phone and a raspberry pi zero. When I start the code, I found my raspberry and the scan page. But when I'm trying to connect to the RPI, the other page appear, but there are no services, the name doesn't appear and the details too.

Can you help me ?

Thank you

Can't read / write anything :

I followed one of your tutorials in order to scan a set of Bluetooth device it works very well but I will currently be able to read the characteristics of these devices and also write. I saw that you made a tutorial about it however I can't manage your tutorial, I can't use properly the functions read, write...
I want to read the data from my sensors without connecting to it because they don't allow the connection.
Can you help me please ?

Print Barcode/QRCode

Hi don... could you please share to us... how to make this code working to print barcode/qrcode thru bluetooth printer thermal esc/pos

Very apreciated and many thanks before
GBU

Event for when a device stops being connected or advertising

I'm using Ionic and I need to update my devices array when a device stops advertising. We have a physical button that turns off after you hold the button down for a period of time.

Basically:

deviceList = [];

scanForDevices(){
      console.log("scan for devices");
      this.ble.startScan([]).subscribe(device => {
        this.zone.run(() => {
            this.deviceList.push(device);
        });
     this.connect(device);
}

Any help would be awesome. Thanks!

Can't write / read with ios

Hello,
I try to write and read the ble using ios but i don't work. I have error writing is not permitted.

So many errors in Ionic 5

Hello, I have just downloaded the code to test it to implement it in my application but there are so many errors.
Anybody could post a link where the code has been corrected for usage in Ionic 5
in home.page.ts and detail.page.ts
some errors are:
cannot find modules...
URL does not point to a valid file..
BLE refers to a value, but is being used as a type here...
Property 'present' does not exist on type

in app.component.ts
cannot resolve all paramenters for MyApp
'StatusBar ' refers to a value, but is being used as a type here
'ion-nav- is a not known element

If you have a link with this example working for Ionic 5 it would be great as this code is obsolete.

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.