我在这里复制并粘贴代码,没有编译问题 https://cloud.google.com/iot/docs/how-tos/commands#iot-core-send-command-nodejs
但它因错误“invalid_grant”而失败。
首先,我安装了 google-cloud/iot,我使用的是最后一个支持的版本:
npm i @google-cloud/iot——好的
npm 版本:6.4.1
node.jo 版本:v8.13.0
火力基地版本:6.11.0
win10专业版
如果我运行 gcloud 命令它工作正常
gcloud iot devices commands send \
--command-data="Hello device" \
--region=us-central1 \
--registry=device001-registry \
--device=device001-dev
这是代码。我刚刚从样品中得到了需要的东西。我不确定我是否错过了一些部署前的步骤。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp()
exports.sendCommandToDevice = functions.https.onRequest((request, response) => {
//Source https://cloud.google.com/iot/docs/how-tos/commands#iot-core-send-command-nodejs
//npm i @google-cloud/iot
const iot = require('@google-cloud/iot');
const client = new iot.v1.DeviceManagerClient();
const cloudRegion = 'us-central1';
const projectId = 'test01'; // 'adjective-noun-123';
const deviceId = 'device001-dev'; // 'my-device';
const registryId = 'device001-registry'; // 'my-registry';
const commandMessage = 'Hello device';
const binaryData = Buffer.from(commandMessage).toString('base64');
const formattedName = client.devicePath(
projectId,
cloudRegion,
registryId,
deviceId
);
// NOTE: The device must be subscribed to the wildcard subfolder
// or you should specify a subfolder.
const devRequest = {
name: formattedName,
binaryData: binaryData,
//subfolder: <your-subfolder>
};
client
.sendCommandToDevice(devRequest)
.then(() => {
console.log('Sent command ok!');
})
.catch(err => {
console.error(err);
});
response.send("Sent command done");
});
日志输出是
i functions: Finished "sendCommandToDevice" in ~1s
> { Error: Getting metadata from plugin failed with error: invalid_grant
> at Http2CallStream.call.on (D:\Jorge\test01\node_modules\
> at emitOne (events.js:121:20)
> at Http2CallStream.emit (events.js:211:7)
> at Http2CallStream.endCall (D:\Jorge\test01\node_modules\
> at D:\Jorge\test01\node_modules\@grpc\grpc-js\build\src\c
> at <anonymous>
> at process._tickCallback (internal/process/next_tick.js:189:7)
> code: '400',
> details: 'Getting metadata from plugin failed with error: invalid_grant',
> metadata: Metadata { options: undefined, internalRepr: Map {} },
> note: 'Exception occurred in retry method that was not classified as transient' }