1

我正在使用带有 Pub/Sub 的 Google Cloud IoT。

我有一个设备读取传感器数据并将其发送到 Pub/Sub 中的主题。

我有一个由该消息触发的主题云功能,我想更新设备配置,但​​是由于以下权限错误,我无法这样做。

index.js:

/**
 * Triggered from a message on a Cloud Pub/Sub topic.
 *
 * @param {!Object} event The Cloud Functions event.
 * @param {!Function} The callback function.
 */

  var google = require('googleapis');
    //var tt = google.urlshortener('v1');
  //console.log(Object.getOwnPropertyNames(google.getAPIs()));
  var cloudiot = google.cloudiot('v1');

function handleDeviceGet(authClient, name, device_id, err, data) {
    if (err) {
        console.log('Error with get device:', device_id);
        console.log(err);
        return;
    }

    console.log('Got device:', device_id);
    console.log(data);
    console.log(data.config);

    var data2 = JSON.parse(
        Buffer.from(data.config.binaryData, 'base64').toString());
    console.log(data2);
    data2.on = !data2.on;
    console.log(data2);

    var request2 = {
        name: name,
        resource: {
            'versionToUpdate' : data.config.version,
            'binaryData' : Buffer(JSON.stringify(data2)).toString('base64')
        },
        auth: authClient
    };

    console.log('request2' + request2);

    var devices = cloudiot.projects.locations.registries.devices;
    devices.modifyCloudToDeviceConfig(request2, (err, data) => {
        if (err) {
            console.log('Error patching device:', device_id);
            console.log(err);
        } else {
            console.log('Patched device:', device_id);
            console.log(data);
        }
    });
}

const handleAuth = (device_id) => { 
    console.log(device_id);
    return (err, authClient) => {
      const project_id = 'animated-bonsai-195009';
      const cloud_region = 'us-central1';
      const registry_id = 'reg1';

      const name = `projects / ${project_id} /locations / ${cloud_region} /` +
            `registries / ${registry_id} /devices / ${device_id}`;

      if (err) {
          console.log(err);
      }

      if (authClient.createScopedRequired &&
          authClient.createScopedRequired()) {
          authClient = authClient.createScoped(
              ['https://www.googleapis.com/auth/cloud-platforme']);
      }

      var request = {
          name: name,
          auth: authClient
      };

      // Get device version
      var devices = cloudiot.projects.locations.registries.devices;
      devices.get(request, (err, data) =>
                  handleDeviceGet(authClient, name, device_id, err, data));
  }
                                      };

exports.subscribe = (event, callback) => {

  // The Cloud Pub/Sub Message object.
  const pubsubMessage = event.data;

  // We're just going to log the message to prove that
  // it worked.

  var obj = JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString());

  console.log(Buffer.from(pubsubMessage.data, 'base64').toString());
  console.log(event);
  console.log(Object.getOwnPropertyNames(event));
  console.log(callback);

  let message = {
    "watter": 1
  };
  message = new Buffer(JSON.stringify(message));

  const req = {
        name: event.data.deviceId,
        resource: message
    };
    console.log(obj.deviceId);
  google.auth.getApplicationDefault(handleAuth(obj['deviceId']));

  // Don't forget to call the callback.
  callback();
};

包.json:

{
  "name": "sample-pubsub",
  "version": "0.0.1",
  "dependencies": {
    "googleapis": "25.0.0"
  }
}

错误:

输出记录错误

4

1 回答 1

1

几个选项:

  • 检查您是否为创建 Google Cloud Function 时使用的项目启用了Google Cloud IoT Core API的 API 访问权限。
  • 检查您是否已为您的项目启用计费
  • 如果您正在部署您的 Google Cloud Functions with gcloud beta functions deploy... 从包含您的.jspackage.json文件的文件夹中,您可能需要设置环境变量 ( GCLOUD_PROJECTand GOOGLE_APPLICATION_CREDENTIALS) 或gcloud auth application-default login在部署之前使用,以防您有多个 Google Cloud 项目并需要启用 API配置的。

更新 本社区教程向您展示了如何执行此操作 - 请注意,Google Cloud Functions 的一些更新要求您使用 NodeJS 客户端库的较新版本,如NodeJS 示例中所做的那样,并在此 PR 中更正,注意package.json 中客户端库的版本

于 2018-02-22T02:02:31.483 回答