Skip to content

Commit

Permalink
Fixes from http in tests / naming
Browse files Browse the repository at this point in the history
  • Loading branch information
gguuss committed Dec 20, 2017
1 parent e0379ee commit 9271b94
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 49 deletions.
46 changes: 23 additions & 23 deletions iot/mqtt_example/cloudiot_mqtt_example_nodejs.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,31 +24,31 @@ const mqtt = require('mqtt');
console.log('Google Cloud IoT Core MQTT example.');
var argv = require(`yargs`)
.options({
project_id: {
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'
},
cloud_region: {
cloudRegion: {
default: 'us-central1',
description: 'GCP cloud region.',
requiresArg: true,
type: 'string'
},
registry_id: {
registryId: {
description: 'Cloud IoT registry ID.',
requiresArg: true,
demandOption: true,
type: 'string'
},
device_id: {
deviceId: {
description: 'Cloud IoT device ID.',
requiresArg: true,
demandOption: true,
type: 'string'
},
private_key_file: {
privateKeyFile: {
description: 'Path to private key file.',
requiresArg: true,
demandOption: true,
Expand All @@ -61,39 +61,39 @@ var argv = require(`yargs`)
choices: ['RS256', 'ES256'],
type: 'string'
},
num_messages: {
numMessages: {
default: 100,
description: 'Number of messages to publish.',
requiresArg: true,
type: 'number'
},
token_exp_mins: {
tokenExpMins: {
default: 20,
description: 'Minutes to JWT token expiration.',
requiresArg: true,
type: 'number'
},
mqtt_bridge_hostname: {
mqttBridgeHostname: {
default: 'mqtt.googleapis.com',
description: 'MQTT bridge hostname.',
requiresArg: true,
type: 'string'
},
mqtt_bridge_port: {
mqttBridgePort: {
default: 8883,
description: 'MQTT bridge port.',
requiresArg: true,
type: 'number'
},
message_type: {
messageType: {
default: 'events',
description: 'Message type to publish.',
requiresArg: true,
choices: ['events', 'state'],
type: 'string'
}
})
.example(`node $0 cloudiot_mqtt_example_nodejs.js --project_id=blue-jet-123 --registry_id=my-registry --device_id=my-node-device --private_key_file=../rsa_private.pem --algorithm=RS256`)
.example(`node $0 cloudiot_mqtt_example_nodejs.js --projectId=blue-jet-123 --registryId=my-registry --deviceId=my-node-device --privateKeyFile=../rsa_private.pem --algorithm=RS256`)
.wrap(120)
.recommendCommands()
.epilogue(`For more information, see https://cloud.google.com/iot-core/docs`)
Expand Down Expand Up @@ -122,30 +122,30 @@ function createJwt (projectId, privateKeyFile, algorithm) {
// messageCount.
// [START iot_mqtt_publish]
function publishAsync (messageCount, numMessages) {
const payload = `${argv.registry_id}/${argv.device_id}-payload-${messageCount}`;
const payload = `${argv.registryId}/${argv.deviceId}-payload-${messageCount}`;
// Publish "payload" to the MQTT topic. qos=1 means at least once delivery.
// Cloud IoT Core also supports qos=0 for at most once delivery.
console.log('Publishing message:', payload);
client.publish(mqttTopic, payload, { qos: 1 });

const delayMs = argv.message_type === 'events' ? 1000 : 2000;
const delayMs = argv.messageType === 'events' ? 1000 : 2000;
if (messageCount < numMessages) {
// If we have published fewer than numMessage messages, publish payload
// messageCount + 1 in 1 second.
setTimeout(function () {
let secsFromIssue = parseInt(Date.now() / 1000) - iatTime;
if (secsFromIssue > argv.token_exp_mins * 60) {
if (secsFromIssue > argv.tokenExpMins * 60) {
iatTime = parseInt(Date.now() / 1000);
console.log(`\tRefreshing token after ${secsFromIssue} seconds.`);

client.end();
connectionArgs.password = createJwt(argv.project_id, argv.private_key_file, argv.algorithm);
connectionArgs.password = createJwt(argv.projectId, argv.privateKeyFile, argv.algorithm);
client = mqtt.connect(connectionArgs);

client.on('connect', (success) => {
console.log('connect');
if (success) {
publishAsync(1, argv.num_messages);
publishAsync(1, argv.numMessages);
} else {
console.log('Client not connected...');
}
Expand Down Expand Up @@ -180,18 +180,18 @@ function publishAsync (messageCount, numMessages) {
// [START iot_mqtt_run]
// The mqttClientId is a unique string that identifies this device. For Google
// Cloud IoT Core, it must be in the format below.
const mqttClientId = `projects/${argv.project_id}/locations/${argv.cloud_region}/registries/${argv.registry_id}/devices/${argv.device_id}`;
const mqttClientId = `projects/${argv.projectId}/locations/${argv.cloudRegion}/registries/${argv.registryId}/devices/${argv.deviceId}`;

// With Google Cloud IoT Core, the username field is ignored, however it must be
// non-empty. The password field is used to transmit a JWT to authorize the
// device. The "mqtts" protocol causes the library to connect using SSL, which
// is required for Cloud IoT Core.
let connectionArgs = {
host: argv.mqtt_bridge_hostname,
port: argv.mqtt_bridge_port,
host: argv.mqttBridgeHostname,
port: argv.mqttBridgePort,
clientId: mqttClientId,
username: 'unused',
password: createJwt(argv.project_id, argv.private_key_file, argv.algorithm),
password: createJwt(argv.projectId, argv.privateKeyFile, argv.algorithm),
protocol: 'mqtts',
secureProtocol: 'TLSv1_2_method'
};
Expand All @@ -200,18 +200,18 @@ let connectionArgs = {
let iatTime = parseInt(Date.now() / 1000);
let client = mqtt.connect(connectionArgs);

client.subscribe(`/devices/${argv.device_id}/config`);
client.subscribe(`/devices/${argv.deviceId}/config`);

// The MQTT topic that this device will publish data to. The MQTT
// topic name is required to be in the format below. The topic name must end in
// 'state' to publish state and 'events' to publish telemetry. Note that this is
// not the same as the device registry's Cloud Pub/Sub topic.
const mqttTopic = `/devices/${argv.device_id}/${argv.message_type}`;
const mqttTopic = `/devices/${argv.deviceId}/${argv.messageType}`;

client.on('connect', (success) => {
console.log('connect');
if (success) {
publishAsync(1, argv.num_messages);
publishAsync(1, argv.numMessages);
} else {
console.log('Client not connected...');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const topicName = `nodejs-docs-samples-test-iot-${uuid.v4()}`;
const registryName = `nodejs-test-registry-iot-${uuid.v4()}`;
const helper = `node ../manager/manager.js`;
const cmd = `node cloudiot_mqtt_example_nodejs.js `;
const cmdSuffix = ` --num_messages=1 --private_key_file=resources/rsa_private.pem --algorithm=RS256`;
const cmdSuffix = ` --numMessages=1 --privateKeyFile=resources/rsa_private.pem --algorithm=RS256`;
const cwd = path.join(__dirname, `..`);

test.before(tools.checkCredentials);
Expand Down Expand Up @@ -53,67 +53,64 @@ test(`should receive configuration message`, async (t) => {
const localRegName = `${registryName}-rsa256`;

let output = await tools.runAsync(`${helper} setupIotTopic ${topicName}`, cwd);
output = await tools.runAsync(
await tools.runAsync(
`${helper} createRegistry ${localRegName} ${topicName}`, cwd);
output = await tools.runAsync(
await tools.runAsync(
`${helper} createRsa256Device ${localDevice} ${localRegName} resources/rsa_cert.pem`, cwd);
t.regex(output, new RegExp(`Created device`));

output = await tools.runAsync(
`${cmd} --message_type=events --registry_id="${localRegName}" --device_id="${localDevice}" ${cmdSuffix}`,
`${cmd} --messageType=events --registryId="${localRegName}" --deviceId="${localDevice}" ${cmdSuffix}`,
cwd);
t.regex(output, new RegExp(`message received`));

// Check / cleanup
output = await tools.runAsync(
await tools.runAsync(
`${helper} getDeviceState ${localDevice} ${localRegName}`, cwd);
t.regex(output, new RegExp(`State`));
output = await tools.runAsync(
await tools.runAsync(
`${helper} deleteDevice ${localDevice} ${localRegName}`, cwd);
t.regex(output, new RegExp(`Successfully deleted device`));
output = await tools.runAsync(`${helper} deleteRegistry ${localRegName}`, cwd);
await tools.runAsync(`${helper} deleteRegistry ${localRegName}`, cwd);
});

test(`should send event message`, async (t) => {
const localDevice = `test-rsa-device`;
const localRegName = `${registryName}-rsa256`;
let output = await tools.runAsync(`${helper} setupIotTopic ${topicName}`, cwd);
output = await tools.runAsync(
await tools.runAsync(`${helper} setupIotTopic ${topicName}`, cwd);
await tools.runAsync(
`${helper} createRegistry ${localRegName} ${topicName}`, cwd);
output = await tools.runAsync(
await tools.runAsync(
`${helper} createRsa256Device ${localDevice} ${localRegName} resources/rsa_cert.pem`, cwd);

output = await tools.runAsync(
`${cmd} --message_type=events --registry_id="${localRegName}" --device_id="${localDevice}" ${cmdSuffix}`,
const output = await tools.runAsync(
`${cmd} --messageType=events --registryId="${localRegName}" --deviceId="${localDevice}" ${cmdSuffix}`,
cwd);
t.regex(output, new RegExp(`Publishing message:`));

// Check / cleanup
output = await tools.runAsync(
await tools.runAsync(
`${helper} getDeviceState ${localDevice} ${localRegName}`, cwd);
output = await tools.runAsync(
await tools.runAsync(
`${helper} deleteDevice ${localDevice} ${localRegName}`, cwd);
output = await tools.runAsync(`${helper} deleteRegistry ${localRegName}`, cwd);
await tools.runAsync(`${helper} deleteRegistry ${localRegName}`, cwd);
});

test(`should send event message`, async (t) => {
const localDevice = `test-rsa-device`;
const localRegName = `${registryName}-rsa256`;
let output = await tools.runAsync(`${helper} setupIotTopic ${topicName}`, cwd);
output = await tools.runAsync(
await tools.runAsync(`${helper} setupIotTopic ${topicName}`, cwd);
await tools.runAsync(
`${helper} createRegistry ${localRegName} ${topicName}`, cwd);
output = await tools.runAsync(
await tools.runAsync(
`${helper} createRsa256Device ${localDevice} ${localRegName} resources/rsa_cert.pem`, cwd);

output = await tools.runAsync(
`${cmd} --message_type=state --registry_id="${localRegName}" --device_id="${localDevice}" ${cmdSuffix}`,
const output = await tools.runAsync(
`${cmd} --messageType=state --registryId="${localRegName}" --deviceId="${localDevice}" ${cmdSuffix}`,
cwd);
t.regex(output, new RegExp(`Publishing message:`));

// Check / cleanup
output = await tools.runAsync(
await tools.runAsync(
`${helper} getDeviceState ${localDevice} ${localRegName}`, cwd);
output = await tools.runAsync(
await tools.runAsync(
`${helper} deleteDevice ${localDevice} ${localRegName}`, cwd);
output = await tools.runAsync(`${helper} deleteRegistry ${localRegName}`, cwd);
await tools.runAsync(`${helper} deleteRegistry ${localRegName}`, cwd);
});

0 comments on commit 9271b94

Please sign in to comment.