Nativescript Bluetooth searching - bluetooth

Im trying to search for Bluetooth devices with this plugin:
https://github.com/nativescript-community/ble
And evertimy I try to search for devices with this code:
doStartScanning(){
{
this.isLoading = true;
// reset the array
this.observablePeripheralArray.splice(0, this.observablePeripheralArray.length);
this.bluetooth.startScanning(
{
filters: [{serviceUUID:'180d'}], // pass an empty array to scan for all services
seconds: 4, // passing in seconds makes the plugin stop scanning after <seconds> seconds
onDiscovered: function (peripheral) {
this.observablePeripheralArray.push(fromObject(peripheral));
}
}
).then(function() {
this.isLoading = false;
},
function (err) {
this.isLoading = false;
alert({
title: "Whoops!",
message: err,
okButtonText: "OK, got it"
});
});
};
}
I get this Error:
JS: Unhandled Promise rejection: Permission denied ; Zone: <root> ; Task: null ; Value: Permission denied undefined
Bluetooth is enabled and the permission granted from the Phone

it was a permissions error. Paste this in your android manifest.xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Related

Renderer process out of memory after app is packaged into EXE

Expected Behavior
In my main renderer window I'm initializing UI from an imported module. When running the app in dev mode everything works but once I package the app into EXE and try to run it, I'm getting renderer process out of memory error.
The expected behavior is that the packaged app should run like the dev mode.
Actual Behavior
I've checked the electron logs and memory consumption in windows task manager. The memory usage keeps increasing until the renderer process crashes and electron logs oom error.
Since I'm new to electron I've read the documentation but unable to figure out why the same thing is running perfectly in dev mode and crashes in prod.
Log : Renderer process oom - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.
Another log after some time : [19156:0921/120104.184:ERROR:gpu_init.cc(440)] Passthrough is not supported, GL is swiftshader
So this is what I'm trying to do -
Import my module which is served on localhost:
This module exposes an object - Tesseract through which I initialize my UI.
In the component which is rendered in my main browser window I initialize the UI like this:
File - index.tsx
useEffect(() => {
if (tsToken) {
Tesseract.ui
.init(tsToken.tsToken, "random_id")
.then((sdk: any) => {
console.log("🚀 ~ file: index.js ~ line 3 ~ sdk", sdk);
// After this line nothing is logged and renderer process crashes (But works when I run electron in dev mode)
sdk.init({
...MasterConfig,
RootElement: document.getElementById("tesseract-root"),
});
const authToken = sessionStorage.getItem("ts_token");
ipcRenderer.send("set-globals", { TAC: authToken });
})
.catch((err: any) => console.error(err));
}
}, [tsToken]);
return <></>;
In the above piece of code we pass a root element to the init method. The init method then initializes a react app in that root element.
EDIT:
This is the init method in that module
SDK.prototype.init = async function (config) {
try {
const parsedConfig = JSON.parse(this.META.uiConfig);
window.Tesseract.ui["MasterConfig"] = merge(parsedConfig, config);
window.Tesseract.ui["info"] = this.META;
const projectType = window.Tesseract.ui.MasterConfig.ProjectConfig.type;
console.log("🚀 ~ file: lib.js ~ line 51 ~ projectType", projectType)
const MasterConfig = window.Tesseract.ui["MasterConfig"];
console.log(MasterConfig);
if (
MasterConfig &&
MasterConfig.UserProperties &&
MasterConfig.UserProperties.userId
) {
console.log("React init here");
// Console logs upto this point and then everything fails
// No error logged
try {
RecorderUI.ReactApp({ ...parsedConfig, ...config }).then((obj) => {
// This is never logged
console.log("UI rendered");
return obj;
}).catch(err => console.log(err));
} catch (err) {
console.log(err);
return err;
}
} else {
const e = new Error("User Id Missing");
e.name = "Missing unique user Id";
throw e;
}
} catch (err) {
console.error(err);
return err;
}
};
This is the UI rendering method:
export default async function entry(config) {
// This is never logged so basically something is happening before this
console.log("somemmthing something");
console.log("Root Element: ",
window.Tesseract?.ui?.MasterConfig?.RootElement);
try {
const { RootElement } = config;
RootElement.attachShadow({ mode: "open" });
await IDBStore.create({
version: 1,
name: "ext",
schema: {
globals: "&key",
},
});
const shadowRoot = RootElement.shadowRoot;
const styleElement = document.createElement("style");
styleElement.innerHTML = `${LoaderCss} ${SourcePreviewCSS} ${NotificationCss} ${LibraryCss} ${SelectModeCss} ${WebcamBoxCss} ${CameraBubbleCss} ${countdownCss} ${indexStyles} ${commonCss} ${colorsCss} ${homeCss} ${recordCss} ${advancedOptionsCss} ${recordingTypesCss} ${toggleOptionsCss} ${tourOverlayCss} ${headerCss} ${checkboxCss} ${tooltipCss} ${dropdownCss} ${toggleCss} ${recordButtonCss} ${bannersCss} ${toolsCss} ${canvasCss} ${paintCss} ${recordingControlsCss} ${controlsMainCss}`;
const reactRoot = document.createElement("div");
reactRoot.setAttribute("id", "react-root");
shadowRoot.appendChild(styleElement);
shadowRoot.appendChild(reactRoot);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
reactRoot
);
window.addEventListener("message", handleMessaging, false);
} catch (err) {
console.error(err);
return new Error(err);
}
}
I've read numerous blog posts, github issues but unable to find what's causing this. I need help in determining what is the difference in internal workings of electron which causes such difference b/w running in dev mode vs. packaging the app.

