Not able to write or send data to BLE hardware using react-native ble-manager[ write error status-3] - javascript

I am able to make a BLE connection with the hardware. By using service UUID and characteristics UUID I am able to receive data from the hardware through start notification function. But when I try to send data to the hardware its showing error [Write error status-3] as shown in the below code.
BleManager.retrieveServices(peripheral.id).then((peripheralInfo) => {
console.log(peripheralInfo);
var service = '6e400001-b5a3-f393-e0a9-e50e24dcca9e';
var WriteCharacteristic = '6e400002-b5a3-f393-e0a9-e50e24dcca9e';
var ReadCharacteristic = '6e400003-b5a3-f393-e0a9-e50e24dcca9e';
setTimeout(() => {
// receiving data from hardware
BleManager.startNotification(peripheral.id, service, ReadCharacteristic).then(() => {
console.log('Started notification on ' + peripheral.id);
setTimeout(() => {
// sending data to the hardware
BleManager.write(peripheral.id, service, WriteCharacteristic, [1,95]).then(() => {
console.log('Writed NORMAL crust');
});
}, 500);
}).catch((error) => {
console.log('Notification error', error);
});
First faced some problems with characteristics not found. After some changes, I am getting error as
Write error Status - 3
I am not able to find any solution for this error.
Thank you in advance

While using BleManager.write, you should first prepare your data
Data preparation:
If your data is not in byte array format you should convert it first. For strings you can use convert-string or other npm package in order to achieve that. Install the package first:
npm install convert-string
Then use it in your application:
// Import/require in the beginning of the file
import { stringToBytes } from "convert-string";
// Convert data to byte array before write/writeWithoutResponse
const data = stringToBytes(yourStringData);
In my case I converted my data to byte format, this way and you can do the same.
const dataByte = convertString.UTF8.stringToBytes(data);
Then used in my code
BleManager.retrieveServices(currentDevice.PID).then((peripheralInfo) => {
console.log(peripheralInfo);
BleManager.write(
currentDevice.PID,
'0000ffe0-0000-1000-8000-00805f9b34fb',
'0000ffe1-0000-1000-8000-00805f9b34fb',
dataByte,
)
.then(() => {
console.log(`Sent ${dataByte}`);
})
.catch((error) => {
console.log(error);
});
});
};

Related

Fetch and Store files with IndexedDB

I need to download a list of files and store them locally with IndexedDB. I am using fetch to retrieve the files as follows:
cacheRecordings() {
var request = window.indexedDB.open("database", 2);
request.onsuccess = event => {
var database = event.target.result;
var transaction = database.transaction(["store"], 'readwrite'); //second step is opening the object store
this.objectStore = transaction.objectStore("store");
}
for (const url of this.urls) {
fetch(url)
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const index = this.objectStore.index('path');
index.openCursor().onsuccess = function(event) { <-- Error is thrown here
this.objectStore.add(url, path);
}.bind(this)
})
.catch((error) => {
console.log(error)
})
}
}
The above code results in the following two errors:
Failed to execute 'openCursor' on 'IDBIndex': The transaction is not active.
Failed to execute 'index' on 'IDBObjectStore': The transaction has finished
How do I store the fetched files using IndexedDB?
I found a relevant question - but it does NOT address my use case of fetched files.
TransactionInactiveError: Failed to execute 'add' on 'IDBObjectStore': The transaction is not active
My guess is that this happens because you are performing an async operation (the fetch) within a sync loop (the for)
To confirm this try storing a single file in the db without the loop. If that's successful, look into executing acync code within a loop

How could i implement Demographic Clarify.ai model on project built on react.js?

I've tried to build a simple React app using basic Clarifai.FACE_DETECT_MODEL, but now I wanna change it to more advanced "Demographic", maybe somebody knows how to di it?
I know that I have to change clarify model but idk exactly how to do it
onButtonClick = () =>{
this.setState({imageUrl: this.state.input});
app.modelsw
.predict(
Clarifai.FACE_DETECT_MODEL,
this.state.input)
.then(response =>this.displayFaceBox(this.calculateFaceLocation(response)))
.catch(err => console.log("OOOOOOPS fix me!!!!"));}````
the demographics now only support requests from the backend. This is the nodejs request.
const {ClarifaiStub} = require("clarifai-nodejs-grpc");
const grpc = require("#grpc/grpc-js");
const metadata = new grpc.Metadata();
metadata.set("authorization", "{My key}");
const stub = ClarifaiStub.json()
stub.PostWorkflowResults(
{
workflow_id: "Demographics",
inputs: [
{data: {image: {url: "https://static.independent.co.uk/s3fs-public/thumbnails/image/2015/06/06/15/Chris-Pratt.jpg"}}}
]
},
metadata,
(err, response) => {
if(response){
console.log(response.results[0].outputs[2].data.regions[0].data.concepts)
} else {
console.log(err)
}
}
)
I think you can replace
Clarifai.FACE_DETECT_MODEL with "c0c0ac362b03416da06ab3fa36fb58e3" to have it use the Demographics model.
I'm not sure if something like Clarifai.DEMOGRAPHICS will work (you can try if you want) but I believe that is just a variable holding the string representing the model. You could put a breakpoint in the debugging console of the web browser and examine the Clarifai object and look for a field that matches demographics in some way, and that is probably the variable for the hash.
Output from the call is specified here: https://www.clarifai.com/models/demographics-image-recognition-model-c0c0ac362b03416da06ab3fa36fb58e3#documentation
it should now be:
onButtonClick = () =>{
this.setState({imageUrl: this.state.input});
app.modelsw
.predict('c0c0ac362b03416da06ab3fa36fb58e3', this.state.input)
.then(response =>this.displayFaceBox(this.calculateFaceLocation(response)))
.catch(err => console.log('Oops fix me!'))
}

Calling child_process with Node.js vs calling child process from C and creating a C++ bind to call from node.js

I would like to call pdftotext to extract the content of 100.000 files (and i need to be fast), so, which of these two implementations would be the fastest?
Implementation 1:
Create a child_process from node.js, for every extraction:
export default (file) => new Promise((resove, reject) => {
const command = 'pdftotext'
const args = ['-layout', '-enc', 'UTF-8', file, '-']
const process = spawn(command, args)
const stdout = []
const stderr = []
process.stdout.on('data', (data) => {
stdout.push(data)
})
process.stderr.on('data', (data) => {
stderr.push(data)
})
process.on('error', (error) => {
if (error.code === 'ENOENT')
error.message = 'pdftotext is not installed, so will be unable to extract the file content'
reject(error)
})
process.on('close', () => {
if (stderr.length)
return reject(stderr.map(Error))
resolve(stdout.join())
})
}
Implementation 2:
Create a child_process from C, and create a C++ binding to call from node.js
-- Without code because I'm still learning how to do it --
Most likely process invocation code will have nonessential impact on performance and the speed of document processing depends on pdftotext implementation and disk io. So I guess there is no point to bother with writing custom process launcher.

Firebase storage failing silently?

I'm trying to get the download url for multiple images, then trigger a change in my app. But... if one of those images doesn't exist for whatever reason, everything fails silently.
Here's the code:
const promises = [];
snapshot.forEach(childSnapshot => {
const child = childSnapshot.val();
const promise = firebase.storage()
.ref(child.songImagePath)
.getDownloadURL()
.catch(err => {
console.log('caught', err);
return "";
})
.then(imageURL => {
return imageURL;
});
promises.push(promise);
});
Promise.all(promises)
.catch(err => {
console.log('caught', err);
})
.then(urls => {
...do something with urls array
});
I'm using child.songImagePath in my database to store the image's location in storage. If ALL paths for ALL images have images, everything works perfectly.
BUT if an upload went awry or for some reason there's no image in the storage location, it fails silently. None of my catches fire. And Promise.all is never resolved.
What's going on here? Is there a way to check for a file's existence before calling getDownloadURL?
EDIT: As #mjr points out, in the documentation they've formatted their error callback slightly differently than I have. This also seems to never fire an error, though:
.then(
imageURL => {
return imageURL;
},
err => {
console.log('caught', err);
return "";
}
);
Firebase Storage JS dev here.
I ran your code with minor changes[1] in Chrome and React Native, and didn't see that behavior.
I see Promise.all always resolving (never failing), with an empty string in the array for invalid files. This is because your .catch handler for getDownloadURL returns an empty string.
For further troubleshooting, it would be useful to know:
version of the firebase JS library you are using
the browser/environment and version
network logs, for example from the network panel in Chrome's dev tools, or similar for other browsers
The firebase-talk Google Group tends to be a better place for open-ended troubleshooting with more back-and-forth.
[1] For reference, here's my code:
const promises = [];
// Swap out the array to test different scenarios
// None of the files exist.
//const arr = ['nofile1', 'nofile2', 'nofile3'];
// All of the files exist.
const arr = ['legitfile1', 'legitfile2', 'legitfile3'];
// Some, but not all, of the files exist.
//const arr = ['legitfile1', 'nofile2', 'nofile3'];
arr.forEach(val => {
  const promise = firebase.storage()
    .ref(val)
    .getDownloadURL()
    .catch(err => {
// This runs for nonexistent files
      console.log('caught', err);
      return "";
    })
    .then(imageURL => {
// This runs for existing files
      return imageURL;
    });
  promises.push(promise);
});
Promise.all(promises)
  .catch(err => {
// This never runs
    console.log('caught', err);
  })
  .then(urls => {
// This always runs
    console.log('urls', urls);
  });

window.WebSocket - window is not defined

I am a bit out of my comfort zone here, so looking for a bit of guidance. I am trying to access an api to display live metrics, using phonic-elixir (https://www.npmjs.com/package/phoenix-elixir) - am just sort of trying to get it running first, so have loaded up their example code and connecting to an api (forgive me if the terminology is all wrong, I am new at this!)
This is my code:
import {Socket} from 'phoenix-elixir';
let socket = new Socket('ws://API_URL_HERE', {params: {'auth-token': 'AUTH_TOKEN'}})
socket.connect()
let channel = socket.channel('updates:new', {})
channel.join()
.receive('ok', resp => { console.log('Joined successfully', resp) })
.receive('error', resp => { console.log('Unable to join', resp) })
channel.on('update', payload => {
console.log('Received: ' + payload);
console.log(payload);
})
export default socket
When I run babel index.js | node I am getting the error: this.transport = opts.transport || window.WebSocket || LongPoll; and ReferenceError: window is not defined
Just some advice to point me in the right direction would be fantastic. Is window not defined because it needs a dom? Do I need a server to run this in?
Thank you :)
I just ported the client to be compatible with node.JS.
Here is the link https://github.com/mcampa/phoenix-channels
The difference with the original client is that this does not use long-polling and you need to pass the absolute url instead of the relative url.
To install it run:
npm install --save phoenix-channels
Same API as the original:
const { Socket } = require('phoenix-channels')
let socket = new Socket("ws://example.com/socket")
socket.connect()
// Now that you are connected, you can join channels with a topic:
let channel = socket.channel("room:lobby", {})
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
phoenix-elixir is client-side library that is supposed to be used in browsers not in node environment. You should create html page with your code and open it in browser to test it out.

Categories

Resources