Google cloud function sending command to IoT device - google-cloud-functions

I am trying to write a function that will send command to a device defined in Google Cloud IoT core. Sending a command from the console works fine.
I’m using the following example from Sending commands to devices
// const cloudRegion = 'us-central1';
// const deviceId = 'my-device';
// const commandMessage = 'message for device';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const iot = require('#google-cloud/iot');
const iotClient = new iot.v1.DeviceManagerClient({
// optional auth parameters.
});
const formattedName = iotClient.devicePath(
projectId,
cloudRegion,
registryId,
deviceId
);
const binaryData = Buffer.from(commandMessage);
const request = {
name: formattedName,
binaryData: binaryData,
};
try {
const responses = await iotClient.sendCommandToDevice(request);
console.log('Sent command: ', responses[0]);
} catch (err) {
console.error('Could not send command:', err);
}
However, in my function log I get the message‘Error: Node.js v10.0.0 is a minimum requirement.‘
I have run node -v in my project and I get v10.16.3 as a result so I am confused. Can anyone offer any advice?
gcloud functions describe results :
availableMemoryMb: 256
entryPoint: updateDevice
eventTrigger:
eventType: providers/cloud.firestore/eventTypes/document.create
failurePolicy: {}
resource: projects/project/databases/(default)/documents/pubsubMessages/{docID}
service: firestore.googleapis.com
ingressSettings: ALLOW_ALL
labels:
deployment-tool: cli-firebase
name: projects/project/locations/us-central1/functions/updateDevice
runtime: nodejs8
serviceAccountEmail: email#appspot.gserviceaccount.com
sourceUploadUrl: https://storage.googleapis.com/gcf-upload-us-central1-xxx
status: ACTIVE
timeout: 60s
updateTime: '2020-05-18T09:56:29.144Z'
versionId: '46'
package.json:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"dependencies": {
"#google-cloud/iot": "^2.0.0",
"#google-cloud/pubsub": "^1.7.3",
"express": "^4.17.1",
"firebase": "^7.14.4",
"firebase-admin": "^8.12.1",
"firebase-functions": "^3.6.1",
"google-auth-library": "^6.0.0",
"googleapis": "^51.0.0"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}

Related

Sequelize error: "Error: Please install sqlite3 package manually" even when my dialect is "mysql"

I am getting this error on running my nodejs project
Error: Please install sqlite3 package manually
Event i added mysql as. dialect in sequelize connection
Here is my server code
const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: 'mysql'
});
sequelize.authenticate().then(() => {
app.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`Example app listening on port ${port}`)
})
// eslint-disable-next-line no-unused-vars
}).catch((error) => {
// eslint-disable-next-line no-console
console.log(error);
throw Error('Error in db connect');
});
Here is code of package.json file
{
"name": "geosafe-backend",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "node src/index",
"format:check": "prettier --check .",
"format:write": "prettier --write .",
"lint:check": "eslint .",
"lint:fix": "eslint --fix ."
},
"author": "Vinit Singh",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"dotenv": "^16.0.2",
"express": "^4.18.1",
"jsonwebtoken": "^8.5.1",
"mysql2": "^2.3.3",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"sequelize": "^6.21.4"
},
"devDependencies": {
"eslint": "^8.23.0",
"eslint-config-prettier": "^8.5.0",
"prettier": "^2.7.1"
}
}
even when i install sqlite3 package i gets table not found error. I this there is some issue in my connection but cannot able to find solution.

Heroku build failing node.js

