【问题标题】:How to Update Device Configuration using Google Cloud functions and MQTT bridge如何使用 Google Cloud 功能和 MQTT 桥接器更新设备配置
【发布时间】:2018-08-01 13:39:00
【问题描述】:

我将 Google Cloud IoT 与 Pub/Sub 结合使用。

我有一个设备读取传感器数据并将其发送到 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();
};

package.json:

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

错误:

【问题讨论】:

  • 请将错误消息的文本复制到问题本身中,以便于阅读和搜索。
  • 我复制了有用的部分:Error: A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified.
  • 我在使用云函数时遇到了同样的问题:我正在尝试在云函数环境中获取 defaultCredentials,但我收到了相同的错误消息。

标签: mqtt google-cloud-functions google-cloud-pubsub google-cloud-iot


【解决方案1】:

几个选项:

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

更新 This community tutorial 向您展示如何执行此操作 - 请注意,Google Cloud Functions 的一些更新要求您使用更新版本的 Node JS 客户端库,如the NodeJS sampleas corrected in this PR,注意 version of the client library in package.json

【讨论】:

    猜你喜欢
    • 2021-10-08
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多