cannot write to a characteristic WebBLE - javascript

I have this index.html file that talks to Raspberry pi 3 running a bleno app over BLE.
<!-- <!DOCTYPE html> -->
<html>
<head>
<meta charset="utf-8">
<title>bluetooth</title>
<script type="text/javascript">
var serv;
var readVal="";
function onButtonClick() {
console.log('clciked');
let filters = [];
var options1 = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
let options = {};
var tem = '00010000-89BD-43C8-9231-40F6E305F96D'.toLowerCase();
filters.push({services: [tem]});
options.acceptAllDevices = false;
options.filters = filters;
console.log('Requesting Bluetooth Device...');
console.log('with ' + JSON.stringify(options));
var listn;
if(navigator.bluetooth){
document.getElementById('result').innerHTML = "Bluetooth Supported";
}
else{
document.getElementById('result').innerHTML = "Bluetooth not Supported";
}
function success(pos) {
var crd = pos.coords;
console.log(crd);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
console.log(navigator);
navigator.geolocation.getCurrentPosition(success, error, options1);
// navigator.
let decoder = new TextDecoder('utf-8');
navigator.bluetooth.requestDevice(options)
.then(device => {
console.log('> Name: ' + device.name);
console.log('> Id: ' + device.id);
console.log('> Connected: ' + device.gatt.connected);
return device.gatt.connect();
})
.then(server => {
return server.getPrimaryService(tem);
})
.then(service => {
serv = service;
console.log(service);
return service.getCharacteristic('00010010-89bd-43c8-9231-40f6e305f96d');
})
.then(characteristic => {
// console.log(characteristic);
return characteristic.readValue();
})
.then(value => {
let decoder = new TextDecoder('utf-8');
var str = decoder.decode(value);
readVal = str;
console.log(value);
console.log(value.toString());
console.log(str);
})
.catch(error => {
console.log('Argh! ' + error);
});
}
function onSend() {
serv.getCharacteristics().then(characteristics =>{
// console.log(characteristics);
var charact;
for(var i = 0; i < characteristics.length; i++){
var ob = characteristics[i];
if(ob['properties']['write'] === true){
charact = ob;
}
}
console.log(charact);
var Encoder = new TextEncoder("utf-8");
console.log(readVal);
var b = Encoder.encode(readVal);
console.log(b);
charact.writeValue(b);
})
.then(_ => {
console.log('wrote data');
})
.catch(err => {
console.log(err);
});
}
</script>
</head>
<body>
<button id = "b1" onclick="onButtonClick();">Click</button>
<h1 id = 'result'></h1>
<div id = 'networks'></div>
<button id="send" onclick="onSend();">Send Back</button>
</body>
</html>
I can read the characteristics from the ble peripheral, but I get a DOMException GATToperation failed due to reasons unknown at index.html line 0.
My bleno app on the Pi, app.js
var bleno = require('bleno');
var fs = require('fs');
var scannedNetworks = [];
const WIFI_SERVICE_UUID = "00010000-89BD-43C8-9231-40F6E305F96D";
const ARGUMENT_1_UUID = "00010001-89BD-43C8-9231-40F6E305F96D";
const RESULT_UUID = "00010010-89BD-43C8-9231-40F6E305F96D";
class ArgumentCharacteristic extends bleno.Characteristic {
constructor(uuid, name) {
super({
uuid: uuid,
properties: ["write"],
value: null,
descriptors: [
new bleno.Descriptor({
uuid: "2901",
value: name
})
]
});
this.argument = 0;
this.name = name;
}
onWriteRequest(data, offset, withoutResponse, callback) {
try {
if(data.length != 1) {
callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH);
return;
}
this.argument = data.readUInt8();
let decoder = new TextDecoder('utf-8');
var str = decoder.decode(value);
console.log(`Argument ${this.name} is now ${this.argument}`);
console.log(str);
callback(this.RESULT_SUCCESS);
} catch (err) {
console.error(err);
callback(this.RESULT_UNLIKELY_ERROR);
}
}
}
class ResultCharacteristic extends bleno.Characteristic {
constructor() {
super({
uuid: RESULT_UUID,
properties: ["read"],
value: null,
descriptors: [
new bleno.Descriptor({
uuid: "2901",
value: "Calculation result"
})
]
});
//this.calcResultFunc = calcResultFunc;
}
onReadRequest(offset, callback) {
try {
fs.readFile('./weights.txt', (err,dat)=>{
if(!err){
var result = dat.toString();
console.log(`Returning result: ${result}`);
let data = new Buffer(result);
//data.writeUInt8(result, 0);
console.log(data);
callback(this.RESULT_SUCCESS, data);
}
});
} catch (err) {
console.error(err);
callback(this.RESULT_UNLIKELY_ERROR);
}
}
}
console.log("Starting bleno...");
bleno.on("stateChange", state => {
if (state === "poweredOn") {
bleno.startAdvertising("Visualizer thresholds", [WIFI_SERVICE_UUID], err => {
if (err) console.log(err);
});
} else {
console.log("Stopping...");
bleno.stopAdvertising();
}
});
bleno.on("advertisingStart", err => {
console.log("Configuring services...");
if(err) {
console.error(err);
return;
}
let argument1 = new ArgumentCharacteristic(ARGUMENT_1_UUID, "Argument 1");
let result = new ResultCharacteristic();
let calculator = new bleno.PrimaryService({
uuid: WIFI_SERVICE_UUID,
characteristics: [
result,
argument1
]
});
bleno.setServices([calculator], err => {
if(err)
console.log(err);
else
console.log("Services configured");
});
});
// some diagnostics
bleno.on("stateChange", state => console.log(`Bleno: Adapter changed state to ${state}`));
bleno.on("advertisingStart", err => console.log("Bleno: advertisingStart"));
bleno.on("advertisingStartError", err => console.log("Bleno: advertisingStartError"));
bleno.on("advertisingStop", err => console.log("Bleno: advertisingStop"));
bleno.on("servicesSet", err => console.log("Bleno: servicesSet"));
bleno.on("servicesSetError", err => console.log("Bleno: servicesSetError"));
bleno.on("accept", clientAddress => console.log(`Bleno: accept ${clientAddress}`));
bleno.on("disconnect", clientAddress => console.log(`Bleno: disconnect ${clientAddress}`));
Can you guys help me where I am going wrong?
Thanks

