Unable to read from BLE with react-native-ble-plx - react-native

I'm using React Native and the BLE package react-native-ble-plx on my Ubuntu machine.
According to the docs, I've done the following:
Scanned for devices
Connected to device
device.discoverAllServicesAndCharacteristics
writeCharacteristicWithResponseForDevice
My problem lies in reading the response I get from sending my command.
RX characteristic is writable, but TX is only notifiable and not readable. Therefore I need to monitor the characteristic with monitorCharacteristicForDevice, however I can't get this to function.
I never recieve neither 'monitor success', 'Error at receiving data from device' nor 'Monitor failure' in the code below.
How do I read the return?
monitorDevice = () => {
this.setState({monitoring: true})
console.log(this.state.servicesDiscovered)
if(this.state.servicesDiscovered){
{this.manager.monitorCharacteristicForDevice(this.state.connectedTo,
SERVICE_UUID,
TX_CHARACTERISTIC,
(error, characteristic) => {
if (error) {
console.error("Error at receiving data from device", error);
return
}
else {
this.setState({monitoring: true})
console.log('monitor success')
console.log('monitor success' + characteristic.value);
this.state.messagesRecieved.push(characteristic.value)
}
})
}
}
else{
console.log("Monitor failure")
}
}
checkBattery = () => {
if(this.state.monitoring){
this.manager.writeCharacteristicWithResponseForDevice(this.state.connectedTo,
SERVICE_UUID,
RX_CHARACTERISTIC,
"YmF0dGVyeQ==")
.then(characteristic => {
console.log("Successfully sent: " + characteristic.value)
return
})
.catch(err => {
console.log(err)
})
}
else{
alert("Not monitoring")
}
}

Related

Node JS emit socket after error in SQL query

**Hello, please do you know how can I send message to client via socket when I have error in my SQl query on server side ? **
Server side
io.on('connect', (socket) => {
console.log("User connected: " + socket.id);
socket.on('disconnet', () => {
console.log("disconnected");
})
.post('/addDiel', (req, res) => { //Pridanie dielu do DB
pool.getConnection((err, connection) => {
if(err) throw err
console.log(`Pripojene ako ID ${connection.threadId}`)
const params = req.body;
res.send({
MenoDielures: params.MenoDielu,
DruhDielures: params.DruhDielu,
ProjektNameres: params.ProjektName
})
ProjektNameDB = params.ProjektName.split('.').join("_");
connection.query('INSERT INTO `Skener_db`.`?` (`MenoDielu`, `DruhDielu`, `DatumCas`) VALUES (?, ?, NOW())', [ProjektNameDB, params.MenoDielu, params.DruhDielu],(err, rows)=> {
connection.release()
if(!err) {
res.send(console.log(`Hodnota ${params.MenoDielu} bola pridana.`))
} else {
console.log(err);
if (err.code == ('ER_DUP_ENTRY')) {
//send message to client
}
//res.send({alertMessage: 'Diel už bol oskenovaný. Oskenuj ďaľší.'})
}
})
console.log(req.body)
})
})
})
My client side:
socket.on('connect', () => {
$('#skuska').html("Socket pripojeny");
})
socket.on('receiveDUPmessage', message => {
$('#skuska').html(message);
})
The code here is just for example. I didnt find solution for my problem, so I'm asking here
You have to emit events and socket is locally scoped. io.sockets is not, So you can do it like this on the server-side:
if(!err) {
res.send(console.log(`Hodnota ${params.MenoDielu} bola pridana.`))
} else {
console.log(err);
if (err.code == ('ER_DUP_ENTRY')) {
//send message to client
io.sockets.emit('my error', 'Some error happened');
}
//res.send({alertMessage: 'Diel už bol oskenovaný. Oskenuj ďaľší.'})
}
And on the client-side do this:
socket.on('my error', function (text) {
console.log(text);
});
Here is some sort of posts that may help you:
How to emit error to be possible catch it on error handler on client-side?
How to emit a socket.io response within post request in NodeJS

