Bluetooth Serial Ionic 2 - ionic-framework

I am trying to build a simple bluetooth serial app to connect to my arduino. I am using ionic2 to make android app.right now, all I am trying to do is list all the availabe bluetooth devices. Below is my code :
import { Component } from '#angular/core';
import { BluetoothSerial } from 'ionic-native';
import { NavController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public working:string;
public var2: string ;
bluetoothSerial.isEnabled(
function() {
this.working= "Bluetooth is enabled";
},
function() {
this.working="Bluetooth is *not* enabled";
}
);
public lists = [];
bluetoothSerial.discoverUnpaired(function(devices) {
this.lists.push(devices);
}, function(){ this.var2 = 'could not find any bluetooth device';});
constructor() { }
}
Whenever I do ionic serve I do plenty of error, mainly because Bluetooth is not recognized (function implementation is missing). It also does not allow me to build app either.
Please help on this.
Thank you so much

Looking at the docs
isEnabled()
Platforms: Android iOS Windows Phone
Reports if bluetooth is enabled
Returns: Promise returns a promise
Couple of things. You cannot call your method like that.
You should capitalize your BluetoothSerial
You should put it in a function
import { Component } from '#angular/core';
import { BluetoothSerial } from 'ionic-native';
import { NavController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public working:string;
public var2: string ;
public lists = [];
constructor(){
this.getAlBluetoothDevices();
}
// put BluetoothSerial inside a function, can't be called different
getAllBluetoothDevices(){
// async so keep everything in this method
BluetoothSerial.isEnabled().then((data)=> {
// not sure of returning value, probably a boolean
console.log("dont know what it returns"+data);
// returns all the available devices, not just the unpaired ones
BluetoothSerial.list().then((allDevices) => {
// set the list to returned value
this.lists = allDevices;
if(!this.lists.length > 0){
this.var2 = "could not find any bluetooth devices";
}
});
});
}
}
}

The below code is for scanning the Bluetooth device
startScanning(){
this.isScanning =true;
this.bluetoothSerial.isEnabled().then(()=>{
this.bluetoothSerial.discoverUnpaired().then((allDevices)=>{
this.devices=allDevices;
this.isScanning =false;
});
});
And this code is for connecting to the device
onDeviceReady(){
let device = this.navParams.get('device');
this.bluetoothSerial.connect(device.id).subscribe((data)=>{
let alert = this.alertCtrl.create({
title: 'Bluetooth',
subTitle: data,
buttons: ['ok']
});
alert.present();
},error=>{
let alert = this.alertCtrl.create({
title: 'Bluetooth',
subTitle: error,
buttons: ['ok']
});
alert.present();
});
}
Note: It's working for me

Related

setting global variable in ipcRenderer.on eventhandler running ionic on electron does not work

This is my code in home.ts to receive values from main-process
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
declare var electron : any;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
arguments: any="ping";
constructor(public navCtrl: NavController) {
}
ionViewDidLoad() {
electron.ipcRenderer.send("test_channel","ping");
electron.ipcRenderer.on("test_channel", function (err,arg) {
this.arguments=arg; // receive new value "pong" from main.js
console.log("Message received from electron: "+arg); // works fine
});
console.log("Message received from electron: "+this.arguments); //does not work, still default value
};
}
This is added in my code in main.js, and it works to receive the event from render-process
var ipcMain = require('electron').ipcMain;
mainWindow.webContents.openDevTools();
ipcMain.on("test_channel",function(err,arg){
console.log(err);
console.log("Received message: "+arg);
global.sharedObj = {prop1: arg};
console.log("Sending message back!");
// Send message back!
mainWindow.webContents.send("test_channel",arg+'yeah');
})
This is added in my index.html, to make it run for ionic
<script>
const electron = require('electron');
</script>
First of all don't duplicate the message name. and in the main.js , send the event request to the renderer process using event.sender.send as shown below:-
ipcMain.on('message_name', (event,args) => {
event.sender.send('message_name_2', args)
});

Ionic 2: push notification on click

