Ionic Native BLE plugin not writing - ionic-framework

I have a bluetooth printer, this model: SEWOO LK-P400
I'm trying to develop inside my Ionic application this plugin: Ionic Native - BLE
How is the right way to develop that? seeams to have a SDK, how to start? I never develop with a custom SDK, I tryed to use the plugin, the connect and disconnect function it's ok, but the write function don't return any erros, the display of the printer turns ON but don't print anything.
the button print function:
async printTest() {
try {
let value = this.stringToBytes('Hello World');
await this.bluetoothProvider.print(this.deviceId.toUpperCase(), this.serviceUUID, this.characteristicUUID, value)
.then(response => {
console.log(retorno);
})
} catch (error) {
console.log(error);
}
}
stringToBytes(string) {
var array = new Uint8Array(string.length);
for (var i = 0, l = string.length; i < l; i++) {
array[i] = string.charCodeAt(i);
}
return array.buffer;
}
the provider function:
print(
deviceId: string,
serviceUUID: string,
characteristicUUID: string,
value: ArrayBuffer): any
{
return this.ble.write(deviceId, serviceUUID, characteristicUUID, value);
}

Related

Skype web sdk audio service plugin not found

I am integrating Skype Web SDK audio service in my IONIC application. Everything works fine but I am not able to make a call. When I click on button to make a call following code gets call and I am getting Beep sound and then error about Pluginnotinstalled.
var conversation = application.conversationsManager.getConversation('tel:+XXXX');
conversation.selfParticipant.audio.state.when('Connected', function () {
console.log('Connected to audio call');
});
conversation.state.changed(function (newValue, reason, oldValue) {
console.log('Conversation state changed from', oldValue, 'to', newValue);
});
conversation.participants.added(function (participant) {
console.log('Participant:', participant.displayName(), 'has been added to the conversation');
});
conversation.audioService.start().then(function() {
console.log('The call has been started successfully');
}, function (error) {
console.log('An error occured starting the call', error);
});
When I run this code, I am getting error, Plugin not Installed. There's no description about what plugin they want.
An error occured starting the call
Error: PluginNotInstalled
Exception — skype-web-sdk.js:20782
(anonymous function) — skype-web-sdk.js:35814
exec2 — skype-web-sdk.js:21498
exec — skype-web-sdk.js:21478
dequeue — skype-web-sdk.js:21253
process — skype-web-sdk.js:21274
When I checked in details, The error is coming from below code of skype-web-sdk.js
function init(specs) {
tm && tm.record(Web.TelemetryEvent.PluginManager, {
action: 'init',
state: state()
});
if (state() == Media.PluginManager.State.Uninitialized) {
var id = '__mainPluginManager_' + guid().replace(/-/g, '_');
Media.log('PluginManager::init - id = ' + id);
language = (specs && specs.language) || "en-us";
isRtl = (specs && specs.rtl) || false;
var PluginObjectCtor_1 = (specs && specs.PluginObject) || Media.PluginObject;
tm = specs && specs.tm;
assert(!task || task.state() != 'pending');
task = new Task('Loading the media plugin.', {
cancel: function (reason) {
Media.log('PluginManager::init canceled ' + id);
stopLoadTimer();
reset(reason);
task.reject(reason);
}
});
tm && tm.monitor(task.promise, Web.TelemetryEvent.PluginManager, {
action: 'initPluginMgr',
state: state(),
id: id
});
state.set(Media.PluginManager.State.Initializing);
isPluginInstalled.get().then(function (installed) {
if (!installed)
throw Exception('PluginNotInstalled');
pluginObj = PluginObjectCtor_1({
id: id,
managerId: '_'
});
pluginObj.event(onPluginObjectEvent, 'async');
pluginObj.state.changed(onPluginObjectState);
Media.watch('pluginObject(' + id + ')::state', state);
Media.log('PluginManager::init - creating inner object');
try {
pluginObj.createInnerObject({
hide: true,
hookEvents: true
});
}
catch (err) {
state.set(Media.PluginManager.State.Uninitialized);
if (task.state() == 'pending')
task.reject(err);
}
}).catch(function (err) {
state.set(Media.PluginManager.State.Uninitialized);
if (task.state() == 'pending')
task.reject(err);
});
}
else {
// init has already been called and the plugin is either
// initializing or is already initialized; in either case
// we will return an existing promise
assert(task);
}
return task.promise;
}
Which browser are you using?
IE11 and Safari both need the Skype for Business Web App plugin which can ben found here: Getting started with Skype Web SDK development
Here you can find more information on how to check if the plugin is installed.

