|
| 1 | +/** |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0. |
| 4 | + */ |
| 5 | + |
| 6 | +import { mqtt, io, iot, greengrass } from 'aws-iot-device-sdk-v2'; |
| 7 | +import { TextDecoder } from 'util'; |
| 8 | + |
| 9 | +type Args = { [index: string]: any }; |
| 10 | + |
| 11 | +const common_args = require('aws-iot-samples-util/cli_args'); |
| 12 | + |
| 13 | +const yargs = require('yargs'); |
| 14 | +yargs.command('*', false, (yargs: any) => { |
| 15 | + common_args.add_universal_arguments(yargs); |
| 16 | + common_args.add_topic_message_arguments(yargs); |
| 17 | + |
| 18 | + yargs |
| 19 | + .option('ca_file', { |
| 20 | + alias: 'r', |
| 21 | + description: '<path>: path to a Root CA certificate file in PEM format (optional, system trust store used by default).', |
| 22 | + type: 'string', |
| 23 | + required: false |
| 24 | + }) |
| 25 | + .option('cert', { |
| 26 | + alias: 'c', |
| 27 | + description: '<path>: path to a PEM encoded certificate to use with mTLS.', |
| 28 | + type: 'string', |
| 29 | + required: true |
| 30 | + }) |
| 31 | + .option('key', { |
| 32 | + alias: 'k', |
| 33 | + description: '<path>: Path to a PEM encoded private key that matches cert.', |
| 34 | + type: 'string', |
| 35 | + required: true |
| 36 | + }) |
| 37 | + .option('thing_name', { |
| 38 | + alias: 'T', |
| 39 | + description: 'Targeted Thing name.', |
| 40 | + type: 'string', |
| 41 | + required: true |
| 42 | + }) |
| 43 | + .option('mode', { |
| 44 | + alias: 'm', |
| 45 | + description: 'Mode options: [publish, subscribe, both] (optional).', |
| 46 | + type: 'string', |
| 47 | + default: 'both', |
| 48 | + choices: ['publish', 'subscribe', 'both'] |
| 49 | + }) |
| 50 | + .option('region', { |
| 51 | + description: 'AWS Region.', |
| 52 | + type: 'string', |
| 53 | + required: true |
| 54 | + }) |
| 55 | + .option('print_discover_resp_only', { |
| 56 | + description: 'Only print the response from Greengrass discovery (optional).', |
| 57 | + type: 'boolean', |
| 58 | + default: false |
| 59 | + }) |
| 60 | + .option('is_ci', { |
| 61 | + description: 'Adjusts sample to output/run in CI mode (optional).', |
| 62 | + type: 'boolean', |
| 63 | + default: false |
| 64 | + }) |
| 65 | +}, main).parse(); |
| 66 | + |
| 67 | +function firstResolved<T>(promises: Promise<T>[]) { |
| 68 | + let rejects: Error[] = []; |
| 69 | + return new Promise<T>((resolve, reject) => { |
| 70 | + promises.forEach((promise) => { |
| 71 | + promise |
| 72 | + .then((value) => { |
| 73 | + resolve(value) |
| 74 | + }) |
| 75 | + .catch((error) => { |
| 76 | + rejects.push(error); |
| 77 | + if (rejects.length == promises.length) { |
| 78 | + reject(rejects); |
| 79 | + } |
| 80 | + }); |
| 81 | + }); |
| 82 | + }); |
| 83 | +} |
| 84 | + |
| 85 | +async function connect_to_iot(mqtt_client: mqtt.MqttClient, argv: Args, discovery_response: greengrass.model.DiscoverResponse) { |
| 86 | + return new Promise<mqtt.MqttClientConnection>((resolve, reject) => { |
| 87 | + const start_connections = () => { |
| 88 | + let attempted_cores: string[] = []; |
| 89 | + let connections: Promise<mqtt.MqttClientConnection>[] = []; |
| 90 | + for (const gg_group of discovery_response.gg_groups) { |
| 91 | + for (const core of gg_group.cores) { |
| 92 | + attempted_cores.push(core.thing_arn.toString()); |
| 93 | + for (const endpoint of core.connectivity) { |
| 94 | + const mqtt_config = iot.AwsIotMqttConnectionConfigBuilder.new_mtls_builder_from_path(argv.cert, argv.key) |
| 95 | + .with_certificate_authority(gg_group.certificate_authorities[0]) |
| 96 | + .with_client_id(argv.thing_name) |
| 97 | + .with_clean_session(false) |
| 98 | + .with_socket_options(new io.SocketOptions(io.SocketType.STREAM, io.SocketDomain.IPV4, 3000)) |
| 99 | + .build(); |
| 100 | + mqtt_config.host_name = endpoint.host_address; |
| 101 | + mqtt_config.port = endpoint.port; |
| 102 | + console.log(`Trying endpoint=${JSON.stringify(endpoint)}`); |
| 103 | + const mqtt_connection = mqtt_client.new_connection(mqtt_config); |
| 104 | + mqtt_connection.on('error', (error) => { |
| 105 | + console.warn(`Connection to endpoint=${JSON.stringify(endpoint)} failed: ${error}`); |
| 106 | + }); |
| 107 | + connections.push(mqtt_connection.connect().then((session_present) => { |
| 108 | + console.log(`Connected to endpoint=${JSON.stringify(endpoint)}`); |
| 109 | + return mqtt_connection; |
| 110 | + })); |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + return connections; |
| 116 | + } |
| 117 | + |
| 118 | + const mqtt_connections = start_connections(); |
| 119 | + firstResolved(mqtt_connections) |
| 120 | + .then((connection) => { |
| 121 | + resolve(connection); |
| 122 | + }) |
| 123 | + .catch((error) => { |
| 124 | + reject(error); |
| 125 | + }); |
| 126 | + }); |
| 127 | +} |
| 128 | + |
| 129 | +async function execute_session(connection: mqtt.MqttClientConnection, argv: Args) { |
| 130 | + console.log("execute_session: topic is " + argv.topic); |
| 131 | + return new Promise<void>(async (resolve, reject) => { |
| 132 | + try { |
| 133 | + let published = false; |
| 134 | + let subscribed = false; |
| 135 | + const decoder = new TextDecoder('utf8'); |
| 136 | + if (argv.mode == 'both' || argv.mode == 'subscribe') { |
| 137 | + const on_publish = (topic: string, payload: ArrayBuffer, dup: boolean, qos: mqtt.QoS, retain: boolean) => { |
| 138 | + const json = decoder.decode(payload); |
| 139 | + console.log(`Publish received. topic:"${topic}" dup:${dup} qos:${qos} retain:${retain}`); |
| 140 | + console.log(json); |
| 141 | + const message = JSON.parse(json); |
| 142 | + if (message.sequence == argv.count) { |
| 143 | + subscribed = true; |
| 144 | + if (subscribed && published) { |
| 145 | + resolve(); |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | + await connection.subscribe(argv.topic, mqtt.QoS.AtLeastOnce, on_publish); |
| 150 | + } |
| 151 | + else { |
| 152 | + subscribed = true; |
| 153 | + } |
| 154 | + |
| 155 | + if (argv.mode == 'both' || argv.mode == 'publish') { |
| 156 | + let published_counts = 0; |
| 157 | + for (let op_idx = 0; op_idx < argv.count; ++op_idx) { |
| 158 | + const publish = async () => { |
| 159 | + const msg = { |
| 160 | + message: argv.message, |
| 161 | + sequence: op_idx + 1, |
| 162 | + }; |
| 163 | + const json = JSON.stringify(msg); |
| 164 | + console.log("execute_session: publishing..."); |
| 165 | + connection.publish(argv.topic, json, mqtt.QoS.AtLeastOnce).then(() => { |
| 166 | + ++published_counts; |
| 167 | + if (published_counts == argv.count) { |
| 168 | + published = true; |
| 169 | + if (subscribed && published) { |
| 170 | + resolve(); |
| 171 | + } |
| 172 | + } |
| 173 | + }); |
| 174 | + } |
| 175 | + setTimeout(publish, op_idx * 1000); |
| 176 | + } |
| 177 | + } |
| 178 | + else { |
| 179 | + published = true; |
| 180 | + } |
| 181 | + } |
| 182 | + catch (error) { |
| 183 | + reject(error); |
| 184 | + } |
| 185 | + }); |
| 186 | +} |
| 187 | + |
| 188 | +async function main(argv: Args) { |
| 189 | + if (argv.verbose && argv.verbose != 'none') { |
| 190 | + const level: io.LogLevel = parseInt(io.LogLevel[argv.verbose.toUpperCase()]); |
| 191 | + io.enable_logging(level); |
| 192 | + } |
| 193 | + |
| 194 | + const client_bootstrap = new io.ClientBootstrap(); |
| 195 | + const socket_options = new io.SocketOptions(io.SocketType.STREAM, io.SocketDomain.IPV4, 3000); |
| 196 | + const tls_options = new io.TlsContextOptions(); |
| 197 | + if (argv.ca_file) { |
| 198 | + tls_options.override_default_trust_store_from_path(undefined, argv.ca_file); |
| 199 | + } |
| 200 | + tls_options.certificate_filepath = argv.cert; |
| 201 | + tls_options.private_key_filepath = argv.key; |
| 202 | + if (io.is_alpn_available()) { |
| 203 | + tls_options.alpn_list.push('x-amzn-http-ca'); |
| 204 | + } |
| 205 | + const tls_ctx = new io.ClientTlsContext(tls_options); |
| 206 | + const discovery = new greengrass.DiscoveryClient(client_bootstrap, socket_options, tls_ctx, argv.region); |
| 207 | + |
| 208 | + // force node to wait 60 seconds before killing itself, promises do not keep node alive |
| 209 | + const timer = setTimeout(() => { }, 60 * 1000); |
| 210 | + |
| 211 | + console.log("Starting discovery for thing " + argv.thing_name); |
| 212 | + |
| 213 | + await discovery.discover(argv.thing_name) |
| 214 | + .then(async (discovery_response: greengrass.model.DiscoverResponse) => { |
| 215 | + console.log("Discovery Response:"); |
| 216 | + |
| 217 | + if (argv.is_ci != true) { |
| 218 | + console.log(JSON.stringify(discovery_response)); |
| 219 | + } else { |
| 220 | + console.log("Received a greengrass discovery result! Not showing result in CI for possible data sensitivity."); |
| 221 | + } |
| 222 | + |
| 223 | + if (argv.print_discover_resp_only) { |
| 224 | + process.exit(0); |
| 225 | + } |
| 226 | + |
| 227 | + const mqtt_client = new mqtt.MqttClient(client_bootstrap); |
| 228 | + return connect_to_iot(mqtt_client, argv, discovery_response); |
| 229 | + }).then(async (connection) => { |
| 230 | + await execute_session(connection, argv); |
| 231 | + console.log("Disconnecting..."); |
| 232 | + return connection.disconnect(); |
| 233 | + }).then(() => { |
| 234 | + console.log('Complete!'); |
| 235 | + }) |
| 236 | + .catch((reason) => { |
| 237 | + console.log(`DISCOVERY SAMPLE FAILED: ${JSON.stringify(reason)}`); |
| 238 | + process.exit(1); |
| 239 | + }); |
| 240 | + |
| 241 | + // Allow node to die if the promise above resolved |
| 242 | + clearTimeout(timer); |
| 243 | + process.exit(0); |
| 244 | +} |
0 commit comments