My dev build was working fine but I can't understand why the deploy is failing.
Using ClearDB add on for MySQL, but I can't tell if the database connection is the problem here as the log output is "Connected".
Log:
-----> Build
Running heroku-postbuild
> react-notes-app#0.1.0 heroku-postbuild /tmp/build_8b518789_
> node api/server.js
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
Connected!
-----> Timed out running buildpack Node.js
Terminated
! Push failed
db.js:
const mysql = require('mysql');
var con = mysql.createPool(db_config);
con.getConnection(function(err) {
if (err) throw err;
console.log("Connected!");
});
//some functions
server.js:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const session = require('express-session');
const PORT = 5000 || process.env.port;
const cors = require('cors');
const path = require('path');
const db = require('./db.js');
var md5 = require('md5');
app.use(express.static(path.join(__dirname, '../build')));
app.use(cors());
app.get('/', function(req,res) {
res.sendFile(path.join(__dirname, '../build', 'index.html'));
});
//other stuff
Read answers to similar posts and some have problems in their dependencies.
package.json:
{
"name": "react-notes-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"cors": "^2.8.5",
"express-session": "^1.17.1",
"md5": "^2.3.0",
"mysql": "^2.18.1",
"node-fetch": "^2.6.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
},
"proxy" : "https://reactnote-app.herokuapp.com",
"scripts": {
"start": "react-scripts start",
"test": "react-scripts test",
"eject": "react-scripts eject",
"heroku-postbuild": "node api/server.js"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"engines":{
"node":"v12.18.3",
"npm":"6.14.6"
}
}

How to run front end and back end in same port to deploy in tomcat server?