Related

How to stop a function called infinitely?

I have this bunch of code which runs infinitely as it can be seen from the terminal img. How can I stop it? Delete function is assigned to a button so I don't know why it runs even though I didn't click that button.
//server.js
app.get("/getMaintenanceTypes",(req,res)=>{
pool.query(`Select * from maintenancetypes`, (err, result) => {
if(!err){
console.log("maintanencetypes", result.rows);
res.status(200).send(result.rows);
}else{
res.status(404).json(err.message)
console.log("maintanencetypes", err.message)
}
})
})
//main.js
const getMainTypes = async () => {
const response = await axios.get(`${serverBaseUrl}/getMaintenanceTypes`);
//console.log("response", response.data);
const response2 = [];
for (var i = 0; i < response.data.length; i++) {
let entry = {
id: null,
title: "",
description: "",
};
entry.id = response.data[i].id;
entry.title = response.data[i].title;
entry.description = response.data[i].description;
response2.push(entry);
//console.log("entry", entry);
}
console.log("RESPONSE2", response2);
return response2;
}
async function deleteAllMainTypes() {
try {
const resp = await axios.delete(
`${serverBaseUrl}/deleteAllMainTypes`
);
} catch (error) {
console.log(error);
}
const maintenanceList = await getMainTypes();
//console.log("main list", maintenanceList);
setMaintenanceList(maintenanceList);
};
const deleteHandler = () => {
deleteAllMainTypes();
}
<Button onClick={deleteHandler} >Delete All</Button>

Return empty array in Fastify handler with async/await function

