So I am trying to test out bluetooth connectivity with some code. Whenever I try to scan for bluetooth devices I do not get a pop-up to allow for it so it keeps waiting for it. I know the code works because we are working in group and it works on the MacOS computer my partner has but it is not working on my windows. I mainly want it to scan for an ESP with BLE. I already enabled the 'Experimental Web Platform features' and the 'Use the new permissions backend for Web Bluetooth' flags and made sure my Chrome is updated and made sure the permissions for bluetooth scanning and devices are enabled.
console.log("Init");
document.getElementById("scan").onclick = scan;
navigator.bluetooth.addEventListener("advertisementreceived", (event) => {
console.log("Advertisement", event);
});
async function scanDevices() {
const devices = await navigator.bluetooth.getDevices();
console.log(devices);
}
async function scan() {
console.log("Scanning...");
let options = {
acceptAllAdvertisements: true,
};
try {
log("Requesting Bluetooth Scan with options: " + JSON.stringify(options));
const scan = await navigator.bluetooth.requestLEScan(options);
log("Scan started with:");
log(" acceptAllAdvertisements: " + scan.acceptAllAdvertisements);
log(" active: " + scan.active);
log(" keepRepeatedDevices: " + scan.keepRepeatedDevices);
log(" filters: " + JSON.stringify(scan.filters));
navigator.bluetooth.addEventListener("advertisementreceived", (event) => {
log("Advertisement received.");
log(" Device Name: " + event.device.name);
log(" Device ID: " + event.device.id);
log(" RSSI: " + event.rssi);
log(" TX Power: " + event.txPower);
log(" UUIDs: " + event.uuids);
event.manufacturerData.forEach((valueDataView, key) => {
logDataView("Manufacturer", key, valueDataView);
});
event.serviceData.forEach((valueDataView, key) => {
logDataView("Service", key, valueDataView);
});
});
setTimeout(stopScan, 10000);
function stopScan() {
console.log("Scan result", scan);
log("Stopping scan...");
scan.stop();
log("Stopped. scan.active = " + scan.active);
}
} catch (error) {
log("Argh! " + error);
}
}
function log(c) {
console.log(c);
}
Use requestDevice to pop up chooser UI.
const device = await navigator.bluetooth.requestDevice(options)
Related
this is my scenario: I have a barcodeScanner ionic plugin in my Ionic application, that is installed on a tablet where I cannot use hardware buttons.
My code:
this.barcodeScanner.scan(option).then((result) => {
console.dir(
"We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled
);
this.product_code = result.text;
if(result.text !== "" && result.text !== null)
{
return this.searchByBarcode(result.text);
}
}, (err) => {
// An error occurred
});
Question
Is there a way to close the plugin after a certain amount of time if no barcode is scanned (or to insert a software button inside the plugin)?
How can I get the MAC address a from Samsung Smart TV in JavaScript?
I tried the code below but nothing happens:
function getMAC() {
var mac = null;
try {
mac = webapis.network.getMac();
} catch (e) {
addResult("getMAC exception [" + e.code + "] name: " + e.name
+ " message: " + e.message);
}
if (null != mac) {
addResult("[getMAC] mac: " + mac);
}
}
Check you TV is running on Tizen.
Check config.xml has <tizen:privilege name="http://developer.samsung.com/privilege/network.public"/>
And... I think you already make the addResult function but just make it if you don't.
I am working on ionic project where i have to implement push notification
but practically what to do i have no idea
again my app is going to be used in corporate environment
so what to do .
Kindly suggest.
Hello Rigel,
Then first of all you have to install FOUR Plugins for that.
1)cordova plugin add https://github.com/phonegap-build/PushPlugin
// For notification
2)cordova plugin add cordova-plugin-device
// For on Device Ready to call
3)cordova plugin add cordova-plugin-dialogs
// For notification Dialog
4)cordova plugin add cordova-plugin-media
// For Notification Sound
and generate API key and SenderId throw developer console.and senderid past in bellow code. And e.regid pass to on server.
<script type="text/javascript" src="PushNotification.js"></script>
<script type="text/javascript">
var pushNotification;
function onDeviceReady() {
$("#app-status-ul").append('<li>deviceready event received</li>');
document.addEventListener("backbutton", function(e)
{
$("#app-status-ul").append('<li>backbutton event received</li>');
if( $("#home").length > 0)
{
// call this to get a new token each time. don't call it to reuse existing token.
//pushNotification.unregister(successHandler, errorHandler);
e.preventDefault();
navigator.app.exitApp();
}
else
{
navigator.app.backHistory();
}
}, false);
try
{
pushNotification = window.plugins.pushNotification;
$("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
if (device.platform == 'android' || device.platform == 'Android' ||
device.platform == 'amazon-fireos' ) {
pushNotification.register(successHandler, errorHandler, {"senderID":"661780372179","ecb":"onNotification"}); // required!
} else {
pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); // required!
}
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
alert(txt);
}
}
// handle APNS notifications for iOS
function onNotificationAPN(e) {
if (e.alert) {
$("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>');
// showing an alert also requires the org.apache.cordova.dialogs plugin
navigator.notification.alert(e.alert);
}
if (e.sound) {
// playing a sound also requires the org.apache.cordova.media plugin
var snd = new Media(e.sound);
snd.play();
}
if (e.badge) {
pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
}
}
// handle GCM notifications for Android
function onNotification(e) {
$("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
$("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
console.log("regID = " + e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if (e.foreground)
{
$("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');
// on Android soundname is outside the payload.
// On Amazon FireOS all custom attributes are contained within payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
// playing a sound also requires the org.apache.cordova.media plugin
var my_media = new Media("/android_asset/www/"+ soundfile);
my_media.play();
}
else
{ // otherwise we were launched because the user touched a notification in the notification tray.
if (e.coldstart)
$("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
else
$("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
}
$("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
//android only
$("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
//amazon-fireos only
$("#app-status-ul").append('<li>MESSAGE -> TIMESTAMP: ' + e.payload.timeStamp + '</li>');
break;
case 'error':
$("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
break;
default:
$("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
break;
}
}
function tokenHandler (result) {
$("#app-status-ul").append('<li>token: '+ result +'</li>');
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send it the token for later use.
}
function successHandler (result) {
$("#app-status-ul").append('<li>success:'+ result +'</li>');
}
function errorHandler (error) {
$("#app-status-ul").append('<li>error:'+ error +'</li>');
}
document.addEventListener('deviceready', onDeviceReady, true);
</script>
<div id="home">
<div id="app-status-div">
<ul id="app-status-ul">
<li>Cordova PushNotification Plugin Demo</li>
</ul>
</div>
</div>
How to POST your registered token(e.regid) on server are bellow.
and important note your e.regid it's know as GCM ID.
if ( e.regid.length > 0 )
{
var userId = localStorage.getItem('userId');
$.ajax({
type: "POST",
url: '' + globURL + 'addgcm.php?user_id='+userId+'&gcm_id='+e.regid+'',
cache: false,
success: function(result){
}
});
// alert(regid);
$("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
console.log("regID = " + e.regid);
}
I am trying to include the barcode scanner plugin for phonegap (phonegap 5.1.1) and I can't make it work (https://github.com/phonegap/phonegap-plugin-barcodescanner)
First of all, I installed the plugin running:
phonegap plugin add phonegap-plugin-barcodescanner
Then I have a javascript function:
function leerBarCode(){
//navigator.notification.alert("LLega a leerBarCode", alertDismissed, "Mensaje", "OK");
cordova.plugins.barcodeScanner.scan(function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
}, function (error) {
alert("Scanning failed: " + error);
});
}
When I click over a button that calls to this function, it doesn't launch the camera. Please, can you help me?
I am trying to execute some Javascript code on deviceready by using a listener.
It doesn't seem to be calling the code - I'm getting nothing in my console, and none of the variables are set.
This is the code example I'm using:
<script>
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: "my.db"});
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
}
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
</script>
Now, I'm not primarily a Javascript developer (so this question may be simple), but is there some reason why the code is not executing? Do I have to run it in an anonymous function?
How do I get the onDeviceReady() function to execute?
deviceready is a special Cordova event; unless you launch your code in a Cordova environment, the event will never get fired (and your code will never get executed).
You can run Cordova in the browser by adding the browser as a platform. For more info, see http://www.raymondcamden.com/2014/09/24/Browser-as-a-platform-for-your-PhoneGapCordova-apps.
You could also use something like Ripple to emulate the Cordova environment in Chrome.
Since Cordova-SQLitePlugin API is asynchronous, you should execute transaction after the db is available/created. Try to implement it in a similar way as below:
var openDb = function (name, ok, error) {
try {
// SQLitePlugin always uses callbacks to specify the status of 'open' operation
var dbRef = window.sqlitePlugin.openDatabase({name: name},
function (db) {
log("DataBase " + name + " opened!");
ok(db);
}, function (e) {
try {
dbRef.close();
} catch (e) {
log("Could not close database", e);
}
error(e);
});
} catch (e) {
log("Could not open " + name + " DataBase");
error(e);
}
};
openDb("my.db", function(db){
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
});