PWA Web Bluetooth API from page to another - progressive-web-apps

I'm building a PWA using Web Bluetooth API. Connection is OK, I set an eventlistener for getting data and when my Arduino with BLE module HM10 send data, I get them.
But my PWA has more than one page. So on first one I have a "Connection" button, and after connection I "listen".
When I go to a second page, I use navigator.bluetooth.getDevices() to get previsouly connected device.
But I get an empty list.
I though my getDevices() function was bugged but I discoverd a strange thing:
my PWA run a browser tab on Chrome. I connect to the device. Then, on another tab I open this url with a Google example (https://googlechrome.github.io/samples/web-bluetooth/get-devices.html) and call Get Bluetooth Devices to get list of connected device, I see my device in this example page.
Without closing this second tab, I use my PWA: all page are able to get the device (using navigator.bluetooth.getDevices()), set the even and get data from the Arduino. Great!
If I close this tab, connection is lost...
So I think my "connection" is not perfect and when I close my PWA first page, I loose it... But as example avaible on internet are about "one page", I'm a bit lost (like the device connection in fact...).
Here is the code I use:
function reconnect_ble()
{
console.log('Search previously connected devices...');
navigator.bluetooth.getDevices()
.then(devices => {
console.log('> Got ' + devices.length + ' Bluetooth devices.');
if (devices.length == 0)
{
alert("No module");
return false;
}
var flag_module = false;
for (const device of devices)
{
var nom = device.name;
// Check if it's our modle
if (nom == pwa_hm10)
{
flag_module = connectToBluetoothDevice(device);
}
}
if (flag_module == false)
{
alert("Nothing for us");
return false;
}
else
{
return true;
}
})
.catch(error => {
console.log('Erreur:' + error);
});
}
//===================================================================================
// First Connection
function connect_ble()
{
return (deviceCache ? Promise.resolve(deviceCache) :
requestBluetoothDevice()).
then(device => connectToBluetoothDevice(device)).
catch(error => display_info(error));
}
//-------------------------------------------------------------------------------------
function connectToBluetoothDevice(device)
{
const abortController = new AbortController();
// Evenement sur ce device
device.addEventListener('advertisementreceived', (event) =>
{
console.log('connectToBluetoothDevice- Advertisements from "' + device.name + '"...');
// Stop watching advertisements to conserve battery life.
abortController.abort();
// Connexion au serveur GATT
device.gatt.connect()
.then(() =>
{
console.log('connectToBluetoothDevice - Server GATT from "' + device.name + '"...');
// Set our event
connectDeviceAndCacheCharacteristic(device).
then(characteristic => startNotifications(characteristic)).
catch(error => display_info(error));
})
.catch(error =>
{
// Erreur pas de connexion
console.log(error);
});
}, { once: true });
console.log('connectToBluetoothDevice - Watching advertisements from "' + device.name + '"...');
device.watchAdvertisements({ signal: abortController.signal })
.catch(error =>
{
console.log(error);
});
}
//----------------------------------------------------------------------------------
// Form to choose device
function requestBluetoothDevice()
{
return navigator.bluetooth.requestDevice(
{
acceptAllDevices: true,
optionalServices: [0xFFE0]
}).
then(device => {
display_info('Selected: ' + device.name);
deviceCache = device;
deviceCache.addEventListener('gattserverdisconnected',handleDisconnection);
return deviceCache;
});
}
//-----------------------------------------------------------------------------------
function connectDeviceAndCacheCharacteristic(device)
{
if (device.gatt.connected && characteristicCache)
{
return Promise.resolve(characteristicCache);
}
return device.gatt.connect().
then(server => {
return server.getPrimaryService(0xFFE0);
}).
then(service => {
return service.getCharacteristic(0xFFE1);
}).
then(characteristic => {
display_info('characteristic founded');
characteristicCache = characteristic;
return characteristicCache;
});
}
//------------------------------------------------------------------------------------
function startNotifications(characteristic)
{
return characteristic.startNotifications().
then(() => {
characteristic.addEventListener('characteristicvaluechanged',handleCharacteristicValueChanged);
});
}
//--------------------------------------------------------------------------------------
function handleCharacteristicValueChanged(event)
{
// Decoding received data
var decodage = new TextDecoder().decode(event.target.value);
traitement_data_ble(decodage);
}
Edit
If you connect to the bluetooth on Page 1, and go to Page 2 on same tab, connection is lost.
If you connect to the bluetooth on Page 1, set an event listenner to get data then open Page 2 on another tab, Page 2 will "see" the bluetooth module, but even if Page 2 set an event listener, this is even from Page 1 that will receive the data.
If you connect to the bluetooth on Page 1, don't set event listenner, open Page 2 in other tab and set event listenner on Page 2, Page 2 will receive the data.
So case 3 seems to be the only way. Maybe using iFrame for the connection page??

Accessing the same device from multiple pages is not supported and the fact that it seems to partially work is more of a bug than a feature. A device can't effectively distinguish between multiple pages on the same host trying to communicate with it so you need to have a single piece of code which manages the connection to the device.
The correct way to do this today is to create a single-page application so that the connection held by that page can remain own even if the user navigates to different "pages" of your application. If you need to create separate windows these can communicate with the device by sending commands back through the single page that owns the connection using postMessage or Broadcast Channel.
The ideal solution, which is not currently supported, is to use a Shared Worker for this. Shared Workers are a type of web worker which is owned by all the currently open pages of your app at once. It can thus hold shared state (such as the Bluetooth connection) in behalf of your application and won't exit unless every window of your app is closed.

Related

PWA - Cache won't update for offline use

I have a PWA which works fine both online and offline (but only with the initial files). However, the offline cache (let’s say a javascript file) is not being refreshed so whenever I am offline the old javascript file is used, but when online the new version is used.
On an iPad I can use Safari to go to the website and add the PWA to the home page.
If I then go offline, it works fine – all pages work etc.
But if I make a change to say a javascript file (something like adding an alert) and also change the version in my service worker, when I am online the change is reflected but when offline it remains at the older version
To clarify let’s say from the start, on going into a page it alerts “A1”
I then change the javascript to alert “A2” and change the version in the service worker.
If I run the app when online, sure enough the app says New Update Available and All Good (some alerts from the main.js file)
Then when I go into the actual page o the alert says “A2” – so all good.
Then go offline.
The alert still says “A1”
It seems that when online it uses the server latest files but when it tries to use cache the files are old and at the moment seem to be the original files.
I have read many sites on this with no success – some suggest it will sort itself in 24 hours. Some suggest setting the maxage of the service worker to 0 (but how do you do this?). Some say the files need renaming each time they change which seems very clunky.
The service worker is definitely working
main.js
$(document).ready(function () {
'use strict';
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register("/sw.js")
.then(res => {
console.log("service worker registered");
res.onupdatefound = () => {
const installingWorker = res.installing;
installingWorker.onstatechange = () => {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller){
alert("new update available");
forceReload();
}
else {
alert("all good");
}
break;
}
}
}
})
.catch(err => console.log("service worker not registered", err))
}
});
const forceReload = () =>{
console.log("ForceReload");
navigator.serviceWorker
.getRegistrations()
.then((registrations) =>{
console.log(registrations);
//alert("reg");
Promise.all(registrations.map((r) => r.unregister()))
caches.keys().then(function(names) {
for (let name of names)
caches.delete(name);
});
},
)
.then(() => {setTimeout(() => {
location.reload();
}, 500);
})
}
sw.js
let version =5; // update this to send update.
var cacheName = 'cacheV5'
var filesToCache = [
'/',
'/manifest.json',
'/index.html',
'/sales10.html',
'/getdata.html',
....
....
'/js/siteJS/sales10.js',
'/js/siteJS/getdata.js',
'/js/jquery/3.4.1/jquery.min.js',
'/js/bootstrap/bootstrap.min.js',
'/js/bootstrap/popper.min.js'
];
/* Start the service worker and cache all of the app's content */
self.addEventListener('install', function(e) {
self.skipWaiting();
e.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(filesToCache);
})
);
});
/* Serve cached content when offline */
self.addEventListener('fetch', function(e) {
e.respondWith(
caches.match(stripQueryStringAndHashFromPath(e.request.url.replace(/^.*\/\/[^\/]+/, ''))).then(function(response) {
return response || fetch(e.request);
})
);
});
function stripQueryStringAndHashFromPath(url) { //added this so when url paramerters passed grabbing the cashed js works
return url.split("?")[0].split("#")[0];
}
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
return true;
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});