WebRTC with PeerJS remote video not showing on Android

I'm using Ionic3 to build an android videochat application.
The videochat works perfectly between two tabs on my browser, but only shows the local video on my android device (the remote video being blank).
I'm using PeerJS for the peer-to-peer connection in my index.html:
I'm using the stunServer {url: "stun:stun.l.google.com:19302"} for the connection.
I'm using the functions shown on the home page: http://peerjs.com/
My config service:
import {Injectable} from '#angular/core';
#Injectable()
export class WebRTCConfig {
peerServerPort: number = 9000;
key:string = '<my peer id>';
stun: string = 'stun.l.google.com:19302';
stunServer = {
url: 'stun:' + this.stun
};
getPeerJSOption() {
return {
// Set API key for cloud server (you don't need this if you're running your own.
key: this.key,
// Set highest debug level (log everything!).
debug: 3,
// Set it to false because of:
// > PeerJS: ERROR Error: The cloud server currently does not support HTTPS.
// > Please run your own PeerServer to use HTTPS.
secure: false,
config: {
iceServers: [
this.stunServer/*,
this.turnServer*/
]
}
};
}
/**********************/
audio: boolean = true;
video: boolean = false;
getMediaStreamConstraints(): MediaStreamConstraints {
return <MediaStreamConstraints> {
audio: this.audio,
video: this.video
}
}
}
Snippet of my Peer WebRTC service:
createPeer(userId: string = '') {
// Create the Peer object where we create and receive connections.
this._peer = new Peer(/*userId,*/ this.config.getPeerJSOption());
setTimeout(()=> {
console.log(this._peer.id);
this.myid = this._peer.id;
}, 3000)
}
myCallId() {
return this.myid;
}
answer(call) {
call.answer(this._localStream);
this._step2(call);
}
init(myEl: HTMLMediaElement, otherEl: HTMLMediaElement, onCalling: Function) {
this.myEl = myEl;
this.otherEl = otherEl;
this.onCalling = onCalling;
// Receiving a call
this._peer.on('call', (call) => {
// Answer the call automatically (instead of prompting user) for demo purposes
this.answer(call);
});
this._peer.on('error', (err) => {
console.log(err.message);
// Return to step 2 if error occurs
if (this.onCalling) {
this.onCalling();
}
// this._step2();
});
this._step1();
}
call(otherUserId: string) {
// Initiate a call!
var call = this._peer.call(otherUserId, this._localStream);
this._step2(call);
}
endCall() {
this._existingCall.close();
// this._step2();
if (this.onCalling) {
this.onCalling();
}
}
private _step1() {
// Get audio/video stream
navigator.getUserMedia({ audio: true, video: true }, (stream) => {
// Set your video displays
this.myEl.src = URL.createObjectURL(stream);
this._localStream = stream;
// this._step2();
if (this.onCalling) {
this.onCalling();
}
}, (error) => {
console.log(error);
});
}
private _step2(call) {
// Hang up on an existing call if present
if (this._existingCall) {
this._existingCall.close();
}
// Wait for stream on the call, then set peer video display
call.on('stream', (stream) => {
this.otherEl.src = URL.createObjectURL(stream);
});
// UI stuff
this._existingCall = call;
// $('#their-id').text(call.peer);
call.on('close', () => {
// this._step2();
if (this.onCalling) {
this.onCalling();
}
});
}
In my chat.ts, I use this to call the function from the peer webrtc service:
call() {
this.webRTCService.call(this.calleeId);
}
It's likely to be a permission problem. You need to grant it permission to use the camera.
Camera Permission - Your application must request permission to use a
device camera.
<uses-permission android:name="android.permission.CAMERA" />
See
https://developer.android.com/guide/topics/media/camera.html

ionic push notification when app is in foreground