A notification appears, but upon clicking them, they only open the application again. What I want is upon clicking the notification, it opens a specific item.
In Laravel, I am using the brozot/Laravel-FCM package for Firebase Cloud Messaging (FCM) to send notifications, and on the other end, I'm using Ionic push notifications to receive and display notifications in the notification tray.
If I don't use setClickAction() on Laravel, the Ionic application opens upon clicking the notification, but if I set setClickAction(), then nothing happens. The notification merely disappears.
Laravel-code:
$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
->setSound('default')
->setClickAction('window.doSomething');
$notification = $notificationBuilder->build();
Ionic 2 framework sample:
import { Component, ViewChild } from '#angular/core';
import { Platform, Nav, MenuController, ModalController, Events, AlertController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Push, PushObject, PushOptions } from '#ionic-native/push';
import { Storage } from '#ionic/storage';
import {
SearchPage
} from '../pages/pages';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = SearchPage;
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
private menu: MenuController,
private modalCtrl: ModalController,
private events: Events,
private push: Push,
private alertCtrl: AlertController,
private storage: Storage
) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
this.pushSetup();
}
pushSetup() {
const options: PushOptions = {
android: {
senderID: 'xxxxxxxxxxx',
forceShow: true
},
ios: {
senderID: 'xxxxxxxxxxx',
alert: 'true',
badge: true,
sound: 'true'
},
windows: {},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => {
});
pushObject.on('registration').subscribe((registration: any) => {
alert(registration.id);
});
pushObject.on('error').subscribe(error => alert('Error with Push plugin' + error));
}
}
(<any>window).doSomething = function () {
alert('doSomething called');
}
What am I missing?
There are these steps that need to be done for general One-Signal push notification to be implemented
Create a OneSignal Account
Add a New APP in the One Signal , configure for Android first (you can target for any platform but i'm focussing on Android as of now) .you need to get the Google Server Key and Google Project Id.
You can get the Above keys from the Firebase using this Steps
Now we are done with Configuring the OneSignal Account, now integrate with the ionic using the cordova plugin
In Ionic2 :
OneSignal.startInit(//google Server Key, //Google ProjectId);
OneSignal.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification);
OneSignal.setSubscription(true);
OneSignal.handleNotificationReceived().subscribe(() => {
// handle received here how you wish.
// this.goToReleatedPage(data.Key, data.Value);
});
OneSignal.handleNotificationOpened().subscribe((data: any) => {
//console.log('MyData'+ JSON.stringify(data.additionalData));
this.parseObject(data);
});
OneSignal.endInit();
ParsingObject in Ionic
public parseObject(obj) {
for (var key in obj) {
this.goToReleatedPage(key, obj[key]);
if (obj[key] instanceof Object) {
this.parseObject(obj[key]);
}
}
}
goToReleatedPage Method
public goToReleatedPage(Key, Value) {
//console.log("Pagename"+" " + Key + "ID" +" " + Value);
if (Key === 'xxxx') {
this.navCtrl.push(xxxPage, {
id: Value
});
} else if (Key === 'Foo') {
this.navCtrl.push(foosPage, {
id: Value,
});
} else if (Key === 'bar') {
this.navCtrl.push(barPage, {
id: Value
});
}
}
While sending the Message from OneSignal , you need to specify which page you need to open and you want to pass Id as follows

How to execute something in ionic when app is being run for the first time?

I am trying to run a bunch of commands when my app is executed for the first time. I found a few pieces of code but none of them seem to work for me. Here is what i have right now :
var applaunchCount = this.storage.get('launchCount');
console.log(applaunchCount);
if(applaunchCount){
this.hello="succesive";
}else{
storage.set('launchCount','1');
this.hello="first";
}
I tried it on my android device the value of hello always remains "succesive".
Edit :
The home.ts file which is the first page
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { FormBuilder, Validators } from '#angular/forms';
import {cloths} from '../defaults.component';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
hello : string;
clothes=cloths;
l : string ;
public loginForm = this.fb.group({
new: ["", ]
});
constructor(public navCtrl: NavController, public fb:FormBuilder, public storage:Storage) {
var applaunchCount = this.storage.get('launchCount');
var app : string;
console.log(applaunchCount);
if(applaunchCount){
//This is a second time launch, and count = applaunchCount
this.hello="succesive";
}else{
//Local storage is not set, hence first time launch. set the local storage item
storage.set('launchCount','1');
this.hello="first";
//Do the other stuff related to first time launch
}
}
buttonLogin(){
this.clothes.push(this.loginForm.get('new').value);
}
}
Getting data from the Storage is an async operation, so you have to wait until the data is ready before using it:
constructor(public navCtrl: NavController, public fb:FormBuilder, public storage:Storage) {
let app : string; // <- You can use let instead of var here
this.storage.get('launchCount').then(applaunchCount => { // <- Wait for the data to be ready
// Now the data from the storage is ready!
console.log(applaunchCount);
if(applaunchCount) {
// This is a second time launch, and count = applaunchCount
this.hello = "succesive";
} else {
// Local storage is not set, hence first time launch. set the local storage item
storage.set('launchCount','1');
this.hello = "first";
// Do the other stuff related to first time launch
}
});
}

ionic 2: how to dismiss loader after data is ready?