Optional Permissions are not being applied after being added

I am adding nativeMessaging permission to my Browser Extension with the following code:
// function triggered by user gesture
const promptPermissionsUpgrade = () =>
new Promise((res) =>
chrome.permissions.request({ permissions: ['nativeMessaging'] }, res)
Then listening for the upgrade:
chrome.permissions.onAdded.addListener(({permissions}) => {
if (permissions && permissions.includes("nativeMessaging")) {
connectNative();
}
});
When I call connectNative(), I run chrome.runtime.connectNative('app_name').
This throws TypeError: chrome.runtime.connectNative is not a function.
I double checked the key in my manifest.json and it is correct ("optional_permissions": ["nativeMessaging"]).
The example in the MDN docs does not say anything about this.
What am I missing?
The app would work as expected on reload, so I realized I could just have the extension reload and voila! It worked as expected.
!chrome.runtime.connectNative && chrome.runtime.reload();
chrome.runtime.connectNative('app_name')
-- runtime.reload docs

Jest puppeteer typescript reference error Page not found

Trying to setup typescript jest with puppeteer
i following step by step instructions as mentioned below
Jest-puppeteer with typescript configuration
there is a simple test
describe('Google', () => {
beforeAll(async () => {
await page.goto('https://google.com')
})
it('should display "google" text on page', async () => {
await expect(page).toMatch('google')
})
})
when i run my test i get weird error
ReferenceError: page is not defined
and it is pointing to the 'await page' object inside beforeAll
i also notice chrome try to kick in and but does not launch may be this error is b/c chrome could not launch.
jest-puppeteer library is responsible for launching a browser and providing browser and page objects
and here is the code taken from the page mentioned above in link
//jest-puppeteer.config.js
let jest_puppeteer_conf = {
launch: {
timeout: 30000,
dumpio: true // Whether to pipe the browser process stdout and stderr
}
}
const isDebugMode = typeof v8debug === 'object' || /--debug|--inspect/.test(process.execArgv.join(' '));
if (isDebugMode) {
jest_puppeteer_conf.launch.headless = false; // for debug: to see what the browser is displaying
jest_puppeteer_conf.launch.slowMo = 250; // slow down by 250ms for each step
jest_puppeteer_conf.launch.devtools = true; // This lets you debug code in the application code browser
jest_puppeteer_conf.launch.args = [ '--start-maximized' ]; // maximise the screen
}
module.exports = jest_puppeteer_conf;
there is a small debug section at the bottom which reminds to add following types i already have them and still no luck, any help is appreciated.
"compilerOptions": {
.....
"types": [
.......
"puppeteer",
"jest-environment-puppeteer",
"expect-puppeteer"
]
}
commenting out the following line fix the issue.
// testEnvironment: "node"

ReferenceError: Cannot access 'web3' before initialization

chrome-browser-output
chrome-console
After installing the create-react-app package and then creating the web3.js file and adding the console.log(web3.version) to the App.js file im getting the above error and im not sure how to fix it and to get it working.
Ive also tried the following and it still throws the same error.
window.addEventListener('load', async () => {
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
// Request account access if needed
await ethereum.enable();
// Acccounts now exposed
web3.eth.sendTransaction({/* ... */});
} catch (error) {
// User denied account access...
}
}
// Legacy dapp browsers...
else if (window.web3) {
window.web3 = new Web3(web3.currentProvider);
// Acccounts always exposed
web3.eth.sendTransaction({/* ... */});
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
}
});
Error can happen if you haven't called window.ethereum.enable(); yet.

COMException "The package id is corrupted" while installing cortana voice commands

I'm trying to add cortana voice commands to my app. However the moment I try to install the voice command definitions I get the COMException "Die Paketidentität ist beschädigt" (The package id is corrupted).
I reduced voice command definition file to a minimum, but that had no effect. My code is:
private static async Task InstallVoiceCommandsIfNecessary()
{
#if WINDOWS_UWP
var installed = Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey("VoiceCommandsInstalled");
if (!installed)
{
try
{
var storageFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Cortana/VoiceCommands.xml"));
await Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager.
InstallCommandDefinitionsFromStorageFileAsync(storageFile);
// The line above is throwing the exception ----^
Windows.Storage.ApplicationData.Current.LocalSettings.Values["VoiceCommandsInstalled"] = true;
}
catch (Exception) { }
}
#endif
}
called from OnLaunched.
The VoiceCommands.xml:
<?xml version="1.0" encoding="utf-8"?>
<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.2">
<CommandSet xml:lang="en-us" Name="StopNowCommandSet_en-us">
<AppName>Stopnow</AppName>
<Example> stop a time </Example>
<Command Name="stopWatch">
<Example> stop a time </Example>
<ListenFor RequireAppName="BeforeOrAfterPhrase"> stop [a] time [in] </ListenFor>
<Feedback> Launching the stopwatch </Feedback>
<Navigate/>
</Command>
</CommandSet>
</VoiceCommands>
I've put a breakpoint at the InstallCommandDefinitionsFromStorageFileAsync and the GetFileFromApplicationUriAsync succeeded.
The problem seems to be the InstallCommandDefinitionsFromStorageFileAsync call.
Update:
The same code works in the Windows 10 Mobile Emulator. Could this be local installation problem?

Resources