I am using reactjs in the front end and node js ,express js in backend which connects to the MySQL DB.
Both are two different folders where generally I was using on different ports.
how to combine them to deploy in tomcat server . what is the right method to do this ?
This is the index file from the backend folder inside my front end folder
....
....
app.post('/data/tournament/registration',(request, response)=>{
console.log(request.body);
connection.query("INSERT INTO registrationdata VALUES ?"
,[request.body],function(error, result, fields){
if(error){
throw error;
}else{
console.log(JSON.stringify(result));
response.send(JSON.stringify(result))
}
});
});
app.listen(8080,()=>{
console.log("Connected to port 8080");
});
....
....
The package JSON file from the backend folder inside the front end folder
{
"name": "mysql_db",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node src/index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"mysql": "^2.18.1"
}
}
I use axios in the front end to fetch the data from backend.
import axios from 'axios';
export default axios.create({
baseURL:'http://localhost:8080'
});
I use the axios instance like in my front end to fetch from backend.
....
....
export const fetchTournaments=()=>async(dispatch)=>{
await mysqlDB.get('/data/tournament/fetch')
.then((response)=>{
console.log(response);
if(response.data !== {}){
dispatch( {
type: ActionTypes.FETCH_TOURNAMENT_SUCCESS,
payload:response.data
});
console.log("Fetched tournament")
History.push('/tournaments')
}else{
dispatch({type:ActionTypes.FETCH_TOURNAMENT_FAILED});
console.log("failed to Fetch tournament")
}
})
.catch((error)=>console.error(error));
};
....
....
This is the package json file of the front end which is basically the root folder
{
"name": "chess4loudoun",
"version": "0.1.0",
"private": true,
"dependencies": {
"#date-io/moment": "^1.3.13",
"#material-ui/core": "^4.9.14",
"#material-ui/icons": "^4.9.1",
"#material-ui/pickers": "^3.2.10",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"axios": "^0.19.2",
"concurrently": "^5.2.0",
"material-table": "^1.57.2",
"moment": "^2.26.0",
"react": "^16.13.1",
"react-countdown": "^2.2.1",
"react-dom": "^16.13.1",
"react-google-login": "^5.1.20",
"react-material-ui-carousel": "^1.4.5",
"react-redux": "^7.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1",
"redux": "^4.0.5",
"redux-persist": "^6.0.0",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start ",
"build": "react-scripts build ",
"test": "react-scripts test",
"eject": "react-scripts eject",
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
UPDATE
As for your other question about where to put your xml file etc that we discussed in comments, you will want to use this in your web.xml file to handle any 404 as per https://create-react-app.dev/docs/advanced-configuration/
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
For Development you can use:
Add this in your express server.js or w/e
app.listen(8080)
Then in your React App's package.json use:
"proxy": "http://localhost:8080"
In production you will want to use the path module to serve the static react files...
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static(path.join(__dirname, 'build')))

Received unknown parameters' when trying to update credit card optional details in Stripe

I'm trying to update the name and expiration date & year of a credit card in Stripe using Firebase Cloud Functions, based on the documentation https://stripe.com/docs/api/cards/update. Here's my code...
exports.updateStripeCard = functions.https.onRequest((request, response) => {
console.log(request.body);
return cors(request, response, () => {
stripe.customers.updateSource(
request.body.customerId,
request.body.cardId,
{ name: request.body.name
,exp_month: request.body.exp_month
,exp_year: request.body.exp_year}
).then((update) => {
// asynchronously called
response.send(update);
return true;
})
.catch(err =>{
console.log(err);
response.send(err);
return err;
});
})
});
When I test it with customerId, cardId, name, month and year, I get the error
'Received unknown parameters: name, exp_month, exp_year'
I even tried to update just the name, like the example in the documentation, and got a 'Received unknown parameters: name' error.
How on earth can I update the card's name, month and year? Is the syntax incorrect?
Here's my package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"main": "index.js",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"dependencies": {
"firebase": "7.14.0",
"firebase-admin": "^8.6.0",
"firebase-functions": "^3.6.0",
"geofire": "^4.1.2",
"stripe": "^8.39.2"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
Any help would be greatly appreciated!
Thanks.

action SDK not working

I have updated my index.js as below
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {actionssdk} = require('actions-on-google');
const app = actionssdk({debug: true});
exports.dairyProduct = functions.https.onRequest((request, response) => {
console.log("request-------------->",request);
console.log("response----------------->",response);
function handleMainIntent(app) {
console.log("Inside Main Intent");
app.ask("Main Indent "+app.getRawInput());
}
function handleTextIntent() {
console.log("Inside Main Intent");
app.tell("First Text Indent");
}
let app = new ActionsSdkApp({request, response});
let actionMap = new Map();
console.log("app---------->",app);
actionMap.set(app.StandardIntents.MAIN, handleMainIntent)
actionMap.set(app.StandardIntents.TEXT, handleTextIntent);
app.ask("This sample application is developing by Thirumani Selvam.M ");
console.log("actionMap---------->",actionMap);
app.handleRequest(actionMap);
});
My updated action.json
{
"actions": [
{
"description": "Default Welcome Intent",
"name": "MAIN",
"fulfillment": {
"conversationName": "testapp"
},
"intent": {
"name": "actions.intent.MAIN",
"trigger": {
"queryPatterns": [
"Talk to Dairy Product"
]
}
}
}
],
"conversations": {
"testapp": {
"name": "testapp",
"url": "https://us-central1-samplejs6-id.cloudfunctions.net/dairyProduct",
"fulfillmentApiVersion": 2,
"inDialogIntents": [
{
"name": "actions.intent.CANCEL"
}
]
}
},
"locale": "en"
}
My package.json code
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"actions-on-google": "^2.0.1",
"firebase-admin": "~5.12.0",
"firebase-functions": "^1.0.1"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.6.0"
},
"private": true
}
i have deployed using "firebase deploy --only functions"
I have updated action using "gactions update --action_package action.json --project samplejs6-id"
I have updated test of actions using"gactions test --action_package action.json --project samplejs6-id"
I didn't get errors in firebase logs.
i have updated title and name in gactions as "Dairy team". it is recommending to type "Talk to Dairy team" . If i type "Talk to Dairy team" , i am getting response as "We're sorry, but something went wrong. Please try again."
Please let me know, how to fix this issue. Thanks in advance
The problem is that you're using the "actions-on-google" library version 2, but your code is written using the version 1 objects and functions. There have been some dramatic changes between the two versions. See the migration guide for details how to upgrade to the new version, or change your package.json file to use version 1.