如何使用Google Cloud功能和MQTT桥更新设备配置

时间:2018-02-21 20:33:12

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

我正在使用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"
  }
}

错误:

Output Logged error

1 个答案:

答案 0 :(得分:1)

一些选择:

  • 检查您是否为创建Google Cloud功能时使用的项目的Google Cloud IoT Core API启用了API访问权限。
  • 检查您的项目是否为enabled billing
  • 如果您使用gcloud beta functions deploy.js文件从package.jsonGCLOUD_PROJECT文件夹中部署Google云功能,则可能需要设置环境变量({{1如果您有多个Google Cloud项目并需要在配置的项目上启用API,请在部署之前使用GOOGLE_APPLICATION_CREDENTIALS)或使用gcloud auth application-default login

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