AWSSDK または CLI CreateTopicRuleで を使用する - AWS IoT Core

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWSSDK または CLI CreateTopicRuleで を使用する

次のサンプルコードは、CreateTopicRule を使用する方法を説明しています。

.NET
SDK for .NET(v4)
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

/// <summary> /// Creates an IoT topic rule. /// </summary> /// <param name="ruleName">The name of the rule.</param> /// <param name="snsTopicArn">The ARN of the SNS topic for the action.</param> /// <param name="roleArn">The ARN of the IAM role.</param> /// <returns>True if successful, false otherwise.</returns> public async Task<bool> CreateTopicRuleAsync(string ruleName, string snsTopicArn, string roleArn) { try { var request = new CreateTopicRuleRequest { RuleName = ruleName, TopicRulePayload = new TopicRulePayload { Sql = "SELECT * FROM 'topic/subtopic'", Description = $"Rule created by .NET example: {ruleName}", Actions = new List<Amazon.IoT.Model.Action> { new Amazon.IoT.Model.Action { Sns = new SnsAction { TargetArn = snsTopicArn, RoleArn = roleArn } } }, RuleDisabled = false } }; await _amazonIoT.CreateTopicRuleAsync(request); _logger.LogInformation($"Created IoT rule {ruleName}"); return true; } catch (Amazon.IoT.Model.ResourceAlreadyExistsException ex) { _logger.LogWarning($"Rule {ruleName} already exists: {ex.Message}"); return false; } catch (Exception ex) { _logger.LogError($"Couldn't create topic rule. Here's why: {ex.Message}"); return false; } }
  • API の詳細については、AWS SDK for .NET API リファレンスの「CreateTopicRule」を参照してください。

C++
SDK for C++
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

//! Create an AWS IoT rule with an SNS topic as the target. /*! \param ruleName: The name for the rule. \param snsTopic: The SNS topic ARN for the action. \param sql: The SQL statement used to query the topic. \param roleARN: The IAM role ARN for the action. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::IoT::createTopicRule(const Aws::String &ruleName, const Aws::String &snsTopicARN, const Aws::String &sql, const Aws::String &roleARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::IoT::IoTClient iotClient(clientConfiguration); Aws::IoT::Model::CreateTopicRuleRequest request; request.SetRuleName(ruleName); Aws::IoT::Model::SnsAction snsAction; snsAction.SetTargetArn(snsTopicARN); snsAction.SetRoleArn(roleARN); Aws::IoT::Model::Action action; action.SetSns(snsAction); Aws::IoT::Model::TopicRulePayload topicRulePayload; topicRulePayload.SetSql(sql); topicRulePayload.SetActions({action}); request.SetTopicRulePayload(topicRulePayload); auto outcome = iotClient.CreateTopicRule(request); if (outcome.IsSuccess()) { std::cout << "Successfully created topic rule " << ruleName << "." << std::endl; } else { std::cerr << "Error creating topic rule " << ruleName << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • API の詳細については、「AWS SDK for C++ API リファレンス」の「CreateTopicRule」を参照してください。

CLI
AWS CLI

Amazon SNS アラートを送信するルールを作成するには

次のcreate-topic-rule 例では、デバイスシャドウにある土壌湿度レベルの読み取り値が低くなったときに Amazon SNS メッセージを送信するルールを作成します。

aws iot create-topic-rule \ --rule-name "LowMoistureRule" \ --topic-rule-payload file://plant-rule.json

この例では、次の JSON コードを plant-rule.json という名前のファイルに保存する必要があります。

{ "sql": "SELECT * FROM '$aws/things/MyRPi/shadow/update/accepted' WHERE state.reported.moisture = 'low'\n", "description": "Sends an alert whenever soil moisture level readings are too low.", "ruleDisabled": false, "awsIotSqlVersion": "2016-03-23", "actions": [{ "sns": { "targetArn": "arn:aws:sns:us-west-2:123456789012:MyRPiLowMoistureTopic", "roleArn": "arn:aws:iam::123456789012:role/service-role/MyRPiLowMoistureTopicRole", "messageFormat": "RAW" } }] }

このコマンドでは何も出力されません。

詳細については、AWS「 IoT デベロッパーガイド」の「Creating anIoT RuleAWSIoT」を参照してください。

  • API の詳細については、「AWS CLI コマンドリファレンス」の「CreateTopicRule」を参照してください。

Java
SDK for Java 2.x
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

/** * Creates an IoT rule asynchronously. * * @param roleARN The ARN of the IAM role that grants access to the rule's actions. * @param ruleName The name of the IoT rule. * @param action The ARN of the action to perform when the rule is triggered. * * This method initiates an asynchronous request to create an IoT rule. * If the request is successful, it prints a confirmation message. * If an exception occurs, it prints the error message. */ public void createIoTRule(String roleARN, String ruleName, String action) { String sql = "SELECT * FROM '" + TOPIC + "'"; SnsAction action1 = SnsAction.builder() .targetArn(action) .roleArn(roleARN) .build(); // Create the action. Action myAction = Action.builder() .sns(action1) .build(); // Create the topic rule payload. TopicRulePayload topicRulePayload = TopicRulePayload.builder() .sql(sql) .actions(myAction) .build(); // Create the topic rule request. CreateTopicRuleRequest topicRuleRequest = CreateTopicRuleRequest.builder() .ruleName(ruleName) .topicRulePayload(topicRulePayload) .build(); CompletableFuture<CreateTopicRuleResponse> future = getAsyncClient().createTopicRule(topicRuleRequest); future.whenComplete((response, ex) -> { if (response != null) { System.out.println("IoT Rule created successfully."); } else { Throwable cause = ex != null ? ex.getCause() : null; if (cause instanceof IotException) { System.err.println(((IotException) cause).awsErrorDetails().errorMessage()); } else if (cause != null) { System.err.println("Unexpected error: " + cause.getMessage()); } else { System.err.println("Failed to create IoT Rule."); } } }); future.join(); }
  • API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「CreateTopicRule」を参照してください。

Kotlin
SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

suspend fun createIoTRule( roleARNVal: String?, ruleNameVal: String?, action: String?, ) { val sqlVal = "SELECT * FROM '$TOPIC '" val action1 = SnsAction { targetArn = action roleArn = roleARNVal } val myAction = Action { sns = action1 } val topicRulePayloadVal = TopicRulePayload { sql = sqlVal actions = listOf(myAction) } val topicRuleRequest = CreateTopicRuleRequest { ruleName = ruleNameVal topicRulePayload = topicRulePayloadVal } IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient -> iotClient.createTopicRule(topicRuleRequest) println("IoT rule created successfully.") } }
  • API の詳細については、「AWS SDK for Kotlin API リファレンス」の「CreateTopicRule」を参照してください。

AWSSDK 開発者ガイドとコード例の完全なリストについては、「」を参照してくださいAWSSDK AWS IoTでの の使用。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。