How can I keep the BarcodeScanner screen open without redirecting me to another page?

I am making an application that allows me to scan QR codes, and I managed to make the code work but my doubt is that when I scan the plugin phonegap-plugin-barcodescanner takes me out of the camera interface, what I want to do is to stay in it and show me an alert with the scanned code, and to give it ok in the alert to stay in it, to avoid being clicked to enter it.
I'm working with the plugin phonegap-plugin-barcodescanner, in ionic 3
public scanQR2() {
this._ButtonText = "Escanear";
this._barcodeScanner.scan().then((barcodeData) => {
if (barcodeData.cancelled) {
console.log("User cancelled the action!");
this._ButtonText = "Escanear";
return false;
}
console.log("Scanned successfully!");
console.log(barcodeData);
}, (err) => {
console.log(err);
});
}
I hope that the application when performing a scan stays on the same interface and does not redirect me to another page

Improving PWA Page Load

I have a PWA, which is essentially a book reader. As a result, it needs lots of data (viz. the book text) to operate. When analyzed by Lighthouse, it scores poorly on the Page Load Check.
My question is: What methods could I employ to improve the page load, while still ensuring offline functionality?
I could have a minimal start page (e.g., just display a 'Please wait, downloading text' message) and then dynamically download (via injected script tag or AJAX) the JSON data file. However, I'm not sure how I would subsequently ensure that the data is fetched from the cache.
Just wondering how others have handled this issue...
Since this question has gone tumbleweed, I decided to post the results of my attempts.
Based on Jake's article, I used the following script and Chrome DevTools to study service worker events:
'use strict';
let container = null;
let updateFound = false;
let newInstall = false;
window.onload = () => {
container = document.querySelector('.container');
let loading = document.createElement('div');
loading.classList.add('loading');
loading.innerHTML = 'Downloading application.<br>Please wait...';
container.appendChild(loading);
console.log(`window.onload: ${Date.now()}`);
swEvents();
};
let swEvents = () => {
if (navigator.serviceWorker) {
navigator.serviceWorker.ready.then(() => {
console.log(`sw.ready: ${Date.now()}`);
if (!updateFound) {
loadApp();
return;
}
newInstall = true;
console.log(`new install: ${Date.now()}`);
}).catch((error) => {
console.log(`sw.ready error: ${error.message}`);
});
}
navigator.serviceWorker.register('/sw.js').then((reg) => {
reg.onupdatefound = () => {
updateFound = true;
console.log(`reg.updatefound: ${Date.now()}`);
const newWorker = reg.installing;
newWorker.onstatechange = (event) => {
if (event.target.state === 'activated') {
console.log(`nw.activated: ${Date.now()}`);
if (newInstall) {
loadApp();
return;
}
refresh();
}
};
};
}).catch((error) => {
console.log(`reg.error: ${error.message}`);
});
};
let refresh = () => {
console.log(`refresh(): ${Date.now()}`);
// window.location.reload(true);
};
let loadApp = () => {
console.log(`loadApp(): ${Date.now()}`);
let child;
while (child = container.firstChild) {
container.removeChild(child);
}
let message = document.createComment('p');
message.textContent = 'Application loading';
container.appendChild(message);
let tag = document.createElement('script');
tag.src = './app.js';
document.body.appendChild(tag);
};
Along the way, I learned that once a service worker is registered, it immediately begins downloading all cached resources. I had assumed that resources were cached only after the page loaded them. I also found some definitive event patterns to indicate which lifecycle phase was occurring.
For a new install, the following events are logged in the above script:
window.onload -> reg.updatefound -> sw.ready -> nw.activated
For this case, when sw.ready fires, all resources have been cached. At this point, I can switch the app from the 'please wait' phase and dynamically load the cached resources and start the app.
For a simple page refresh, the following events are logged:
window.onload -> sw.ready
This will be the event sequence if the app has already been downloaded and no updates are available. At this point, I can again switch phase and start the app.
For a page refresh when the service worker script has been updated, the following events are logged:
window.onload -> sw.ready -> reg.updatefound -> nw.activated
In this case, when nw.activated fires, all cached resources have been updated. Another page refresh is required to actually load the changes. At this point, the user could be prompted to update. Or the app would update on its own the next time it was started.
By tracking these event patterns, it is easy to tell which lifecycle phase the service worker is in and take the appropriate action.