In my Ionic 2 app, I have i have component that GET to fetch data.
i want to maker loader and dismiss it after data is ready.
i tried to look on other posts around the stack overflow but my issue is different.
i did something but the loader is forever and its not helps me.
It looks like following:
import { Component,ViewChild } from '#angular/core';
import { NavController,LoadingController,AlertController,ViewController} from 'ionic-angular';
import { Facebook } from 'ionic-native';
//import pages
import {LoginPage} from "../../pages/login/login";
import {User} from '../../models/user'
import { Storage} from '#ionic/storage';
//import provider
import { ProfileData } from '../../providers/profile-data';
import { NotesData } from '../../providers/notes-data';
import firebase from 'firebase'
import {AddNote} from "../add-note/add-note";
/*
Generated class for the NotesList page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-notes-list',
templateUrl: 'notes-list.html'
})
export class NotesList {
//facebook user
userProfile: any = null;
uid: any = null;
fireUid:any=null;
name:string=null;
photo: any =null;
user:User=null;
photos:any=null;
currentUser:any=null;
photonew:any=null;
//notes list
notes:any=null;
data:any;
pages: Array<{title: string, component: any}>;
constructor(public navCtrl: NavController,public profileData:ProfileData,private viewCtrl: ViewController,public notesData:NotesData,private loadingCtrl: LoadingController,private alertCtrl: AlertController,public storage:Storage) {
this.data={};
this.data.title="";
this.data.desc="";
}
ionViewDidLoad() {
//if i do that the loader is forever
/*
let loader = this.loadingCtrl.create({
dismissOnPageChange: true,
});
loader.present();
*/
// here i want the loader to be until the data is ready.
this.getNotesList(); //this functions not returns data so i can't do this.getNotesList().then(()=>
}
getNotesList(){
console.log("get event");
var that=this;
this.notesData.getNotesLIst().on('value', snapshot => {
let notesList= [];
snapshot.forEach( snap => {
console.log("id note"+snap.val().id);
notesList.push({
id: snap.val().id,
title: snap.val().title,
desc: snap.val().desc,
color:snap.val().color,
photo:snap.val().photo,
});
});
that.notes = notesList;
});
}
addNote(){
this.navCtrl.push(AddNote);
}
logOutFacebook(){
Facebook.logout().then((response)=>
{
this.navCtrl.push(LoginPage);
alert(JSON.stringify(response));
},(error)=>{
alert(error);
})
}
}
At first, you should show how do you implement your loading page. Is it a splash screen with cordorva? Or just as div displaying some image?
If it is a splash screen, you can add this code in your component after you get data, (it is from starter template, you can see the detail by creating a new project with ionic start):
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
});
And, if you use a div in your index page, it is similar, you can just get that element and remove it, with pure js.
okay it succeed to do that
this is my answer
ionViewDidLoad() {
let loader = this.loadingCtrl.create({});
loader.present();
this.getNotesList().then((x) => {
if (x) loader.dismiss();
});
}
getNotesList(){
return new Promise(resolve => {
var that=this;
this.notesData.getNotesLIst().on('value', snapshot => {
let notesList= [];
snapshot.forEach( snap => {
console.log("id note"+snap.val().id);
notesList.push({
id: snap.val().id,
title: snap.val().title,
desc: snap.val().desc,
color:snap.val().color,
photo:snap.val().photo,
});
});
that.notes = notesList;
resolve(true);
});
})
}

Best way to connect ionic 2 nativ facebook with firebase

at the moment iam implementing a signIn into my ionic 2 app.
I want to use ionic 2 native facebook and somehow save the data to my firebase app.
Is there any way to archive that?
One way is to create a new firebase auth user with the facebook email adress and some password hash, but maybe there is a better solution.
Here is what i got so far (i know, not much) :)
import {NavController, Loading, Platform, Storage, LocalStorage} from "ionic-angular";
import {OnInit, Inject, Component} from "#angular/core";
import {ForgotPasswordPage} from "../forgot-password/forgot-password";
import {SignUpPage} from "../sign-up/sign-up";
import {HomePage} from "../../home/home";
import * as firebase from 'firebase';
import {Facebook} from 'ionic-native';
/*
Generated class for the LoginPage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
templateUrl: 'build/pages/auth/login/login.html',
})
export class LoginPage {
private local: any;
constructor(private navCtrl: NavController, private platform:Platform) {
this.local = new Storage(LocalStorage);
}
openForgotPasswordPage():void {
this.navCtrl.push(ForgotPasswordPage);
}
openSignUpPage():void {
this.navCtrl.push(SignUpPage);
}
login() {
firebase.auth().signInWithEmailAndPassword("test#test.com", "correcthorsebatterystaple").then(function (result) {
console.log("AUTH OK "+ result);
}, function (error) {
console.log("dawdaw");
});
}
facebookLogin() {
Facebook.login(['public_profile', 'user_birthday']).then(() => {
this.local.set('logged', true);
this.navCtrl.setRoot(HomePage);
}, (...args) => {
console.log(args);
})
} }
facebookLogin() {
Facebook.login(['public_profile', 'user_birthday']).then((result) => {
var creds = firebase.auth.FacebookAuthProvider.credential(result.access_token);
return firebase.auth().signInWithCredential(creds);
})
.then((_user) => {
console.log("_user:", _user);
})
.catch((_error) => {
console.error("Error:", _error);
});
}
see more info here - https://firebase.google.com/docs/auth/web/facebook-login#advanced-handle-the-sign-in-flow-manually
I have not tried this, so might not be 100% working, but try this Gist I found: https://gist.github.com/katowulf/de9ef6b04552091864fb807092764224