Failed to subscribe to multiple topics(connection gets interupted) - javascript
I wanted to get the message from mutiple topics but the connection gets interupted as when i recieve the message and publish the message, byitself it publishes the same message which i had published in the before rather than my own message to the client. Btw this code is to find the missing packet that is being recieved by the client and it publishes back the missing packet in the format(1,first_packet - lastpacket). the published message that is sent to the client is sent back to the subscriber without any acknoledgement
can anyone figure out why this code gets interupted as when i try to subscribe to multiple topic and this code get exited when it gets the same published message
//importing heading files
var mqtt = require('mqtt'); // to import mqtt
const mongoose = require("mongoose"); // to import mongoose
const Data = require('./models/data'); // to import the models data
const TopicT = require("./models/topict");
const Topic = require("./models/topic");
const Packets = require("./models/packets");
const TopicS = require("./models/topics");
const TopicK = require("./models/topick");
var ObjectId = require('mongodb').ObjectID;
//packet module
temp_sum = 0
new_sum = 0
const packetfind = require('./packetfind');
var count = 0;
alphas = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
mongoose
// .connect("mongodb+srv://blackfrog:blackfrog#cluster0.pxmd1.mongodb.net/emvolio", {
.connect("mongodb://127.0.0.1:27017/eagleeye", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => {
console.log("Database is Connected");
})
.catch((err) => {
console.log(err);
});
options = {
username: "000000",
password: "password",
clean: true
};
//Mqtt Connections
var client = mqtt.connect("mqtt://localhost:1883", options);
// var client = mqtt.connect("mqtt://15.207.2.27:1883", options);
client.on("connect", function () {
console.log("mqtt connected");
});
client.on('message', async function (topic, message, packet) {
console.log("message is " + message);
console.log("topic is " + topic);
var topic_arr = topic.split('/');
var fullPacket = message.toString().split(';');
var message_arr = fullPacket[0].toString().split(',');
var netConArr = fullPacket.shift();
netConArr = [];
if (fullPacket) {
for (let i = 0; i <= fullPacket.length; i++) {
if (fullPacket[i]) {
var net = fullPacket[i].toString().split(',');
netConArr.push({ "network": net[0], "mcc": net[1], "mnc": net[2], "loc": net[3], "cellid": net[4] });
}
}
}
var re = /:/gi;
var con = /(\w+)\s(\w+)/;
var interMedDt = message_arr[1].replace(re, " ");
interMedDt = interMedDt.replace(con, "$2 $1");
var datTimes = new Date(interMedDt);
await datTimes.setHours((message_arr[2].split()[0]).split(':')[0]);
await datTimes.setMinutes((message_arr[2].split()[0]).split(':')[1]);
await datTimes.setSeconds((message_arr[2].split()[0]).split(':')[2]);
var timeZone;
if (message_arr[22]) {
timeZone = Number(15 * message_arr[22]);
} else {
timeZone = Number(15 * 22);
}
var latitude;
var longitude;
//console.log(timeZone,message_arr[22], datTimes)
datTimes = await new Date(datTimes.setMinutes(datTimes.getMinutes() - timeZone));
//console.log(topic_arr, message_arr);
const id = await Data.find({ id: topic_arr[0] }).then((data) => {
return data;
}).catch(err => {
console.log(err);
});
//console.log("data was successfully recived");
//console.log("id:",id);
//Receiving Data
var count_data = 0;
switch (topic_arr[1]) {
case 'T':
const new_packet = await {
lastupdatedTime: new Date(),
packet_number: message_arr[0],
dateTime: new Date(datTimes),
date: message_arr[1],
time: message_arr[2],
temp1: message_arr[3],
temp2: message_arr[4],
temp3: message_arr[5],
battery_charge: message_arr[6],
latitude: message_arr[7],
longitude: message_arr[8],
setpoint: message_arr[9],
lid_open: message_arr[10],
battery_temp: message_arr[11],
hs_heatsink: message_arr[12],
cs_heatsink: message_arr[13],
ntc_main_board: message_arr[14],
pid_value: message_arr[15],
average_voltage: message_arr[16],
charging_indicator: message_arr[17],
fan_lock: message_arr[18],
network_status: message_arr[19],
password: message_arr[20],
average_temp: message_arr[21],
time_zone: message_arr[22],
ntc_voltage_board_temp1: message_arr[23],
ntc_voltage_board_temp2: message_arr[24],
ntc_charging_board_temp1: message_arr[25],
ntc_charging_board_temp2: message_arr[26],
warning_status: message_arr[27],
imei_number: message_arr[28],
networkConnection: netConArr,
};
// packets
// console.log(new_packet)
var loc = await TopicT.find(
{ id: ObjectId(id[0]._id) },
{ last_latitude: 1, last_longitude: 1 }
);
console.log(loc);
if (Number(message_arr[7]) && Number(message_arr[8])) {
latitude = message_arr[7];
longitude = message_arr[8];
} else {
latitude = loc[0].last_latitude;
longitude = loc[0].last_longitude;
}
if (new Date(new_packet.lastupdatedTime) >= new Date(new_packet.dateTime)) {
await TopicT.updateOne({ id: ObjectId(id[0]._id) }, { last_latitude: latitude, last_longitude: longitude, packets: new_packet })
.then((data) => console.log(data))
.then((data) => console.log("data was successfully added to the topic collection"))
.catch((err) => console.log(err));
new_packet.id = ObjectId(id[0]._id);
const packets = new Packets(new_packet);
//console.log("Fullpacket", new_packet);
//test case1: first packet\
if (count == 0) {
temp_packet = new_packet.packet_number;
}
else {
great_check = 0
count_temp = 0
count_packet = 0
// for (i =0; i<temp_packet.length; i+=1)
// {
// if (temp_packet[i] == "0")
// {
// count_temp += 1;
// }
// if (new_packet.packet_number[i] == "0")
// {
// count_packet += 1;
// }
// }
// if count_temp >
var first = parseInt(temp_packet, 36);
var end = parseInt(new_packet.packet_number, 36);
if (first > end )
{
break;
}
if ((alphas.indexOf(new_packet.packet_number[4]) != (alphas.indexOf(temp_packet[4]) + 1)) && (great_check == 0)) {
console.log("packet INDEXis "+new_packet.packet_number);
console.log("temp INDEX is "+temp_packet);
value = packetfind.packetfind(new_packet.packet_number, temp_packet);
console.log("value is " +value)
temp_packet = new_packet.packet_number;
console.log("temp_packet", temp_packet, "value[1]", value[1], "value[2]", value[2],);
if (value[0] == 1) {
var interval = setInterval(function () {
let pub_topic = topic_arr[0] + '/R';
let pubmessage = 1 + ',' + value[1] + '-' + value[2] + ';';
console. log("pub", pubmessage);
let pub_options = { qos: 0, retain: false };
client.publish(pub_topic, pubmessage, pub_options, function (err) {
if (err) {
console.log("An error occurred during publish");
} else {
console.log("Published successfully");
value.splice(0, value.length);
}
});
}, 10000);
setTimeout(function () {
clearInterval(interval);
}, 10000);
break;
}
}
else{
if (great_check == 0)
{
temp_packet = new_packet.packet_number;
}
}
}
count = count + 1;
//console.log("temp packet number", temp_packet) ;
await packets.save()
.then((data) => console.log(data))
.catch((err) => console.log(err));
break;
}
else {
break;
}A
case 'K':
const k_packet = await {
lastupdatedTime: new Date(),
packet_number: message_arr[0],
date: message_arr[1],
time: message_arr[2],
vacc_recipient_name: message_arr[3],
recipient_id: message_arr[4],
recipient_dob: message_arr[5],
vacc_name: message_arr[6],
manufacture_date: message_arr[7],
vacc_batch: message_arr[8],
remarks: message_arr[9],
variant: message_arr[10],
};
k_packet.id = ObjectId(id[0]._id);
const packetK = new TopicK(k_packet);
k_packet.save()
.then((data) => console.log(data))
.then((data) => console.log("data was successfully added to the topicK collection"))
.catch((err) => console.log(err));
break;
case 'S':
const s_packet = new TopicS({
id: id[0]._id,
packet_number: message_arr[0],
imei: message_arr[1],
lid_opening: message_arr[2],
});
s_packet.save()
.then((data) => console.log(data))
.catch((err) => console.log(err));
break;
default:
break;
}
});
client.on("error", function (error) {
console.log("Can't connect" + error);
process.exit(1);
});
client.subscribe("#", { qos: 1 });
Related
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 ! ;)
Firebase cloud messaging sendToDevice works properly but sendMulticast fails for the same list of tokens
For certain types of messages, I want to target users by FIRTokens vs topic, which are stored in my real-time database. I load these tokens with async/await and then decide if I want to send notifications to a topic vs a smaller list of users. The data loading code works as expected. But what's odd is that if I use .sendMulticast(payload), the notifications fail for all tokens in the list. On the other hand if I use .sendToDevice(adminFIRTokens, payload) the notification goes successfully to all my users. Right now my list has 2 tokens and with sendMulticast I have 2 failures and with sendToDevice I have 2 successes. Am I missing the point of what sendMulticast is supposed to do? According to the docs: Send messages to multiple devices: The REST API and the Admin FCM APIs allow you to multicast a message to a list of device registration tokens. You can specify up to 500 device registration tokens per invocation. So both should logically work. Then why does one fail and the other work? In fact with sendToDevice I get a multicastId in the response! Here are some console outputs: sendToDevice: Sent filtered message notification successfully: { results: [ { messageId: '0:1...45' }, { messageId: '16...55' } ], canonicalRegistrationTokenCount: 0, failureCount: 0, successCount: 2, multicastId: 3008...7000 } sendMulticast: List of tokens that caused failures: dJP03n-RC_Y:...MvPkTbuV,fDo1S8jPbCM:...2YETyXef Cloud function to send the notification: functions.database .ref("/discussionMessages/{autoId}/") .onCreate(async (snapshot, context) => { // console.log("Snapshot: ", snapshot); try { const groupsRef = admin.database().ref("people/groups"); const adminUsersRef = groupsRef.child("admin"); const filteredUsersRef = groupsRef.child("filtered"); const filteredUsersSnapshot = await filteredUsersRef.once("value"); const adminUsersSnapshot = await adminUsersRef.once("value"); var adminUsersFIRTokens = {}; var filteredUsersFIRTokens = {}; if (filteredUsersSnapshot.exists()) { filteredUsersFIRTokens = filteredUsersSnapshot.val(); } if (adminUsersSnapshot.exists()) { adminUsersFIRTokens = adminUsersSnapshot.val(); } const topicName = "SpeechDrillDiscussions"; const message = snapshot.val(); const senderName = message.userName; const senderCountry = message.userCountryEmoji; const title = senderName + " " + senderCountry; const messageText = message.message; const messageTimestamp = message.messageTimestamp.toString(); const messageID = message.hasOwnProperty("messageID") ? message.messageID : undefined; const senderEmailId = message.userEmailAddress; const senderUserName = getUserNameFromEmail(senderEmailId); const isSenderFiltered = filteredUsersFIRTokens.hasOwnProperty( senderUserName ); var payload = { notification: { title: title, body: messageText, sound: "default", }, data: { messageID: messageID, messageTimestamp: messageTimestamp, }, }; if (isSenderFiltered) { adminFIRTokens = Object.values(adminUsersFIRTokens); // payload.tokens = adminFIRTokens; //Needed for sendMulticast return ( admin .messaging() .sendToDevice(adminFIRTokens, payload) // .sendMulticast(payload) .then(function (response) { if (response.failureCount === 0) { console.log( "Sent filtered message notification successfully:", response ); } else { console.log( "Sending filtered message notification failed for some tokens:", response ); } // if (response.failureCount > 0) { // const failedTokens = []; // response.responses.forEach((resp, idx) => { // if (!resp.success) { // failedTokens.push(adminFIRTokens[idx]); // } // }); // console.log( // "List of tokens that caused failures: " + failedTokens // ); // } return true; }) ); } else { payload.topic = topicName; return admin .messaging() .send(payload) .then(function (response) { console.log("Notification sent successfully:", response); return true; }); } } catch (error) { console.log("Notification sent failed:", error); return false; } });
I think it's an issue of using a different payload structure. This is the old one (without iOS specific info): var payload = { notification: { title: title, body: messageText, sound: "default", }, data: { messageID: messageID, messageTimestamp: messageTimestamp, }, }; Whereas this is the new version (apns has iOS specific info) var payload = { notification: { title: title, body: messageText, }, data: { messageID: messageID, messageTimestamp: messageTimestamp, }, apns: { payload: { aps: { sound: "default", }, }, }, }; With the new structure, both send and sendMulticast are working properly. Which would fail to send or give errors like apns key is not supported in payload. The new function: functions.database .ref("/discussionMessages/{autoId}/") .onCreate(async (snapshot, context) => { // console.log("Snapshot: ", snapshot); try { const groupsRef = admin.database().ref("people/groups"); const adminUsersRef = groupsRef.child("admin"); const filteredUsersRef = groupsRef.child("filtered"); const filteredUsersSnapshot = await filteredUsersRef.once("value"); const adminUsersSnapshot = await adminUsersRef.once("value"); var adminUsersFIRTokens = {}; var filteredUsersFIRTokens = {}; if (filteredUsersSnapshot.exists()) { filteredUsersFIRTokens = filteredUsersSnapshot.val(); } if (adminUsersSnapshot.exists()) { adminUsersFIRTokens = adminUsersSnapshot.val(); } // console.log( // "Admin and Filtered Users: ", // adminUsersFIRTokens, // " ", // filteredUsersFIRTokens // ); const topicName = "SpeechDrillDiscussions"; const message = snapshot.val(); // console.log("Received new message: ", message); const senderName = message.userName; const senderCountry = message.userCountryEmoji; const title = senderName + " " + senderCountry; const messageText = message.message; const messageTimestamp = message.messageTimestamp.toString(); const messageID = message.hasOwnProperty("messageID") ? message.messageID : undefined; const senderEmailId = message.userEmailAddress; const senderUserName = getUserNameFromEmail(senderEmailId); const isSenderFiltered = filteredUsersFIRTokens.hasOwnProperty( senderUserName ); console.log( "Will attempt to send notification for message with message id: ", messageID ); var payload = { notification: { title: title, body: messageText, }, data: { messageID: messageID, messageTimestamp: messageTimestamp, }, apns: { payload: { aps: { sound: "default", }, }, }, }; console.log("Is sender filtered? ", isSenderFiltered); if (isSenderFiltered) { adminFIRTokens = Object.values(adminUsersFIRTokens); console.log("Sending filtered notification with sendMulticast()"); payload.tokens = adminFIRTokens; //Needed for sendMulticast return admin .messaging() .sendMulticast(payload) .then((response) => { console.log( "Sent filtered message (using sendMulticast) notification: ", JSON.stringify(response) ); if (response.failureCount > 0) { const failedTokens = []; response.responses.forEach((resp, idx) => { if (!resp.success) { failedTokens.push(adminFIRTokens[idx]); } }); console.log( "List of tokens that caused failures: " + failedTokens ); } return true; }); } else { console.log("Sending topic message with send()"); payload.topic = topicName; return admin .messaging() .send(payload) .then((response) => { console.log( "Sent topic message (using send) notification: ", JSON.stringify(response) ); return true; }); } } catch (error) { console.log("Notification sent failed:", error); return false; } });
Aws SDK In lambda function
I am working on lambda function and creating a method for AWS-SDK historical metric report using node, js and I am getting the following errors. Have look at a SS of error here is my code function getKeyByValue(object, value) { return Object.keys(object).find(key => object[key] === value); } exports.handler = async (event) => { const AWS = require('aws-sdk'); var connect = new AWS.Connect({ apiVersion: '2017-08-08' }); let queueARN = event.queueARN || null; const connectInstanceId = process.env.instanceID; let flag =0, nextToken = null; let queueARNsObject = {}, queueARNsArray=[], queueTypeObject={}; do{ let listQueuesParams = { InstanceId: connectInstanceId, /* required */ QueueTypes: [ "STANDARD", ], NextToken: nextToken, }; let listQueuesPromise = connect.listQueues(listQueuesParams).promise(); listQueuesResult = await listQueuesPromise; // console.log(listQueuesResult); listQueuesResult.QueueSummaryList.forEach(queue => { if(queueARN != null){ if (queue.Arn == queueARN){ queueARNsArray = [queue.Arn]; queueARNsObject[queue.Name]= queue.Arn; queueTypeObject[queue.QueueType]= queue.Arn; flag = 1; return; } }else{ queueARNsObject[queue.Name]= queue.Arn; queueTypeObject[queue.QueueType]= queue.Arn; queueARNsArray.push(queue.Arn); nextToken = listQueuesResult.NextToken; } }); }while (flag=0 && nextToken != null); const HistoricalMetricsList = [ { Name : 'CONTACTS_HANDLED', Unit : 'COUNT', Statistic : 'SUM' }, { Name : 'CONTACTS_ABANDONED', Unit : 'COUNT', Statistic : 'SUM' }, ]; // Metrics params var getHistoricalMetricsParams = { InstanceId: connectInstanceId, StartTime: 1592993700, EndTime: 1593039900, Filters: { Channels: ["VOICE"], Queues: queueARNsArray }, HistoricalMetrics: HistoricalMetricsList, Groupings: ["QUEUE"] }; // get current metrics by queues var getHistoricalMetricsPromise = connect .getMetricData(getHistoricalMetricsParams) .promise(); var getHistoricalMetricsResult = await getHistoricalMetricsPromise; // console.log("current |||||||| 1 metrics:", JSON.stringify(getCurrentMetricsResult)); let queueMetricsArray = []; if(getHistoricalMetricsResult.MetricResults.length){ getHistoricalMetricsResult.MetricResults.forEach(queue => { let queueMetrics = { "Queue_Name" : getKeyByValue(queueARNsObject ,queue.Dimensions.Queue.Arn), "CallsHandled": queue.Collections[0].Value , "CallsAbanoded": queue.Collections[1].Value , } queueMetricsArray.push(queueMetrics); console.log("TYPE||||", getKeyByValue(queueTypeObject ,queue.Dimensions.Queue.Arn)) }); }else{ keys.forEach(key => { let queueMetrics = { "Queue_Name" : getKeyByValue(event ,queue.Dimensions.Queue.Arn), "CONTACTS_HANDLED": 0, "CONTACTS_ABANDONED": 0 } queueMetricsArray.push(queueMetrics); }) } const response = { responseCode: 200, metricResults: queueMetricsArray }; return response; }; I don't have any idea what this is an error about. if anyone of you knows please help me to fix it Thanks. i've done the same thing with Real-Time Metric report and that is running perfectly
cannot write to a characteristic WebBLE
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
Redis how node return True in function async/await
forgive me the question. I'm not used to node and sync / await I have the following function which queries a mongodb returning a json, I'm saving that return on redis. So far so good. findLightnings: async (request, h) => { const q = request.query.q.split(':'); const index = q[0]; const value = q[1].split(','); const dateInit = new Date(request.query.dateInit); const dateEnd = new Date(request.query.dateEnd); const page = request.query.page; const distance = request.query.distance; const redis = require('redis'); const client = redis.createClient(); let limit = 300; let filter = { $and: [{ data: { $gte: dateInit.toISOString(), $lte: dateEnd.toISOString() } }] } if (index === 'latlng') { filter['$and'][0]['geo.coordinates'] = { $near: { $geometry: { type: 'Point', coordinates: value.map(Number), $minDistance: 0, $maxDistance: distance } } } limit = 100; } else { filter['$and'][0][`cidade.${index}`] = { $in: value } } return client.get('elektro', async (err, reply) => { let resp = null; if (reply) { console.log(reply); //<<<<<<<< Return Json OK resp = reply // <<<<<<<<<< Return TRUE in json's place } else { console.log('db') const query = await Lightning.find(filter).sort('data').skip(page*limit).limit(limit).exec(); client.set('elektro', JSON.stringify(query)); client.expire('elektro', 3600); resp = query } return JSON.stringify(resp); }) } The problem is time to recover this data from the redis. In the console log json appears normal, how much tento returns that value for the main function it comes 'TRUE' and not the json saved in redis. Someone can give me a helping hand on this. I really need this function.
const redis = require('redis'); const client = redis.createClient(6379); const bluebird = require("bluebird"); bluebird.promisifyAll(redis.RedisClient.prototype); bluebird.promisifyAll(redis.Multi.prototype); const redisdata = await client.getAsync("user:photos"); if (redisdata) { console.log(`cache EXISTS`) return res.json({ source: 'cache', data: JSON.parse(redisdata) }) }
I was able to solve the problem with the redis client.getAsync(). which already has a native async function: source: Node-redis The final code is as follows: findLightnings: async (request, h) => { const q = request.query.q.split(':'); const index = q[0]; const value = q[1].split(','); const dateInit = new Date(request.query.dateInit); const dateEnd = new Date(request.query.dateEnd); const page = request.query.page; const distance = request.query.distance; let limit = 300; let filter = { $and: [{ data: { $gte: dateInit.toISOString(), $lte: dateEnd.toISOString() } }] } if (index === 'latlng') { filter['$and'][0]['geo.coordinates'] = { $near: { $geometry: { type: 'Point', coordinates: value.map(Number), $minDistance: 0, $maxDistance: distance } } } limit = 100; } else { filter['$and'][0][`cidade.${index}`] = { $in: value } } return getAsync('findLightnings'+ '/' + request.query.q + '/' + request.query.dateInit + '/' + request.query.dateEnd).then(async (res) => { if(res){ console.log('Fonte Dados => redis') return res }else{ console.log('Fonte Dados => db') try { const query = await Lightning.find(filter).sort('data').exec();//.skip(page*limit).limit(limit).exec(); client.set('findLightnings'+ '/' + request.query.q + '/' + request.query.dateInit + '/' + request.query.dateEnd, JSON.stringify(query)); return query; } catch (err) { return Boom.badData(err); } } client.close(); }); },