I'm trying to make a web3 wallet with Moralis with Fasitify in back and VueJS in front.
(I would like to say that I already do this in web client (vuejs) and everything works well!)
In my back, I fetch all the asset from user. It works, I get them all well and I can send them back to the front
But I need to process/sort the data to recover only part of it and send it to the front to avoid doing too much treatment at the front and reduce your workload.
I do that :
*handlers/token.js*
const getTokenBalances = async () => {
let userTokens;
const options = {
chain: "bsc",
address: "0x935A438C29bd810c9aBa2F3Df5144d2dF4F3c0A0",
};
userTokens = await Moralis.Web3API.account.getTokenBalances(options);
return userTokens;
};
and if I return userTokens, I had it in Postman. But now, I do something like :
const getTokenBalances = async (tokens) => {
let userTokens;
let userBalances = [];
const options = {
chain: "bsc",
address: "0x935A438C29bd810c9aBa2F3Df5144d2dF4F3c0A0",
};
userTokens = await Moralis.Web3API.account.getTokenBalances(options);
userTokens.forEach((token) => {
if (
!token.name.match(/^.*\.io/) &&
!token.name.match(/^.*\.IO/) &&
!token.name.match(/^.*\.net/) &&
!token.name.match(/^.*\.Net/) &&
!token.name.match(/^.*\.com/) &&
!token.name.match(/^.*\.org/)
) {
getTokenPair(token).then((value) => {
if (value > 2) {
checkTokenPrice(token).then((price) => {
if (price > 0.001) {
userBalances.push(token);
}
});
}
});
}
});
userBalances.sort((a, b) => {
return b.total_value_usd - a.total_value_usd;
});
return userBalances;
};
userBalances its always empty in my response in Postman (And I don't understand why ?)
The getTokenPair function :
const getTokenPair = async (token) => {
const BNBTokenAddress = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"; //BNB
const options = {
token0_address: token.token_address,
token1_address: BNBTokenAddress,
exchange: "pancakeswapv2",
chain: "bsc",
};
try {
const pairAddress = await Moralis.Web3API.defi.getPairAddress(options);
let amount = 0;
//console.log("token pairAddress : " + pairAddress.pairAddress);
if (pairAddress.token1.symbol === "BUSD") {
try {
let reserve = await getPairReserves(pairAddress.pairAddress);
amount += reserve / 10 ** 18;
} catch (err) {
console.log("error getReservesBUSD : " + err);
}
}
if (pairAddress.token1.symbol === "WBNB") {
try {
let reserve = await getPairReserves(pairAddress.pairAddress);
amount += reserve / 10 ** 18;
} catch (err) {
console.log("error getReservesWBNB : " + err);
}
}
//console.log("amount : " + amount)
return amount;
} catch (err) {
console.log("error getPair : " + err);
}
};
and the checkTokenPrice function :
const checkTokenPrice = async (token) => {
let price;
const options = {
address: token.token_address,
chain: "bsc",
exchange: "PancakeSwapv2",
};
try {
const priceToken = await Moralis.Web3API.token.getTokenPrice(options);
price = priceToken.usdPrice.toFixed(7);
token.price = priceToken.usdPrice.toFixed(7);
token.balance = insertDecimal(token.balance, token.decimals);
token.total_value_usd = (token.balance * token.price).toFixed(2);
return price;
} catch (err) {
console.log("error tokenPrice : " + err);
}
};
They are await method in all the function I use so maybe there is a connection.
Thanks for you help !
**** EDIT *****
I solve my problem like this :
const getTokenBalances = async () => {
let userTokens;
let userBalances = [];
const options = {
chain: "bsc",
address: "0x935A438C29bd810c9aBa2F3Df5144d2dF4F3c0A0",
};
userTokens = await Moralis.Web3API.account.getTokenBalances(options);
for (token of userTokens) {
if (
!token.name.match(/^.*\.io/) &&
!token.name.match(/^.*\.IO/) &&
!token.name.match(/^.*\.net/) &&
!token.name.match(/^.*\.Net/) &&
!token.name.match(/^.*\.com/) &&
!token.name.match(/^.*\.org/)
) {
let value = await getTokenPair(token);
if(value > 2) {
let price = await checkTokenPrice(token);
if (price > 0.001) {
userBalances.push(token);
}
}
}
}
return userBalances;
};
Thanks for the help ! ;)

