0

我一直在寻找一种使用谷歌云功能管理云物联网核心设备的方法。经过几天的测试,我无法弄清楚如何将设备添加到注册表中。

我尝试使用 npm 在我的电脑上安装 googleapis 模块,但是在 github 上的 apis 目录中找不到 cloudiot 核心(安装包的版本是 22.2.0,但在 github 上是 22.3.0)。

有任何想法吗 ?如何安装最新版本?

4

2 回答 2

0

更新

目前,当您没有从发现文档中显式加载 API 时,NodeJS 客户端库似乎与 IoT 存在问题。

要暂时解决此问题,请执行以下操作来初始化您的 API 客户端:

const serviceAccountJson = `/home/class/iot_creds.json`;
const API_VERSION = 'v1';
const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
function getClient (serviceAccountJson, cb) {
  const serviceAccount = JSON.parse(fs.readFileSync(serviceAccountJson));
  const jwtAccess = new google.auth.JWT();
  jwtAccess.fromJSON(serviceAccount);
  // Note that if you require additional scopes, they should be specified as a
  // string, separated by spaces.
  jwtAccess.scopes = 'https://www.googleapis.com/auth/cloud-platform';
  // Set the default authentication to the above JWT access.
  google.options({ auth: jwtAccess });
  const discoveryUrl = `${DISCOVERY_API}?version=${API_VERSION}`;
  google.discoverAPI(discoveryUrl, {}, (err, client) => {
    if (err) {
      console.log('Error during API discovery', err);
      return undefined;
    }
    cb(client);
  });
}

原来的

NodeJS管理示例当前使用 Google API 客户端(例如"googleapis": "20.1.0"package.json中)库,而不是单独的库。

如果您还没有,请尝试按照示例自述文件中的说明在本地运行示例:

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
cd nodejs-docs-samples/iot/manager
npm install
node manager.js

如果示例在本地无法运行,请告诉我们节点版本 ( node --version) 和安装的模块版本(package.lock或的输出npm ls)。

如果示例在本地为您工作(在运行之后npm install),那么问题在于如何从云函数后端执行示例。

于 2017-11-08T17:44:42.303 回答
0

谷歌云平台服务 API 的惯用客户端库 因此,您可能很久以前就解决了这个问题,我不完全确定它们何时可用,但是您也可以利用谷歌的惯用客户端库:https ://cloud.google.com /nodejs/docs/reference/iot/0.1.x/

从云函数创建设备可以很简单:

包.json

{
  "name": "iot-manage",
  "version": "0.0.1",
  "engines": {
    "node": ">=4.3.2"
  },
  "dependencies": {
    "@google-cloud/iot": "0.1.x"
  }
}

index.js

const cloudRegion = [region];
const projectId = [GPC project];
const registryId = [registry]; 
const device = [device];
const iot = require('@google-cloud/iot');

exports.createDevice = (req, res) => {
  var message = req.query.message || req.body.message || 'Devices Parsed';
  var client = new iot.v1.DeviceManagerClient({ });
  var formattedParent = client.registryPath(projectId, cloudRegion, registryId);

  const device = {
  Id: device,
  credentials: [
    {
      publicKey: {
        format: 'RSA_X509_PEM',
        key: "-----BEGIN CERTIFICATE-----\n\
MIIC9TCCAd2gAwIBAgIJAIYmm9vVQM4rMA0GCSqGSIb3DQEBCwUAMBExDzANBgNV\n\
...
Q2VnbmKgQjgE+GZU58lSlrfWmXF+aZrbDz22cARP/TYqt9o1ieGOE3E=\n\
-----END CERTIFICATE-----"
      }
    }
  ]
  };

  var request = {
    parent: formattedParent,
    device: device,
  };
  client.createDevice(request)
    .then(responses => {
      var response = responses[0];
      console.log("Created Device");
      // doThingsWith(response)
  })
  .catch(err => {
    console.error(err);
  });
  res.status(200).send(message);
};
于 2018-09-28T21:24:35.027 回答