I am making a ionic 3 app. I want notifications to appear even when app is in foreground. I have tried using FCM Plugin I'm getting notifications only when app is in background.
Home.ts
import { AngularFireDatabase } from 'angularfire2/database';
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import firebase from 'firebase';
declare var FCMPlugin;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
firestore = firebase.database().ref('/pushtokens');
firemsg = firebase.database().ref('/messages');
constructor(public navCtrl: NavController,public afd:AngularFireDatabase) {
this.tokensetup().then((token)=>{
this.storeToken(token);
})
}
ionViewDidLoad() {
FCMPlugin.onNotification(function (data) {
if (data.wasTapped) {
//Notification was received on device tray and tapped by the user.
alert(JSON.stringify(data));
} else {
//Notification was received in foreground. Maybe the user needs to be notified.
alert(JSON.stringify(data));
}
});
FCMPlugin.onTokenRefresh(function (token) {
alert(token);
});
}
tokensetup(){
var promise = new Promise((resolve,reject)=>{
FCMPlugin.getToken(function(token){
resolve(token);
},(err)=>{
reject(err);
});
})
return promise;
}
storeToken(token){
this.afd.list(this.firestore).push({
uid: firebase.auth().currentUser.uid,
devtoken: token
}).then(()=>{
alert('Token stored')
}).catch(()=>{
alert('Token not stored');
})
// this.afd.list(this.firemsg).push({
// sendername:'adirzoari',
// message: 'hello for checking'
// }).then(()=>{
// alert('Message stored');
// }).catch(()=>{
// alert('message not stored');
// })
}
}
the function cloud for notifications
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var wrotedata;
exports.Pushtrigger = functions.database.ref('/messages/{messageId}').onWrite((event) => {
wrotedata = event.data.val();
admin.database().ref('/pushtokens').orderByChild('uid').once('value').then((alltokens) => {
var rawtokens = alltokens.val();
var tokens = [];
processtokens(rawtokens).then((processedtokens) => {
for (var token of processedtokens) {
tokens.push(token.devtoken);
}
var payload = {
"notification":{
"title":"From" + wrotedata.sendername,
"body":"Msg" + wrotedata.message,
"sound":"default",
},
"data":{
"sendername":wrotedata.sendername,
"message":wrotedata.message
}
}
return admin.messaging().sendToDevice(tokens, payload).then((response) => {
console.log('Pushed notifications');
}).catch((err) => {
console.log(err);
})
})
})
})
function processtokens(rawtokens) {
var promise = new Promise((resolve, reject) => {
var processedtokens = []
for (var token in rawtokens) {
processedtokens.push(rawtokens[token]);
}
resolve(processedtokens);
})
return promise;
}
it works only when the app in the background. but when i exit from the app and it's not in the background I don't get any notification.
You need to edit the FCM Plugin files. I found the solution only for android now.
I use https://github.com/fechanique/cordova-plugin-fcm this FCM plugin for android and ios in cordova.
You need to edit file MyFirebaseMessagingService.java line 53(line no be may be differ).
In this file there is a method onMessageReceived at the end of the method there is a line which is commented, this line calling an another method i.e. sendNotification(....).
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), data);
You have to uncomment this line and change last parameter from remoteMessage.getData() to data (data variable is already there in the code).
And comment this line FCMPlugin.sendPushPayload( data );
Now you are good to go. Now you are able to receive notification even when app is opened (foreground), you will receive the banner (floating) notifications.
If you found anything for IOS please let me know!!!
I am using firebase plugin for ionic 3.
There is a check if notification data contain "notification_foreground" or not and save it in variable foregroundNotification.
if(data.containsKey("notification_foreground")){
foregroundNotification = true;
}
then it create showNotification variable which decide if we need to show notification or not and pass this to the sendMessage (show notification function).
if (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title) || (data != null && !data.isEmpty())) {
boolean showNotification = (FirebasePlugin.inBackground() || !FirebasePlugin.hasNotificationsCallback() || foregroundNotification) && (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title));
sendMessage(data, messageType, id, title, body, showNotification, sound, vibrate, light, color, icon, channelId, priority, visibility);
}
your payload should contain notification_foreground, notification_title and notification_body.

Ionic App 2 Launch Calculator