Javascript for of loop runs only once

I'm fetching data form a API and since I have to collect lots of data, I'm using the setTimeOut function to delay the requests by 3s each. But, when I try to run the code, the for loop only run once and finishes the program.
const fs = require('fs')
const { JSDOM } = require("jsdom")
const { window } = new JSDOM("")
const $ = require("jquery")(window)
const path = require('path')
const fetchArt = require('./utils/fetchArt.js')
const { data } = require('jquery')
const { resolve } = require('path')
let replacer = RegExp(' ', 'g')
let slash = RegExp('/', 'g')
const requestArtSongs = (artist) => {
return $.getJSON("https://www.vagalume.com.br/" + artist + "/index.js").then(
function (data) {
return data.artist.lyrics.item
}
)
}
const map = (lang) => {
switch (lang) {
case 1: return 'pt'
case 2: return 'en'
default: return lang
}
}
const requestMusic = (artist, song) => {
return $.getJSON(
"https://api.vagalume.com.br/search.php"
+ "?art=" + artist
+ "&mus=" + song
+ "&apikey={key}"
).then(function (data) {
return [data.mus[0].text, data.mus[0].lang]
})
}
const makeRequest = (art, songs) => {
songs.forEach((song, i) => {
delay(3000 * (i+1))
.then(() => makeSongRequest(art, song.desc))
})
}
const writeFile = (art, songName, mus) => {
gen = gens[0]
let music = {
artist: art,
song: {
name: songName,
text: mus[0],
lang: map(mus[1])
}
}
if (fs.existsSync(path.join(__dirname, 'Genders', gen, art))) {
fs.writeFile(path.join(__dirname, 'Genders', gen, art, `${songName.replace(slash, '')}.json`),
JSON.stringify(music, null, 4),
(err) => {
if (err) throw err
console.log('Song ' + songName + ' written!')
})
} else {
fs.mkdir(path.join(__dirname, 'Genders', gen, art), { recursive: true }, err => {
if (err) throw err
fs.writeFile(path.join(__dirname, 'Genders', gen, art, `${songName.replace(slash, '')}.json`),
JSON.stringify(music, null, 4),
(err) => {
if (err) throw err
console.log('Song ' + songName + ' written!')
})
})
}
}
const makeSongRequest = (art, songName) => {
requestMusic(art, songName)
.then(mus => {
writeFile(art, songName, mus)
})
}
const delay = t => new Promise (resolve => setTimeout(resolve, t))
const writeSongs = (artist) => {
art = artist.replace(replacer, '-').toLowerCase()
return new Promise(() => {
requestArtSongs(art)
.then((songs) => {
makeRequest(artist, songs)
})
})
}
const main = async () => {
let gens = ['Funk']
for (let gen of gens){
let arts = await fetchArt(gen)
for (let art of arts) {
await writeSongs(art)
}
}
}
main()
On my main function, I'm trying to fetch lyrics from the API. For each gender (in this case, only 'Funk') I get the artists that sing that gender. Then, for each artist I run the writeSongs function that does lots of stuff.
I'm using Node JS to do all the work.

Asynchronous indexedDB in a class object

