首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Google云物联网核心中添加多个设备?

如何在Google云物联网核心中添加多个设备?
EN

Stack Overflow用户
提问于 2021-12-13 12:55:49
回答 2查看 103关注 0票数 0

我正在寻找一种方法连接多个设备大约1000到IoT核心在一次。我将通过仪表盘一次添加一个设备。

我阅读了文档这里

我在文档中找到了下面的代码,但我不知道如何使用它。

代码语言:javascript
复制
const iot = require('@google-cloud/iot');

const iotClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.
});

async function createDevice() {
  // Construct request
  const regPath = iotClient.registryPath(projectId, cloudRegion, registryId);
  const device = {
    id: deviceId,
    credentials: [
      {
        publicKey: {
          format: 'RSA_X509_PEM',
          key: readFileSync(rsaCertificateFile).toString(),
        },
      },
    ],
  };

  const request = {
    parent: regPath,
    device,
  };

  const [response] = await iotClient.createDevice(request);
  console.log('Created device', response);
}

createDevice();

我希望每个设备都有自己的凭据,device_Id应该是这样的:device_Id标签-00001,标签-00002,等等.

这有可能吗你能指引我正确的方向吗。

EN

回答 2

Stack Overflow用户

发布于 2022-06-11 15:55:38

您可以添加设备本身的凭据和device_id。一开始似乎很复杂。如果您在下面共享的链接中进行演示,它将有所帮助。

https://www.cloudskillsboost.google/quests/49?locale=en

票数 0
EN

Stack Overflow用户

发布于 2022-06-13 02:14:12

为了能够添加多个设备,我设计了代码,以便从证书文件(certPath)中创建一个列表。因此,代码将遍历列表,并在每次迭代中创建一个设备。代码还将按照您所描述的方式分配device_id (tag-00001、tag-00002、.)。

代码语言:javascript
复制
const cloudRegion = 'asia-east1'; //define your region here
const deviceId = 'tag-';
const projectId = 'your-project-id';
const registryId = 'your-registry';
const certPath = '/home/riccod/cert_file/'; //add certificate full path

const iot = require('@google-cloud/iot');
const fs = require('fs');
const {readFileSync} = require('fs');

var i = 1;
const iotClient = new iot.v1.DeviceManagerClient({});

function getCert() {
        var certArr = [];
        fs.readdirSync(certPath).forEach(file => {
                if (file.match(/rsa_cert_\d+\.pem/g) != null) { //modify regex based on your certificate filenames
                        certArr.push(`${certPath}${file}`);
                }
        });
        return certArr;
}

async function createDevice() {
  // Construct request
  const regPath = iotClient.registryPath(projectId, cloudRegion, registryId);
  var certArr = getCert();

  for (const element of certArr) {
    const device = {
      id: `${deviceId}${i.toString().padStart(5,'0')}`,
      credentials: [
        {
          publicKey: {
            format: 'RSA_X509_PEM',
            key: readFileSync(element).toString(),
          },
        },
     ],
    };

    const request = {
    parent: regPath,
    device,
    };
    i++;
    const [response] = await iotClient.createDevice(request);
    console.log('Created device', response);
  }
}

getCert();
createDevice();

请参阅代码运行后的结果:

注意:我只有2个证书文件,因此创建了2个设备。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70335019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档