How to close Camera using phonegap-barcode-scanner plugin within service IONIC

I am using phonegap-barcodescanner-plugin to read qr while a service is reading instant payments on background.
I am detecting a new instant payment in the service and launching an event subscribed in the page where the barcodeScanner is launched
event.subscribe('instant-payment', (val) => {
console.log("Hi--------------", val)
this.navCtrl.pop()
});
the event is correctly fired and the log is ok but I'm trying to do a navCtrl.pop() and the Activity is never closed, I thought was going to work same way like cancelling scanner
scan() {
this.barcodeScanner.scan(this.options).then(barcodeData => {
if (barcodeData.cancelled == true) {
this.navCtrl.pop()
} else {
}
}).catch(err => {
console.log('Error', err);
});
}
Is there anyway to force close barcodeScanner and go back to the last "IonicPage".
Thanks for any help.

Kill the page from loading feather

I am using Ionic 2 and would like to kill the page from feather loading similar to PHP die(); function
Below is the method that I currently working with.
fetch_data() {
let loader = this.loadingCtrl.create({ content: 'Loading...' });
loader.present();
this.bank.types().subscribe( response => {
this.linkBankTypes = response.results;
loader.dismiss();
}, err => {
loader.dismiss();
loader = this.loadingCtrl.create({ content: 'No Internet connection. Make sure Wi-Fi or cellular data is turned on, then try again.' });
//Kill the page from here
});
}
PHP's die() function stops creation of the page and lets PHP run environment to return a nasty error message to the client browser.
You can cause the Ionic to crash by throwing exceptions, but that is not a pleasant user experience and not recommended.
Instead you either navigate to an error page or show a message indicating the error.
The NavController's push or popcan be used to navigate to an error page or back to the previous page.