Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add iot commands beta samples & tests #767

Merged
merged 8 commits into from
Oct 16, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions iot/beta-features/commands/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>

# Google Cloud IoT Core NodeJS Command Samples

This folder contains NodeJS samples that demonstrate sending and receiving
commands.

## Quickstart

1. Install the Google Cloud SDK as described in [the Cloud IoT Core documentation](https://cloud.google.com/iot/docs/how-tos/getting-started#set_up_the_google_cloud_sdk_and_gcloud).
1. Create a Cloud Pub/Sub topic:

gcloud pubsub topics create projects/my-iot-project/topics/device-events

1. Add the service account `cloud-iot@system.gserviceaccount.com` with the role `Publisher` to that
Cloud Pub/Sub topic from the [Cloud Developer Console](https://console.cloud.google.com)
or by setting the `GOOGLE_CLOUD_PROJECT` environment variable and using the
helper script in the `scripts/` folder.

1. Create a registry:

gcloud iot registries create my-registry \
--project=my-iot-project \
--region=us-central1 \
--event-pubsub-topic=projects/my-iot-project/topics/device-events

1. Use the `generate_keys.sh` script to generate your signing keys:

./scripts/generate_keys.sh

1. Create a device.

gcloud beta iot devices create my-node-device \
--project=my-iot-project \
--region=us-central1 \
--registry=my-registry \
--public-key path=rsa_cert.pem,type=rs256

1. Start a receiver using the sample in the `receive` folder.
1. Send a command using the sample in `send` folder.
42 changes: 42 additions & 0 deletions iot/beta-features/commands/receive/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>

# Google Cloud IoT Core NodeJS Command Receiver

This sample app receives commands from Cloud IoT Core.

Note that before you can run this sample, you must register a device as
described in the parent README.

# Setup

Run the following command to install the library dependencies for NodeJS:

npm install

Place `rsa_cert.pem` and `rsa_private.pem` into the resources directory under `receive/resources`

# Running the sample

The following command summarizes the sample usage:

Google Cloud IoT Core MQTT example.
Options:
--projectId The Project ID to use. Defaults to the value of the GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT
environment variables. [string]
--cloudRegion GCP cloud region. [string] [default: "us-central1"]
--registryId Cloud IoT registry ID. [string] [required]
--deviceId Cloud IoT device ID. [string] [required]
--privateKeyFile Path to private key file. [string] [required]
--algorithm Encryption algorithm to generate the JWT. [string] [required] [choices: "RS256", "ES256"]
--tokenExpMins Minutes to JWT token expiration. [number] [default: 20]
--mqttBridgeHostname MQTT bridge hostname. [string] [default: "mqtt.googleapis.com"]
--mqttBridgePort MQTT bridge port. [number] [default: 8883]
--help Show help [boolean]

Examples:
node receive.js --projectId=blue-jet-123 \
--registryId=my-registry --deviceId=my-node-device \
--privateKeyFile=../rsa_private.pem --algorithm=RS256 \
--cloudRegion=us-central1

For more information, see https://cloud.google.com/iot-core/docs
25 changes: 25 additions & 0 deletions iot/beta-features/commands/receive/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "nodejs-docs-samples-iot-mqtt-example",
"version": "0.0.1",
"description": "MQTT Example for Google Cloud IoT Core using NodeJS.",
"main": "cloudiot_mqtt_example_nodejs.js",
"license": "Apache-2.0",
"author": "Google Inc.",
"scripts": {
"lint": "repo-tools lint",
"pretest": "npm run lint",
"test": "repo-tools test run --cmd ava -- -T 3m --verbose receiveTest.js"
},
"dependencies": {
"@google-cloud/pubsub": "0.13.2",
"jsonwebtoken": "^8.3.0",
"mqtt": "2.15.0",
"yargs": "8.0.2"
},
"devDependencies": {
"@google-cloud/nodejs-repo-tools": "^2.3.5",
"ava": "0.22.0",
"semistandard": "^12.0.1",
"uuid": "3.1.0"
}
}
162 changes: 162 additions & 0 deletions iot/beta-features/commands/receive/receive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/**
* Copyright 2018 Google LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// [START iot_mqtt_include]
const fs = require('fs');
const jwt = require('jsonwebtoken');
const mqtt = require('mqtt');
// [END iot_mqtt_include]

console.log('Google Cloud IoT Core MQTT example.');
let argv = require(`yargs`)
.options({
projectId: {
default: process.env.GCLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT,
description: 'The Project ID to use. Defaults to the value of the GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variables.',
requiresArg: true,
type: 'string'
},
cloudRegion: {
default: 'us-central1',
description: 'GCP cloud region.',
requiresArg: true,
type: 'string'
},
registryId: {
description: 'Cloud IoT registry ID.',
requiresArg: true,
demandOption: true,
type: 'string'
},
deviceId: {
description: 'Cloud IoT device ID.',
requiresArg: true,
demandOption: true,
type: 'string'
},
privateKeyFile: {
description: 'Path to private key file.',
requiresArg: true,
demandOption: true,
type: 'string'
},
algorithm: {
description: 'Encryption algorithm to generate the JWT.',
requiresArg: true,
demandOption: true,
choices: ['RS256', 'ES256'],
type: 'string'
},
maxDuration: {
default: -1,
description: 'Max number of minutes to run before ending the client. Set to -1 for no maximum',
requiresArg: true,
type: 'number'
},
tokenExpMins: {
default: 20,
description: 'Minutes to JWT token expiration.',
requiresArg: true,
type: 'number'
},
mqttBridgeHostname: {
default: 'mqtt.googleapis.com',
description: 'MQTT bridge hostname.',
requiresArg: true,
type: 'string'
},
mqttBridgePort: {
default: 8883,
description: 'MQTT bridge port.',
requiresArg: true,
type: 'number'
}
})
.example(`node $0 --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t --cloudRegion=us-central1`)
.wrap(120)
.recommendCommands()
.epilogue(`For more information, see https://cloud.google.com/iot-core/docs`)
.help()
.strict()
.argv;

// Create a Cloud IoT Core JWT for the given project id, signed with the given
// private key.
// [START iot_mqtt_jwt]
function createJwt (projectId, privateKeyFile, algorithm) {
const token = {
'iat': parseInt(Date.now() / 1000),
'exp': parseInt(Date.now() / 1000) + 20 * 60, // 20 minutes
'aud': projectId
};
const privateKey = fs.readFileSync(privateKeyFile);
return jwt.sign(token, privateKey, { algorithm: algorithm });
}
// [END iot_mqtt_jwt]

// [START iot_mqtt_run]
const mqttClientId = `projects/${argv.projectId}/locations/${argv.cloudRegion}/registries/${argv.registryId}/devices/${argv.deviceId}`;
let connectionArgs = {
host: argv.mqttBridgeHostname,
port: argv.mqttBridgePort,
clientId: mqttClientId,
username: 'unused',
password: createJwt(argv.projectId, argv.privateKeyFile, argv.algorithm),
protocol: 'mqtts',
qos: 1,
secureProtocol: 'TLSv1_2_method'
};

// Create a client, and connect to the Google MQTT bridge.
let client = mqtt.connect(connectionArgs);

// Subscribe to the /devices/{device-id}/commands topic to receive commands.
client.subscribe(`/devices/${argv.deviceId}/commands/#`);

if (argv.maxDuration > 0) {
setTimeout(() => {
console.log(`Closing connection to MQTT after ${argv.maxDuration} seconds.`);
client.end();
}, argv.maxDuration * 60 * 1000);
}

client.on('connect', (success) => {
console.log('connect');
if (!success) {
console.log('Client not connected...');
} else {
// TODO: wait for commands
console.log('Client connected, waiting for commands');
}
});

client.on('close', () => {
console.log('close');
});

client.on('error', (err) => {
console.log('error', err);
});

client.on('message', (topic, message, packet) => {
console.log('message received: ', Buffer.from(message, 'base64').toString('ascii'));
});

client.on('packetsend', () => {
// Note: logging packet send is very verbose
});
// [END iot_mqtt_run]
77 changes: 77 additions & 0 deletions iot/beta-features/commands/receive/receiveTest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* Copyright 2018 Google LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

const path = require(`path`);
const PubSub = require(`@google-cloud/pubsub`);
const test = require(`ava`);
const tools = require(`@google-cloud/nodejs-repo-tools`);
const uuid = require(`uuid`);

const topicName = `nodejs-docs-samples-test-iot-${uuid.v4()}`;
const registryName = `nodejs-test-registry-iot-${uuid.v4()}`;
const localRegName = `${registryName}-rsa256`;
const localDevice = `test-device-rsa256`;

const helper = `node manager.js`;
const receiveCmd = `node receive.js`;
const sendCmd = `node send.js`;
const receiveCmdSuffix = `--privateKeyFile=resources/rsa_private.pem --algorithm=RS256`;
// TODO: update manager paths when going from beta->GA
const cwdHelper = path.join(__dirname, `../../../manager`);
const cwdSend = path.join(__dirname, `../send`);
const installDeps = `npm install`;

const pubsub = PubSub();

test.before(tools.checkCredentials);
test.before(async () => {
let pubsubRes = await pubsub.createTopic(topicName);
const topic = pubsubRes[0];
console.log(`Topic ${topic.name} created.`);
});

test.after.always(async () => {
const topic = pubsub.topic(topicName);
await topic.delete();
console.log(`Topic ${topic.name} deleted.`);
});

test(`should receive command message`, async (t) => {
await tools.runAsync(installDeps, cwdHelper);
await tools.runAsync(`${helper} setupIotTopic ${topicName}`, cwdHelper);
await tools.runAsync(
`${helper} createRegistry ${localRegName} ${topicName}`, cwdHelper);
await tools.runAsync(
`${helper} createRsa256Device ${localDevice} ${localRegName} ./resources/rsa_cert.pem`, cwdHelper);

// This command needs to run asynchronously without await to ensure the send comand happens while
// mqtt client is available. Limit client to last only 15 seconds (0.25 minutes)
let out = tools.runAsync(
`${receiveCmd} --deviceId=${localDevice} --registryId=${localRegName} --maxDuration=0.25 ${receiveCmdSuffix}`);

await tools.runAsync(
`${sendCmd} sendCommand ${localDevice} ${localRegName} "me want cookies"`, cwdSend);

// await for original command to resolve before checking regex
t.regex(await out, new RegExp(`me want cookies`));

await tools.runAsync(
`${helper} getDeviceState ${localDevice} ${localRegName}`, cwdHelper);
await tools.runAsync(
`${helper} deleteDevice ${localDevice} ${localRegName}`, cwdHelper);
await tools.runAsync(`${helper} deleteRegistry ${localRegName}`, cwdHelper);
});
6 changes: 6 additions & 0 deletions iot/beta-features/commands/receive/resources/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Test public certificate files

The certificates in this folder are only provided for testing and should not be
used for registering or connecting your devices.

If the keys in this folder do not match the keys in ~/nodejs-docs-samples/iot/manager/resources, the tests will fail.
Loading