ICE restart with SIP.js

What is the proper procedure to do ICE restart when using SIP.js? (v0.20.0)
This is what I'm trying:
oniceconnectionstatechange: (event) => {
const newState = sdh.peerConnection.iceConnectionState;
if (newState == 'failed') {
sdh.peerConnection.restartIce();
sdh.peerConnection.createOffer({'iceRestart': true})
.then(function(offer) {
return sdh.peerConnection.setLocalDescription(offer);
});
}
}
It seems to execute without an error, but also no result.
FireFox debug-tool "about:webrtc" shows "ICE restarts: 0", so I guess it didn't even begin restart.
ps: failed state is induced by restarting RTP Engine (Kamailio setup). After RTP Engine restarts there is still audio for about 20 seconds and only when ICE state changes to "failed" audio stops.
Found solution that fixed my problem:
sdh.peerConnectionDelegate = {
oniceconnectionstatechange: (event) => {
const newState = sdh.peerConnection.iceConnectionState;
if (newState === 'disconnected') {
sdh.peerConnection.restartIce();
sdh.peerConnection.createOffer({'iceRestart': true})
.then((offer) => {
sdh.peerConnection.setLocalDescription(offer);
session.sessionDescriptionHandlerModifiersReInvite = [offer];
session.invite()
.then(() => {
session.logger.debug('iceRestart: RE-invite completed');
})
.catch((error) => {
if (error instanceof RequestPendingError) {
session.logger.error('iceRestart: RE-invite is already in progress');
}
throw error;
});
});
}
}
};

facebook login working on development mode or server mod, when create a build, it's not working on any devices. react native app

feature unavailable facebook login in currently unavailable for this app, since we are updating additionl details for this app. please try again later
working only on my system and device, not working in others,
how to resolve this issue,please help
FacebookSignIn = async () => {
// Attempt login with permissions
try {
const result = await LoginManager.logInWithPermissions(['public_profile', 'email']);
console.log("fb login", result)
if (!result.isCancelled) {
await AccessToken.getCurrentAccessToken()
.then(async res => {
console.log("token", res);
// Create a Firebase credential with the AccessToken
const facebookCredential = auth.FacebookAuthProvider.credential(res.accessToken);
console.log("token", res);
// Sign-in the user with the credential
this.setState({ loder: true })
await auth().signInWithCredential(facebookCredential)
.then(response => {
console.log("Login Data", response);
const data = {
"name": response.additionalUserInfo.profile.first_name,
"email": response.additionalUserInfo.profile.email,
"user_type": 0
}
console.log(data);
fetchPostMethod('/facebook-sign-up', data)
.then(async response => {
this.setState({ loder: false })
if (response.status == 200) {
if (response.data.user_type == 0) {
try {
let user = JSON.stringify(response?.data?.user_type)
await AsyncStorage.setItem('SignINToken', response?.data?.token);
await AsyncStorage.setItem('UserType', user);
this.logmodl();
} catch (e) {
console.log("Login error", e)
}
} else {
this.user();
}
console.log("SignIn Successful", response);
} else {
this.field();
}
})
.catch(response => {
this.setState({ loder: false })
console.log("SignIn faild", response.message);
})
this.setState({ FacebookUserInfo: response });
})
.catch(error => {
console.log('Login Data Error', error);
})
})
.catch(error => {
console.log('Something went wrong obtaining access token ', error);
})
}
} catch (error) {
console.log("ERROR WHILE LOGIN! ", error);
}
}
feature unavailable facebook login in currently unavailable for this app, since we are updating additionl details for this app. please try again later
working only on my system and device, not working in others,
how to resolve this issue,please help
Pay attention! For enable Facebook login for other users you need visit the Facebook developer site
and enable work mode for application, moving this switch

bleManager.startDeviceScan not working on iOS react-native-ble-plx

