From c286c3e39c5895c3d6ba4f1a11be798cfe9f23a1 Mon Sep 17 00:00:00 2001 From: Gus Class Date: Fri, 20 Dec 2019 15:53:58 -0800 Subject: [PATCH 1/4] IoT Core cloud client migration 3/4, device CRUD --- iot/manager/manager.js | 259 ++++++++++++++++++++++++----------------- 1 file changed, 149 insertions(+), 110 deletions(-) diff --git a/iot/manager/manager.js b/iot/manager/manager.js index 80e33e3e05..1532f4f6a5 100644 --- a/iot/manager/manager.js +++ b/iot/manager/manager.js @@ -354,36 +354,42 @@ const patchRsa256ForAuth = async ( cloudRegion ) => { // [START iot_patch_rsa] - // Client retrieved in callback - // getClient(serviceAccountJson, function(client) {...}); // const cloudRegion = 'us-central1'; // const deviceId = 'my-rsa-device'; // const projectId = 'adjective-noun-123'; // const registryId = 'my-registry'; - const parentName = `projects/${projectId}/locations/${cloudRegion}`; - const registryName = `${parentName}/registries/${registryId}`; - const request = { - name: `${registryName}/devices/${deviceId}`, - updateMask: 'credentials', - resource: { - credentials: [ - { - publicKey: { - format: 'RSA_X509_PEM', - key: fs.readFileSync(rsaPublicKeyFile).toString(), - }, + const iot = require('@google-cloud/iot'); + const iotClient = new iot.v1.DeviceManagerClient({ + // optional auth parameters. + }); + + const devPath = iotClient.devicePath( + projectId, + cloudRegion, + registryId, + deviceId + ); + + const device = { + name: devPath, + credentials: [ + { + publicKey: { + format: 'RSA_X509_PEM', + key: fs.readFileSync(rsaPublicKeyFile).toString(), }, - ], - }, + }, + ], }; try { - const {data} = await client.projects.locations.registries.devices.patch( - request - ); + const responses = await iotClient.updateDevice({ + device: device, + updateMask: {paths: ['credentials']}, + }); console.log('Patched device:', deviceId); - console.log(data); + console.log('Response', responses[0]); } catch (err) { console.error('Error patching device:', deviceId, err); } @@ -400,36 +406,42 @@ const patchEs256ForAuth = async ( cloudRegion ) => { // [START iot_patch_es] - // Client retrieved in callback - // getClient(serviceAccountJson, function(client) {...}); // const cloudRegion = 'us-central1'; // const deviceId = 'my-es-device'; // const projectId = 'adjective-noun-123'; // const registryId = 'my-registry'; - const parentName = `projects/${projectId}/locations/${cloudRegion}`; - const registryName = `${parentName}/registries/${registryId}`; - const request = { - name: `${registryName}/devices/${deviceId}`, - updateMask: 'credentials', - resource: { - credentials: [ - { - publicKey: { - format: 'ES256_PEM', - key: fs.readFileSync(esPublicKeyFile).toString(), - }, + const iot = require('@google-cloud/iot'); + const iotClient = new iot.v1.DeviceManagerClient({ + // optional auth parameters. + }); + + const devPath = iotClient.devicePath( + projectId, + cloudRegion, + registryId, + deviceId + ); + + const device = { + name: devPath, + credentials: [ + { + publicKey: { + format: 'ES256_PEM', + key: fs.readFileSync(esPublicKeyFile).toString(), }, - ], - }, + }, + ], }; try { - const {data} = await client.projects.locations.registries.devices.patch( - request - ); + const responses = await iotClient.updateDevice({ + device: device, + updateMask: {paths: ['credentials']}, + }); console.log('Patched device:', deviceId); - console.log(data); + console.log('Response', responses[0]); } catch (err) { console.error('Error patching device:', deviceId, err); } @@ -439,23 +451,24 @@ const patchEs256ForAuth = async ( // List all of the devices in the given registry. const listDevices = async (client, registryId, projectId, cloudRegion) => { // [START iot_list_devices] - // Client retrieved in callback - // getClient(serviceAccountJson, function(client) {...}); // const cloudRegion = 'us-central1'; // const projectId = 'adjective-noun-123'; // const registryId = 'my-registry'; - const parentName = `projects/${projectId}/locations/${cloudRegion}`; - const registryName = `${parentName}/registries/${registryId}`; + const iot = require('@google-cloud/iot'); + const iotClient = new iot.v1.DeviceManagerClient({ + // optional auth parameters. + }); - const request = { - parent: registryName, - }; + const parentName = iotClient.registryPath(projectId, cloudRegion, registryId); try { - const {data} = await client.projects.locations.registries.devices.list( - request - ); - console.log('Current devices in registry:', data['devices']); + const responses = await iotClient.listDevices({parent: parentName}); + const devices = responses[0]; + + for (let i = 0; i < devices.length; i++) { + const device = devices[i]; + console.log(`Device ${i}: `, device); + } } catch (err) { console.error('Could not list devices', err); } @@ -614,25 +627,26 @@ const getDevice = async ( cloudRegion ) => { // [START iot_get_device] - // Client retrieved in callback - // getClient(serviceAccountJson, function(client) {...}); // const cloudRegion = 'us-central1'; // const deviceId = 'my-device'; // const projectId = 'adjective-noun-123'; // const registryId = 'my-registry'; - const parentName = `projects/${projectId}/locations/${cloudRegion}`; - const registryName = `${parentName}/registries/${registryId}`; - const request = { - name: `${registryName}/devices/${deviceId}`, - }; + const iot = require('@google-cloud/iot'); + const iotClient = new iot.v1.DeviceManagerClient({ + // optional auth parameters. + }); + const devicePath = iotClient.devicePath( + projectId, + cloudRegion, + registryId, + deviceId + ); try { - const {data} = await client.projects.locations.registries.devices.get( - request - ); + const responses = await iotClient.getDevice({name: devicePath}); + const data = responses[0]; - console.log('Found device:', deviceId); - console.log(data); + console.log('Found device:', deviceId, data); } catch (err) { console.error('Could not find device:', deviceId); console.error('Trace:', err); @@ -649,23 +663,36 @@ const getDeviceState = async ( cloudRegion ) => { // [START iot_get_device_state] - // Client retrieved in callback - // getClient(serviceAccountJson, function(client) {...}); // const cloudRegion = 'us-central1'; // const deviceId = 'my-device'; // const projectId = 'adjective-noun-123'; // const registryId = 'my-registry'; - const parentName = `projects/${projectId}/locations/${cloudRegion}`; - const registryName = `${parentName}/registries/${registryId}`; - const request = { - name: `${registryName}/devices/${deviceId}`, - }; + const iot = require('@google-cloud/iot'); + const iotClient = new iot.v1.DeviceManagerClient({ + // optional auth parameters. + }); + const devicePath = iotClient.devicePath( + projectId, + cloudRegion, + registryId, + deviceId + ); try { - const { - data, - } = await client.projects.locations.registries.devices.states.list(request); - console.log('State:', data); + const responses = await iotClient.listDeviceStates({name: devicePath}); + const states = responses[0].deviceStates; + for (let i = 0; i < states.length; i++) { + const state = states[i]; + console.log( + 'State:', + state, + '\nData:\n', + state.binaryData.toString('utf8') + ); + } + if (states.length == 0) { + console.log(`No states for device: ${deviceId}`); + } } catch (err) { console.error('Could not find device:', deviceId); console.error('trace:', err); @@ -682,29 +709,41 @@ const getDeviceConfigs = async ( cloudRegion ) => { // [START iot_get_device_configs] - // Client retrieved in callback - // getClient(serviceAccountJson, function(client) {...}); // const cloudRegion = 'us-central1'; // const deviceId = 'my-device'; // const projectId = 'adjective-noun-123'; // const registryId = 'my-registry'; - const parentName = `projects/${projectId}/locations/${cloudRegion}`; - const registryName = `${parentName}/registries/${registryId}`; - const request = { - name: `${registryName}/devices/${deviceId}`, - }; + const iot = require('@google-cloud/iot'); + const iotClient = new iot.v1.DeviceManagerClient({ + // optional auth parameters. + }); + const devicePath = iotClient.devicePath( + projectId, + cloudRegion, + registryId, + deviceId + ); try { - const { - data, - } = await client.projects.locations.registries.devices.configVersions.list( - request - ); - - console.log('Configs:', data); + const responses = await iotClient.listDeviceConfigVersions({ + name: devicePath, + }); + const configs = responses[0].deviceConfigs; + for (let i = 0; i < configs.length; i++) { + const config = configs[i]; + console.log( + 'Config:', + config, + '\nData:\n', + config.binaryData.toString('utf8') + ); + } + if (configs.length == 0) { + console.log(`No states for device: ${deviceId}`); + } } catch (err) { console.error('Could not find device:', deviceId); - console.error('Trace:', err); + console.error('trace:', err); } // [END iot_get_device_configs] }; @@ -720,32 +759,35 @@ const setDeviceConfig = async ( version ) => { // [START iot_set_device_config] - // Client retrieved in callback - // getClient(serviceAccountJson, function(client) {...}); // const cloudRegion = 'us-central1'; // const deviceId = 'my-device'; // const projectId = 'adjective-noun-123'; // const registryId = 'my-registry'; // const data = 'test-data'; // const version = 0; - const parentName = `projects/${projectId}/locations/${cloudRegion}`; - const registryName = `${parentName}/registries/${registryId}`; + const iot = require('@google-cloud/iot'); + const iotClient = new iot.v1.DeviceManagerClient({ + // optional auth parameters. + }); + + const formattedName = iotClient.devicePath( + projectId, + cloudRegion, + registryId, + deviceId + ); const binaryData = Buffer.from(data).toString('base64'); const request = { - name: `${registryName}/devices/${deviceId}`, + name: formattedName, versionToUpdate: version, binaryData: binaryData, }; try { - const { - data, - } = await client.projects.locations.registries.devices.modifyCloudToDeviceConfig( - request - ); + const responses = await iotClient.modifyCloudToDeviceConfig(request); - console.log('Success:', data); + console.log('Success:', responses[0]); } catch (err) { console.error('Could not update config:', deviceId); console.error('Message:', err); @@ -762,15 +804,15 @@ const sendCommand = async ( commandMessage ) => { // [START iot_send_command] - // const iot = require('@google-cloud/iot'); - // const client = new iot.v1.DeviceManagerClient(); // const cloudRegion = 'us-central1'; // const deviceId = 'my-device'; // const commandMessage = 'message for device'; // const projectId = 'adjective-noun-123'; // const registryId = 'my-registry'; - - const binaryData = Buffer.from(commandMessage).toString('base64'); + const iot = require('@google-cloud/iot'); + const iotClient = new iot.v1.DeviceManagerClient({ + // optional auth parameters. + }); const formattedName = client.devicePath( projectId, @@ -778,19 +820,16 @@ const sendCommand = async ( registryId, deviceId ); - - // NOTE: The device must be subscribed to the wildcard subfolder - // or you should specify a subfolder. + const binaryData = Buffer.from(commandMessage); const request = { name: formattedName, binaryData: binaryData, - //subfolder: }; try { - await client.sendCommandToDevice(request); + const responses = await client.sendCommandToDevice(request); - console.log('Sent command'); + console.log('Sent command: ', responses[0]); } catch (err) { console.error('Could not send command:', err); } From 8bf600496151459d1cd7aef8de84759c388bc353 Mon Sep 17 00:00:00 2001 From: Gus Class Date: Fri, 20 Dec 2019 16:13:05 -0800 Subject: [PATCH 2/4] FIx output to match test expectations --- iot/manager/manager.js | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/iot/manager/manager.js b/iot/manager/manager.js index 1532f4f6a5..1e1fe81304 100644 --- a/iot/manager/manager.js +++ b/iot/manager/manager.js @@ -465,6 +465,12 @@ const listDevices = async (client, registryId, projectId, cloudRegion) => { const responses = await iotClient.listDevices({parent: parentName}); const devices = responses[0]; + if (devices.length > 0) { + console.log('Current devices in registry:'); + } else { + console.log('No devices in registry.'); + } + for (let i = 0; i < devices.length; i++) { const device = devices[i]; console.log(`Device ${i}: `, device); @@ -681,6 +687,12 @@ const getDeviceState = async ( try { const responses = await iotClient.listDeviceStates({name: devicePath}); const states = responses[0].deviceStates; + if (states.length === 0) { + console.log(`No States for device: ${deviceId}`); + } else { + console.log(`States for device: ${deviceId}`); + } + for (let i = 0; i < states.length; i++) { const state = states[i]; console.log( @@ -690,9 +702,6 @@ const getDeviceState = async ( state.binaryData.toString('utf8') ); } - if (states.length == 0) { - console.log(`No states for device: ${deviceId}`); - } } catch (err) { console.error('Could not find device:', deviceId); console.error('trace:', err); @@ -729,6 +738,13 @@ const getDeviceConfigs = async ( name: devicePath, }); const configs = responses[0].deviceConfigs; + + if (configs.length === 0) { + console.log(`No configs for device: ${deviceId}`); + } else { + console.log(`Configs:`); + } + for (let i = 0; i < configs.length; i++) { const config = configs[i]; console.log( @@ -738,9 +754,6 @@ const getDeviceConfigs = async ( config.binaryData.toString('utf8') ); } - if (configs.length == 0) { - console.log(`No states for device: ${deviceId}`); - } } catch (err) { console.error('Could not find device:', deviceId); console.error('trace:', err); @@ -814,7 +827,7 @@ const sendCommand = async ( // optional auth parameters. }); - const formattedName = client.devicePath( + const formattedName = iotClient.devicePath( projectId, cloudRegion, registryId, @@ -827,7 +840,7 @@ const sendCommand = async ( }; try { - const responses = await client.sendCommandToDevice(request); + const responses = await iotClient.sendCommandToDevice(request); console.log('Sent command: ', responses[0]); } catch (err) { From 21e0878f7d5354fbacf532e0c9f09371f573687f Mon Sep 17 00:00:00 2001 From: Gus Class Date: Fri, 20 Dec 2019 16:21:46 -0800 Subject: [PATCH 3/4] Nudge lint --- iot/manager/manager.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/iot/manager/manager.js b/iot/manager/manager.js index 1e1fe81304..3e52cf80c8 100644 --- a/iot/manager/manager.js +++ b/iot/manager/manager.js @@ -28,6 +28,10 @@ const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest'; const client = new iot.v1.DeviceManagerClient(); // [END iot_get_client] +if (client === undefined && false) { + console.log('Did not instantiate client.'); +} + // Configures the topic for Cloud IoT Core. const setupIotTopic = async topicName => { const {PubSub} = require('@google-cloud/pubsub'); From f8f8671d00406027d1139cb705c23770f2702232 Mon Sep 17 00:00:00 2001 From: Gus Class Date: Mon, 23 Dec 2019 13:09:14 -0800 Subject: [PATCH 4/4] Fix lint --- iot/manager/manager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iot/manager/manager.js b/iot/manager/manager.js index 3e52cf80c8..ae5b16274b 100644 --- a/iot/manager/manager.js +++ b/iot/manager/manager.js @@ -28,7 +28,7 @@ const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest'; const client = new iot.v1.DeviceManagerClient(); // [END iot_get_client] -if (client === undefined && false) { +if (client === undefined) { console.log('Did not instantiate client.'); }