Error to get All services and cheracteristcs from ble device using Polidea/react-native-ble-plx - react-native

Hi I am trying to connect a bluetooth device using the Polidea/react-native-ble-plx library.
First I do the scan and it works fine:
scanAndConnect() {
console.log('scanAndConnect');
this.manager.startDeviceScan(null, null, (error, device) => {
//console.log('Scanning...' + error);
if (error) {
// Handle error (scanning will be stopped automatically)
console.log('Scanning ERROR');
return;
}
if ((device.id=== '54:6C:0E:A0:7B:6D')
{
console.log('device found: ' + device.name + '(' + device.id + ')');
this.manager.stopDeviceScan();
}
}
The second step I try to connect. And it s works too!
device.connect().then((dev) => {
console.log("try to connect")
}).then((dev) => {
console.log("success to connect")
}).catch((error) => {
console.log("connect error:" + error)
throw error
});
So, now I want to get all the services and charactrists to read some informations from device, but this feature doesnt work for me.
I am using this method
device.discoverAllServicesAndCharacteristics();
And I always received an error.
Some time I receive the follow error message:
1) WARN Possible Unhandled Promise Rejection (id: 0):
BleError: Device 54:6C:0E:A0:7B:6D is not connected
I didnt understand the first one, because I have the device connected.
var status = this.manager.isDeviceConnected(device.id).then((status)=>console.log('status1: '+status))
the line above returns false before I call the connect method and it returns true after it.
But when I try to get the services and characteristics I have the message that the device isnt connected

Related

Axios triggering weird in React native app

Hello i have a weird thing going on,im using axios in order to send post-get http request for my app.The thing is that axios in my pc working good but in my laptop need console.log("") before axios request i dont know why.This happens in all my files.
It gives me this error : Possible Unhandled Promise Rejection (id : 0 ):
[Axios error: Request failed with statis code 404]
Here is my code :
function getProfile(){
try{
//console.log("") <-------------------------- Here i put it
axios.post(URL+'/checkData',
{
usernameCheckAXIOS : username,
passwordCheckAXIOS : password,
})
.then((response)=>{
console.log(response.data)
setProfile(response.data);
if(response.data.responseOfProfile == false){
Alert.alert("Access Dinied")
}
else{
navigation.navigate('Home')
}
})
}catch(error){}
}
If you are getting a “Possible unhandled promise rejection” warning in your React Native app, it means that a promise was rejected, but the rejection was not handled. Promises in JavaScript are used to handle asynchronous operations, and they can either be resolved or rejected.
axios.post(URL+'/checkData',
{
usernameCheckAXIOS : username,
passwordCheckAXIOS : password,
})
.then((response)=>{
//... your code
})
.chatch(error => console.log(error)) // <-- add this line
The HTTP 404 Not Found response status code indicates that the server cannot find the requested resource
so verify your URL, should be invalid because it cannot be found.
[Axios error: Request failed with statis code 404] is an error URL not found.
Are you sure that the url URL+'/checkData' is valid ?

Error: Timed out while waiting for handshake

I am using scp2 to copy a file to targetPath. config contains host, username, privateKey, path and port.
const client = require('scp2');
export function scpAsync(config, targetPath) {
return new Promise((resolve, reject) => {
client.scp(config, targetPath, err => {
if (!err){
resolve();
} else {
const errorMessage = err;
reject(errorMessage);
}
});
});
}
When doing so I am getting the error:
Error: Timed out while waiting for handshake
I tried to pass also
promptForPass: false
but it did not change anything. Besides that I used debug mode which told me that I am connected to the server and I put a higher setTimeout but then the error is just coming later. I was checking the documentation of scp2 and their GitHub. I use the function like explained there (https://www.npmjs.com/package/scp2) and regarding the error they could fix it with an higher setTimeout (https://github.com/spmjs/node-scp2/issues/107). I tried with a local ftp server, ngrok and ftp on ec2 instance. All with the same problem.
I would be happy to get help. I asked this question also on superuser but did not get an answer:
https://superuser.com/questions/1576964/error-timed-out-while-waiting-for-handshake

How to prevent dynamicLink listener from firing multiple times in react-native?

I have enabled signInWithEmailLink() from firebase in my react-native app.
Everything works successfully, the user is also created but the I think the onLink(handleLink) listener is fired multiple times and leads to an error even after user sign-in.
Logs:
link is tru
LOG email: email#gmail.com //I have hidden the actual email
LOG email: email#gmail.com
LOG email: email#gmail.com
LOG USer created
LOG EROR: [Error: [auth/invalid-action-code] The out of band code is invalid. This can happen if the code is malformed, expired, or has already been used.]
LOG EROR: [Error: [auth/invalid-action-code] The out of band code is invalid. This can happen if the code is malformed, expired, or has already been used.]
LOG EROR: [Error: [auth/invalid-action-code] The out of band code is invalid. This can happen if the code is malformed, expired, or has already been used.]
As you can see its fired multiple times, how can I prevent this??
This is my code:
const handleLink = async link => {
console.log('opened Link: ', link.url);
if (auth().isSignInWithEmailLink(link.url)) {
console.log('link is tru');
try {
const email = await AsyncStorage.getItem('email');
console.log('email: ', email);
await auth()
.signInWithEmailLink(`${email}`, link.url)
.then(() => {
console.log('USer created');
})
.catch(err => {
console.log('EROR: ', err);
});
} catch (err) {
console.log('err: ', err);
}
} else {
console.log('link is false');
}
};
const link = dynamicLinks().onLink(handleLink);
Help would be very much appreciated
Since console.log('email: ', email); is called 3 times, i assume that console.log('link is tru'); is also called 3 times, so the problem is that the whole handleLink function is called 3 times before auth().signInWithEmailLink finishes.
I ran into the same issue here is the answer.
Email link Authentication has a longer expiration time (around 6 hours). If you'll create 2 or more sign in emails in a row, you should be able to login with the latest link being received. You'll also be able to receive an error message for example in iOS, "The action code is invalid. This can happen if the code is malformed, expired, or has already been used" when you clicked the older links.

getaddrinfo ENOTFOUND API Google Cloud

I'm trying to execute API.AI tutorial for building a weather bot for Google Assistant (the one here: https://dialogflow.com/docs/getting-started/basic-fulfillment-conversation)
I made everything successfully, created the bot within API, created the Fulfillments, installed NodeJS on my pc, connected Google Cloud Platform, etc.
Then I created the index.js file by copying it exactly how it's stated on API.ai tutorial with my API key from World Weather Organisation (see below).
But when I use the bot, it doesn't work. On the Google Cloud Platform the error is always the same:
Error: getaddrinfo ENOTFOUND api.worldweatheronline.com
api.worldweatheronline.com:80
at errnoException (dns.js:28)
at GetAddrInfoReqWrap.onlookup (dns.js:76)
No matter how often I do it I get the same error. So I don't actually reach the API. I tried to see if anything changed from WWO side (URL, etc.) but apparently no. I updated NodeJS and still same issue. I refreshed the Google Cloud platform completely and didn't help.
That one I really can't debug. Could anyone help?
Here's the code from API.ai:
'use strict';
const http = require('http');
const host = 'api.worldweatheronline.com';
const wwoApiKey = '[YOUR_API_KEY]';
exports.weatherWebhook = (req, res) => {
// Get the city and date from the request
let city = req.body.result.parameters['geo-city']; // city is a required param
// Get the date for the weather forecast (if present)
let date = '';
if (req.body.result.parameters['date']) {
date = req.body.result.parameters['date'];
console.log('Date: ' + date);
}
// Call the weather API
callWeatherApi(city, date).then((output) => {
// Return the results of the weather API to Dialogflow
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'speech': output, 'displayText': output }));
}).catch((error) => {
// If there is an error let the user know
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'speech': error, 'displayText': error }));
});
};
function callWeatherApi (city, date) {
return new Promise((resolve, reject) => {
// Create the path for the HTTP request to get the weather
let path = '/premium/v1/weather.ashx?format=json&num_of_days=1' +
'&q=' + encodeURIComponent(city) + '&key=' + wwoApiKey + '&date=' + date;
console.log('API Request: ' + host + path);
// Make the HTTP request to get the weather
http.get({host: host, path: path}, (res) => {
let body = ''; // var to store the response chunks
res.on('data', (d) => { body += d; }); // store each response chunk
res.on('end', () => {
// After all the data has been received parse the JSON for desired data
let response = JSON.parse(body);
let forecast = response['data']['weather'][0];
let location = response['data']['request'][0];
let conditions = response['data']['current_condition'][0];
let currentConditions = conditions['weatherDesc'][0]['value'];
// Create response
let output = `Current conditions in the ${location['type']}
${location['query']} are ${currentConditions} with a projected high of
${forecast['maxtempC']}°C or ${forecast['maxtempF']}°F and a low of
${forecast['mintempC']}°C or ${forecast['mintempF']}°F on
${forecast['date']}.`;
// Resolve the promise with the output text
console.log(output);
resolve(output);
});
res.on('error', (error) => {
reject(error);
});
});
});
}
Oh boy, in fact the reason was most stupid ever. I didn't enable "billing" on Google Cloud Platform and that's why it blocked everything (even though I'm using a free test of the API). They just wanted my credit card number. It works now
I had the same issue trying to hit my db. Billing wasn't the fix as I had billing enabled already.
For me it was knexfile.js setup for MySql - specifically the connection object. In that object, you should replace the host key with socketPath; and prepend /cloudsql/ to the value. Here's an example:
connection: {
// host: process.env.APP_DB_HOST, // The problem
socketPath: `/cloudsql/${process.env.APP_DB_HOST}`, // The fix
database: process.env.APP_DB_NAME,
user: process.env.APP_DB_USR,
password: process.env.APP_DB_PWD
}
Where process.env.APP_DB_HOST is your Instance connection name.
PS: I imagine that even if you're not using Knex, the host or server parameter of a typical DB connectionstring will have to be called socketPath when connecting to Google Cloud SQL.

Unable to connect to adapter

I have following code called when loading the page:
var resourceRequest = new WLResourceRequest(
"adapters/adapter-name/rest/init/" + timeStamp,
WLResourceRequest.GET
);
However it returns error in my console:
GET http://localhost:10080/project-name/adapters/adapter-name/rest/init/0 404
(Not Found)
While this code works:
function wlEnvInit() {
console.log("CONNECTING 1111");
WL.Client.connect({c
onSuccess: function(){
console.log("CONNECTED 2222");
},
onFailure: function(error) {
console.log("ERROR IN CONNECTION");
console.log(error);
}
});
}
How to troubleshoot this?
Make sure the adapter is really deployed by visiting the console
Make sure that your application is pointing to an IP address of the host machine where the MobileFirst Server is deployed to
Make sure your adapter call is correct
Example calling:
Client side:https://github.com/MobileFirst-Platform-Developer-Center/ResourceRequestCordova/blob/release80/www/js/index.js#L54
Server side: https://github.com/MobileFirst-Platform-Developer-Center/Adapters/blob/release80/JavaAdapter/src/main/java/com/sample/adapter/JavaAdapterResource.java#L25