|
| 1 | +/** |
| 2 | + * Copyright 2017, Google, Inc. |
| 3 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. |
| 5 | + * You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software |
| 10 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + * See the License for the specific language governing permissions and |
| 13 | + * limitations under the License. |
| 14 | + */ |
| 15 | + |
| 16 | +'use strict'; |
| 17 | +// [START iot_http_includes] |
| 18 | +const fs = require('fs'); |
| 19 | +const jwt = require('jsonwebtoken'); |
| 20 | +const request = require('request'); |
| 21 | +// [END iot_http_includes] |
| 22 | + |
| 23 | +console.log('Google Cloud IoT Core HTTP example.'); |
| 24 | +var argv = require(`yargs`) |
| 25 | + .options({ |
| 26 | + project_id: { |
| 27 | + default: process.env.GCLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, |
| 28 | + description: 'The Project ID to use. Defaults to the value of the GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variables.', |
| 29 | + requiresArg: true, |
| 30 | + type: 'string' |
| 31 | + }, |
| 32 | + cloud_region: { |
| 33 | + default: 'us-central1', |
| 34 | + description: 'GCP cloud region.', |
| 35 | + requiresArg: true, |
| 36 | + type: 'string' |
| 37 | + }, |
| 38 | + registry_id: { |
| 39 | + description: 'Cloud IoT registry ID.', |
| 40 | + requiresArg: true, |
| 41 | + demandOption: true, |
| 42 | + type: 'string' |
| 43 | + }, |
| 44 | + device_id: { |
| 45 | + description: 'Cloud IoT device ID.', |
| 46 | + requiresArg: true, |
| 47 | + demandOption: true, |
| 48 | + type: 'string' |
| 49 | + }, |
| 50 | + private_key_file: { |
| 51 | + description: 'Path to private key file.', |
| 52 | + requiresArg: true, |
| 53 | + demandOption: true, |
| 54 | + type: 'string' |
| 55 | + }, |
| 56 | + algorithm: { |
| 57 | + description: 'Encryption algorithm to generate the RSA or EC JWT.', |
| 58 | + requiresArg: true, |
| 59 | + demandOption: true, |
| 60 | + choices: ['RS256', 'ES256'], |
| 61 | + type: 'string' |
| 62 | + }, |
| 63 | + num_messages: { |
| 64 | + default: 100, |
| 65 | + description: 'Number of messages to publish.', |
| 66 | + requiresArg: true, |
| 67 | + type: 'number' |
| 68 | + }, |
| 69 | + http_bridge_address: { |
| 70 | + default: 'cloudiot-device.googleapis.com', |
| 71 | + description: 'HTTP bridge address.', |
| 72 | + requiresArg: true, |
| 73 | + type: 'string' |
| 74 | + }, |
| 75 | + message_type: { |
| 76 | + default: 'events', |
| 77 | + description: 'Message type to publish.', |
| 78 | + requiresArg: true, |
| 79 | + choices: ['events', 'state'], |
| 80 | + type: 'string' |
| 81 | + } |
| 82 | + }) |
| 83 | + .example(`node $0 cloudiot_http_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`) |
| 84 | + .wrap(120) |
| 85 | + .recommendCommands() |
| 86 | + .epilogue(`For more information, see https://cloud.google.com/iot-core/docs`) |
| 87 | + .help() |
| 88 | + .strict() |
| 89 | + .argv; |
| 90 | + |
| 91 | +// Create a Cloud IoT Core JWT for the given project ID, signed with the given |
| 92 | +// private key. |
| 93 | +// [START iot_http_jwt] |
| 94 | +function createJwt (projectId, privateKeyFile, algorithm) { |
| 95 | + // Create a JWT to authenticate this device. The device will be disconnected |
| 96 | + // after the token expires, and will have to reconnect with a new token. The |
| 97 | + // audience field should always be set to the GCP project ID. |
| 98 | + const token = { |
| 99 | + 'iat': parseInt(Date.now() / 1000), |
| 100 | + 'exp': parseInt(Date.now() / 1000) + 20 * 60, // 20 minutes |
| 101 | + 'aud': projectId |
| 102 | + }; |
| 103 | + const privateKey = fs.readFileSync(privateKeyFile); |
| 104 | + return jwt.sign(token, privateKey, { algorithm: algorithm }); |
| 105 | +} |
| 106 | +// [END iot_http_jwt] |
| 107 | + |
| 108 | +// Publish numMessages message asynchronously, starting from message |
| 109 | +// messageCount. Telemetry events are published at a rate of 1 per second and |
| 110 | +// states at a rate of 1 every 2 seconds. |
| 111 | +// [START iot_http_publish] |
| 112 | +function publishAsync (messageCount, numMessages) { |
| 113 | + const payload = `${argv.registry_id}/${argv.device_id}-payload-${messageCount}`; |
| 114 | + console.log('Publishing message:', payload); |
| 115 | + const binaryData = Buffer.from(payload).toString('base64'); |
| 116 | + const postData = argv.message_type === 'events' ? { |
| 117 | + binary_data: binaryData |
| 118 | + } : { |
| 119 | + state: { |
| 120 | + binary_data: binaryData |
| 121 | + } |
| 122 | + }; |
| 123 | + const options = { |
| 124 | + url: url, |
| 125 | + headers: { |
| 126 | + 'Authorization': 'Bearer ' + authToken |
| 127 | + }, |
| 128 | + json: true, |
| 129 | + body: postData |
| 130 | + }; |
| 131 | + // Send events for high-frequency updates, update state only occasionally. |
| 132 | + const delayMs = argv.message_type === 'events' ? 1000 : 2000; |
| 133 | + request.post(options, function (error, response, body) { |
| 134 | + if (error) { |
| 135 | + return console.error('Received error: ', error); |
| 136 | + } |
| 137 | + console.log('Received response: '); |
| 138 | + console.dir(response); |
| 139 | + if (messageCount < numMessages) { |
| 140 | + // If we have published fewer than numMessage messages, publish payload |
| 141 | + // messageCount + 1. |
| 142 | + setTimeout(function () { |
| 143 | + publishAsync(messageCount + 1, numMessages); |
| 144 | + }, delayMs); |
| 145 | + } |
| 146 | + }); |
| 147 | +} |
| 148 | +// [END iot_http_publish] |
| 149 | + |
| 150 | +// [START iot_run_http] |
| 151 | +// A unique string that identifies this device. For Google Cloud IoT Core, it |
| 152 | +// must be in the format below. |
| 153 | +const devicePath = `projects/${argv.project_id}/locations/${argv.cloud_region}/registries/${argv.registry_id}/devices/${argv.device_id}`; |
| 154 | + |
| 155 | +// The request path, set accordingly depending on the message type. |
| 156 | +const pathSuffix = argv.message_type === 'events' |
| 157 | + ? ':publishEvent' : ':setState'; |
| 158 | +const url = `https://${argv.http_bridge_address}/v1beta1/${devicePath}${pathSuffix}`; |
| 159 | +const authToken = createJwt(argv.project_id, argv.private_key_file, argv.algorithm); |
| 160 | + |
| 161 | +// Publish messages. |
| 162 | +publishAsync(1, argv.num_messages); |
| 163 | +// [END iot_run_http] |
0 commit comments