I have written a tiny indexedDB library but dosen't seem to work as expected. So my question is how do i fix or properly reconstruct the code bellow to work as expected with a promise. I'm out of idea.
Although the add and delete method works in terms of successfully adding and deleting item from the database but the delete method won't signal it .then function
class IDB {
constructor(name, version) {
this.name = name;
this.version = version;
this.db = null;
}
open(callback) {
const req = window.indexedDB.open(this.name, this.version);
req.onupgradeneeded = (e) => {
let db = e.target.result;
callback(db);
}
req.onsuccess = (e) => {
this.db = e.target.result;
this.db.onversionchange = () => {
this.db.close();
console.log('Tell user to reload the page');
}
}
req.onerror = (e) => {
let db = e.target.errorCode;
return;
}
}
result(req) {
return new Promise((resolve, reject) => {
if (req) {
req.onsuccess = (e) => {
let res = e.target.result;
if (res) {
resolve(res);
}
};
req.onerror = (e) => {
let err = e.target.errorCode;
if (err) {
reject(err);
}
};
}
})
}
add(store, Items) {
let req;
let tx = this.db.transaction([store], 'readwrite').objectStore(store);
Items.forEach(item => {
req = tx.add(item);
});
return this.result(req);
}
get(store, key) {
let req = this.db.transaction([store], 'readonly')
.objectStore(store).get(key);
return this.result(req);
}
cursor(store) {
let req = this.db.transaction(store).objectStore(store)
.openCursor();
return this.result(req);
}
delete(store, key) {
let req = this.db.transaction([store], 'readwrite')
.objectStore(store).delete(key);
return this.result(req);
}
}
Usage
const employeeData = [
{ id: "00-01", name: "gopal", age: 35, email: "gopal#tutorialspoint.com" },
{ id: "00-02", name: "prasad", age: 32, email: "prasad#tutorialspoint.com" }
];
const idb = new IDB('mydb', 1);
idb.open((db) => {
if (!db.objectStoreNames.contains('user')) {
db.createObjectStore('user', {keyPath: 'id'});
}
});
idb.add('user', employeeData).then(() => alert('Items added')).catch(() => alert('failed'));
But I would prefer the usage with the async/await code
await idb.add('..', ..) // blah blah

Getting TypeError: FabricUserControllers is not a constructor which can not be catch

