我正在寻找一种方法连接多个设备大约1000到IoT核心在一次。我将通过仪表盘一次添加一个设备。
我阅读了文档这里。
我在文档中找到了下面的代码,但我不知道如何使用它。
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,等等.
这有可能吗你能指引我正确的方向吗。
发布于 2022-06-11 15:55:38
您可以添加设备本身的凭据和device_id。一开始似乎很复杂。如果您在下面共享的链接中进行演示,它将有所帮助。
发布于 2022-06-13 02:14:12
为了能够添加多个设备,我设计了代码,以便从证书文件(certPath)中创建一个列表。因此,代码将遍历列表,并在每次迭代中创建一个设备。代码还将按照您所描述的方式分配device_id (tag-00001、tag-00002、.)。
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个设备。
https://stackoverflow.com/questions/70335019
复制相似问题