I am working on IonicApp 2 and I have a screen in which, when the user clicks the filed we wanted to show the calculator so that the user can perform the calculation.
Is there a way we could do it?
Regards,
Raaj
Install plugins
ionic plugin add cordova-plugin-inappbrowser
ionic plugin add cordova-plugin-appavailability
ionic plugin add cordova-plugin-device
thank import them
import { InAppBrowser, AppAvailability, Device } from 'ionic-native';
now try this
launchExternalApp(iosSchemaName: string, androidPackageName: string, appUrl: string, httpUrl: string, username: string) {
let app: string;
if (Device.device.platform === 'iOS') {
app = iosSchemaName;
} else if (Device.device.platform === 'Android') {
app = androidPackageName;
} else {
let browser = new InAppBrowser(httpUrl + username, '_system');
return;
}
AppAvailability.check(app).then(
(success) => { // success callback
let browser = new InAppBrowser(appUrl + username, '_system');
},
(error) => { // error callback
let browser = new InAppBrowser(httpUrl + username, '_system');
}
);
}
openInstagram(username: string) {
this.launchExternalApp('instagram://', 'com.instagram.android', 'instagram://user?username=', 'https://www.instagram.com/', username);
}
openTwitter(username: string) {
this.launchExternalApp('twitter://', 'com.twitter.android', 'twitter://user?screen_name=', 'https://twitter.com/', username);
}
openFacebook(username: string) {
this.launchExternalApp('fb://', 'com.facebook.katana', 'fb://profile/', 'https://www.facebook.com/', username);
}

Video.js player add chromecast button?

I have tried numerous ways of adding a cast button to video.js player but cannot do this for the life of me. Can anyone help?
I'm using the hellovideo cms for videos and need plugins added but have no idea about jquery etc.. so please if anyone can help?
There is a really nice plugin for this: https://github.com/kim-company/videojs-chromecast
Just follow the setup instructions (adding the js and css to your page).
I tried kim-company/videojs-chromecast. It only works with an older version of videojs, I used 5.4.6. It's quite buggy. Another I tried was benjipott/video.js-chromecast, which claims to work with newer videojs, but I didn't like it at all. So I gave up on videojs, I always found the native HTML5 video player more reliable and easier to work with (videojs just wraps this anyway). For the chromecast stuff, I provide a nearby button that links to chromecast.link, where I wrote a full web chromecast sender app. Pass the video and poster URL in the fragment, per this example:
https://chromecast.link/#content=http://host/some.mp4,poster=http://host/poster.jpg,subtitles=http://host/webvtt.srt
I recently answered this question, you can check it out here: How to implement chromecast support for html5 player for more information
var session = null;
$( document ).ready(function(){
var loadCastInterval = setInterval(function(){
if (chrome.cast.isAvailable) {
console.log('Cast has loaded.');
clearInterval(loadCastInterval);
initializeCastApi();
} else {
console.log('Unavailable');
}
}, 1000);
});
function initializeCastApi() {
var applicationID = chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID;
var sessionRequest = new chrome.cast.SessionRequest(applicationID);
var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
sessionListener,
receiverListener);
chrome.cast.initialize(apiConfig, onInitSuccess, onInitError);
};
function sessionListener(e) {
session = e;
console.log('New session');
if (session.media.length != 0) {
console.log('Found ' + session.media.length + ' sessions.');
}
}
function receiverListener(e) {
if( e === 'available' ) {
console.log("Chromecast was found on the network.");
}
else {
console.log("There are no Chromecasts available.");
}
}
function onInitSuccess() {
console.log("Initialization succeeded");
}
function onInitError() {
console.log("Initialization failed");
}
$('#castme').click(function(){
launchApp();
});
function launchApp() {
console.log("Launching the Chromecast App...");
chrome.cast.requestSession(onRequestSessionSuccess, onLaunchError);
}
function onRequestSessionSuccess(e) {
console.log("Successfully created session: " + e.sessionId);
session = e;
}
function onLaunchError() {
console.log("Error connecting to the Chromecast.");
}
function onRequestSessionSuccess(e) {
console.log("Successfully created session: " + e.sessionId);
session = e;
loadMedia();
}
function loadMedia() {
if (!session) {
console.log("No session.");
return;
}
var videoSrc = document.getElementById("myVideo").src;
var mediaInfo = new chrome.cast.media.MediaInfo(videoSrc);
mediaInfo.contentType = 'video/mp4';
var request = new chrome.cast.media.LoadRequest(mediaInfo);
request.autoplay = true;
session.loadMedia(request, onLoadSuccess, onLoadError);
}
function onLoadSuccess() {
console.log('Successfully loaded video.');
}
function onLoadError() {
console.log('Failed to load video.');
}
$('#stop').click(function(){
stopApp();
});
function stopApp() {
session.stop(onStopAppSuccess, onStopAppError);
}
function onStopAppSuccess() {
console.log('Successfully stopped app.');
}
function onStopAppError() {
console.log('Error stopping app.');
}