From ad4c02921d1f5bfdce1f336171e62e4a20e3e958 Mon Sep 17 00:00:00 2001 From: ace-n Date: Tue, 4 Jun 2019 18:15:53 -0700 Subject: [PATCH 1/2] Update IoT samples to Node 8 --- iot/beta-features/gateway/gateway.js | 724 ++++--- iot/http_example/cloudiot_http_example.js | 4 +- iot/manager/manager.js | 1700 ++++++++--------- iot/manager/system-test/manager.test.js | 116 +- .../cloudiot_mqtt_example_nodejs.js | 4 +- iot/scripts/iam.js | 71 +- iot/scripts/package.json | 3 + 7 files changed, 1281 insertions(+), 1341 deletions(-) diff --git a/iot/beta-features/gateway/gateway.js b/iot/beta-features/gateway/gateway.js index 83c9be9b16..605b8fe9e0 100644 --- a/iot/beta-features/gateway/gateway.js +++ b/iot/beta-features/gateway/gateway.js @@ -13,6 +13,8 @@ * limitations under the License. */ +/* eslint-disable prefer-destructuring */ + 'use strict'; // [START iot_gateway_include] @@ -28,28 +30,23 @@ const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest'; // Returns an authorized API client by discovering the Cloud IoT Core API with // the provided API key. -function getClient(serviceAccountJson, cb) { - google.auth - .getClient({ - scopes: ['https://www.googleapis.com/auth/cloud-platform'], - }) - .then(authClient => { - const discoveryUrl = `${DISCOVERY_API}?version=${API_VERSION}`; - - google.options({ - auth: authClient, - }); +const getClient = async () => { + const authClient = await google.auth.getClient({ + scopes: ['https://www.googleapis.com/auth/cloud-platform'], + }); - google - .discoverAPI(discoveryUrl) - .then(client => { - cb(client); - }) - .catch(err => { - console.log('Error during API discovery.', err); - }); - }); -} + const discoveryUrl = `${DISCOVERY_API}?version=${API_VERSION}`; + + google.options({ + auth: authClient, + }); + + try { + return google.discoverAPI(discoveryUrl); + } catch (err) { + console.log('Error during API discovery.', err); + } +}; // [END iot_gateway_client_config] // [START iot_gateway_client_backoff_variables] @@ -73,7 +70,7 @@ let publishChainInProgress = false; // 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 createJwt = (projectId, privateKeyFile, algorithm) => { // Create a JWT to authenticate this device. The device will be disconnected // after the token expires, and will have to reconnect with a new token. The // audience field should always be set to the GCP project id. @@ -84,11 +81,11 @@ function createJwt(projectId, privateKeyFile, algorithm) { }; const privateKey = fs.readFileSync(privateKeyFile); return jwt.sign(token, privateKey, {algorithm: algorithm}); -} +}; // [END iot_mqtt_jwt] // Creates a gateway. -function createGateway( +const createGateway = ( client, projectId, cloudRegion, @@ -96,7 +93,7 @@ function createGateway( gatewayId, certificateFile, algorithm -) { +) => { // [START create_gateway] // const cloudRegion = 'us-central1'; // const deviceId = 'my-unauth-device'; @@ -142,18 +139,16 @@ function createGateway( } ); // [END create_gateway] -} +}; // Creates a device to bind to a gateway. -function createDeviceForGateway( +const createDeviceForGateway = async ( client, projectId, cloudRegion, registryId, - deviceId, - gatewayId, - cb -) { + deviceId +) => { // [START create_device] // const cloudRegion = 'us-central1'; // const deviceId = 'my-unauth-device'; @@ -167,116 +162,101 @@ function createDeviceForGateway( let exists = false; let device = {}; - client.projects.locations.registries.devices.get(getRequest, (err, res) => { - if (err) { - // Device not found - console.log('Error while getting device', err); - } else { - console.log('Device exists'); - device = res.data; - exists = true; - } + try { + const {data} = await client.projects.locations.registries.devices.get( + getRequest + ); + console.log('Device exists'); + device = data; + exists = true; + } catch (err) { + // Device not found + console.log('Error while getting device', err); + } - if (exists) { - cb(client, projectId, cloudRegion, registryId, device, gatewayId); - } else { - console.log('Creating device:', deviceId); - - const createRequest = { - parent: parentName, - resource: { - id: deviceId, - gatewayConfig: { - gatewayType: 'NON_GATEWAY', - gatewayAuthMethod: 'ASSOCIATION_ONLY', - }, + if (exists) { + return device; + } else { + console.log('Creating device:', deviceId); + + const createRequest = { + parent: parentName, + resource: { + id: deviceId, + gatewayConfig: { + gatewayType: 'NON_GATEWAY', + gatewayAuthMethod: 'ASSOCIATION_ONLY', }, - }; + }, + }; - client.projects.locations.registries.devices.create( - createRequest, - (err, res) => { - if (err) { - console.log('Could not create device'); - console.log(err); - } else { - console.log('Created device'); - device = res.data; - console.log(device); - } - cb(client, projectId, cloudRegion, registryId, device, gatewayId); - } + try { + const {data} = await client.projects.locations.registries.devices.create( + createRequest ); + console.log('Created device'); + device = data; + console.log(device); + return device; + } catch (err) { + console.log('Could not create device'); + console.log(err); } - }); + } // [END create_device] -} +}; // Binds a device to a gateway so that it can be attached. -function bindDeviceToGateway( +const bindDeviceToGateway = async ( client, projectId, cloudRegion, registryId, deviceId, gatewayId -) { +) => { // [START bind_device_to_gateway] // const cloudRegion = 'us-central1'; // const deviceId = 'my-unauth-device'; // const gatewayId = 'my-gateway'; // const projectId = 'adjective-noun-123'; // const registryId = 'my-registry'; - const callback = ( + const device = await createDeviceForGateway( client, projectId, cloudRegion, registryId, - device, + deviceId, gatewayId - ) => { - console.log(`Binding device: ${JSON.stringify(device.id)}`); - const parentName = `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}`; + ); - const bindRequest = { - parent: parentName, - deviceId: device.id, - gatewayId: gatewayId, - }; + console.log(`Binding device: ${JSON.stringify(device.id)}`); + const parentName = `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}`; - client.projects.locations.registries.bindDeviceToGateway( - bindRequest, - err => { - if (err) { - console.log('Could not bind device', err); - } else { - console.log('Bound device to', gatewayId); - } - } - ); + const bindRequest = { + parent: parentName, + deviceId: device.id, + gatewayId: gatewayId, }; - createDeviceForGateway( - client, - projectId, - cloudRegion, - registryId, - deviceId, - gatewayId, - callback - ); + try { + await client.projects.locations.registries.bindDeviceToGateway(bindRequest); + console.log('Bound device to', gatewayId); + } catch (err) { + console.log('Could not bind device', err); + } // [END bind_device_to_gateway] -} +}; // Unbinds a device from a gateway. -function unbindDeviceFromGateway( +const unbindDeviceFromGateway = async ( client, projectId, cloudRegion, registryId, deviceId, gatewayId -) { +) => { // [START unbind_device_to_gateway] // const cloudRegion = 'us-central1'; // const deviceId = 'my-unauth-device'; @@ -292,27 +272,25 @@ function unbindDeviceFromGateway( gatewayId: gatewayId, }; - client.projects.locations.registries.unbindDeviceFromGateway( - unbindRequest, - err => { - if (err) { - console.log('Could not unbind device', err); - } else { - console.log('Device no longer bound.'); - } - } - ); + try { + await client.projects.locations.registries.unbindDeviceFromGateway( + unbindRequest + ); + console.log('Device no longer bound.'); + } catch (err) { + console.log('Could not unbind device', err); + } // [END unbind_device_to_gateway] -} +}; // Unbinds the given device from all gateways -function unbindDeviceFromAllGateways( +const unbindDeviceFromAllGateways = async ( client, projectId, cloudRegion, registryId, deviceId -) { +) => { const parentName = `projects/${projectId}/locations/${cloudRegion}`; const registryName = `${parentName}/registries/${registryId}`; const request = { @@ -320,63 +298,69 @@ function unbindDeviceFromAllGateways( }; // get information about this device - client.projects.locations.registries.devices.get(request, (err, res) => { - if (err) { - console.error('Could not get device', err); - return; - } + let device; + try { + const {data} = await client.projects.locations.registries.devices.get( + request + ); + device = data; + } catch (err) { + console.error('Could not get device', err); + return; + } + + if (device) { + const isGateway = device.gatewayConfig.gatewayType === 'GATEWAY'; - const device = res.data; - if (device) { - const isGateway = device.gatewayConfig.gatewayType === 'GATEWAY'; + if (!isGateway) { + const listGatewaysForDeviceRequest = { + parent: registryName, + 'gatewayListOptions.associationsDeviceId': deviceId, + }; - if (!isGateway) { - const listGatewaysForDeviceRequest = { + // get list of all gateways this non-gateway device is bound to + let gateways = []; + try { + const {data} = await client.projects.locations.registries.devices.list( + listGatewaysForDeviceRequest + ); + + if (data.devices && data.devices.length > 0) { + gateways = data.devices; + } + } catch (err) { + console.error('Could not list gateways', err); + return; + } + + const promises = gateways.map(gateway => { + const unbindRequest = { parent: registryName, - 'gatewayListOptions.associationsDeviceId': deviceId, + deviceId: device.id, + gatewayId: gateway.id, }; - // get list of all gateways this non-gateway device is bound to - client.projects.locations.registries.devices.list( - listGatewaysForDeviceRequest, - (err, res) => { - if (err) { - console.error('Could not list gateways', err); - return; - } - - const data = res.data; - if (data.devices && data.devices.length > 0) { - const gateways = data.devices; - - gateways.forEach(gateway => { - const unbindRequest = { - parent: registryName, - deviceId: device.id, - gatewayId: gateway.id, - }; - - // for each gateway, make the call to unbind it - client.projects.locations.registries.unbindDeviceFromGateway( - unbindRequest, - err => { - if (err) { - console.log('Could not unbind device', err); - } else { - console.log('Unbound device from gateways', gateway.id); - } - } - ); - }); - } + // for each gateway, make the call to unbind it + return new Promise(async (resolve, reject) => { + try { + await client.projects.locations.registries.unbindDeviceFromGateway( + unbindRequest + ); + console.log('Unbound device from gateways', gateway.id); + resolve(); + } catch (err) { + console.log('Could not unbind device', err); + reject(); } - ); - } + }); + }); + + await Promise.all(promises); } - }); -} + } +}; -function unbindAllDevices(client, projectId, cloudRegion, registryId) { +const unbindAllDevices = async (client, projectId, cloudRegion, registryId) => { const parentName = `projects/${projectId}/locations/${cloudRegion}`; const registryName = `${parentName}/registries/${registryId}`; const request = { @@ -384,42 +368,47 @@ function unbindAllDevices(client, projectId, cloudRegion, registryId) { }; // get information about this device - client.projects.locations.registries.devices.list(request, (err, res) => { - if (err) { - console.error('Could not list devices', err); - return; - } - const data = res.data; + let devices; + try { + const {data} = await client.projects.locations.registries.devices.list( + request + ); + if (!data) { return; } - const devices = data.devices; - - if (devices && devices.length > 0) { - devices.forEach(device => { - if (device) { - const isGateway = - device.gatewayConfig && - device.gatewayConfig.gatewayType === 'GATEWAY'; - - if (!isGateway) { - unbindDeviceFromAllGateways( - client, - projectId, - cloudRegion, - registryId, - device.id - ); - } + devices = data.devices; + } catch (err) { + console.error('Could not list devices', err); + return; + } + + if (devices && devices.length > 0) { + const promises = devices.map(device => { + if (device) { + const isGateway = + device.gatewayConfig && + device.gatewayConfig.gatewayType === 'GATEWAY'; + + if (!isGateway) { + return unbindDeviceFromAllGateways( + client, + projectId, + cloudRegion, + registryId, + device.id + ); } - }); - } - }); -} + } + }); + + await Promise.all(promises); + } +}; // Lists gateways in a registry. -function listGateways(client, projectId, cloudRegion, registryId) { +const listGateways = async (client, projectId, cloudRegion, registryId) => { // [START list_gateways] // const cloudRegion = 'us-central1'; // const projectId = 'adjective-noun-123'; @@ -430,36 +419,40 @@ function listGateways(client, projectId, cloudRegion, registryId) { fieldMask: 'config,gatewayConfig', }; - client.projects.locations.registries.devices.list(request, (err, res) => { - if (err) { - console.log('Could not list devices'); - console.log(err); + let devices; + try { + const {data} = await client.projects.locations.registries.devices.list( + request + ); + devices = data.devices; + } catch (err) { + console.log('Could not list devices'); + console.log(err); + return; + } + + console.log('Current gateways in registry:'); + devices.forEach(device => { + if ( + device.gatewayConfig !== undefined && + device.gatewayConfig.gatewayType === 'GATEWAY' + ) { + console.log('----\n', device); } else { - const data = res.data; - console.log('Current gateways in registry:'); - data.devices.forEach(device => { - if ( - device.gatewayConfig !== undefined && - device.gatewayConfig.gatewayType === 'GATEWAY' - ) { - console.log('----\n', device); - } else { - console.log('\t', device); - } - }); + console.log('\t', device); } }); // [END list_gateways] -} +}; // Lists devices bound to a gateway. -function listDevicesForGateway( +const listDevicesForGateway = async ( client, projectId, cloudRegion, registryId, gatewayId -) { +) => { // [START list_devices_for_gateway] // const cloudRegion = 'us-central1'; // const gatewayId = 'my-gateway'; @@ -471,33 +464,37 @@ function listDevicesForGateway( 'gatewayListOptions.associationsGatewayId': gatewayId, }; - client.projects.locations.registries.devices.list(request, (err, res) => { - if (err) { - console.log('Could not list devices'); - console.log(err); - } else { - console.log('Current devices bound to gateway: ', gatewayId); - const data = res.data; - if (data.devices && data.devices.length > 0) { - data.devices.forEach(device => { - console.log(`\tDevice: ${device.numId} : ${device.id}`); - }); - } else { - console.log('No devices bound to this gateway.'); - } - } - }); + let devices; + try { + const {data} = await client.projects.locations.registries.devices.list( + request + ); + devices = data.devices; + } catch (err) { + console.log('Could not list devices'); + console.log(err); + return; + } + + console.log('Current devices bound to gateway: ', gatewayId); + if (devices && devices.length > 0) { + devices.forEach(device => { + console.log(`\tDevice: ${device.numId} : ${device.id}`); + }); + } else { + console.log('No devices bound to this gateway.'); + } // [END list_devices_for_gateway] -} +}; // Lists gateways a given device is bound to. -function listGatewaysForDevice( +const listGatewaysForDevice = async ( client, projectId, cloudRegion, registryId, deviceId -) { +) => { // [START list_gateways_for_device] // const cloudRegion = 'us-central1'; // const deviceId = 'my-device'; @@ -509,62 +506,68 @@ function listGatewaysForDevice( 'gatewayListOptions.associationsDeviceId': deviceId, }; - client.projects.locations.registries.devices.list(request, (err, res) => { - if (err) { - console.log('Could not list gateways for device'); - console.log(err); - } else { - console.log('Current gateways for device:', deviceId); - const data = res.data; - if (data.devices && data.devices.length > 0) { - data.devices.forEach(gateway => { - console.log(`\tDevice: ${gateway.numId} : ${gateway.id}`); - }); - } else { - console.log('No gateways associated with this device.'); - } - } - }); + let devices; + try { + const {data} = await client.projects.locations.registries.devices.list( + request + ); + devices = data.devices; + } catch (err) { + console.log('Could not list gateways for device'); + console.log(err); + return; + } + + console.log('Current gateways for device:', deviceId); + if (devices && devices.length > 0) { + devices.forEach(gateway => { + console.log(`\tDevice: ${gateway.numId} : ${gateway.id}`); + }); + } else { + console.log('No gateways associated with this device.'); + } // [END list_gateways_for_device] -} +}; // Attaches a device to a gateway. -function attachDevice(deviceId, client) { +const attachDevice = async (deviceId, client) => { // [START attach_device] // const deviceId = 'my-unauth-device'; const attachTopic = `/devices/${deviceId}/attach`; console.log(`Attaching: ${attachTopic}`); const attachPayload = '{}'; - client.publish(attachTopic, attachPayload, {qos: 1}, err => { - if (!err) { - shouldBackoff = false; - backoffTime = MINIMUM_BACKOFF_TIME; - } else { - console.log(err); - } - }); + + try { + await client.publish(attachTopic, attachPayload, {qos: 1}); + + shouldBackoff = false; + backoffTime = MINIMUM_BACKOFF_TIME; + } catch (err) { + console.log(err); + } // [END attach_device] -} +}; // Detaches a device from a gateway. -function detachDevice(deviceId, client) { +const detachDevice = async (deviceId, client) => { // [START detach_device] const detachTopic = `/devices/${deviceId}/detach`; console.log(`Detaching: ${detachTopic}`); const detachPayload = '{}'; - client.publish(detachTopic, detachPayload, {qos: 1}, err => { - if (!err) { - shouldBackoff = false; - backoffTime = MINIMUM_BACKOFF_TIME; - } else { - console.log(err); - } - }); + + try { + await client.publish(detachTopic, detachPayload, {qos: 1}); + + shouldBackoff = false; + backoffTime = MINIMUM_BACKOFF_TIME; + } catch (err) { + console.log(err); + } // [END detach_device] -} +}; // Listen for configuration messages on a gateway and bound device. -function listenForConfigMessages( +const listenForConfigMessages = ( gatewayId, deviceId, registryId, @@ -575,7 +578,7 @@ function listenForConfigMessages( mqttBridgeHostname, mqttBridgePort, clientDuration -) { +) => { // [START listen_for_config_messages] // const parentName = `projects/${projectId}/locations/${region}`; // const registryName = `${parentName}/registries/${registryId}`; @@ -640,10 +643,10 @@ function listenForConfigMessages( // Note: logging packet send is very verbose }); // [END listen_for_config_messages] -} +}; // Listen for error messages on a gateway. -function listenForErrorMessages( +const listenForErrorMessages = ( gatewayId, registryId, projectId, @@ -654,7 +657,7 @@ function listenForErrorMessages( mqttBridgePort, clientDuration, deviceId -) { +) => { // [START listen_for_error_messages] // const parentName = `projects/${projectId}/locations/${region}`; // const registryName = `${parentName}/registries/${registryId}`; @@ -712,10 +715,10 @@ function listenForErrorMessages( // Note: logging packet send is very verbose }); // [END listen_for_error_messages] -} +}; // Sends telemetry on behalf of a device. -function sendDataFromBoundDevice( +const sendDataFromBoundDevice = ( gatewayId, deviceId, registryId, @@ -727,7 +730,7 @@ function sendDataFromBoundDevice( mqttBridgePort, numMessages, tokenExpMins -) { +) => { // [START iot_send_delegate_data] // const parentName = `projects/${projectId}/locations/${region}`; // const registryName = `${parentName}/registries/${registryId}`; @@ -800,11 +803,11 @@ function sendDataFromBoundDevice( // Note: logging packet send is very verbose }); // [END iot_send_delegate_data] -} +}; // Publish numMessages messages asynchronously, starting from message // messagesSent. -function publishAsync( +const publishAsync = ( client, iatTime, tokenExpMins, @@ -817,7 +820,7 @@ function publishAsync( projectId, privateKeyFile, algorithm -) { +) => { // [START iot_mqtt_publish] // If we have published enough messages or backed off too many times, stop. if (messagesSent > numMessages || backoffTime >= MAXIMUM_BACKOFF_TIME) { @@ -890,7 +893,7 @@ function publishAsync( }, schedulePublishDelayMs); }, publishDelayMs); // [END iot_mqtt_publish] -} +}; let argv = require(`yargs`) // eslint-disable-line .demandCommand(1, 'You need at least one command before moving on') @@ -971,133 +974,122 @@ let argv = require(`yargs`) // eslint-disable-line `createGateway `, `Creates a gateway`, {}, - opts => { - const cb = function(client) { - createGateway( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.gatewayId, - opts.publicKeyFile, - opts.algorithm - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await createGateway( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.gatewayId, + opts.publicKeyFile, + opts.algorithm + ); } ) .command( `listGateways `, `Lists gateways in a registry.`, {}, - opts => { - const cb = function(client) { - listGateways(client, opts.projectId, opts.cloudRegion, opts.registryId); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await listGateways( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId + ); } ) .command( `bindDeviceToGateway `, `Binds a device to a gateway`, {}, - opts => { - const cb = function(client) { - bindDeviceToGateway( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.deviceId, - opts.gatewayId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await bindDeviceToGateway( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.deviceId, + opts.gatewayId + ); } ) .command( `unbindDeviceFromGateway `, `Unbinds a device from a gateway`, {}, - opts => { - const cb = function(client) { - unbindDeviceFromGateway( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.deviceId, - opts.gatewayId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await unbindDeviceFromGateway( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.deviceId, + opts.gatewayId + ); } ) .command( `unbindDeviceFromAllGateways `, `Unbinds a device from all gateways`, {}, - opts => { - const cb = function(client) { - unbindDeviceFromAllGateways( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.deviceId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await unbindDeviceFromAllGateways( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.deviceId + ); } ) .command( `unbindAllDevices `, `Unbinds all devices in a given registry. Mainly for clearing registries`, {}, - opts => { - const cb = client => { - unbindAllDevices( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await unbindAllDevices( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId + ); } ) .command( `listDevicesForGateway `, `Lists devices in a gateway.`, {}, - opts => { - const cb = function(client) { - listDevicesForGateway( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.gatewayId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await listDevicesForGateway( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.gatewayId + ); } ) .command( `listGatewaysForDevice `, `Lists gateways for a given device.`, {}, - opts => { - const cb = function(client) { - listGatewaysForDevice( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.deviceId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await listGatewaysForDevice( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.deviceId + ); } ) .command( diff --git a/iot/http_example/cloudiot_http_example.js b/iot/http_example/cloudiot_http_example.js index 568906c0ba..63cf9459a4 100644 --- a/iot/http_example/cloudiot_http_example.js +++ b/iot/http_example/cloudiot_http_example.js @@ -21,7 +21,7 @@ const request = require('retry-request', {request: require('request')}); // [END iot_http_includes] console.log('Google Cloud IoT Core HTTP example.'); -const argv = require(`yargs`) +const {argv} = require(`yargs`) .options({ projectId: { default: process.env.GCLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, @@ -94,7 +94,7 @@ const argv = require(`yargs`) .recommendCommands() .epilogue(`For more information, see https://cloud.google.com/iot-core/docs`) .help() - .strict().argv; + .strict(); // [START iot_http_variables] // A unique string that identifies this device. For Google Cloud IoT Core, it diff --git a/iot/manager/manager.js b/iot/manager/manager.js index afadc5a49b..31e08e2378 100644 --- a/iot/manager/manager.js +++ b/iot/manager/manager.js @@ -13,6 +13,8 @@ * limitations under the License. */ +/* eslint-disable prefer-destructuring */ + 'use strict'; const fs = require('fs'); @@ -25,70 +27,64 @@ const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest'; const client = new iot.v1.DeviceManagerClient(); // Configures the topic for Cloud IoT Core. -function setupIotTopic(topicName) { +const setupIotTopic = async topicName => { const {PubSub} = require('@google-cloud/pubsub'); const pubsub = new PubSub(); const topic = pubsub.topic(topicName); const serviceAccount = `serviceAccount:cloud-iot@system.gserviceaccount.com`; - topic.iam - .getPolicy() - .then(results => { - const policy = results[0] || {}; - policy.bindings || (policy.bindings = []); - console.log(JSON.stringify(policy, null, 2)); - - let hasRole = false; - let binding = { - role: 'roles/pubsub.publisher', - members: [serviceAccount], - }; + let policy = await topic.iam.getPolicy(); + policy = policy[0] || {}; - policy.bindings.forEach(_binding => { - if (_binding.role === binding.role) { - binding = _binding; - hasRole = true; - return false; - } - }); + policy.bindings || (policy.bindings = []); + console.log(JSON.stringify(policy, null, 2)); - if (hasRole) { - binding.members || (binding.members = []); - if (binding.members.indexOf(serviceAccount) === -1) { - binding.members.push(serviceAccount); - } - } else { - policy.bindings.push(binding); - } + let hasRole = false; + let binding = { + role: 'roles/pubsub.publisher', + members: [serviceAccount], + }; - // Updates the IAM policy for the topic - return topic.iam.setPolicy(policy); - }) - .then(results => { - const updatedPolicy = results[0]; + policy.bindings.forEach(_binding => { + if (_binding.role === binding.role) { + binding = _binding; + hasRole = true; + return false; + } + }); - console.log(JSON.stringify(updatedPolicy, null, 2)); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} + if (hasRole) { + binding.members || (binding.members = []); + if (binding.members.indexOf(serviceAccount) === -1) { + binding.members.push(serviceAccount); + } + } else { + policy.bindings.push(binding); + } + + // Updates the IAM policy for the topic + try { + const [updatedPolicy] = await topic.iam.setPolicy(policy); + console.log(JSON.stringify(updatedPolicy, null, 2)); + } catch (err) { + console.error('ERROR:', err); + } +}; -function createIotTopic(topicName) { +const createIotTopic = async topicName => { // Imports the Google Cloud client library const {PubSub} = require('@google-cloud/pubsub'); // Instantiates a client const pubsub = new PubSub(); - pubsub.createTopic(topicName).then(() => { - setupIotTopic(topicName); - }); -} + await pubsub.createTopic(topicName); + await setupIotTopic(topicName); +}; // Lookup the registry, assuming that it exists. -function lookupRegistry(client, registryId, projectId, cloudRegion) { +const lookupRegistry = async (client, registryId, projectId, cloudRegion) => { // [START iot_lookup_registry] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -101,26 +97,25 @@ function lookupRegistry(client, registryId, projectId, cloudRegion) { name: registryName, }; - client.projects.locations.registries.get(request, (err, res) => { - if (err) { - console.log('Could not look up registry'); - console.log(err); - } else { - console.log('Looked up existing registry'); - console.log(res.data); - } - }); + try { + const {data} = await client.projects.locations.registries.get(request); + + console.log('Looked up existing registry'); + console.log(data); + } catch (err) { + console.log('Could not look up registry'); + console.log(err); + } // [END iot_lookup_registry] -} +}; -function createRegistry( +const createRegistry = async ( client, registryId, projectId, cloudRegion, - pubsubTopicId, - foundCb -) { + pubsubTopicId +) => { // [START iot_create_registry] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -143,52 +138,20 @@ function createRegistry( }, }; - client.projects.locations.registries.create(request, (err, res) => { - if (err) { - if (err.code === 409) { - // The registry already exists - look it up instead. - foundCb(client, registryId, projectId, cloudRegion); - } else { - console.log('Could not create registry'); - console.log(err); - } - } else { - console.log('Successfully created registry'); - console.log(res.data); - } - }); - // [END iot_create_registry] -} - -// Create a new registry, or look up an existing one if it doesn't exist. -function lookupOrCreateRegistry( - client, - registryId, - projectId, - cloudRegion, - pubsubTopicId -) { - // [START iot_lookup_or_create_registry] - // Client retrieved in callback - // getClient(serviceAccountJson, function(client) {...}); - // const cloudRegion = 'us-central1'; - // const projectId = 'adjective-noun-123'; - // const registryId = 'my-registry'; - // const pubsubTopicId = 'my-iot-topic'; + try { + const {data} = await client.projects.locations.registries.create(request); - createRegistry( - client, - registryId, - projectId, - cloudRegion, - pubsubTopicId, - lookupRegistry - ); - // [END iot_lookup_or_create_registry] -} + console.log('Successfully created registry'); + console.log(data); + } catch (err) { + console.log('Could not create registry'); + console.log(err); + } + // [END iot_create_registry] +}; // Create a new device with a given public key format -function createDevice( +const createDevice = async ( client, deviceId, registryId, @@ -196,7 +159,7 @@ function createDevice( cloudRegion, publicKeyFormat, publicKeyFile -) { +) => { // [START iot_create_device] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -224,27 +187,29 @@ function createDevice( resource: body, }; - client.projects.locations.registries.devices.create(request, (err, res) => { - if (err) { - console.log('Could not create device'); - console.log(err); - } else { - console.log('Created device'); - console.log(res.data); - } - }); + try { + const {data} = await client.projects.locations.registries.devices.create( + request + ); + + console.log('Created device'); + console.log(data); + } catch (err) { + console.log('Could not create device'); + console.log(err); + } // [END iot_create_device] -} +}; // Create a new device with the given id. The body defines the parameters for // the device, such as authentication. -function createUnauthDevice( +const createUnauthDevice = async ( client, deviceId, registryId, projectId, cloudRegion -) { +) => { // [START iot_create_unauth_device] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -261,27 +226,29 @@ function createUnauthDevice( resource: {id: deviceId}, }; - client.projects.locations.registries.devices.create(request, (err, res) => { - if (err) { - console.log('Could not create device'); - console.log(err); - } else { - console.log('Created device'); - console.log(res.data); - } - }); + try { + const {data} = await client.projects.locations.registries.devices.create( + request + ); + + console.log('Created device'); + console.log(data); + } catch (err) { + console.log('Could not create device'); + console.log(err); + } // [END iot_create_unauth_device] -} +}; // Create a device using RSA256 for authentication. -function createRsaDevice( +const createRsaDevice = async ( client, deviceId, registryId, projectId, cloudRegion, rsaCertificateFile -) { +) => { // [START iot_create_rsa_device] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -310,27 +277,29 @@ function createRsaDevice( console.log(JSON.stringify(request)); - client.projects.locations.registries.devices.create(request, (err, res) => { - if (err) { - console.log('Could not create device'); - console.log(err); - } else { - console.log('Created device'); - console.log(res.data); - } - }); + try { + const {data} = await client.projects.locations.registries.devices.create( + request + ); + + console.log('Created device'); + console.log(data); + } catch (err) { + console.log('Could not create device'); + console.log(err); + } // [END iot_create_rsa_device] -} +}; // Create a device using ES256 for authentication. -function createEsDevice( +const createEsDevice = async ( client, deviceId, registryId, projectId, cloudRegion, esCertificateFile -) { +) => { // [START iot_create_es_device] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -357,27 +326,29 @@ function createEsDevice( resource: body, }; - client.projects.locations.registries.devices.create(request, (err, res) => { - if (err) { - console.log('Could not create device'); - console.log(err); - } else { - console.log('Created device'); - console.log(res.data); - } - }); + try { + const {data} = await client.projects.locations.registries.devices.create( + request + ); + + console.log('Created device'); + console.log(data); + } catch (err) { + console.log('Could not create device'); + console.log(err); + } // [END iot_create_es_device] -} +}; // Add RSA256 authentication to the given device. -function patchRsa256ForAuth( +const patchRsa256ForAuth = async ( client, deviceId, registryId, rsaPublicKeyFile, projectId, cloudRegion -) { +) => { // [START iot_patch_rsa] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -402,27 +373,29 @@ function patchRsa256ForAuth( }, }; - client.projects.locations.registries.devices.patch(request, (err, res) => { - if (err) { - console.log('Error patching device:', deviceId); - console.log(err); - } else { - console.log('Patched device:', deviceId); - console.log(res.data); - } - }); + try { + const {data} = await client.projects.locations.registries.devices.patch( + request + ); + + console.log('Patched device:', deviceId); + console.log(data); + } catch (err) { + console.log('Error patching device:', deviceId); + console.log(err); + } // [END iot_patch_rsa] -} +}; // Add ES256 authentication to the given device. -function patchEs256ForAuth( +const patchEs256ForAuth = async ( client, deviceId, registryId, esPublicKeyFile, projectId, cloudRegion -) { +) => { // [START iot_patch_es] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -447,20 +420,22 @@ function patchEs256ForAuth( }, }; - client.projects.locations.registries.devices.patch(request, (err, res) => { - if (err) { - console.log('Error patching device:', deviceId); - console.log(err); - } else { - console.log('Patched device:', deviceId); - console.log(res.data); - } - }); + try { + const {data} = await client.projects.locations.registries.devices.patch( + request + ); + + console.log('Patched device:', deviceId); + console.log(data); + } catch (err) { + console.log('Error patching device:', deviceId); + console.log(err); + } // [END iot_patch_es] -} +}; // List all of the devices in the given registry. -function listDevices(client, registryId, projectId, cloudRegion) { +const listDevices = async (client, registryId, projectId, cloudRegion) => { // [START iot_list_devices] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -474,20 +449,20 @@ function listDevices(client, registryId, projectId, cloudRegion) { parent: registryName, }; - client.projects.locations.registries.devices.list(request, (err, res) => { - if (err) { - console.log('Could not list devices'); - console.log(err); - } else { - const data = res.data; - console.log('Current devices in registry:', data['devices']); - } - }); + try { + const {data} = await client.projects.locations.registries.devices.list( + request + ); + console.log('Current devices in registry:', data['devices']); + } catch (err) { + console.log('Could not list devices'); + console.log(err); + } // [END iot_list_devices] -} +}; // List all of the registries in the given project. -function listRegistries(client, projectId, cloudRegion) { +const listRegistries = async (client, projectId, cloudRegion) => { // [START iot_list_registries] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -499,27 +474,24 @@ function listRegistries(client, projectId, cloudRegion) { parent: parentName, }; - client.projects.locations.registries.list(request, (err, res) => { - if (err) { - console.log('Could not list registries'); - console.log(err); - } else { - const data = res.data; - console.log('Current registries in project:\n', data['deviceRegistries']); - } - }); + try { + const {data} = await client.projects.locations.registries.list(request); + console.log('Current registries in project:\n', data['deviceRegistries']); + } catch (err) { + console.log('Could not list registries'); + console.log(err); + } // [END iot_list_registries] -} +}; // Delete the given device from the registry. -function deleteDevice( +const deleteDevice = async ( client, deviceId, registryId, projectId, - cloudRegion, - cb -) { + cloudRegion +) => { // [START iot_delete_device] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -532,79 +504,75 @@ function deleteDevice( name: `${registryName}/devices/${deviceId}`, }; - client.projects.locations.registries.devices.delete(request, (err, res) => { - if (err) { - console.log('Could not delete device:', deviceId); - console.log(err); - } else { - console.log('Successfully deleted device:', deviceId); - console.log(res.data); - if (cb) { - cb(); - } - } - }); + try { + const {data} = await client.projects.locations.registries.devices.delete( + request + ); + + console.log('Successfully deleted device:', deviceId); + console.log(data); + } catch (err) { + console.log('Could not delete device:', deviceId); + console.log(err); + } // [END iot_delete_device] -} +}; // Clear the given registry by removing all devices and deleting the registry. -function clearRegistry(client, registryId, projectId, cloudRegion) { +const clearRegistry = async (client, registryId, projectId, cloudRegion) => { const parentName = `projects/${projectId}/locations/${cloudRegion}`; const registryName = `${parentName}/registries/${registryId}`; const requestDelete = { name: registryName, }; - const after = function() { - client.projects.locations.registries.delete(requestDelete, (err, res) => { - if (err) { - console.log('Could not delete registry', err); - } else { - console.log(`Successfully deleted registry ${registryName}`); - console.log(res.data); - } - }); - }; - const request = { parent: registryName, }; - client.projects.locations.registries.devices.list(request, (err, res) => { - if (err) { - console.log('Could not list devices', err); - return; - } + let devices; + try { + const {data} = await client.projects.locations.registries.devices.list( + request + ); + devices = data.devices; + } catch (err) { + console.log('Could not list devices', err); + return; + } - const data = res.data; - console.log('Current devices in registry:', data['devices']); - const devices = data['devices']; + // Delete devices in registry + console.log('Current devices in registry:', devices); + if (devices) { + const promises = devices.map((device, index) => { + console.log(`${device.id} [${index}/${devices.length}] removed`); + return deleteDevice( + client, + device.id, + registryId, + projectId, + cloudRegion + ); + }); + await Promise.all(promises); + } - if (devices) { - devices.forEach((device, index) => { - console.log(`${device.id} [${index}/${devices.length}] removed`); - if (index === devices.length - 1) { - deleteDevice( - client, - device.id, - registryId, - projectId, - cloudRegion, - after - ); - } else { - deleteDevice(client, device.id, registryId, projectId, cloudRegion); - } - }); - } else { - after(); - } - }); -} + // Delete registry + try { + const {data} = await client.projects.locations.registries.delete( + requestDelete + ); + + console.log(`Successfully deleted registry ${registryName}`); + console.log(data); + } catch (err) { + console.log('Could not delete registry', err); + } +}; // Delete the given registry. Note that this will only succeed if the registry // is empty. -function deleteRegistry(client, registryId, projectId, cloudRegion) { +const deleteRegistry = async (client, registryId, projectId, cloudRegion) => { // [START iot_delete_registry] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -617,20 +585,26 @@ function deleteRegistry(client, registryId, projectId, cloudRegion) { name: registryName, }; - client.projects.locations.registries.delete(request, (err, res) => { - if (err) { - console.log('Could not delete registry'); - console.log(err); - } else { - console.log('Successfully deleted registry'); - console.log(res); - } - }); + try { + const res = await client.projects.locations.registries.delete(request); + + console.log('Successfully deleted registry'); + console.log(res); + } catch (err) { + console.log('Could not delete registry'); + console.log(err); + } // [END iot_delete_registry] -} +}; // Retrieve the given device from the registry. -function getDevice(client, deviceId, registryId, projectId, cloudRegion) { +const getDevice = async ( + client, + deviceId, + registryId, + projectId, + cloudRegion +) => { // [START iot_get_device] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -644,20 +618,28 @@ function getDevice(client, deviceId, registryId, projectId, cloudRegion) { name: `${registryName}/devices/${deviceId}`, }; - client.projects.locations.registries.devices.get(request, (err, res) => { - if (err) { - console.log('Could not find device:', deviceId); - console.log(err); - } else { - console.log('Found device:', deviceId); - console.log(res.data); - } - }); + try { + const {data} = await client.projects.locations.registries.devices.get( + request + ); + + console.log('Found device:', deviceId); + console.log(data); + } catch (err) { + console.log('Could not find device:', deviceId); + console.log(err); + } // [END iot_get_device] -} +}; // Retrieve the given device's state from the registry. -function getDeviceState(client, deviceId, registryId, projectId, cloudRegion) { +const getDeviceState = async ( + client, + deviceId, + registryId, + projectId, + cloudRegion +) => { // [START iot_get_device_state] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -671,28 +653,26 @@ function getDeviceState(client, deviceId, registryId, projectId, cloudRegion) { name: `${registryName}/devices/${deviceId}`, }; - client.projects.locations.registries.devices.states.list( - request, - (err, data) => { - if (err) { - console.log('Could not find device:', deviceId); - console.log(err); - } else { - console.log('State:', data.data); - } - } - ); + try { + const { + data, + } = await client.projects.locations.registries.devices.states.list(request); + console.log('State:', data); + } catch (err) { + console.log('Could not find device:', deviceId); + console.log(err); + } // [END iot_get_device_state] -} +}; // Retrieve the given device's configuration history from the registry. -function getDeviceConfigs( +const getDeviceConfigs = async ( client, deviceId, registryId, projectId, cloudRegion -) { +) => { // [START iot_get_device_configs] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -706,22 +686,23 @@ function getDeviceConfigs( name: `${registryName}/devices/${deviceId}`, }; - client.projects.locations.registries.devices.configVersions.list( - request, - (err, data) => { - if (err) { - console.log('Could not find device:', deviceId); - console.log(err); - } else { - console.log('Configs:', data.data); - } - } - ); + try { + const { + data, + } = await client.projects.locations.registries.devices.configVersions.list( + request + ); + + console.log('Configs:', data); + } catch (err) { + console.log('Could not find device:', deviceId); + console.log(err); + } // [END iot_get_device_configs] -} +}; // Send configuration data to device. -function setDeviceConfig( +const setDeviceConfig = async ( client, deviceId, registryId, @@ -729,7 +710,7 @@ function setDeviceConfig( cloudRegion, data, version -) { +) => { // [START iot_set_device_config] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -749,28 +730,29 @@ function setDeviceConfig( binaryData: binaryData, }; - client.projects.locations.registries.devices.modifyCloudToDeviceConfig( - request, - (err, data) => { - if (err) { - console.log('Could not update config:', deviceId); - console.log('Message: ', err); - } else { - console.log('Success :', data); - } - } - ); + try { + const { + data, + } = await client.projects.locations.registries.devices.modifyCloudToDeviceConfig( + request + ); + + console.log('Success:', data); + } catch (err) { + console.log('Could not update config:', deviceId); + console.log('Message:', err); + } // [END iot_set_device_config] -} +}; // sends a command to a specified device subscribed to the commands topic -function sendCommand( +const sendCommand = async ( deviceId, registryId, projectId, cloudRegion, commandMessage -) { +) => { // [START iot_send_command] // const iot = require('@google-cloud/iot'); // const client = new iot.v1.DeviceManagerClient(); @@ -796,19 +778,18 @@ function sendCommand( //subfolder: }; - client - .sendCommandToDevice(request) - .then(() => { - console.log('Sent command'); - }) - .catch(err => { - console.error(err); - }); + try { + await client.sendCommandToDevice(request); + + console.log('Sent command'); + } catch (err) { + console.error(err); + } // [END iot_send_command] -} +}; // Retrieve the given device from the registry. -function getRegistry(client, registryId, projectId, cloudRegion) { +const getRegistry = async (client, registryId, projectId, cloudRegion) => { // [START iot_get_registry] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -821,48 +802,43 @@ function getRegistry(client, registryId, projectId, cloudRegion) { name: `${registryName}`, }; - client.projects.locations.registries.get(request, (err, data) => { - if (err) { - console.log('Could not find registry:', registryId); - console.log(err); - } else { - console.log('Found registry:', registryId); - console.log(data.data); - } - }); + try { + const {data} = await client.projects.locations.registries.get(request); + + console.log('Found registry:', registryId); + console.log(data); + } catch (err) { + console.log('Could not find registry:', registryId); + console.log(err); + } // [END iot_get_registry] -} +}; // Returns an authorized API client by discovering the Cloud IoT Core API with // the provided API key. -function getClient(serviceAccountJson, cb) { +const getClient = async serviceAccountJson => { // the getClient method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS // environment variables if serviceAccountJson is not passed in - google.auth - .getClient({ - keyFilename: serviceAccountJson, - scopes: ['https://www.googleapis.com/auth/cloud-platform'], - }) - .then(authClient => { - const discoveryUrl = `${DISCOVERY_API}?version=${API_VERSION}`; - - google.options({ - auth: authClient, - }); - - google - .discoverAPI(discoveryUrl) - .then(client => { - cb(client); - }) - .catch(err => { - console.log('Error during API discovery.', err); - }); - }); -} + const authClient = await google.auth.getClient({ + keyFilename: serviceAccountJson, + scopes: ['https://www.googleapis.com/auth/cloud-platform'], + }); + + const discoveryUrl = `${DISCOVERY_API}?version=${API_VERSION}`; + + google.options({ + auth: authClient, + }); + + try { + return google.discoverAPI(discoveryUrl); + } catch (err) { + console.log('Error during API discovery.', err); + } +}; // Retrieves the IAM policy for a given registry. -function getIamPolicy(client, registryId, projectId, cloudRegion) { +const getIamPolicy = async (client, registryId, projectId, cloudRegion) => { // [START iot_get_iam_policy] // Client retrieved in callback // getClient(serviceAccountJson, function(client) {...}); @@ -875,35 +851,40 @@ function getIamPolicy(client, registryId, projectId, cloudRegion) { resource_: `${registryName}`, }; - client.projects.locations.registries.getIamPolicy(request, (err, data) => { - if (err) { - console.log('Could not find policy for: ', registryId); - console.log('Trace: ', err); - } else { - data = data.data; - console.log(`ETAG: ${data.etag}`); - data.bindings = data.bindings || []; - data.bindings.forEach(_binding => { - console.log(`Role: ${_binding.role}`); - _binding.members || (_binding.members = []); - _binding.members.forEach(_member => { - console.log(`\t${_member}`); - }); - }); - } + let bindings, etag; + try { + const {data} = await client.projects.locations.registries.getIamPolicy( + request + ); + bindings = data.bindings; + etag = data.etag; + } catch (err) { + console.log('Could not find policy for: ', registryId); + console.log('Trace: ', err); + return; + } + + console.log(`ETAG: ${etag}`); + bindings = bindings || []; + bindings.forEach(_binding => { + console.log(`Role: ${_binding.role}`); + _binding.members || (_binding.members = []); + _binding.members.forEach(_member => { + console.log(`\t${_member}`); + }); }); // [END iot_get_iam_policy] -} +}; // Sets the IAM permissions for a given registry to a single member / role. -function setIamPolicy( +const setIamPolicy = async ( client, registryId, projectId, cloudRegion, member, role -) { +) => { // [START iot_set_iam_policy] // Client retrieved in callback // setClient(serviceAccountJson, function(client) {...}); @@ -926,28 +907,34 @@ function setIamPolicy( }, }; - client.projects.locations.registries.setIamPolicy(request, (err, data) => { - if (err) { - console.log('Could not set policy for: ', registryId); - console.log('Trace: ', err); - } else { - console.log(`ETAG: ${data.etag}`); - console.log(JSON.stringify(data)); - data.bindings = data.bindings || []; - data.bindings.forEach(_binding => { - console.log(`Role: ${_binding.role}`); - _binding.members || (_binding.members = []); - _binding.members.forEach(_member => { - console.log(`\t${_member}`); - }); - }); - } + let bindings, etag; + try { + const {data} = await client.projects.locations.registries.setIamPolicy( + request + ); + bindings = data.bindings; + etag = data.etag; + + console.log(JSON.stringify(data)); + } catch (err) { + console.log('Could not set policy for: ', registryId); + console.log('Trace: ', err); + } + + console.log(`ETAG: ${etag}`); + bindings = bindings || []; + bindings.forEach(_binding => { + console.log(`Role: ${_binding.role}`); + _binding.members || (_binding.members = []); + _binding.members.forEach(_member => { + console.log(`\t${_member}`); + }); }); // [END iot_set_iam_policy] -} +}; // Creates a gateway. -function createGateway( +const createGateway = async ( client, projectId, cloudRegion, @@ -955,7 +942,7 @@ function createGateway( gatewayId, publicKeyFormat, publicKeyFile -) { +) => { // [START iot_create_gateway] // const cloudRegion = 'us-central1'; // const deviceId = 'my-unauth-device'; @@ -991,30 +978,29 @@ function createGateway( }, }; - client.projects.locations.registries.devices.create( - createRequest, - (err, res) => { - if (err) { - console.log('Could not create device'); - console.log(err); - } else { - console.log('Created device'); - console.log(res.data); - } - } - ); + try { + const {data} = await client.projects.locations.registries.devices.create( + createRequest + ); + + console.log('Created device'); + console.log(data); + } catch (err) { + console.log('Could not create device'); + console.log(err); + } // [END iot_create_gateway] -} +}; // Binds a device to a gateway so that it can be attached. -function bindDeviceToGateway( +const bindDeviceToGateway = async ( client, projectId, cloudRegion, registryId, deviceId, gatewayId -) { +) => { // [START iot_bind_device_to_gateway] // const cloudRegion = 'us-central1'; // const deviceId = 'my-unauth-device'; @@ -1031,25 +1017,25 @@ function bindDeviceToGateway( gatewayId: gatewayId, }; - client.projects.locations.registries.bindDeviceToGateway(bindRequest, err => { - if (err) { - console.log('Could not bind device', err); - } else { - console.log(`Bound ${deviceId} to`, gatewayId); - } - }); + try { + await client.projects.locations.registries.bindDeviceToGateway(bindRequest); + + console.log(`Bound ${deviceId} to`, gatewayId); + } catch (err) { + console.log('Could not bind device', err); + } // [END iot_bind_device_to_gateway] -} +}; // Unbinds a device from a gateway. -function unbindDeviceFromGateway( +const unbindDeviceFromGateway = async ( client, projectId, cloudRegion, registryId, deviceId, gatewayId -) { +) => { // [START iot_unbind_device_to_gateway] // const cloudRegion = 'us-central1'; // const deviceId = 'my-unauth-device'; @@ -1065,27 +1051,26 @@ function unbindDeviceFromGateway( gatewayId: gatewayId, }; - client.projects.locations.registries.unbindDeviceFromGateway( - unbindRequest, - err => { - if (err) { - console.log('Could not unbind device', err); - } else { - console.log(`Unbound ${deviceId} from`, gatewayId); - } - } - ); + try { + await client.projects.locations.registries.unbindDeviceFromGateway( + unbindRequest + ); + + console.log(`Unbound ${deviceId} from`, gatewayId); + } catch (err) { + console.log('Could not unbind device', err); + } // [END iot_unbind_device_to_gateway] -} +}; // Unbinds the given device from all gateways -function unbindDeviceFromAllGateways( +const unbindDeviceFromAllGateways = async ( client, projectId, cloudRegion, registryId, deviceId -) { +) => { const parentName = `projects/${projectId}/locations/${cloudRegion}`; const registryName = `${parentName}/registries/${registryId}`; const request = { @@ -1093,63 +1078,70 @@ function unbindDeviceFromAllGateways( }; // get information about this device - client.projects.locations.registries.devices.get(request, (err, res) => { - if (err) { - console.error('Could not get device', err); - return; - } + let device; + try { + const {data} = await client.projects.locations.registries.devices.get( + request + ); + device = data; + } catch (err) { + console.error('Could not get device', err); + return; + } - const device = res.data; - if (device) { - const isGateway = device.gatewayConfig.gatewayType === 'GATEWAY'; - - if (!isGateway) { - const listGatewaysForDeviceRequest = { - parent: registryName, - 'gatewayListOptions.associationsDeviceId': deviceId, - }; - - // get list of all gateways this non-gateway device is bound to - client.projects.locations.registries.devices.list( - listGatewaysForDeviceRequest, - (err, res) => { - if (err) { - console.error('Could not list gateways', err); - return; - } + if (device) { + const isGateway = device.gatewayConfig.gatewayType === 'GATEWAY'; - const data = res.data; - if (data.devices && data.devices.length > 0) { - const gateways = data.devices; - - gateways.forEach(gateway => { - const unbindRequest = { - parent: registryName, - deviceId: device.id, - gatewayId: gateway.id, - }; - - // for each gateway, make the call to unbind it - client.projects.locations.registries.unbindDeviceFromGateway( - unbindRequest, - err => { - if (err) { - console.log('Could not unbind device', err); - } else { - console.log('Unbound device from gateways', gateway.id); - } - } - ); - }); - } - } + if (!isGateway) { + const listGatewaysForDeviceRequest = { + parent: registryName, + 'gatewayListOptions.associationsDeviceId': deviceId, + }; + + // get list of all gateways this non-gateway device is bound to + let gateways; + try { + const { + devices, + } = await client.projects.locations.registries.devices.list( + listGatewaysForDeviceRequest ); + gateways = devices; + } catch (err) { + console.error('Could not list gateways', err); + return; + } + + if (gateways && gateways > 0) { + const promises = gateways.map(gateway => { + const unbindRequest = { + parent: registryName, + deviceId: device.id, + gatewayId: gateway.id, + }; + + // for each gateway, make the call to unbind it + return new Promise((resolve, reject) => { + try { + client.projects.locations.registries.unbindDeviceFromGateway( + unbindRequest + ); + console.log('Unbound device from gateways', gateway.id); + resolve(); + } catch (err) { + console.log('Could not unbind device', err); + reject(); + } + }); + }); + + return Promise.all(promises); } } - }); -} + } +}; -function unbindAllDevices(client, projectId, cloudRegion, registryId) { +const unbindAllDevices = async (client, projectId, cloudRegion, registryId) => { const parentName = `projects/${projectId}/locations/${cloudRegion}`; const registryName = `${parentName}/registries/${registryId}`; const request = { @@ -1157,43 +1149,42 @@ function unbindAllDevices(client, projectId, cloudRegion, registryId) { }; // get information about this device - client.projects.locations.registries.devices.list(request, (err, res) => { - if (err) { - console.log('Could not list devices', err); - return; - } + let devices; + try { + const {data} = await client.projects.locations.registries.devices.list( + request + ); + devices = data.devices; + } catch (err) { + console.log('Could not list devices', err); + return; + } - const data = res.data; - if (!data) { - return; - } + if (devices && devices.length > 0) { + const promises = devices.map(device => { + if (device) { + const isGateway = + device.gatewayConfig && + device.gatewayConfig.gatewayType === 'GATEWAY'; - const devices = data.devices; - - if (devices && devices.length > 0) { - devices.forEach(device => { - if (device) { - const isGateway = - device.gatewayConfig && - device.gatewayConfig.gatewayType === 'GATEWAY'; - - if (!isGateway) { - unbindDeviceFromAllGateways( - client, - projectId, - cloudRegion, - registryId, - device.id - ); - } + if (!isGateway) { + return unbindDeviceFromAllGateways( + client, + projectId, + cloudRegion, + registryId, + device.id + ); } - }); - } - }); -} + } + }); + + return Promise.all(promises); + } +}; // Lists gateways in a registry. -function listGateways(client, projectId, cloudRegion, registryId) { +const listGateways = async (client, projectId, cloudRegion, registryId) => { // [START iot_list_gateways] // const cloudRegion = 'us-central1'; // const projectId = 'adjective-noun-123'; @@ -1204,36 +1195,40 @@ function listGateways(client, projectId, cloudRegion, registryId) { fieldMask: 'config,gatewayConfig', }; - client.projects.locations.registries.devices.list(request, (err, res) => { - if (err) { - console.log('Could not list devices'); - console.log(err); + let devices; + try { + const {data} = await client.projects.locations.registries.devices.list( + request + ); + devices = data.devices; + } catch (err) { + console.log('Could not list devices'); + console.log(err); + return; + } + + console.log('Current gateways in registry:'); + devices.forEach(device => { + if ( + device.gatewayConfig !== undefined && + device.gatewayConfig.gatewayType === 'GATEWAY' + ) { + console.log('----\n', device); } else { - const data = res.data; - console.log('Current gateways in registry:'); - data.devices.forEach(device => { - if ( - device.gatewayConfig !== undefined && - device.gatewayConfig.gatewayType === 'GATEWAY' - ) { - console.log('----\n', device); - } else { - console.log('\t', device); - } - }); + console.log('\t', device); } }); // [END iot_list_gateways] -} +}; // Lists devices bound to a gateway. -function listDevicesForGateway( +const listDevicesForGateway = async ( client, projectId, cloudRegion, registryId, gatewayId -) { +) => { // [START iot_list_devices_for_gateway] // const cloudRegion = 'us-central1'; // const gatewayId = 'my-gateway'; @@ -1245,33 +1240,37 @@ function listDevicesForGateway( 'gatewayListOptions.associationsGatewayId': gatewayId, }; - client.projects.locations.registries.devices.list(request, (err, res) => { - if (err) { - console.log('Could not list devices'); - console.log(err); - } else { - console.log('Current devices bound to gateway: ', gatewayId); - const data = res.data; - if (data.devices && data.devices.length > 0) { - data.devices.forEach(device => { - console.log(`\tDevice: ${device.numId} : ${device.id}`); - }); - } else { - console.log('No devices bound to this gateway.'); - } - } - }); + let devices; + try { + const {data} = await client.projects.locations.registries.devices.list( + request + ); + devices = data.devices; + } catch (err) { + console.log('Could not list devices'); + console.log(err); + return; + } + + console.log('Current devices bound to gateway: ', gatewayId); + if (devices && devices.length > 0) { + devices.forEach(device => { + console.log(`\tDevice: ${device.numId} : ${device.id}`); + }); + } else { + console.log('No devices bound to this gateway.'); + } // [END iot_list_devices_for_gateway] -} +}; // Lists gateways a given device is bound to. -function listGatewaysForDevice( +const listGatewaysForDevice = async ( client, projectId, cloudRegion, registryId, deviceId -) { +) => { // [START iot_list_gateways_for_device] // const cloudRegion = 'us-central1'; // const deviceId = 'my-device'; @@ -1283,24 +1282,28 @@ function listGatewaysForDevice( 'gatewayListOptions.associationsDeviceId': deviceId, }; - client.projects.locations.registries.devices.list(request, (err, res) => { - if (err) { - console.log('Could not list gateways for device'); - console.log(err); - } else { - console.log('Current gateways for device:', deviceId); - const data = res.data; - if (data.devices && data.devices.length > 0) { - data.devices.forEach(gateway => { - console.log(`\tDevice: ${gateway.numId} : ${gateway.id}`); - }); - } else { - console.log('No gateways associated with this device.'); - } - } - }); + let devices; + try { + const {data} = await client.projects.locations.registries.devices.list( + request + ); + devices = data.devices; + } catch (err) { + console.log('Could not list gateways for device'); + console.log(err); + return; + } + + console.log('Current gateways for device:', deviceId); + if (devices && devices.length > 0) { + devices.forEach(gateway => { + console.log(`\tDevice: ${gateway.numId} : ${gateway.id}`); + }); + } else { + console.log('No gateways associated with this device.'); + } // [END iot_list_gateways_for_device] -} +}; require(`yargs`) // eslint-disable-line .demand(1) @@ -1331,53 +1334,47 @@ require(`yargs`) // eslint-disable-line `createRsa256Device `, `Creates an RSA256 device.`, {}, - opts => { - const cb = function(client) { - createRsaDevice( - client, - opts.deviceId, - opts.registryId, - opts.projectId, - opts.cloudRegion, - opts.rsaPath - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await createRsaDevice( + client, + opts.deviceId, + opts.registryId, + opts.projectId, + opts.cloudRegion, + opts.rsaPath + ); } ) .command( `createEs256Device `, `Creates an ES256 device.`, {}, - opts => { - const cb = function(client) { - createEsDevice( - client, - opts.deviceId, - opts.registryId, - opts.projectId, - opts.cloudRegion, - opts.esPath - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await createEsDevice( + client, + opts.deviceId, + opts.registryId, + opts.projectId, + opts.cloudRegion, + opts.esPath + ); } ) .command( `createUnauthDevice `, `Creates a device without authorization.`, {}, - opts => { - const cb = function(client) { - createUnauthDevice( - client, - opts.deviceId, - opts.registryId, - opts.projectId, - opts.cloudRegion - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await createUnauthDevice( + client, + opts.deviceId, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); } ) .command( @@ -1398,36 +1395,46 @@ require(`yargs`) // eslint-disable-line type: 'string', }, }, - opts => { - const cb = client => { - createDevice( - client, - opts.deviceId, - opts.registryId, - opts.projectId, - opts.cloudRegion, - opts.publicKeyFormat, - opts.publicKeyFile - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await createDevice( + client, + opts.deviceId, + opts.registryId, + opts.projectId, + opts.cloudRegion, + opts.publicKeyFormat, + opts.publicKeyFile + ); } ) .command( `createRegistry `, `Creates a device registry.`, {}, - opts => { - const cb = function(client) { - lookupOrCreateRegistry( - client, - opts.registryId, - opts.projectId, - opts.cloudRegion, - opts.pubsubTopic - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await createRegistry( + client, + opts.registryId, + opts.projectId, + opts.cloudRegion, + opts.pubsubTopic + ); + } + ) + .command( + `lookupRegistry `, + `Gets a device registry.`, + {}, + async opts => { + const client = await getClient(opts.serviceAccount); + await lookupRegistry( + client, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); } ) .command( @@ -1446,191 +1453,182 @@ require(`yargs`) // eslint-disable-line `deleteDevice `, `Deletes a device from the device registry.`, {}, - opts => { - const cb = function(client) { - deleteDevice( - client, - opts.deviceId, - opts.registryId, - opts.projectId, - opts.cloudRegion - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await deleteDevice( + client, + opts.deviceId, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); } ) .command( `clearRegistry `, `!!Be careful! Removes all devices and then deletes a device registry!!`, {}, - opts => { - const cb = function(client) { - clearRegistry( - client, - opts.registryId, - opts.projectId, - opts.cloudRegion - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await clearRegistry( + client, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); } ) .command( `deleteRegistry `, `Deletes a device registry.`, {}, - opts => { - const cb = function(client) { - deleteRegistry( - client, - opts.registryId, - opts.projectId, - opts.cloudRegion - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await deleteRegistry( + client, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); } ) .command( `getDevice `, `Retrieves device info given a device ID.`, {}, - opts => { - const cb = function(client) { - getDevice( - client, - opts.deviceId, - opts.registryId, - opts.projectId, - opts.cloudRegion - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await getDevice( + client, + opts.deviceId, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); } ) .command( `getDeviceConfigs `, `Retrieves device configurations given a device ID.`, {}, - opts => { - const cb = function(client) { - getDeviceConfigs( - client, - opts.deviceId, - opts.registryId, - opts.projectId, - opts.cloudRegion - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + getDeviceConfigs( + client, + opts.deviceId, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); } ) .command( `getDeviceState `, `Retrieves device state given a device ID.`, {}, - opts => { - const cb = function(client) { - getDeviceState( - client, - opts.deviceId, - opts.registryId, - opts.projectId, - opts.cloudRegion - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + getDeviceState( + client, + opts.deviceId, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); + } + ) + .command( + `getRegistry `, + `Retrieves a registry.`, + {}, + async opts => { + const client = await getClient(opts.serviceAccount); + await getRegistry( + client, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); } ) - .command(`getRegistry `, `Retrieves a registry.`, {}, opts => { - const cb = function(client) { - getRegistry(client, opts.registryId, opts.projectId, opts.cloudRegion); - }; - getClient(opts.serviceAccount, cb); - }) .command( `listDevices `, `Lists the devices in a given registry.`, {}, - opts => { - const cb = function(client) { - listDevices(client, opts.registryId, opts.projectId, opts.cloudRegion); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await listDevices( + client, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); } ) .command( `listRegistries`, `Lists the registries in a given project.`, {}, - opts => { - const cb = function(client) { - listRegistries(client, opts.projectId, opts.cloudRegion); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await listRegistries(client, opts.projectId, opts.cloudRegion); } ) .command( `patchEs256 `, `Patches a device with ES256 authorization credentials.`, {}, - opts => { - const cb = function(client) { - patchEs256ForAuth( - client, - opts.deviceId, - opts.registryId, - opts.es256Path, - opts.projectId, - opts.cloudRegion - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await patchEs256ForAuth( + client, + opts.deviceId, + opts.registryId, + opts.es256Path, + opts.projectId, + opts.cloudRegion + ); } ) .command( `patchRsa256 `, `Patches a device with RSA256 authentication credentials.`, {}, - opts => { - const cb = function(client) { - patchRsa256ForAuth( - client, - opts.deviceId, - opts.registryId, - opts.rsa256Path, - opts.projectId, - opts.cloudRegion - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await patchRsa256ForAuth( + client, + opts.deviceId, + opts.registryId, + opts.rsa256Path, + opts.projectId, + opts.cloudRegion + ); } ) .command( `setConfig `, `Sets a devices configuration to the specified data.`, {}, - opts => { - const cb = function(client) { - setDeviceConfig( - client, - opts.deviceId, - opts.registryId, - opts.projectId, - opts.cloudRegion, - opts.configuration, - opts.version || 0 - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await setDeviceConfig( + client, + opts.deviceId, + opts.registryId, + opts.projectId, + opts.cloudRegion, + opts.configuration, + opts.version || 0 + ); } ) .command( `sendCommand `, `Sends a command message to a device subscribed to the commands topic`, {}, - opts => { - sendCommand( + async opts => { + await sendCommand( opts.deviceId, opts.registryId, opts.projectId, @@ -1643,29 +1641,30 @@ require(`yargs`) // eslint-disable-line `getIamPolicy `, `Gets the IAM permissions for a given registry`, {}, - opts => { - const cb = function(client) { - getIamPolicy(client, opts.registryId, opts.projectId, opts.cloudRegion); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await getIamPolicy( + client, + opts.registryId, + opts.projectId, + opts.cloudRegion + ); } ) .command( `setIamPolicy `, `Gets the IAM permissions for a given registry`, {}, - opts => { - const cb = function(client) { - setIamPolicy( - client, - opts.registryId, - opts.projectId, - opts.cloudRegion, - opts.member, - opts.role - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await setIamPolicy( + client, + opts.registryId, + opts.projectId, + opts.cloudRegion, + opts.member, + opts.role + ); } ) .command( @@ -1686,133 +1685,122 @@ require(`yargs`) // eslint-disable-line type: 'string', }, }, - opts => { - const cb = function(client) { - createGateway( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.gatewayId, - opts.publicKeyFormat, - opts.publicKeyFile - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await createGateway( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.gatewayId, + opts.publicKeyFormat, + opts.publicKeyFile + ); } ) .command( `listGateways `, `Lists gateways in a registry.`, {}, - opts => { - const cb = function(client) { - listGateways(client, opts.projectId, opts.cloudRegion, opts.registryId); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await listGateways( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId + ); } ) .command( `bindDeviceToGateway `, `Binds a device to a gateway`, {}, - opts => { - const cb = function(client) { - bindDeviceToGateway( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.deviceId, - opts.gatewayId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await bindDeviceToGateway( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.deviceId, + opts.gatewayId + ); } ) .command( `unbindDeviceFromGateway `, `Unbinds a device from a gateway`, {}, - opts => { - const cb = function(client) { - unbindDeviceFromGateway( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.deviceId, - opts.gatewayId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await unbindDeviceFromGateway( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.deviceId, + opts.gatewayId + ); } ) .command( `unbindDeviceFromAllGateways `, `Unbinds a device from all gateways`, {}, - opts => { - const cb = function(client) { - unbindDeviceFromAllGateways( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.deviceId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await unbindDeviceFromAllGateways( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.deviceId + ); } ) .command( `unbindAllDevices `, `Unbinds all devices in a given registry. Mainly for clearing registries`, {}, - opts => { - const cb = client => { - unbindAllDevices( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await unbindAllDevices( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId + ); } ) .command( `listDevicesForGateway `, `Lists devices in a gateway.`, {}, - opts => { - const cb = function(client) { - listDevicesForGateway( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.gatewayId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await listDevicesForGateway( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.gatewayId + ); } ) .command( `listGatewaysForDevice `, `Lists gateways for a given device.`, {}, - opts => { - const cb = function(client) { - listGatewaysForDevice( - client, - opts.projectId, - opts.cloudRegion, - opts.registryId, - opts.deviceId - ); - }; - getClient(opts.serviceAccount, cb); + async opts => { + const client = await getClient(opts.serviceAccount); + await listGatewaysForDevice( + client, + opts.projectId, + opts.cloudRegion, + opts.registryId, + opts.deviceId + ); } ) .example( diff --git a/iot/manager/system-test/manager.test.js b/iot/manager/system-test/manager.test.js index 7fe2f4b4d8..3c23c1aacb 100644 --- a/iot/manager/system-test/manager.test.js +++ b/iot/manager/system-test/manager.test.js @@ -81,15 +81,12 @@ it('should create and delete an unauthorized device', async () => { `${cmd} createUnauthDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual(new RegExp('Created device').test(output), true); + assert.ok(output.includes('Created device')); output = await tools.runAsync( `${cmd} deleteDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual( - new RegExp('Successfully deleted device').test(output), - true - ); + assert.ok(output.includes('Successfully deleted device')); }); it('should list configs for a device', async () => { @@ -98,20 +95,17 @@ it('should list configs for a device', async () => { `${cmd} createUnauthDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual(new RegExp('Created device').test(output), true); + assert.ok(output.includes('Created device')); output = await tools.runAsync( `${cmd} getDeviceConfigs ${localDevice} ${registryName}`, cwd ); - assert.strictEqual(new RegExp('Configs').test(output), true); + assert.ok(output.includes('Configs')); output = await tools.runAsync( `${cmd} deleteDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual( - new RegExp('Successfully deleted device').test(output), - true - ); + assert.ok(output.includes('Successfully deleted device')); }); it('should create and delete an RSA256 device', async () => { @@ -120,20 +114,17 @@ it('should create and delete an RSA256 device', async () => { `${cmd} createRsa256Device ${localDevice} ${registryName} ${rsaPublicCert}`, cwd ); - assert.strictEqual(new RegExp('Created device').test(output), true); + assert.ok(output.includes('Created device')); output = await tools.runAsync( `${cmd} getDeviceState ${localDevice} ${registryName}`, cwd ); - assert.strictEqual(new RegExp('State').test(output), true); + assert.ok(output.includes('State')); output = await tools.runAsync( `${cmd} deleteDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual( - new RegExp('Successfully deleted device').test(output), - true - ); + assert.ok(output.includes('Successfully deleted device')); }); it('should create and delete an ES256 device', async () => { @@ -142,20 +133,17 @@ it('should create and delete an ES256 device', async () => { `${cmd} createEs256Device ${localDevice} ${registryName} ${ecPublicKey}`, cwd ); - assert.strictEqual(new RegExp('Created device').test(output), true); + assert.ok(output.includes('Created device')); output = await tools.runAsync( `${cmd} getDeviceState ${localDevice} ${registryName}`, cwd ); - assert.strictEqual(new RegExp('State').test(output), true); + assert.ok(output.includes('State')); output = await tools.runAsync( `${cmd} deleteDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual( - new RegExp('Successfully deleted device').test(output), - true - ); + assert.ok(output.includes('Successfully deleted device')); }); it('should patch an unauthorized device with RSA256', async () => { @@ -164,20 +152,17 @@ it('should patch an unauthorized device with RSA256', async () => { `${cmd} createUnauthDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual(new RegExp('Created device').test(output), true); + assert.ok(output.includes('Created device')); output = await tools.runAsync( `${cmd} patchRsa256 ${localDevice} ${registryName} ${rsaPublicCert}`, cwd ); - assert.strictEqual(new RegExp('Patched device:').test(output), true); + assert.ok(output.includes('Patched device:')); output = await tools.runAsync( `${cmd} deleteDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual( - new RegExp('Successfully deleted device').test(output), - true - ); + assert.ok(output.includes('Successfully deleted device')); }); it('should patch an unauthorized device with ES256', async () => { @@ -186,20 +171,17 @@ it('should patch an unauthorized device with ES256', async () => { `${cmd} createUnauthDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual(new RegExp('Created device').test(output), true); + assert.ok(output.includes('Created device')); output = await tools.runAsync( `${cmd} patchEs256 ${localDevice} ${registryName} ${ecPublicKey}`, cwd ); - assert.strictEqual(new RegExp('Patched device:').test(output), true); + assert.ok(output.includes('Patched device:')); output = await tools.runAsync( `${cmd} deleteDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual( - new RegExp('Successfully deleted device').test(output), - true - ); + assert.ok(output.includes('Successfully deleted device')); }); it('should create and list devices', async () => { @@ -208,21 +190,15 @@ it('should create and list devices', async () => { `${cmd} createUnauthDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual(new RegExp('Created device').test(output), true); + assert.ok(output.includes('Created device')); output = await tools.runAsync(`${cmd} listDevices ${registryName}`, cwd); - assert.strictEqual( - new RegExp(/Current devices in registry:/).test(output), - true - ); - assert.strictEqual(new RegExp(localDevice).test(output), true); + assert.ok(output.includes('Current devices in registry:')); + assert.ok(output.includes(localDevice)); output = await tools.runAsync( `${cmd} deleteDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual( - new RegExp('Successfully deleted device').test(output), - true - ); + assert.ok(output.includes('Successfully deleted device')); }); it('should create and get a device', async () => { @@ -232,15 +208,12 @@ it('should create and get a device', async () => { `${cmd} createUnauthDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual(new RegExp('Created device').test(output), true); + assert.ok(output.includes('Created device')); output = await tools.runAsync( `${cmd} getDevice ${localDevice} ${registryName}`, cwd ); - assert.strictEqual( - new RegExp(`Found device: ${localDevice}`).test(output), - true - ); + assert.ok(output.includes(`Found device: ${localDevice}`)); output = await tools.runAsync( `${cmd} deleteDevice ${localDevice} ${registryName}`, cwd @@ -255,9 +228,10 @@ it('should create and get an iam policy', async () => { `${cmd} setIamPolicy ${registryName} ${localMember} ${localRole}`, cwd ); - assert.strictEqual(new RegExp('ETAG').test(output), true); + assert.ok(output.includes('ETAG')); + output = await tools.runAsync(`${cmd} getIamPolicy ${registryName}`, cwd); - assert.strictEqual(new RegExp('dpebot').test(output), true); + assert.ok(output.includes('dpebot')); }); it('should create and delete a registry', async () => { @@ -268,18 +242,12 @@ it('should create and delete a registry', async () => { `${cmd} createRegistry ${createRegistryId} ${topicName}`, cwd ); - assert.strictEqual( - new RegExp('Successfully created registry').test(output), - true - ); + assert.ok(output.includes('Successfully created registry')); output = await tools.runAsync( `${cmd} deleteRegistry ${createRegistryId}`, cwd ); - assert.strictEqual( - new RegExp('Successfully deleted registry').test(output), - true - ); + assert.ok(output.includes('Successfully deleted registry')); }); it('should send command message to device', async () => { @@ -299,7 +267,7 @@ it('should send command message to device', async () => { const output = await tools.runAsync( `${cmd} sendCommand ${deviceId} ${registryName} ${commandMessage}` ); - assert.strictEqual(new RegExp('Sent command').test(output), true); + assert.ok(output.includes('Sent command')); await tools.runAsync(`${cmd} deleteDevice ${deviceId} ${registryName}`, cwd); }); @@ -311,7 +279,7 @@ it('should create a new gateway', async () => { ); // test no error on create gateway. - assert.strictEqual(new RegExp('Created device').test(gatewayOut), true); + assert.ok(gatewayOut.includes('Created device')); await iotClient.deleteDevice({ name: iotClient.devicePath(projectId, region, registryName, gatewayId), @@ -326,7 +294,7 @@ it('should list gateways', async () => { // look for output in list gateway const gateways = await tools.runAsync(`${cmd} listGateways ${registryName}`); - assert.strictEqual(new RegExp(`${gatewayId}`).test(gateways), true); + assert.ok(gateways.includes(`${gatewayId}`)); await iotClient.deleteDevice({ name: iotClient.devicePath(projectId, region, registryName, gatewayId), @@ -335,7 +303,7 @@ it('should list gateways', async () => { it('should bind existing device to gateway', async () => { const gatewayId = `nodejs-test-gateway-iot-${uuid.v4()}`; - await tools.runAsync( + await tools.runAsyncWithIO( `${cmd} createGateway ${registryName} ${gatewayId} RSA_X509_PEM ${rsaPublicCert}` ); @@ -353,20 +321,14 @@ it('should bind existing device to gateway', async () => { `${cmd} bindDeviceToGateway ${registryName} ${gatewayId} ${deviceId}` ); - assert.strictEqual( - new RegExp(`Binding device: ${deviceId}`).test(bind), - true - ); - assert.strictEqual(new RegExp('Could not bind device').test(bind), false); + assert.ok(bind.includes(`Binding device: ${deviceId}`)); + assert.strictEqual(bind.includes('Could not bind device'), false); // test unbind const unbind = await tools.runAsync( `${cmd} unbindDeviceFromGateway ${registryName} ${gatewayId} ${deviceId}` ); - assert.strictEqual( - new RegExp(`Unbound ${deviceId} from ${gatewayId}`).test(unbind), - true - ); + assert.ok(unbind.includes(`Unbound ${deviceId} from ${gatewayId}`)); await iotClient.deleteDevice({ name: iotClient.devicePath(projectId, region, registryName, gatewayId), @@ -399,9 +361,9 @@ it('should list devices bound to gateway', async () => { `${cmd} listDevicesForGateway ${registryName} ${gatewayId}` ); - assert.strictEqual(new RegExp(deviceId).test(devices), true); + assert.ok(devices.includes(deviceId)); assert.strictEqual( - new RegExp('No devices bound to this gateway.').test(devices), + devices.includes('No devices bound to this gateway.'), false ); @@ -442,9 +404,9 @@ it('should list gateways for bound device', async () => { `${cmd} listGatewaysForDevice ${registryName} ${deviceId}` ); - assert.strictEqual(new RegExp(gatewayId).test(devices), true); + assert.ok(devices.includes(gatewayId)); assert.strictEqual( - new RegExp('No gateways associated with this device').test(devices), + devices.includes('No gateways associated with this device'), false ); diff --git a/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js b/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js index 4a589a4f74..9d261eb644 100644 --- a/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js +++ b/iot/mqtt_example/cloudiot_mqtt_example_nodejs.js @@ -37,7 +37,7 @@ let backoffTime = 1; let publishChainInProgress = false; console.log('Google Cloud IoT Core MQTT example.'); -const argv = require(`yargs`) +const {argv} = require(`yargs`) .options({ projectId: { default: process.env.GCLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT, @@ -242,7 +242,7 @@ const argv = require(`yargs`) .recommendCommands() .epilogue(`For more information, see https://cloud.google.com/iot-core/docs`) .help() - .strict().argv; + .strict(); // Create a Cloud IoT Core JWT for the given project id, signed with the given // private key. diff --git a/iot/scripts/iam.js b/iot/scripts/iam.js index d829405568..a7e4c9d72a 100644 --- a/iot/scripts/iam.js +++ b/iot/scripts/iam.js @@ -20,7 +20,7 @@ * For more information, see https://cloud.google.com/iot. */ -function setTopicPolicy(topicName) { +const setTopicPolicy = async topicName => { // Imports the Google Cloud client library const {PubSub} = require('@google-cloud/pubsub'); @@ -33,48 +33,43 @@ function setTopicPolicy(topicName) { // The new IAM policy const serviceAccount = 'serviceAccount:cloud-iot@system.gserviceaccount.com'; - topic.iam - .getPolicy() - .then(results => { - const policy = results[0] || {}; - policy.bindings || (policy.bindings = []); - console.log(JSON.stringify(policy, null, 2)); + let policy = await topic.iam.getPolicy(); + policy = policy[0] || {}; - let hasRole = false; - let binding = { - role: 'roles/pubsub.publisher', - members: [serviceAccount], - }; + policy.bindings || (policy.bindings = []); + console.log(JSON.stringify(policy, null, 2)); - policy.bindings.forEach(_binding => { - if (_binding.role === binding.role) { - binding = _binding; - hasRole = true; - return false; - } - }); + let hasRole = false; + let binding = { + role: 'roles/pubsub.publisher', + members: [serviceAccount], + }; - if (hasRole) { - binding.members || (binding.members = []); - if (binding.members.indexOf(serviceAccount) === -1) { - binding.members.push(serviceAccount); - } - } else { - policy.bindings.push(binding); - } + policy.bindings.forEach(_binding => { + if (_binding.role === binding.role) { + binding = _binding; + hasRole = true; + return false; + } + }); - // Updates the IAM policy for the topic - return topic.iam.setPolicy(policy); - }) - .then(results => { - const updatedPolicy = results[0]; + if (hasRole) { + binding.members || (binding.members = []); + if (binding.members.indexOf(serviceAccount) === -1) { + binding.members.push(serviceAccount); + } + } else { + policy.bindings.push(binding); + } - console.log(JSON.stringify(updatedPolicy, null, 2)); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} + // Updates the IAM policy for the topic + try { + const [updatedPolicy] = await topic.iam.setPolicy(policy); + console.log(JSON.stringify(updatedPolicy, null, 2)); + } catch (err) { + console.error('ERROR:', err); + } +}; if (module === require.main) { setTopicPolicy(process.argv[2]); diff --git a/iot/scripts/package.json b/iot/scripts/package.json index ccf21d392f..8987b75016 100644 --- a/iot/scripts/package.json +++ b/iot/scripts/package.json @@ -4,6 +4,9 @@ "main": "iam.js", "author": "Google Inc.", "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, "dependencies": { "@google-cloud/pubsub": "^0.28.0" } From e7e9f9130f87ab995b3da279dc81d00f86b3551f Mon Sep 17 00:00:00 2001 From: ace-n Date: Wed, 5 Jun 2019 13:11:19 -0700 Subject: [PATCH 2/2] Remove extraneous runAsyncWithIO --- iot/manager/system-test/manager.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iot/manager/system-test/manager.test.js b/iot/manager/system-test/manager.test.js index 3c23c1aacb..310eba1ac1 100644 --- a/iot/manager/system-test/manager.test.js +++ b/iot/manager/system-test/manager.test.js @@ -303,7 +303,7 @@ it('should list gateways', async () => { it('should bind existing device to gateway', async () => { const gatewayId = `nodejs-test-gateway-iot-${uuid.v4()}`; - await tools.runAsyncWithIO( + await tools.runAsync( `${cmd} createGateway ${registryName} ${gatewayId} RSA_X509_PEM ${rsaPublicCert}` );