设备数据可通过消息路由能力流转至函数中,您可以通过函数控制其他设备。

背景信息

以设置当光照指数>500时关闭灯为例。

操作步骤

  1. 函数计算控制台创建一个函数。

    函数的代码配置示例如下:

    'use strict';
    
    const leSdk = require('linkedge-core-sdk');
    
    const iotData = new leSdk.IoTData();
    
    const productKey = 'Light Product Key';
    const deviceName = 'Light Device Name';
    
    module.exports.handler = function (event, context, callback) {
    
      console.log(`LightMonitor is invoking with ${event.toString()}.`);
    
      var illuminance;
      try {
        var obj = JSON.parse(event.toString());
        if (!obj.payload) {
          callback(new Error(`Can't find "payload" in event.`));
          return;
        }
        var payload = JSON.parse(obj.payload);
        if (!payload['MeasuredIlluminance']) {
          callback(new Error(`Can't find "MeasuredIlluminance" in event.`));
          return;
        }
        illuminance = payload['MeasuredIlluminance'].value || 0;
      } catch (err) {
        err = new Error(`Parse event failed due to ${err}.`);
        callback(err);
        return;
      }
    
      if (illuminance > 500) {
        turnOff(callback);
      } else if (illuminance <= 100) {
        turnOn(callback);
      } else {
        console.log(`Illuminance value is ${illuminance}, ignore.`);
        callback(null);
      }
    };
    
    function turnOff(callback) {
      // Turn off the light according to product key and device name.
      iotData.setThingProperties({
        productKey,
        deviceName,
        payload: {'LightSwitch': 0},
      }, function (err) {
        if (err) {
          console.log(`Failed to turn off the light due to ${err}.`);
          callback(err);
        } else {
          console.log(`Turns off light successfully.`);
          callback(null);
        }
      });
    }
    
    function turnOn(callback) {
      // Turn on the light according to product key and device name.
      iotData.setThingProperties({
        productKey,
        deviceName,
        payload: {'LightSwitch': 1},
      }, function (err) {
        if (err) {
          console.log(`Failed to turn on the light due to ${err}.`);
          callback(err);
        } else {
          console.log(`Turns on light successfully.`);
          callback(null);
        }
      });
    }

    Link IoT Edge提供的完整的设备联动示例代码请在这里查看。

  2. 物联网平台控制台边缘实例页面中,单击新增实例,然后创建一个边缘实例。
  3. 在已创建的边缘实例的实例详情页面,选择函数计算,然后为该实例分配第一步中创建的函数。
    说明 为边缘实例配置函数时,选择运行模式为 按需运行