This article explains how to establish a connection with Google cloud services using nodeJS* API. While this was written for the Intel® Edison board, it should work on any platform that runs nodeJS. This includes creating a cloud project, store and retrieve data.
Create Google cloud project
Log in to Google cloud portal and click Create Project at the top-left of the page.
Type a name for the project and press the create button
You can see an activity window on the bottom of the page. Once the project is created project overview page shows up.
Select APIs (under APIs & auth) from the left pane.
Search for the required API and click Enable API.
For e.g., Google Cloud Datastore API
Now select Credentials from the left pane, press the Create new Client ID button and select Service account.
After successful creation a private key file (*.json) is downloaded. Save the file which will be used for authentication.
Setting up the development environment
Install Google Cloud Node.js Client
npm install --save gcloud
Copy the downloaded JSON key file to the board.
Create a datastore/db object
"cloud" : {"projectId": "iot-cloud-project","keyFilename": "./key.json"
}
db = gcloud.datastore.dataset(cloud);
Store Data
Each entity in the storage requires a unique key to store in the database and consists of a namespace and path attributes.
key = {"namespace": this.namespace,"path": [data[i].sensor_id, data[i].timestamp] } db.save({ key: key, data: data[i] }, function(err) { if (!err) { //console.log("Test data saved"); } });
Query Data
Timestamp based query
dataQuery = db.createQuery(namespace, readQuery.sensor_id)
.filter('timestamp >=', readQuery.timestamp);
Sensorid based query
dataQuery = db.createQuery(namespace, readQuery.sensor_id);
Run query
db.runQuery(dataQuery, function(err, result) { if(err) { logger.error(JSON.stringify(err, null, '')); } else { logger.info('Google - Data received: %d', result.length); });
References
Google Cloud documentation - https://cloud.google.com/docs/
Google Cloud Node.js Client - https://github.com/GoogleCloudPlatform/gcloud-node
Cloud Datastore concepts - https://cloud.google.com/datastore/docs/concepts/overview
Cloud Datastore API - https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.14.0/datastore