Google Cloud IoT sendCommandToDevice node.js sends command but catches error - node.js

I have this in Google's App Engine (node.js).
My device gets all the commands but I still get the Could not send command. Is the device connected? error.
BTW, already tried this: Await for function before end()
And same result.
Trying to follow this example BTW:
https://cloud.google.com/nodejs/docs/reference/iot/0.2.x/v1.DeviceManagerClient#sendCommandToDevice
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
var urlencodedParser = bodyParser.urlencoded({
extended: false
})
const iot = require('#google-cloud/iot');
app.get('/', urlencodedParser, (req, res) => {
res.setHeader('Content-Type', 'application/json');
const projectId = req.query.proyecto;
const cloudRegion = req.query.region;
const registryId = req.query.registro;
const numSerie = req.query.numSerie;
const command = req.query.command;
const client = new iot.v1.DeviceManagerClient();
if (client === undefined) {
console.log('Did not instantiate client.');
} else {
console.log('Did instantiate client.');
sendCom();
}
async function sendCom() {
const formattedName = client.devicePath(projectId, cloudRegion, registryId, numSerie)
const binaryData = Buffer.from(command);
const request = {
name: formattedName,
binaryData: binaryData,
};
return client.sendCommandToDevice(request).then(responses => res.status(200).end(JSON.stringify({
data: OK
}))).catch(err => res.status(404).end('Could not send command. Is the device connected?'));
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
On my end I should get status 200 and OK but it doesn't happen.

Related

node-scheduler to send response from node REST API

I am working with node REST API. I need to send 2 different responses from single API. So I am sending first response from API as res.send(). Then I am using node-schedule to send remaining 1 response after some time using node-fetch.
But failing when using fetch from node-schedule. fetch is going to catch block directly.
require('dotenv').config();
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const schedule = require('node-schedule');
const rule = new schedule.RecurrenceRule();
rule.second = new schedule.Range(0,59,20);
const subscriptionRouter = express.Router();
const port = process.env.NODE_APP_PORT || 3000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', subscriptionRouter);
app.listen(port, () => {
console.log(`Running on port ${port}`);
});
var reqComing = {};
subscriptionRouter.route('/subscriptions')
.post((req, res) => {
reqComing = {...req.body};
let responseJSON = {};
// msgId will be having some random generated value
if(msgId ==""){
responseJSON.statusCode = 400;
responseJSON.statusDesc = "Bad Request";
responseJSON.msgId = msgId;
}
else{
responseJSON.statusCode = 200;
responseJSON.statusDesc = "Posted";
responseJSON.msgId = msgId;
}
res.send(responseJSON);
})
if(JSON.stringify(reqComing) === '{}'){
schedule.scheduleJob(rule,function(){
let objectToBeSent = {someData};
fetch('URl where to send response',
{
method: 'post',
body: JSON.stringify(objectToBeSent),
headers: {'Content-Type': 'application/json'}
})
.then(res => console.log(res.text()))
.catch(err => console.log("Error while sending response", err));
});
}

export a function inside socket connection

I have created a socket server as shown below.
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server, {cors:{origin:'*'}})
const mongoose= require("mongoose")
const port = process.env.PORT || 4002;
server.listen(port, ()=>{
console.log(`Listening on port ${port}......`)
})
onlineUsers = [];
const addNewUser = (userId, socketId)=>{
!onlineUsers.some((user)=>user.userId === userId) &&
onlineUsers.push({userId,socketId})
}
const removeUser= (socketId) =>{
onlineUsers = onlineUsers.filter((user)=> user.socketId!==socketId)
}
const getUser = (userId)=>{
return onlineUsers.find(user=>user.userId ===userId)
}
io.on("connection", (socket=> {
console.log("User connected:", socket.id);
socket.on("disconnect",()=>{
removeUser(socket.id)
})
socket.on("newUser",(userId)=>{
addNewUser(userId, socket.id)
})
export function handleMessaging (userId,clientID,messageId )
{
const receiver = getUser(userId);
if(receiver)
{
io.to(receiver.socketId).emit("sendMessage", {data:"working properly"});
return true;
}
else return false
}
}));
I want to export the function handle messaging so that I can use it inside the API like (shown below) to see if a user is online and if yes, send a message.
But as someone new to programming, I can't figure out how to export handle messaging the proper way. I tried to use export but its telling me "Modifiers cannot appear here".
router.post('/:companyId' async (req, res) => {
const {userId,clientId,messageId} = req.body
handleMessaging (userId,clientID,messageId )
{
//do xyz
}
}

Send a CORS request to Localhost from an electron application

I'm working on a project that involves an application built with Electron that interfaces with an express server, running on Localhost or the home network.
Problem right now is, I'm having trouble getting the server to acknowledge any requests from the application.
Here is my front end logic in the electron application:
let ipAddress;
let port;
let requestAddress;
function connect(){
const ipField = document.getElementById("nu-ip").value;
const portField = document.getElementById("nu-port").value;
port = portField;
if (ipField === "") {
ipAddress = 'localhost';
} else {
ipAddress = ipField;
}
port = portField;
if(port === ""){
requestAddress = `http://$(ipAddress)`;
} else {
requestAddress = `http://${ipAddress}:${port}`;
};
alert(requestAddress);
const request = newXMLHttpRequest();
alert(requestAddress);
request.open("GET",`${requestAddress}/connect`).send();
request.onReadyStateChange = (res) => {
alert(res);
}
}
function startup() {
console.log('Hey where does this show up?')
const NuToggle = document.getElementById("NuHelper-enable");
const NuTools = document.getElementById("Nu-tools");
const connectButton = document.getElementById("connect-button");
NuToggle.addEventListener("change", (event) => {
if(event.target.value === 'enable'){
//alert("NuHelper has been enabled");
NuTools.style.display='block';
connectButton.addEventListener('click', connect);
}
})
}
window.onload = startup;
And here is my server:
//require in our basic dependencies
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const errorHandler = require('errorhandler');
const cors = require('cors');
const PORT = 80;
const app = express();
app.use(morgan('dev'));
app.use(bodyParser);
app.use(errorHandler);
app.use(cors());
app.get('/connect',(req, res, next) => {
res.sendStatus(200);
})
app.listen(PORT, () => {
console.log(`Nu is listening on PORT ${PORT}`);
})
I put 80 into the PORT input and it'll alert "http://localhost:80", but it'll get no response at all from the server, and my logging middleware won't acknowledge that it received any request at all, which makes me think that I'm sending the request to the wrong address. Thanks in advance to anyone who understands how to solve this!

Await for function before end()

edit: added a bit more code.
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
var urlencodedParser = bodyParser.urlencoded({extended: false})
const {google} = require('googleapis');
const {PubSub} = require('#google-cloud/pubsub');
const iot = require('#google-cloud/iot');
const API_VERSION = 'v1';
const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
app.get('/', urlencodedParser, (req, res) => {
const projectId = req.query.proyecto;
const cloudRegion = req.query.region;
const registryId = req.query.registro;
const numSerie = req.query.numSerie;
const command = req.query.command;
const client = new iot.v1.DeviceManagerClient();
if (client === undefined) {
console.log('Did not instantiate client.');
} else {
console.log('Did instantiate client.');
sendCom();
}
async function sendCom() {
const formattedName = await client.devicePath(projectId, cloudRegion, registryId, numSerie)
const binaryData = Buffer.from(command);
const request = {
name: formattedName,
binaryData: binaryData,
};
return client.sendCommandToDevice(request).then(responses => res.status(200).send(JSON.stringify({
data: OK
}))).catch(err => res.status(404).send('Could not send command. Is the device connected?'));
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
I have this function, that I call after the client initiate: sendCom();
async function sendCom() {
const formattedName = await client.devicePath(projectId, cloudRegion, registryId, deviceId)
const binaryData = Buffer.from(command);
const request = { name: formattedName, binaryData: binaryData, };
client.sendCommandToDevice(request)
.then(responses => {
res.status(200).send(JSON.stringify({ data: OK })).end();
})
.catch(err => {
res.status(404).send('Could not send command. Is the device connected?').end();
});
}
My problem is that sendCommandToDevice gets executed perfectly, however I get the catch error.
As I understand it, it's because in the .then ends the connection.
I've looked at this and thats's what I tried, however I'm not sure I understand what's going on.
You can not use send with end.
end() is used when you want to end the request and want to respond with no data.
send() is used to end the request and respond with some data.
You can found more about it here.

Strange Node await never unblocks

Node v8.3 + Express + using async / await complete source code below where await doesn't return unless I moved the terminal!!
// Express
const express = require('express');
const app = express();
// Lodash
const _ = require('lodash');
// DBR
const dbr = require('./build/Release/dbr');
dbr.initLicense("t0068MgAAAGvV3VqfqOzkuVGi7x/PFfZUQoUyJOakuduaSEoI2Pc8+kMwjrojxQgE5aJphmhagRmq/S9lppTkM4w3qCQezxk=");
// Promisify
const {promisify} = require('util');
const decodeFilePromise = promisify(dbr.decodeFileAsync);
app.get('/', async (req, res) => {
console.log("Received a barcode scan request!");
try {
const oneDimensionType = 0x3FF;
const scannedResults = await decodeFilePromise('test.jpg', oneDimensionType);
const imeiResults = _.uniq(_.map(_.filter(scannedResults, ['format', 'CODE_128']), 'value'));
console.log(`Successfully scanned the image: ${imeiResults}`);
res.send(`IMEI results: ${imeiResults}`);
}
catch (err) {
console.log(`Failed to scan the image: ${err}`);
res.send('Could not scan the barcode!');
}
});
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
What do I mean by "unless I moved the terminal" ? Please see the attached GIF: https://youtu.be/HW_MqLzEC9M

Resources