I am trying to pair a gateway to React native app using the react-native-ble-plx.
The below source code works fine in Android wheras in iOS, the bleManager.startDeviceScan() is not triggered. Nothing happens after this step.
Any help is much appreciated!
Source code:
const connectBLE = () => {
const subscription = bleManager.onStateChange(async (state) => {
if (state === 'PoweredOn') {
subscription.remove();
scanAndConnect();
}
};
}
const scanAndConnect = () => {
bleManager.startDeviceScan(null, null, async (error, device) => {
if (error) {
showToast(error, 'error');
console.log('Handle error - scanning will be stopped automatically');
return;
}
console.log('Devices');
console.log(device.name);
// Check if it is a device you are looking for based on device name
if (device.name === "BLE_0006") {
// Stop scanning as we have found the device.
bleManager.stopDeviceScan();
// Establish Device connection.
device
.connect()
.then((deviceData) => {
/** Show Toast on Device disconnect */
bleManager.onDeviceDisconnected(
deviceData.id,
(connectionError, connectionData) => {
if (connectionError) {
console.log(connectionError);
}
console.log('Device is disconnected');
console.log(connectionData);
},
);
/** Discover All Services and Characteristics */
return device.discoverAllServicesAndCharacteristics();
})
.then(async (deviceObject) => {
console.log('deviceObject');
console.log(deviceObject);
/** Subscribe for the Readable service */
device.monitorCharacteristicForService(
Enum.bleConnectionInfo.customServiceUUID,
Enum.bleConnectionInfo.readCharacteristicUUID,
(error, characteristic) => {
if (error) {
console.log('Error in monitorCharacteristicForService');
console.log(error.message);
return;
}
console.log(characteristic.uuid, characteristic.value);
]);
},
);
})
.catch((error) => {
console.warn(error);
showToast(error, 'error');
});
}
});
}
This might be helpful for someone!
The Issue was resolved by moving the bleManager() initialization outside the functional component.

React Native BLE with MiBand

I'm really new to this but I already know (by searching other projects through the Internet) that the MiBands have an authentication process.
The thing is I have tried to write without and with response to the only service UUID I got through the connection and it's always saying the band has not that UUID Service.
I am using React-Native-BLE-PLX library.
As it can be seen in the image I use the device's Service UUID since I cannot get any other service but it always says that it does not exist.
search(){
this.manager = new BleManager();
this.manager.startDeviceScan(null, null, (error, device) => {
if (error) {
console.log(error.message);
return;
}
if (device.name == 'Mi Band 3') {
this.manager.stopDeviceScan();
this.device = device;
this.connect();
}
});
}
connect() {
console.log("CONNECTING...");
this.device.connect()
.then(async (device) => {
console.log("CONNECTED!!!");
console.log("DEVICE CONNECTED:\n");
console.log(device);
this.auth(device);
// return this.manager.discoverAllServicesAndCharacteristicsForDevice(device.id)
})
// .then((device) => {
// console.log(device);
// this.send(device);
// })
// .catch((error) => {
// console.log("ERROR: ");
// console.log(error);
// });
}
async auth(device) {
console.log("DEVICE: \n");console.log(this.device);
console.log("DEVICE'S SERVICE UUID: \n" +this.device.serviceUUIDs[0]);
console.log("TRYING");
this.manager.writeCharacteristicWithoutResponseForDevice('D7:2D:F8:F2:24:3F', '0000fee0-0000-1000-8000-00805f9b34fb', '00000009-0000-3512-2118-0009af100700', 0x01 + 0x00 + new Buffer("OLA MUNDO"))
.then((device) => {
console.log("STUFF GOING ON:\n");
console.log(device);
})
.catch((error) => {
throw error;
});
}
Really need help and thanks for that.
If there is something I need to describe more please just tell me.
Directly after getting connected you must first discover the services and characteristics. After that you can start the authentication part. However your authentication part is totally wrong. Do a bit of Googling to find out how to do it properly...