I am new to node.js and Javascript.
I have two javascript files "FabricUserController.js" and "UserController.js". So I have create the class in "FabricUserController.js" and export it into "UserController.js".
I am integrate the GetAll fucntion of "FabricUserController.js" to "UserController.js" in GetAllProduce fucntion.
I am trying run the below code however its giving me "TypeError: FabricUserControllers is not a constructor" error which is not handle in try catch{} block
Please see below code
let FabricUserControllers3 = require("./FabricUserController");
GetAllProduce: function (req, res, next) {
try{
let output = {};
var resArray = new Array();
let VZID = req.body.username;
console.log('test', 'GetAllProduce')
console.log('USername', VZID)
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
let connError = new Error(500, "Error connecting to TEST database", err);
res.status(connError.status).json(connError);
} else {
let query = {};
client.db(config.Database.TEST.dbName).collection("Produce").find(query).toArray(function (err, response) {
console.log(response);
if (err) {
let roleError = new Error(500, "Error getting Produce information", err);
res.status(500).json(roleError);
} else if (response.length > 0) {
//DO someting here
//FabricUserControllers3 = {};
FabricUserControllers3 = new FabricUserControllers();// getting issue here
FabricUserControllers3.GetAll((VZID), (response) => {
console.log("data result", result)
res.status(200).json(response);
client.close();
})
} else {
output.message = "Produce doesn't exist";
res.status(409).json(output);
client.close();
}
});
}
});
}catch(e){
if (e instanceof TypeError){
console.log('error1', e.message);
printError(e,true);
}else{
console.log("error2", e.message);
printError(e, false);
}
}
},
FabricUserController.js
'use strict';
const {
FileSystemWallet,
Gateway
} = require('fabric-network');
const fs = require('fs');
const path = require('path');
var MongoClient = require('mongodb').MongoClient;
var Client = require('node-rest-client').Client;
var client = new Client();
const configPath = path.resolve(__dirname, '..', 'config', 'Config.json');
const configJSON = fs.readFileSync(configPath, 'utf8');
const config1 = JSON.parse(configJSON);
var connection_file = config1.connection_file;
var appAdmin = config1.appAdmin;
var gatewayDiscovery = config1.gatewayDiscovery;
var appAdminSecret = config1.appAdminSecret;
var orgMSPID = config1.orgMSPID;
var caName = config1.caName;
const ccpPath = path.resolve(__dirname, '..', 'config', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);
let response = {};
class FabricUserControllers {
constructor() {
console.log("constructer called")
}
async ProduceRegistration(Username, produceid, callback) {
// Create a new file system based wallet for managing identities.
try {
const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
setTimeout(() => {
cb();
resolve();
}, timeout);
});
let query2 = {}
query2.PRODUCEID = produceid;
// console.log('PRODUCEID',produceid)
var PRODUCE = {};
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
console.log('Username', Username)
// Check to see if we've already enrolled the user.
const userExists = await wallet.exists(Username);
if (!userExists) {
console.log('An identity for the user: ' + Username + ' does not exist in the wallet');
console.log('call the registerUser before retrying');
response.data = null;
response.httpstatus = 400;
response.message = `An identity for the ${Username} does not exist in the wallet`;
return response;
}
// Create a new gateway for connecting to our peer node.
const gateway = new Gateway();
await gateway.connect(ccpPath, {
wallet,
identity: Username,
discovery: {
enabled: false,
asLocalhost: true
}
});
///
MongoClient.connect(config.Database.TEST.connectString, function (err, client) {
if (err) {
// let connError = new Error(500, "Error connecting to TEST database", err);
response.data=null;
response.httpstatus = 500;
response.message = "Error connecting to TEST database :" + err;
// res.status(connError.status).json(connError);
return response;
} else {
client.db(config.Database.TEST.dbName).collection("Produce").find(query2).toArray(function (err, docs) {
if (err) {
response.httpstatus = 500;
response.message = "Error with DB :" + err;
return response;
}
else{
console.log("blockchain_status", docs[0].blockchain_status)
console.log('Role name DB',docs);
console.log('Role name DB1',docs[0]);
if(docs[0].STATUS)
PRODUCE.produceid = docs[0].PRODUCEID;
PRODUCE.produceName = docs[0].PRODUCE;
PRODUCE.farmLocation = docs[0].FARMLOCATION;
PRODUCE.plantingDate = docs[0].PLANTINGDATE;
PRODUCE.harvestDate = docs[0].HARVESTDATE;
PRODUCE.status = docs[0].STATUS;
PRODUCE.produceQuantites = docs[0].VARIETY;
PRODUCE.gapInfo = docs[0].GAP;
PRODUCE.farmerID = docs[0].farmerID;
console.log('Produce', PRODUCE);
const doStuffAsync = async () => {
setAsyncTimeout(async () => {
// Get the network (channel) our contract is deployed to.
const network = await gateway.getNetwork('dfarmchannel');
// Get the contract from the network.
const contract = network.getContract(config1.chaincodeName);
var args = JSON.stringify(PRODUCE)
console.log("type of arg", typeof (args));
// Submit the specified transaction.
// console.log('produceID', args.produceID);
if(args==null || args==''){
console.log('Server not responding please try again');
}else
{
const result = await contract.submitTransaction('ProduceRegistration', args);
var argsJson = JSON.parse(result)
// console.log('result', argsJson)
// console.log('result1', result)
if(argsJson.produceID !="" && argsJson.produceID !=null && argsJson.produceID !="undefined" && argsJson.produceID !=undefined){
// // return false;
response.data = result
response.httpstatus = 200;
response.message = `Transaction has been submitted ansd successfull with Result :${result}`;
return callback(response);
// console.log('result before', response);
// console.log('Transaction has been submitted ansd successfull with Result :' + result);
}else{
console.log('blockchain server not responed')
// return false
response.httpstatus = 500;
response.message = `Please enter produce ID :`;
return response;
}
}
}, 4000);
};
doStuffAsync();
}
client.close();
})
}
})
await gateway.disconnect();
}
catch (error) {
// if(error) throw error;
response.error = error;
response.httpstatus = 500;
response.message = "Failed to enroll admin due to above error";
return response;
}
};
}
module.exports = FabricUserControllers;
#Abhirock, on your main file you have:
let FabricUserControllers3 = require("./FabricUserController");
FabricUserControllers3 = new FabricUserControllers();// getting issue here
You are trying to override FabricUserControllers3 creating a new object FabricUserControllers but you are not importing it. Try next solution to see if it solves your problem:
const FabricUserController = require("./FabricUserController");
const fabricUserControllers3 = new FabricUserController();
Hope it helps :))

Categories

Resources