AWS IOT 构造库
AWS CDK v1在2023-06-01上达到了支持结束. 此软件包不再更新,用户应该迁移到 AWS CDK v2.
关于如何移徙的更多信息,请参见: 移动到 AWS CDK v2 指南。 。 。 .
AWS IOT Core允许您连接数十亿个IOT设备以及数以万亿计的路由 向AWS服务发送信息而不管理基础设施.
安装
安装模块 :
$ npm i @aws-cdk/aws-iot
导入到您的代码 :
import * as iot from '@aws-cdk/aws-iot';
import * as actions from '@aws-cdk/aws-iot-actions';
TopicRule
创建一个主题规则,使您的设备能够与 AWS 服务交互. 您可以以下列动作创建主题规则:
const func = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromInline(`
exports.handler = (event) => {
console.log("It is test for lambda action of AWS IoT Rule.", event);
};`
),
});
new iot.TopicRule(this, 'TopicRule', {
topicRuleName: 'MyTopicRule', // optional
description: 'invokes the lambda function', // optional
sql: iot.IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, timestamp() as timestamp FROM 'device/+/data'"),
actions: [new actions.LambdaFunctionAction(func)],
});
或者,你可以在构建后添加一个动作 TopicRule 实例如下:
declare const func: lambda.Function;
const topicRule = new iot.TopicRule(this, 'TopicRule', {
sql: iot.IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, timestamp() as timestamp FROM 'device/+/data'"),
});
topicRule.addAction(new actions.LambdaFunctionAction(func));
您也可以提供 errorAction 如下,
如果规则的行为无法执行,则IOT规则将触发:
import * as logs from '@aws-cdk/aws-logs';
const logGroup = new logs.LogGroup(this, 'MyLogGroup');
new iot.TopicRule(this, 'TopicRule', {
sql: iot.IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, timestamp() as timestamp FROM 'device/+/data'"),
errorAction: new actions.CloudWatchLogsAction(logGroup),
});
如果你想让主题规则禁用, 请添加属性 enabled: false 现改为:
new iot.TopicRule(this, 'TopicRule', {
sql: iot.IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, timestamp() as timestamp FROM 'device/+/data'"),
enabled: false,
});
另见 @aws-cdk/aws- iot- actions (英语) 用于其他行动.