

지원 종료 알림: 2026년 5월 20일에 AWS 에 대한 지원이 종료됩니다 AWS IoT Events. 2026년 5월 20일 이후에는 AWS IoT Events 콘솔 또는 AWS IoT Events 리소스에 더 이상 액세스할 수 없습니다. 자세한 내용은 [AWS IoT Events 지원 종료를 참조하세요](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-end-of-support.html).

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# AWS IoT Events 사용 사례에 대한 자습서
<a name="iotevents-tutorials"></a>

AWS IoT Events 자습서에서는 기본 설정 AWS IoT Events부터 보다 구체적인 사용 사례에 이르기까지의 다양한 측면을 다루는 절차 모음을 제공합니다. 각 자습서에서는 감지기 모델 생성, 입력 구성, 작업 설정, 다른 AWS 서비스와의 통합을 통해 강력한 IoT 솔루션을 만드는 데 도움이 되는 실제 기술을 구축하는 데 도움이 되는 실제 시나리오의 예를 보여줍니다.

이 장에서는 다음을 수행하는 방법을 설명합니다.
+ 감지기 모델에 포함할 상태를 결정하는 데 도움을 받고, 감지기 인스턴스가 하나 혹은 여러 개가 필요할지 결정하십시오.
+  AWS CLI를 사용하는 예를 따르십시오.
+ 디바이스로부터 원격 측정 데이터를 수신하는 입력과 감지기 모델을 생성하여 해당 데이터를 전송하는 디바이스의 상태를 모니터링하고 보고할 수 있습니다.
+ 입력, 감지기 모델 및 AWS IoT Events 서비스에 대한 제한과 한계를 검토하십시오.
+ 감지기 모델의 더 복잡한 예시를 설명과 함께 참조하십시오.

**Topics**
+ [AWS IoT Events 를 사용하여 IoT 디바이스 모니터링](iotevents-how-to-use.md)
+ [CLI를 사용하여 두 상태에 대한 AWS IoT Events 감지기 생성](iotevents-simple-example.md)
+ [AWS IoT Events 감지기 모델 제한 사항 및 제한 사항](iotevents-restrictions-detector-model.md)
+ [주석이 달린 예제:를 사용한 HVAC 온도 제어 AWS IoT Events](iotevents-commented-example.md)

# AWS IoT Events 를 사용하여 IoT 디바이스 모니터링
<a name="iotevents-how-to-use"></a>

 AWS IoT Events 를 사용하여 디바이스 또는 프로세스를 모니터링하고 중요한 이벤트에 따라 조치를 취할 수 있습니다. 이렇게 하려면 다음 기본 단계를 따르십시오.

**입력 생성**  
디바이스와 프로세스가 원격 측정 데이터를 AWS IoT Events로 보낼 방법이 있어야 합니다. 이를 통해 메시지를 AWS IoT Events에 *입력*으로 전송합니다. 다음과 같은 여러 방법으로 메시지를 입력으로 보낼 수 있습니다.  
+ [BatchPutMessage](https://docs.aws.amazon.com/iotevents/latest/apireference/API_iotevents-data_BatchPutMessage.html) 작업을 사용합니다.
+ [`iotEvents` rule-action](https://docs.aws.amazon.com/iot/latest/developerguide/iotevents-rule-action.html)을 [AWS IoT Core 규칙 엔진](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rule-actions.html)으로 정의합니다. rule-action은 입력의 메시지 데이터를 AWS IoT Events로 전달합니다.
+ 에서 [CreateDataset](https://docs.aws.amazon.com/iotanalytics/latest/userguide/automate.html#aws-iot-analytics-automate-create-dataset) 작업을 AWS IoT 분석사용하여 로 데이터 세트를 생성합니다`contentDeliveryRules`. 이러한 규칙은 데이터 세트 콘텐츠가 자동으로 전송되는 AWS IoT Events 입력을 지정합니다.
+  AWS IoT Events 감지기 모델의 `onInput` `onExit` 또는 `transitionEvents` 이벤트에서 [iotEvents 작업을](https://docs.aws.amazon.com/iotevents/latest/apireference/API_IotEventsAction.html) 정의합니다. 작업을 시작한 이벤트와 감지기 모델 인스턴스에 대한 정보가 지정된 이름을 사용하여 시스템에 입력으로 피드백됩니다.
디바이스가 이러한 방식으로 데이터를 전송하기 전에 하나 이상의 입력을 정의해야 합니다. 이렇게 하려면 각 입력에 이름을 지정하고 입력이 모니터링하는 수신 메시지 데이터의 필드를 지정합니다.는 여러 소스에서 JSON 페이로드 형태로 입력을 AWS IoT Events 수신합니다. 각 입력을 자체적으로 처리하거나 다른 입력과 결합하여 더 복잡한 이벤트를 감지할 수 있습니다.

**감지기 모델 생성**  
*상태*를 사용하여 *감지기 모델*(디바이스 또는 프로세스의 모델)을 정의합니다. 각 상태에 대해 수신되는 입력을 평가하여 중요 이벤트를 탐지하는 조건부(부울) 논리를 정의합니다. 이벤트가 감지되면 상태를 변경하거나 다른 AWS 서비스를 사용하여 사용자 지정 빌드 또는 사전 정의된 작업을 시작할 수 있습니다. 특정 상태가 시작 또는 종료할 때 또한 선택적으로 특정 조건이 충족될 때 작업을 시작하는 추가 이벤트를 정의할 수 있습니다.  
이 자습서에서는 모델이 특정 상태에 들어가거나 종료될 때 Amazon SNS 메시지를 작업으로 전송합니다.

**디바이스 또는 프로세스 모니터링**  
여러 디바이스 또는 프로세스를 모니터링하는 경우 각 입력에 특정 디바이스를 식별하거나 입력의 출처를 처리하는 필드를 지정합니다. (`key`의 `CreateDetectorModel` 필드 참조.) 새 장치가 식별되면(`key`로 식별되는 입력 필드에 새 값이 표시됨) 감지기가 생성됩니다. (각 감지기는 감지기 모델의 인스턴스입니다.) 그러면 새 감지기는 해당 감지기 모델이 업데이트되거나 삭제될 때까지 해당 디바이스에서 오는 입력에 계속 응답합니다.  
단일 프로세스를 모니터링하는 경우 여러 디바이스 또는 하위 프로세스가 입력을 보낸다 하더라도 고유한 식별 `key` 필드를 지정하지 마십시오. 이 경우 첫 번째 입력이 도착하면 단일 감지기(인스턴스)가 생성됩니다.

**메시지를 감지기 모델에 입력으로 전송**  
디바이스에서 메시지를 보내거나 AWS IoT Events 감지기에 대한 입력으로 처리하는 방법에는 여러 가지가 있습니다.이 경우 메시지에 대한 추가 형식을 지정할 필요가 없습니다. 이 자습서에서는 AWS IoT 콘솔을 사용하여 메시지 데이터를 전달하는 AWS IoT Core 규칙 엔진에 대한 [AWS IoT Events 작업](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rule-actions.html#iotevents-rule) 규칙을 작성합니다 AWS IoT Events. 이렇게 하려면 입력을 이름으로 식별해야 합니다. 그런 다음 AWS IoT 콘솔을 계속 사용하여 입력으로 전달되는 일부 메시지를 생성합니다 AWS IoT Events.

## 감지기 모델에 어떤 상태가 필요한지 어떻게 알 수 있나요?
<a name="how-to-use-iotevents-what-states"></a>

감지기 모델의 상태를 결정하려면 취할 수 있는 조치를 먼저 결정하십시오. 예를 들어, 자동차가 휘발유를 사용하는 경우 여행을 시작할 때 연료 게이지를 보고 연료 충전이 필요한지 확인합니다. 여기서 한 가지 조치를 취할 수 있습니다. 운전자에게 “연료를 충전하십시오”라고 말하는 것입니다. 감지기 모델에는 “자동차에 연료가 필요하지 않음”과 “자동차에 연료가 필요함”이라는 두 가지 상태가 필요합니다. 일반적으로 가능한 각 동작에 대해 하나의 상태를 정의하고, 조치가 필요하지 않은 경우를 위한 상태를 하나 더 정의하려고 합니다. 이 방법은 작업 자체가 더 복잡한 경우에도 적용됩니다. 예를 들어 가장 가까운 주유소 또는 가장 저렴한 주유소의 위치 정보를 찾아보고 포함할 수 있지만, 이는 “연료를 충전하십시오”라는 메시지를 보낼 때 이렇게 합니다.

다음으로 전환할 상태를 결정하려면 입력 내용을 살펴보십시오. 입력에는 어떤 상태로 전환되어야 하는지 결정하는 데 필요한 정보가 들어 있습니다. 입력을 만들려면 디바이스나 프로세스에서 보낸 메시지에서 결정을 내리는 데 도움이 되는 필드를 하나 이상 선택합니다. 이 예시에서는 현재 연료 수준(“연료 비율”)을 알려주는 입력이 하나 필요합니다. 자동차가 여러 개의 서로 다른 필드를 포함하는 서로 다른 메시지를 여러 개 보내고 있을 수 있습니다. 이 입력을 생성하려면 메시지와 현재 연료 게이지 수준을 보고하는 필드를 선택해야 합니다. 이동하려는 거리(“목적지까지의 거리”)를 하드코딩하여 단순하게 만들 수 있습니다. 즉, 평균 이동 거리를 사용할 수 있습니다. 입력값을 바탕으로 계산을 할 수 있습니다(연료 비율이 몇 갤런으로 환산되나요? 보유한 갤런과 평균 “갤런당 마일”을 감안하면 평균 이동 거리가 주행 가능 거리보다 길까요?). 이러한 계산을 수행하고 *이벤트*에서 메시지를 전송합니다.

지금까지는 두 개의 상태와 한 개의 입력이 있습니다. 첫 번째 상태에는 입력을 기반으로 계산을 수행하고 두 번째 상태로 이동 여부를 결정하는 이벤트가 필요합니다. 이는 전환 이벤트입니다. (`transitionEvents`가 상태의 `onInput` 이벤트 목록에 있습니다. **첫 번째 상태에서 *입력*을 받은 후, 이벤트의 `condition`이 충족되면 *이벤트*가 두 번째 상태로 *전환*됩니다.) 두 번째 상태에 도달하면 해당 상태로 전환되는 즉시 메시지가 전송됩니다. (`onEnter` 이벤트를 사용합니다. 두 번째 상태로 전환되면 이 이벤트가 메시지를 보냅니다. 다른 입력이 도착할 때까지 기다릴 필요가 없습니다.) 다른 유형의 이벤트도 있지만 여기까지가 간단한 예시입니다.

다른 유형의 이벤트는 `onExit` 및 `onInput`입니다. 입력이 수신되고 조건이 충족되는 즉시 `onInput` 이벤트는 지정된 작업을 수행합니다. 작업이 현재 상태를 종료하고 조건이 충족되면 `onExit` 이벤트는 지정된 작업을 수행합니다.

놓친 것이 있나요? 네, 어떻게 하면 첫 번째 상태 “자동차에 연료가 필요하지 않음”으로 돌아갈 수 있을까요? 연료 탱크를 가득 채우면 입력란에 탱크가 가득 찼다고 표시됩니다. 두 번째 상태에서는 (두 번째 상태의 `onInput:` 이벤트에서) 입력이 수신될 때 발생하는 첫 번째 상태로의 전환 이벤트가 필요합니다. 원하는 곳으로 갈 수 있을 만큼 연료가 충분하다는 계산이 나오면 다시 첫 번째 상태로 전환해야 합니다.

이것이 기본입니다. 일부 감지기 모델은 가능한 동작뿐만 아니라 중요한 입력을 반영하는 상태를 추가하여 더 복잡해집니다. 예를 들어 온도를 추적하는 감지기 모델에는 “정상”, “고온”, “잠재적 문제”의 세 가지 상태가 있을 수 있습니다. 온도가 특정 수준 이상으로 올라갔지만 아직 너무 뜨거워지지 않은 경우 잠재적 문제 상태로 전환됩니다. 이 온도로 15분 이상 유지되지 않으면 경보를 보내고 싶지 않을 것입니다. 그 전에 온도가 정상으로 돌아오면 감지기는 정상 상태로 다시 전환됩니다. 타이머가 만료되면 감지기가 너무 뜨거워진 상태로 전환되어 경보를 보내므로 주의해야 합니다. 변수와 더 복잡한 이벤트 조건 세트를 사용하여 동일한 작업을 수행할 수 있습니다. 하지만 실제로는 다른 상태를 사용하여 계산 결과를 저장하는 것이 더 쉬운 경우가 많습니다.

## 감지기 인스턴스가 하나 필요한지 아니면 여러 개가 필요한지 어떻게 알 수 있습니까?
<a name="how-to-use-iotevents-instances"></a>

필요한 인스턴스 수를 결정하려면 “무엇을 알고 싶은가요?”라고 스스로 질문하십시오. 오늘 날씨가 어떤지 알고 싶다고 가정해 봅시다. 비가 오나요(상태)? 우산을 써야 하나요(작업)? 온도를 알려주는 센서, 습도를 알려주는 센서, 기압, 풍속, 강수를 알려주는 센서를 사용할 수 있습니다. 하지만 이러한 모든 센서를 함께 모니터링하여 날씨 상태(비, 눈, 흐린 날씨, 맑음)와 적절한 작업(우산 챙기기 또는 자외선 차단제 바르기)을 파악해야 합니다. 센서 수가 많더라도 하나의 감지기 인스턴스가 날씨 상태를 모니터링하고 취해야 할 작업을 알려주는 것이 좋습니다.

하지만 해당 리전의 일기 예보관이라면 리전 곳곳의 다양한 위치에 이러한 센서 그룹이 여러 개 있을 수 있습니다. 각 지역의 사람들은 해당 지역의 날씨가 어떤지 알아야 합니다. 이 경우 여러 개의 감지기 인스턴스가 필요합니다. 각 위치의 각 센서가 보고하는 데이터에는 `key` 필드로 지정한 필드가 포함되어야 합니다. 이 필드를 사용하면 AWS IoT Events 가 해당 영역에 대한 감지기 인스턴스를 만든 다음, 해당 감지기 인스턴스가 도착할 때마다 이 정보를 해당 감지기 인스턴스로 계속 라우팅할 수 있습니다. 날씨 때문에 머리 스타일을 망치거나 얼굴이 타는 일은 더 이상 없습니다\$1

기본적으로 모니터링해야 할 한 개의 상황(프로세스 또는 위치 한 개)이 있다면 한 개의 감지기 인스턴스가 필요합니다. 모니터링해야 할 상황(위치, 프로세스)이 많은 경우 여러 개의 감지기 인스턴스가 필요합니다.

# CLI를 사용하여 두 상태에 대한 AWS IoT Events 감지기 생성
<a name="iotevents-simple-example"></a>

이 예제에서는 AWS CLI 명령을 사용하여 AWS IoT Events APIs를 호출하여 엔진의 두 가지 상태인 정상 상태와 과압 조건을 모델링하는 감지기를 생성합니다.

엔진에서 측정된 압력이 특정 임계값을 초과하면 모델은 과압 상태로 전환하고 Amazon Simple Notification Service(SNS) 메시지를 보내 기술자에게 상태를 알립니다. 압력 판독값이 3회 연속 임계값 아래로 떨어지면 모델은 정상 상태로 돌아가고 상태가 해결되었음을 확인하는 Amazon SNS 메시지를 하나 더 보냅니다. 비선형 복구 단계 또는 일회성 변칙 복구 측정값 발생 시 과압/정상 메시지가 끊길 가능성을 없애려면 압력 판독값이 임계값 아래로 3회 연속 측정된 값이 필요합니다.

다음은 감지기 생성 단계의 개요입니다.

***입력*을 생성합니다.**  
디바이스와 프로세스를 모니터링하려면 원격 측정 데이터를 AWS IoT Events로 보낼 방법이 있어야 합니다. 이는 메시지를 *입력*으로 전송하여 수행됩니다 AWS IoT Events. 여러 가지 방법으로 이 작업을 수행할 수 있습니다.  
+ [BatchPutMessage](https://docs.aws.amazon.com/iotevents/latest/apireference/API_iotevents-data_BatchPutMessage.html) 작업을 사용합니다. 이 방법은 쉽지만 디바이스 또는 프로세스가 SDK 또는를 통해 AWS IoT Events API에 액세스할 수 있어야 합니다 AWS CLI.
+ 에서 메시지 데이터를 전달하는 AWS IoT Core 규칙 엔진에 대한 [AWS IoT Events 작업](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rule-actions.html#iotevents-rule) 규칙을 AWS IoT Core작성합니다 AWS IoT Events. 이렇게 하면 입력이 이름으로 식별됩니다. 디바이스 또는 프로세스가 메시지를 전송할 수 있거나 이미 전송 중인 경우이 방법을 사용합니다 AWS IoT Core. 이 방법을 사용하면 일반적으로 장치의 컴퓨팅 성능이 덜 필요합니다.
+ 에서 [ CreateDataset](https://docs.aws.amazon.com/iotanalytics/latest/userguide/automate.html#aws-iot-analytics-automate-create-dataset) 작업을 AWS IoT Analytics사용하여 데이터 세트 콘텐츠가 자동으로 전송되는 AWS IoT Events 입력을 `contentDeliveryRules` 지정하는를 사용하여 데이터 세트를 생성합니다. AWS IoT 분석에서 집계되거나 분석된 데이터를 기반으로 디바이스 또는 프로세스를 제어하려면 이 방법을 사용하십시오.
디바이스에서 이러한 방식으로 데이터를 전송하려면 먼저 하나 이상의 입력을 정의해야 합니다. 이렇게 하려면 각 입력에 이름을 지정하고 입력이 모니터링하는 수신 메시지 데이터의 필드를 지정하십시오.

**감지기 모델 생성**  
*상태*를 사용하여 *감지기 모델*(장비 또는 프로세스의 모델)을 생성합니다. 각 상태에 대해 수신되는 입력을 평가하여 중요 이벤트를 탐지하는 조건부(부울) 논리를 정의합니다. 이벤트가 감지되면 상태를 변경하거나 다른 AWS 서비스를 사용하여 사용자 지정 빌드 또는 사전 정의된 작업을 시작할 수 있습니다. 특정 상태가 시작 또는 종료할 때 또한 선택적으로 특정 조건이 충족될 때 작업을 시작하는 추가 이벤트를 정의할 수 있습니다.

**여러 디바이스 또는 프로세스 모니터링**  
여러 디바이스 또는 프로세스를 모니터링하고 각 디바이스를 개별적으로 추적하려면 각 입력에 특정 디바이스를 식별하거나 입력이 들어오는 프로세스를 식별하는 필드를 지정하십시오. `CreateDetectorModel`의 `key` 필드를 참조하십시오. 새 디바이스가 식별되면 (`key`로 식별되는 입력 필드에 새 값이 표시됨) 감지기 인스턴스가 생성됩니다. 새 감지기 인스턴스는 해당 감지기 모델이 업데이트되거나 삭제될 때까지 해당 특정 디바이스에서 들어오는 입력에 계속 응답합니다. 입력 `key` 필드의 고유 값 수만큼 고유한 감지기(인스턴스)가 있습니다.

**단일 디바이스 또는 프로세스 모니터링**  
단일 프로세스를 모니터링하는 경우 여러 디바이스 또는 하위 프로세스가 입력을 보낸다 하더라도 고유한 식별 `key` 필드를 지정하지 마십시오. 이 경우 첫 번째 입력이 도착하면 단일 감지기(인스턴스)가 생성됩니다. 예를 들어 집 내부의 각 방에는 온도 센서가 있지만 집 전체를 냉난방하는 HVAC 장치는 하나뿐일 수 있습니다. 따라서 각 방의 사용자가 자신의 의견(입력)이 수용되기를 원하더라도 이를 단일 프로세스로만 제어할 수 있습니다.

**디바이스 또는 프로세스의 메시지를 감지기 모델에 입력으로 전송**  
디바이스 또는 프로세스에서 입력의 AWS IoT Events 감지기에 대한 입력으로 메시지를 보내는 몇 가지 방법을 설명했습니다**. 입력을 생성하고 감지기 모델을 구축했으면 이제 데이터 전송을 시작할 준비가 되었습니다.  
감지기 모델을 생성하거나 기존 감지기 모델을 업데이트하면 신규 또는 업데이트된 감지기 모델이 메시지를 수신하고 감지기(인스턴스) 생성을 시작하기까지 몇 분이 걸립니다. 감지기 모델이 업데이트되면 이 기간 동안 이전 버전에 기반한 동작이 계속 나타날 수 있습니다.

**Topics**
+ [AWS IoT Events 입력을 생성하여 디바이스 데이터 캡처](iotevents-create-input.md)
+ [에서 디바이스 상태를 나타내는 감지기 모델 생성 AWS IoT Events](iotevents-create-detector.md)
+ [에서 감지기에 입력으로 메시지 전송 AWS IoT Events](iotevents-batch-put-messages.md)

# AWS IoT Events 입력을 생성하여 디바이스 데이터 캡처
<a name="iotevents-create-input"></a>

에 대한 입력을 설정할 때를 활용하여 디바이스가 센서 데이터를 통신 AWS CLI 하는 방법을 정의할 AWS IoT Events수 있습니다. 예를 들어 디바이스가 모터 식별자 및 센서 판독값과 함께 JSON 형식의 메시지를 전송하는 경우 압력 및 모터 ID와 같은 메시지의 특정 속성을 매핑하는 입력을 생성하여이 데이터를 캡처할 수 있습니다. 프로세스는 JSON 파일에서 입력을 정의하고, 관련 데이터 포인트를 지정하고,를 사용하여 입력을 등록하는 AWS CLI 것으로 시작됩니다 AWS IoT Events. 이를 통해 AWS IoT 는 실시간 센서 데이터를 기반으로 중요한 조건을 모니터링하고 이에 대응할 수 있습니다.

예를 들어 다음 형식으로 메시지를 전송한다고 가정해 보겠습니다.

```
{
  "motorid": "Fulton-A32",
  "sensorData": {
    "pressure": 23,
    "temperature": 47
  }
}
```

다음 AWS CLI 명령을 사용하여 `pressure` 데이터와 `motorid` (메시지를 전송한 특정 디바이스를 식별하는)를 캡처하는 입력을 생성할 수 있습니다.

```
aws iotevents create-input  --cli-input-json file://pressureInput.json 
```

파일 `pressureInput.json`에는 다음이 포함되어 있습니다.

```
{
  "inputName": "PressureInput",
  "inputDescription": "Pressure readings from a motor",
  "inputDefinition": {
    "attributes": [
      { "jsonPath": "sensorData.pressure" },
      { "jsonPath": "motorid" }
    ]
  }
}
```

직접 입력을 생성할 때는 먼저 디바이스 또는 프로세스에서 예제 메시지를 JSON 파일로 수집해야 합니다. 이를 사용해 콘솔 또는 CLI에서 입력을 생성할 수 있습니다.

# 에서 디바이스 상태를 나타내는 감지기 모델 생성 AWS IoT Events
<a name="iotevents-create-detector"></a>

[AWS IoT Events 입력을 생성하여 디바이스 데이터 캡처](iotevents-create-input.md)에서 모터의 압력 데이터를 보고하는 메시지를 기반으로 `input`을 만들었습니다. 예제를 계속하기 위해 모터의 과압 상황에 대응하는 감지기 모델을 살펴보겠습니다.

“`Normal`” 및 “`Dangerous`”의 두 가지 상태를 생성합니다. 각 감지기(인스턴스)는 생성될 때 "`Normal`" 상태로 전환됩니다. 인스턴스는 `key` “`motorid`”에 대한 고유한 값을 가진 입력이 도착하면 생성됩니다.

감지기 인스턴스가 70 이상의 압력 판독값을 수신하면 "`Dangerous`" 상태로 전환되고 Amazon SNS 메시지를 경고로 보냅니다. 압력 측정값이 정상(70 미만)으로 3회 연속 입력되면 감지기는 "`Normal`" 상태로 돌아가고 다른 Amazon SNS 메시지를 모두 지우기 상태로 보냅니다.

이 예제 감지기 모델은 정의에 Amazon 리소스 이름(ARN)이 `"targetArn": "arn:aws:sns:us-east-1:123456789012:underPressureAction"` 및 `"targetArn": "arn:aws:sns:us-east-1:123456789012:pressureClearedAction"`으로 표시된 두 개의 Amazon SNS 주제를 생성했다고 가정합니다.

자세한 내용은 [Amazon Simple Notification Service 개발자 안내서](https://docs.aws.amazon.com/sns/latest/dg/)를 참조하십시오. 더 구체적인 설명은 *Amazon Simple Notification Service API 참조*의 [CreateTopic](https://docs.aws.amazon.com/sns/latest/api/API_CreateTopic.html) 작업을 참조하십시오.

또한이 예제에서는 적절한 권한이 있는 AWS Identity and Access Management (IAM) 역할을 생성했다고 가정합니다. 이 역할의 ARN은 감지기 모델 정의에 `"roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole"`과 같이 표시됩니다. [에 대한 권한 설정 AWS IoT Events](iotevents-permissions.md)의 단계에 따라 이 역할을 생성하고 역할의 ARN을 감지기 모델 정의의 적절한 위치에 복사하십시오.

다음 AWS CLI 명령을 사용하여 감지기 모델을 생성할 수 있습니다.

```
aws iotevents create-detector-model  --cli-input-json file://motorDetectorModel.json
```

`"motorDetectorModel.json"` 파일에는 다음 코드가 포함되어 있습니다.

```
{
  "detectorModelName": "motorDetectorModel",
  "detectorModelDefinition": {
    "states": [
      {
        "stateName": "Normal",
        "onEnter": {
          "events": [
            {
              "eventName": "init",
              "condition": "true",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "pressureThresholdBreached",
                    "value": "0"
                  }
                }
              ]
            }
          ]
        },
        "onInput": {
          "transitionEvents": [
            {
              "eventName": "Overpressurized",
              "condition": "$input.PressureInput.sensorData.pressure > 70",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "pressureThresholdBreached",
                    "value": "$variable.pressureThresholdBreached + 3"
                  }
                }
              ],
              "nextState": "Dangerous"
            }
          ]
        }
      }, 
      {
        "stateName": "Dangerous",
        "onEnter": {
          "events": [
            {
              "eventName": "Pressure Threshold Breached",
              "condition": "$variable.pressureThresholdBreached > 1",
              "actions": [
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-east-1:123456789012:underPressureAction"
                  }
                }
              ]
            }
          ]
        },
        "onInput": {
          "events": [
            {
              "eventName": "Overpressurized",
              "condition": "$input.PressureInput.sensorData.pressure > 70",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "pressureThresholdBreached",
                    "value": "3"
                  }
                }
              ]
            },
            {
              "eventName": "Pressure Okay",
              "condition": "$input.PressureInput.sensorData.pressure <= 70",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "pressureThresholdBreached",
                    "value": "$variable.pressureThresholdBreached - 1"
                  }
                }
              ]
            }
          ],
          "transitionEvents": [
            {
              "eventName": "BackToNormal",
              "condition": "$input.PressureInput.sensorData.pressure <= 70 && $variable.pressureThresholdBreached <= 1",
              "nextState": "Normal"
            }
          ]
        },
        "onExit": {
          "events": [
            {
              "eventName": "Normal Pressure Restored",
              "condition": "true",
              "actions": [
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-east-1:123456789012:pressureClearedAction"
                  }
                }
              ]
            }
          ]
        }
      }
    ],
    "initialStateName": "Normal"
  },
  "key" : "motorid",
  "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole"
}
```

# 에서 감지기에 입력으로 메시지 전송 AWS IoT Events
<a name="iotevents-batch-put-messages"></a>

이제 디바이스에서 보낸 메시지의 중요 필드를 식별하는 입력이 정의되었습니다([AWS IoT Events 입력을 생성하여 디바이스 데이터 캡처](iotevents-create-input.md) 참조). 이전 섹션에서는 모터의 과압 이벤트에 반응하는 `detector model`을 생성했습니다([에서 디바이스 상태를 나타내는 감지기 모델 생성 AWS IoT Events](iotevents-create-detector.md) 참조).

예제를 완료하려면 디바이스(이 경우에는 AWS CLI 가 설치된 컴퓨터)의 메시지를 감지기에 입력으로 보내십시오.

**참고**  
감지기 모델을 생성하거나 기존 감지기 모델을 업데이트하면 새 또는 업데이트된 감지기 모델이 메시지를 수신하고 감지기(인스턴스)를 생성하기 시작하기까지 몇 분 정도 걸립니다. 감지기 모델을 업데이트하면 이 기간 동안 이전 버전에 기반한 동작이 계속 나타날 수 있습니다.

다음 AWS CLI 명령을 사용하여 임계값을 위반하는 데이터가 포함된 메시지를 보냅니다.

```
aws iotevents-data batch-put-message --cli-input-json file://highPressureMessage.json --cli-binary-format raw-in-base64-out
```

파일 “`highPressureMessage.json`”에는 다음이 포함되어 있습니다.

```
{
  "messages": [
    {
      "messageId": "00001",
      "inputName": "PressureInput",
      "payload": "{\"motorid\": \"Fulton-A32\", \"sensorData\": {\"pressure\": 80, \"temperature\": 39} }"
    }
  ]
}
```

전송되는 각 메시지에서 `messageId`를 변경해야 합니다. 변경하지 않으면 AWS IoT Events 시스템은 메시지를 중복 제거합니다. 메시지는 지난 5분 이내에 전송된 다른 메시지`messageID`와 동일한 경우 AWS IoT Events 무시합니다.

이때 모터 `"Fulton-A32"`의 이벤트를 모니터링하기 위한 감지기(인스턴스)가 생성됩니다. 이 감지기는 생성되었을 때의 `"Normal"` 상태로 들어갑니다. 하지만 임계값을 초과하는 압력 값을 보냈기 때문에 즉시 `"Dangerous"` 상태로 전환됩니다. 그러면 감지기는 ARN이 `arn:aws:sns:us-east-1:123456789012:underPressureAction`인 Amazon SNS 엔드포인트로 메시지를 전송합니다.

다음 AWS CLI 명령을 실행하여 압력 임계값 미만의 데이터가 포함된 메시지를 보냅니다.

```
aws iotevents-data batch-put-message --cli-input-json file://normalPressureMessage.json --cli-binary-format raw-in-base64-out
```

파일 `normalPressureMessage.json`에는 다음이 포함되어 있습니다.

```
{
  "messages": [
    {
      "messageId": "00002",
      "inputName": "PressureInput",
      "payload": "{\"motorid\": \"Fulton-A32\", \"sensorData\": {\"pressure\": 60, \"temperature\": 29} }"
    }
  ]
}
```

5분 이내에 `BatchPutMessage` 명령을 호출할 때마다 파일의 `messageId`를 변경해야 합니다. 메시지를 두 번 더 보내십시오. 메시지가 세 번 전송되면 모터 “`Fulton-A32`”의 감지기(인스턴스)가 Amazon SNS 엔드포인트 `"arn:aws:sns:us-east-1:123456789012:pressureClearedAction"`으로 메시지를 보내고 `"Normal"` 상태를 다시 입력합니다.

**참고**  
`BatchPutMessage`를 사용하여 한 번에 여러 메시지를 보낼 수 있습니다. 하지만 이러한 메시지가 처리되는 순서는 보장되지 않습니다. 메시지(입력)가 순서대로 처리되도록 하려면 메시지를 한 번에 하나씩 보내고 API가 호출될 때마다 응답 성공을 기다리십시오.

다음은 이 섹션에 설명된 감지기 모델 예제로 생성된 SNS 메시지 페이로드의 예시입니다.

**“압력 임계값 위반” 이벤트 발생 시**

```
IoT> {
  "eventTime":1558129816420,
  "payload":{
    "actionExecutionId":"5d7444df-a655-3587-a609-dbd7a0f55267",
    "detector":{
      "detectorModelName":"motorDetectorModel",
      "keyValue":"Fulton-A32",
      "detectorModelVersion":"1"
    },
    "eventTriggerDetails":{
      "inputName":"PressureInput",
      "messageId":"00001",
      "triggerType":"Message"
    },
    "state":{
      "stateName":"Dangerous",
      "variables":{
        "pressureThresholdBreached":3
      },
      "timers":{}
    }
  },
  "eventName":"Pressure Threshold Breached"
}
```

**“정상 압력 복원” 이벤트 발생 시**

```
IoT> {
  "eventTime":1558129925568,
  "payload":{
    "actionExecutionId":"7e25fd38-2533-303d-899f-c979792a12cb",
    "detector":{
      "detectorModelName":"motorDetectorModel",
      "keyValue":"Fulton-A32",
      "detectorModelVersion":"1"
    },
    "eventTriggerDetails":{
      "inputName":"PressureInput",
      "messageId":"00004",
      "triggerType":"Message"
    },
    "state":{
      "stateName":"Dangerous",
      "variables":{
        "pressureThresholdBreached":0
      },
      "timers":{}
    }
  },
  "eventName":"Normal Pressure Restored"
}
```

타이머를 정의한 경우 해당 타이머의 현재 상태는 SNS 메시지 페이로드에도 표시됩니다.

메시지 페이로드에는 메시지가 전송된 시점 (즉, SNS 작업이 실행된 시점)의 감지기(인스턴스) 상태에 대한 정보가 포함됩니다. [https://docs.aws.amazon.com/iotevents/latest/apireference/API_iotevents-data_DescribeDetector.html](https://docs.aws.amazon.com/iotevents/latest/apireference/API_iotevents-data_DescribeDetector.html) 작업을 사용하여 감지기 상태에 대한 유사한 정보를 얻을 수 있습니다.

# AWS IoT Events 감지기 모델 제한 사항 및 제한 사항
<a name="iotevents-restrictions-detector-model"></a>

감지기 모델을 생성할 때 고려해야 할 중요한 사항은 다음과 같습니다.

**`actions` 필드 사용 방법**  
`actions` 값은 객체의 목록입니다. 객체를 두 개 이상 가질 수 있지만 각 객체에는 하나의 작업만 허용됩니다.  

**Example**  

```
              "actions": [
                {
                  "setVariable": {
                    "variableName": "pressureThresholdBreached",
                    "value": "$variable.pressureThresholdBreached - 1"
                  }
                }
                {
                  "setVariable": {
                    "variableName": "temperatureIsTooHigh",
                    "value": "$variable.temperatureIsTooHigh - 1"
                  }
                }
              ]
```

**`condition` 필드 사용 방법**  
`condition`은(는) `transitionEvents`에 필수 항목이며 다른 경우에는 선택 사항입니다.  
해당 `condition` 필드가 없는 경우 이는 `"condition": true`와 같습니다.  
조건 표현식의 평가 결과는 부울 값이어야 합니다. 결과가 부울 값이 아닌 경우 해당 값은 `false`와 동일하며 이벤트에서 지정된 `nextState`로의 전환 또는 `actions`으로 시작되지 않습니다.

**변수 값의 사용 가능 여부**  
기본적으로 변수 값이 이벤트에 설정된 경우 새 값을 사용할 수 없거나 같은 그룹 내 다른 이벤트의 조건을 평가하는 데 사용할 수 없습니다. 새 값은 사용할 수 없거나 동일한 `onInput`, `onEnter` 또는 `onExit` 필드의 이벤트 조건에 사용되었습니다.  
감지기 모델 정의에서 `evaluationMethod` 파라미터를 설정하여 이 동작을 변경하십시오. `evaluationMethod`를 `SERIAL`로 설정하면 변수가 업데이트되고 이벤트가 정의된 순서대로 이벤트 조건이 평가됩니다. 그렇지 않고 `evaluationMethod`를 `BATCH`로 설정하거나 기본값으로 설정하면, 상태 내의 변수가 업데이트되고 모든 이벤트 조건이 평가된 후에만 상태 내의 이벤트가 수행됩니다.  
`"Dangerous"` 상태, `onInput` 필드에서 조건이 충족되는 경우(현재 입력의 압력이 70 이하인 경우), `"Pressure Okay"` 이벤트의 `"$variable.pressureThresholdBreached"`가 하나씩 감소합니다.   

```
            {
              "eventName": "Pressure Okay",
              "condition": "$input.PressureInput.sensorData.pressure <= 70",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "pressureThresholdBreached",
                    "value": "$variable.pressureThresholdBreached - 1"
                  }
                }
              ]
            }
```
감지기는 `"$variable.pressureThresholdBreached"`가 0에 도달했을 때 (즉, 감지기가 70 이하의 압력 측정값을 연속으로 세 번 수신했을 때) `"Normal"` 상태로 다시 전환되어야 합니다. `transitionEvents`의 `"BackToNormal"` 이벤트는 `"$variable.pressureThresholdBreached"`가 1보다 작거나 같은지(0이 아님) 테스트하고 `"$input.PressureInput.sensorData.pressure"`에서 제공한 현재 값이 70 미만인지 다시 확인해야 합니다.  

```
          "transitionEvents": [
            {
              "eventName": "BackToNormal",
              "condition": "$input.PressureInput.sensorData.pressure <= 70 && $variable.pressureThresholdBreached <= 1",
              "nextState": "Normal"
            }
          ]
```
그렇지 않으면 조건에서 변수 값만 테스트할 경우 정상 판독값 2개와 과압 판독값이 뒤따르는 경우 조건을 충족하고 `"Normal"` 상태로 다시 전환됩니다. 조건은 이전에 입력이 처리되었을 때 `"$variable.pressureThresholdBreached"`에 제공된 값을 확인하는 것입니다. 이 경우 `"Overpressurized"` 이벤트에서 변수 값이 3으로 재설정되지만 이 새 값은 어떤 `condition`도 사용할 수 없다는 점에 유의하십시오.  
기본적으로 컨트롤이 `onInput` 필드에 들어갈 때마다 `condition`은(는) `onInput`에서 지정한 작업에 의해 변수가 변경되기 전의 입력 처리 시작 시점의 변수 값만 볼 수 있습니다. `onEnter` 및 `onExit`도 마찬가지입니다. 상태를 입력하거나 종료할 때 변수에 적용된 변경 사항은 동일한 `onEnter` 또는 `onExit` 필드에 지정된 다른 조건에서는 사용할 수 없습니다.

**감지기 모델 업데이트 시 지연 시간**  
감지기 모델을 업데이트, 삭제 및 재생성하는 경우([UpdateDetectorModel](https://docs.aws.amazon.com/iotevents/latest/apireference/API_UpdateDetectorModel.html) 참조), 생성된 모든 감지기(인스턴스)가 삭제되고 새 모델을 사용하여 감지기를 다시 생성하기까지 약간의 지연이 발생합니다. 새 감지기 모델이 적용되고 새 입력이 도착한 후에 다시 생성됩니다. 이 기간 동안에는 이전 버전의 감지기 모델에서 생성된 감지기가 입력을 계속 처리할 수 있습니다. 이 기간 동안에는 이전 감지기 모델에서 정의한 알림을 계속 받을 수 있습니다.

**입력 키의 공백**  
입력 키에는 공백이 허용되지만 키 참조는 입력 속성 정의와 표현식에서 키 값을 참조할 때 모두 백틱으로 묶어야 합니다. 예를 들어 다음과 같은 메시지 페이로드가 있다고 가정합니다.  

```
{
  "motor id": "A32",
  "sensorData" {
    "motor pressure": 56,
    "motor temperature": 39
  }
}
```
다음을 사용하여 입력을 정의합니다.  

```
{
  "inputName": "PressureInput",
  "inputDescription": "Pressure readings from a motor",
  "inputDefinition": {
    "attributes": [
      { "jsonPath": "sensorData.`motor pressure`" },
      { "jsonPath": "`motor id`" }
    ]
  }
}
```
조건 표현식에서는 백틱도 사용하여 이러한 키의 값을 참조해야 합니다.  

```
$input.PressureInput.sensorData.`motor pressure`
```

# 주석이 달린 예제:를 사용한 HVAC 온도 제어 AWS IoT Events
<a name="iotevents-commented-example"></a>

다음 예제 JSON 파일 중 일부에는 주석이 인라인으로 포함되어 있어 유효하지 않은 JSON이 됩니다. 이러한 예제의 전체 버전(주석 제외)은 [예:에서 HVAC 온도 제어 사용 AWS IoT Events](iotevents-examples-hvac.md)에서 확인할 수 있습니다.

이 예제는 다음 작업을 수행할 수 있는 온도 조절기 제어 모델을 구현합니다.
+ 여러 영역을 모니터링하고 제어하는 데 사용할 수 있는 감지기 모델을 하나만 정의합니다. 감지기 인스턴스는 각 영역에 대해 생성됩니다.
+ 각 제어 영역의 여러 센서에서 온도 데이터를 수집합니다.
+ 특정 지역의 온도 설정점을 변경합니다.
+ 인스턴스가 사용 중인 동안 각 영역의 작동 파라미터를 설정하고 이러한 파라미터를 재설정합니다.
+ 영역에 센서를 동적으로 추가 또는 삭제합니다.
+ 냉난방 장치를 보호할 수 있는 최소 런타임을 지정하십시오.
+ 비정상적인 센서 판독값을 거부합니다.
+ 센서 중 하나에서 지정된 임계값보다 온도가 높거나 낮다고 보고하는 경우 즉시 난방 또는 냉방을 작동시키는 비상 설정점을 정의합니다.
+ 비정상적인 측정값 및 온도 급상승을 보고합니다.

**Topics**
+ [의 감지기 모델에 대한 입력 정의 AWS IoT Events](iotevents-commented-example-inputs.md)
+ [AWS IoT Events 감지기 모델 정의 생성](iotevents-commented-example-detector-model.md)
+ [BatchUpdateDetector를 사용하여 AWS IoT Events 감지기 모델 업데이트](iotevents-commented-example-batch-update-detector.md)
+ [의 입력에 BatchPutMessage 사용 AWS IoT Events](iotevents-commented-example-input-usage-examples.md)
+ [에서 MQTT 메시지 수집 AWS IoT Events](iotevents-commented-example-ingest-mqtt.md)
+ [에서 Amazon SNS 메시지 생성 AWS IoT Events](iotevents-commented-example-generated-sns.md)
+ [에서 DescribeDetector API 구성 AWS IoT Events](iotevents-commented-example-describe-detector.md)
+ [에 규칙 AWS IoT Core 엔진 사용 AWS IoT Events](iotevents-commented-examples-iot-rules-examples.md)

# 의 감지기 모델에 대한 입력 정의 AWS IoT Events
<a name="iotevents-commented-example-inputs"></a>

여러 영역의 온도를 모니터링하고 제어하는 데 사용할 수 있는 하나의 감지기 모델을 만들려고 합니다. 각 영역에는 온도를 보고하는 센서가 여러 개 있을 수 있습니다. 각 구역에는 냉난방 장치가 각각 하나씩 있으며, 이 장치를 켜거나 끄면 해당 구역의 온도를 제어할 수 있다고 가정합니다. 각 영역은 하나의 감지기 인스턴스로 제어됩니다.

모니터링하고 제어하는 영역마다 특성이 다르기 때문에 제어 파라미터가 다를 수 있으므로 각 영역에 해당 파라미터를 제공하도록 `'seedTemperatureInput'`을 정의합니다. 이러한 입력 메시지 중 하나를 AWS IoT Events에 보내면 해당 영역에서 사용하려는 파라미터가 포함된 새 감지기 모델 인스턴스가 생성됩니다. 해당 입력의 정의는 다음과 같습니다.

CLI 명령:

```
aws iotevents create-input --cli-input-json file://seedInput.json
```

파일: `seedInput.json`

```
{
  "inputName": "seedTemperatureInput",
  "inputDescription": "Temperature seed values.",
  "inputDefinition": {
    "attributes": [
      { "jsonPath": "areaId" },
      { "jsonPath": "desiredTemperature" },
      { "jsonPath": "allowedError" },
      { "jsonPath": "rangeHigh" },
      { "jsonPath": "rangeLow" },
      { "jsonPath": "anomalousHigh" },
      { "jsonPath": "anomalousLow" },
      { "jsonPath": "sensorCount" },
      { "jsonPath": "noDelay" }
    ]
  }
}
```

응답:

```
{
    "inputConfiguration": {
        "status": "ACTIVE", 
        "inputArn": "arn:aws:iotevents:us-west-2:123456789012:input/seedTemperatureInput", 
        "lastUpdateTime": 1557519620.736, 
        "creationTime": 1557519620.736, 
        "inputName": "seedTemperatureInput", 
        "inputDescription": "Temperature seed values."
    }
}
```

**참고**
+ 모든 메시지에서 `'areaId'` 수신된 각 고유자에 대해 새 감지기 인스턴스가 생성됩니다. `'areaDetectorModel'` 정의의 `'key'` 필드를 참조하십시오.
+ 평균 온도는 `'allowedError'`에 의해 해당 지역의 난방 또는 냉방 장치가 활성화되기 전의 `'desiredTemperature'`와 다를 수 있습니다.
+ 센서가 `'rangeHigh'`보다 높은 온도를 보고하면 감지기가 급상승을 보고하고 즉시 냉각 장치를 가동합니다.
+ 센서가 `'rangeLow'`보다 낮은 온도를 보고하면 감지기는 스파이크를 보고하고 즉시 난방 장치를 가동합니다.
+ 센서가 `'anomalousHigh'`보다 높거나 `'anomalousLow'`보다 낮은 온도를 보고하는 경우 감지기는 비정상적인 센서 판독값을 보고하지만 보고된 온도 판독값은 무시합니다. 
+ `'sensorCount'`은(는) 해당 구역에 대해 보고하는 센서 수를 감지기에 알려줍니다. 감지기는 수신한 각 온도 측정값에 적절한 가중치를 부여하여 해당 구역의 평균 온도를 계산합니다. 따라서 감지기는 각 센서가 보고하는 내용을 추적할 필요가 없으며 필요에 따라 센서 수를 동적으로 변경할 수 있습니다. 하지만 개별 센서가 오프라인 상태가 되면 감지기는 이를 인식하지 못하거나 허용치를 적용하지 못합니다. 각 센서의 연결 상태를 모니터링하기 위해 다른 감지기 모델을 특별히 생성하는 것이 좋습니다. 상호 보완적인 두 개의 감지기 모델을 사용하면 두 모델의 설계가 단순해집니다.
+ `'noDelay'` 값은 `true` 또는 `false`일 수 있습니다. 장치의 무결성을 보호하고 작동 수명을 연장하려면 난방 또는 냉방 장치를 작동한 후, 최소 일정 시간 동안 켜두어야 합니다. `'noDelay'`가 `false`로 설정된 경우, 감지기 인스턴스는 냉방 및 난방 장치의 전원을 끄기 전에 지연 시간을 적용하여 최소 시간 동안 작동되도록 합니다. 변수 값을 사용하여 타이머를 설정할 수 없기 때문에 감지기 모델 정의에 지연 시간(초)이 하드코딩되었습니다.

센서 데이터를 감지기 인스턴스로 전송하는 데 `'temperatureInput'`이 사용됩니다.

CLI 명령:

```
aws iotevents create-input --cli-input-json file://temperatureInput.json
```

파일: `temperatureInput.json`

```
{
  "inputName": "temperatureInput",
  "inputDescription": "Temperature sensor unit data.",
  "inputDefinition": {
    "attributes": [
      { "jsonPath": "sensorId" },
      { "jsonPath": "areaId" },
      { "jsonPath": "sensorData.temperature" }
    ]
  }
}
```

응답:

```
{
    "inputConfiguration": {
        "status": "ACTIVE", 
        "inputArn": "arn:aws:iotevents:us-west-2:123456789012:input/temperatureInput", 
        "lastUpdateTime": 1557519707.399, 
        "creationTime": 1557519707.399, 
        "inputName": "temperatureInput", 
        "inputDescription": "Temperature sensor unit data."
    }
}
```

**참고**
+ 예제 감지기 인스턴스에서 센서를 직접 제어하거나 모니터링하는 데 `'sensorId'`가 사용되지 않습니다. 감지기 인스턴스가 보낸 알림에 자동으로 전달됩니다. 이를 통해 오류가 발생한 센서(예: 비정상적인 판독값을 정기적으로 전송하는 센서가 곧 고장날 수 있음) 또는 오프라인 상태가 된 센서(장치의 심장 박동을 모니터링하는 추가 감지기 모델의 입력으로 사용되는 경우)를 식별하는 데 사용할 수 있습니다. 또한 측정값이 평균과 정기적으로 다를 경우 `'sensorId'`은(는) 해당 구역의 따뜻한 곳이나 차가운 곳을 식별하는 데도 도움이 됩니다.
+ 센서의 데이터를 적절한 감지기 인스턴스로 라우팅하는 데 `'areaId'`가 사용됩니다. 감지기 인스턴스는 모든 메시지에서 `'areaId'` 수신된 각 고유에 대해 생성됩니다. `'areaDetectorModel'` 정의의 `'key'` 필드를 참조하십시오.

# AWS IoT Events 감지기 모델 정의 생성
<a name="iotevents-commented-example-detector-model"></a>

`'areaDetectorModel'` 예제에는 주석이 인라인으로 되어 있습니다.

CLI 명령:

```
aws iotevents create-detector-model --cli-input-json file://areaDetectorModel.json
```

파일: `areaDetectorModel.json`

```
{
  "detectorModelName": "areaDetectorModel",
  "detectorModelDefinition": {
    "states": [
      {
        "stateName": "start",
        // In the 'start' state we set up the operation parameters of the new detector instance. 
        //   We get here when the first input message arrives. If that is a 'seedTemperatureInput' 
        //   message, we save the operation parameters, then transition to the 'idle' state. If 
        //   the first message is a 'temperatureInput', we wait here until we get a 
        //   'seedTemperatureInput' input to ensure our operation parameters are set. We can 
        //   also reenter this state using the 'BatchUpdateDetector' API. This enables us to
        //   reset the operation parameters without needing to delete the detector instance.
        "onEnter": {
          "events": [
            {
              "eventName": "prepare",
              "condition": "true",
              "actions": [
                {
                  "setVariable": {
                    // initialize 'sensorId' to an invalid value (0) until an actual sensor reading 
                    //   arrives
                    "variableName": "sensorId",
                    "value": "0"
                  }
                },
                {
                  "setVariable": {
                    // initialize 'reportedTemperature' to an invalid value (0.1) until an actual 
                    //   sensor reading arrives
                    "variableName": "reportedTemperature",
                    "value": "0.1"
                  }
                },
                {
                  "setVariable": {
                    // When using 'BatchUpdateDetector' to re-enter this state, this variable should 
                    //   be set to true.
                    "variableName": "resetMe",
                    "value": "false"
                  }
                }
              ]
            }
          ]
        },
        "onInput": {
          "transitionEvents": [
            {
              "eventName": "initialize",
              "condition": "$input.seedTemperatureInput.sensorCount > 0",
              // When a 'seedTemperatureInput' message with a valid 'sensorCount' is received,
              //   we use it to set the operational parameters for the area to be monitored.
              "actions": [
                { 
                  "setVariable": {
                    "variableName": "rangeHigh",
                    "value": "$input.seedTemperatureInput.rangeHigh"
                  }
                },
                { 
                  "setVariable": {
                    "variableName": "rangeLow",
                    "value": "$input.seedTemperatureInput.rangeLow"
                  }
                },
                { 
                  "setVariable": {
                    "variableName": "desiredTemperature",
                    "value": "$input.seedTemperatureInput.desiredTemperature"
                  }
                },
                { 
                  "setVariable": {
                    // Assume we're at the desired temperature when we start.
                    "variableName": "averageTemperature",
                    "value": "$input.seedTemperatureInput.desiredTemperature"
                  }
                },
                { 
                  "setVariable": {
                    "variableName": "allowedError",
                    "value": "$input.seedTemperatureInput.allowedError"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "anomalousHigh",
                    "value": "$input.seedTemperatureInput.anomalousHigh"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "anomalousLow",
                    "value": "$input.seedTemperatureInput.anomalousLow"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "sensorCount",
                    "value": "$input.seedTemperatureInput.sensorCount"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "noDelay",
                    "value": "$input.seedTemperatureInput.noDelay == true"
                  }
                }
              ],
              "nextState": "idle"
            },
            {
              "eventName": "reset",
              "condition": "($variable.resetMe == true) && ($input.temperatureInput.sensorData.temperature < $variable.anomalousHigh && $input.temperatureInput.sensorData.temperature > $variable.anomalousLow)",
              // This event is triggered if we have reentered the 'start' state using the 
              //   'BatchUpdateDetector' API with 'resetMe' set to true. When we reenter using
              //   'BatchUpdateDetector' we do not automatically continue to the 'idle' state, but
              //   wait in 'start' until the next input message arrives. This event enables us to 
              //   transition to 'idle' on the next valid 'temperatureInput' message that arrives.
              "actions": [
                {
                  "setVariable": {
                    "variableName": "averageTemperature",
                    "value": "((($variable.averageTemperature * ($variable.sensorCount - 1)) + $input.temperatureInput.sensorData.temperature) / $variable.sensorCount)"
                  }
                }
              ],
              "nextState": "idle"
            }
          ]
        },
        "onExit": {
          "events": [
            {
              "eventName": "resetHeatCool",
              "condition": "true",
              // Make sure the heating and cooling units are off before entering 'idle'.
              "actions": [
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:heatOff"
                  }
                },
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:coolOff"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Heating/Off"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Cooling/Off"
                  }
                }
              ]
            }
          ]
        }
      },


      {
        "stateName": "idle",
        "onInput": {
          "events": [
            {
              "eventName": "whatWasInput",
              "condition": "true",
              // By storing the 'sensorId' and the 'temperature' in variables, we make them 
              //   available in any messages we send out to report anomalies, spikes, or just
              //   if needed for debugging.
              "actions": [
                {
                  "setVariable": {
                    "variableName": "sensorId",
                    "value": "$input.temperatureInput.sensorId"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "reportedTemperature",
                    "value": "$input.temperatureInput.sensorData.temperature"
                  }
                }
              ]
            },
            {
              "eventName": "changeDesired",
              "condition": "$input.seedTemperatureInput.desiredTemperature != $variable.desiredTemperature",
              // This event enables us to change the desired temperature at any time by sending a
              //   'seedTemperatureInput' message. But note that other operational parameters are not
              //   read or changed.
              "actions": [
                { 
                  "setVariable": {
                    "variableName": "desiredTemperature",
                    "value": "$input.seedTemperatureInput.desiredTemperature"
                  }
                }
              ]
            },
            {
              "eventName": "calculateAverage",
              "condition": "$input.temperatureInput.sensorData.temperature < $variable.anomalousHigh && $input.temperatureInput.sensorData.temperature > $variable.anomalousLow",
              // If a valid temperature reading arrives, we use it to update the average temperature.
              //   For simplicity, we assume our sensors will be sending updates at about the same rate,
              //   so we can calculate an approximate average by giving equal weight to each reading we receive.
              "actions": [
                {
                  "setVariable": {
                    "variableName": "averageTemperature",
                    "value": "((($variable.averageTemperature * ($variable.sensorCount - 1)) + $input.temperatureInput.sensorData.temperature) / $variable.sensorCount)"
                  }
                }
              ]
            }
          ],
          "transitionEvents": [
            {
              "eventName": "anomalousInputArrived",
              "condition": "$input.temperatureInput.sensorData.temperature >= $variable.anomalousHigh || $input.temperatureInput.sensorData.temperature <= $variable.anomalousLow",
              // When an anomalous reading arrives, send an MQTT message, but stay in the current state.
              "actions": [
                { 
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/anomaly"
                  }
                }
              ],
              "nextState": "idle"
            },

            {
              "eventName": "highTemperatureSpike",
              "condition": "$input.temperatureInput.sensorData.temperature > $variable.rangeHigh",
              // When even a single temperature reading arrives that is above the 'rangeHigh', take
              //   emergency action to begin cooling, and report a high temperature spike.
              "actions": [
                {
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/spike"
                  }
                },
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:coolOn"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Cooling/On"
                  }
                },
                {
                  "setVariable": {
                    // This is necessary because we want to set a timer to delay the shutoff
                    //   of a cooling/heating unit, but we only want to set the timer when we 
                    //   enter that new state initially.
                    "variableName": "enteringNewState",
                    "value": "true"
                  }
                }
              ],
              "nextState": "cooling"
            },

            {
              "eventName": "lowTemperatureSpike",
              "condition": "$input.temperatureInput.sensorData.temperature < $variable.rangeLow",
              // When even a single temperature reading arrives that is below the 'rangeLow', take
              //   emergency action to begin heating, and report a low-temperature spike.
              "actions": [
                {
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/spike"
                  }
                },
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:heatOn"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Heating/On"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "enteringNewState",
                    "value": "true"
                  }
                }
              ],
              "nextState": "heating"
            },

            {
              "eventName": "highTemperatureThreshold",
              "condition": "(((($variable.averageTemperature * ($variable.sensorCount - 1)) + $input.temperatureInput.sensorData.temperature) / $variable.sensorCount) > ($variable.desiredTemperature + $variable.allowedError))",
              // When the average temperature is above the desired temperature plus the allowed error factor,
              //   it is time to start cooling. Note that we calculate the average temperature here again
              //   because the value stored in the 'averageTemperature' variable is not yet available for use
              //   in our condition.
              "actions": [
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:coolOn"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Cooling/On"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "enteringNewState",
                    "value": "true"
                  }
                }
              ],
              "nextState": "cooling"
            },

            {
              "eventName": "lowTemperatureThreshold",
              "condition": "(((($variable.averageTemperature * ($variable.sensorCount - 1)) + $input.temperatureInput.sensorData.temperature) / $variable.sensorCount) < ($variable.desiredTemperature - $variable.allowedError))",
              // When the average temperature is below the desired temperature minus the allowed error factor,
              //   it is time to start heating. Note that we calculate the average temperature here again
              //   because the value stored in the 'averageTemperature' variable is not yet available for use
              //   in our condition.
              "actions": [
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:heatOn"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Heating/On"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "enteringNewState",
                    "value": "true"
                  }
                }
              ],
              "nextState": "heating"
            }
          ]
        }
      },


      {
        "stateName": "cooling",
        "onEnter": {
          "events": [
            {
              "eventName": "delay",
              "condition": "!$variable.noDelay && $variable.enteringNewState",
              // If the operational parameters specify that there should be a minimum time that the 
              //   heating and cooling units should be run before being shut off again, we set
              //   a timer to ensure the proper operation here.
              "actions": [
                {
                  "setTimer": {
                    "timerName": "coolingTimer",
                    "seconds": 180
                  }
                },
                {
                  "setVariable": {
                    // We use this 'goodToGo' variable to store the status of the timer expiration 
                    //   for use in conditions that also use input variable values. If 
                    //   'timeout()' is used in such mixed conditionals, its value is lost.
                    "variableName": "goodToGo",
                    "value": "false"
                  }
                }
              ]
            },
            {
              "eventName": "dontDelay",
              "condition": "$variable.noDelay == true",
              // If the heating/cooling unit shutoff delay is not used, no need to wait.
              "actions": [
                {
                  "setVariable": {
                    "variableName": "goodToGo",
                    "value": "true"
                  }
                }
              ]
            },
            {
              "eventName": "beenHere",
              "condition": "true",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "enteringNewState",
                    "value": "false"
                  }
                }
              ]
            }
          ]
        },

        "onInput": {
          "events": [
            // These are events that occur when an input is received (if the condition is
            //   satisfied), but don't cause a transition to another state.
            {
              "eventName": "whatWasInput",
              "condition": "true",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "sensorId",
                    "value": "$input.temperatureInput.sensorId"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "reportedTemperature",
                    "value": "$input.temperatureInput.sensorData.temperature"
                  }
                }
              ]
            },
            {
              "eventName": "changeDesired",
              "condition": "$input.seedTemperatureInput.desiredTemperature != $variable.desiredTemperature",
              "actions": [
                { 
                  "setVariable": {
                    "variableName": "desiredTemperature",
                    "value": "$input.seedTemperatureInput.desiredTemperature"
                  }
                }
              ]
            },
            {
              "eventName": "calculateAverage",
              "condition": "$input.temperatureInput.sensorData.temperature < $variable.anomalousHigh && $input.temperatureInput.sensorData.temperature > $variable.anomalousLow",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "averageTemperature",
                    "value": "((($variable.averageTemperature * ($variable.sensorCount - 1)) + $input.temperatureInput.sensorData.temperature) / $variable.sensorCount)"
                  }
                }
              ]
            },
            {
              "eventName": "areWeThereYet",
              "condition": "(timeout(\"coolingTimer\"))",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "goodToGo",
                    "value": "true"
                  }
                }
              ]
            }
          ],
          "transitionEvents": [
            // Note that some tests of temperature values (for example, the test for an anomalous value) 
            //   must be placed here in the 'transitionEvents' because they work together with the tests 
            //   in the other conditions to ensure that we implement the proper "if..elseif..else" logic. 
            //   But each transition event must have a destination state ('nextState'), and even if that 
            //   is actually the current state, the "onEnter" events for this state will be executed again.
            //   This is the reason for the 'enteringNewState' variable and related.
            {
              "eventName": "anomalousInputArrived",
              "condition": "$input.temperatureInput.sensorData.temperature >= $variable.anomalousHigh || $input.temperatureInput.sensorData.temperature <= $variable.anomalousLow",
              "actions": [
                { 
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/anomaly"
                  }
                }
              ],
              "nextState": "cooling"
            },

            {
              "eventName": "highTemperatureSpike",
              "condition": "$input.temperatureInput.sensorData.temperature > $variable.rangeHigh",
              "actions": [
                {
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/spike"
                  }
                }
              ],
              "nextState": "cooling"
            },

            {
              "eventName": "lowTemperatureSpike",
              "condition": "$input.temperatureInput.sensorData.temperature < $variable.rangeLow",
              "actions": [
                {
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/spike"
                  }
                },
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:coolOff"
                  }
                },
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:heatOn"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Cooling/Off"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Heating/On"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "enteringNewState",
                    "value": "true"
                  }
                }
              ],
              "nextState": "heating"
            },

            {
              "eventName": "desiredTemperature",
              "condition": "(((($variable.averageTemperature * ($variable.sensorCount - 1)) + $input.temperatureInput.sensorData.temperature) / $variable.sensorCount) <= ($variable.desiredTemperature - $variable.allowedError)) && $variable.goodToGo == true",
              "actions": [
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:coolOff"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Cooling/Off"
                  }
                }
              ],
              "nextState": "idle"
            }
          ]
        }
      },


      {
        "stateName": "heating",
        "onEnter": {
          "events": [
            {
              "eventName": "delay",
              "condition": "!$variable.noDelay && $variable.enteringNewState",
              "actions": [
                {
                  "setTimer": {
                    "timerName": "heatingTimer",
                    "seconds": 120
                  }
                },
                {
                  "setVariable": {
                    "variableName": "goodToGo",
                    "value": "false"
                  }
                }
              ]
            },
            {
              "eventName": "dontDelay",
              "condition": "$variable.noDelay == true",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "goodToGo",
                    "value": "true"
                  }
                }
              ]
            },
            {
              "eventName": "beenHere",
              "condition": "true",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "enteringNewState",
                    "value": "false"
                  }
                }
              ]
            }
          ]
        },

        "onInput": {
          "events": [
            {
              "eventName": "whatWasInput",
              "condition": "true",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "sensorId",
                    "value": "$input.temperatureInput.sensorId"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "reportedTemperature",
                    "value": "$input.temperatureInput.sensorData.temperature"
                  }
                }
              ]
            },
            {
              "eventName": "changeDesired",
              "condition": "$input.seedTemperatureInput.desiredTemperature != $variable.desiredTemperature",
              "actions": [
                { 
                  "setVariable": {
                    "variableName": "desiredTemperature",
                    "value": "$input.seedTemperatureInput.desiredTemperature"
                  }
                }
              ]
            },
            {
              "eventName": "calculateAverage",
              "condition": "$input.temperatureInput.sensorData.temperature < $variable.anomalousHigh && $input.temperatureInput.sensorData.temperature > $variable.anomalousLow",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "averageTemperature",
                    "value": "((($variable.averageTemperature * ($variable.sensorCount - 1)) + $input.temperatureInput.sensorData.temperature) / $variable.sensorCount)"
                  }
                }
              ]
            },
            {
              "eventName": "areWeThereYet",
              "condition": "(timeout(\"heatingTimer\"))",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "goodToGo",
                    "value": "true"
                  }
                }
              ]
            }
          ],
          "transitionEvents": [
            {
              "eventName": "anomalousInputArrived",
              "condition": "$input.temperatureInput.sensorData.temperature >= $variable.anomalousHigh || $input.temperatureInput.sensorData.temperature <= $variable.anomalousLow",
              "actions": [
                { 
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/anomaly"
                  }
                }
              ],
              "nextState": "heating"
            },

            {
              "eventName": "highTemperatureSpike",
              "condition": "$input.temperatureInput.sensorData.temperature > $variable.rangeHigh",
              "actions": [
                {
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/spike"
                  }
                },
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:heatOff"
                  }
                },
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:coolOn"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Heating/Off"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Cooling/On"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "enteringNewState",
                    "value": "true"
                  }
                }
              ],
              "nextState": "cooling"
            },

            {
              "eventName": "lowTemperatureSpike",
              "condition": "$input.temperatureInput.sensorData.temperature < $variable.rangeLow",
              "actions": [
                {
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/spike"
                  }
                }
              ],
              "nextState": "heating"
            },

            {
              "eventName": "desiredTemperature",
              "condition": "(((($variable.averageTemperature * ($variable.sensorCount - 1)) + $input.temperatureInput.sensorData.temperature) / $variable.sensorCount) >= ($variable.desiredTemperature + $variable.allowedError)) && $variable.goodToGo == true",
              "actions": [
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:heatOff"
                  }
                },
                {
                  "iotTopicPublish": {
                    "mqttTopic": "hvac/Heating/Off"
                  }
                }
              ],
              "nextState": "idle"
            }
          ]
        }
      } 

    ],

    "initialStateName": "start"
  },
  "key": "areaId",
  "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole" 
}
```

응답:

```
{
    "detectorModelConfiguration": {
        "status": "ACTIVATING", 
        "lastUpdateTime": 1557523491.168, 
        "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole", 
        "creationTime": 1557523491.168, 
        "detectorModelArn": "arn:aws:iotevents:us-west-2:123456789012:detectorModel/areaDetectorModel", 
        "key": "areaId", 
        "detectorModelName": "areaDetectorModel", 
        "detectorModelVersion": "1"
    }
}
```

# BatchUpdateDetector를 사용하여 AWS IoT Events 감지기 모델 업데이트
<a name="iotevents-commented-example-batch-update-detector"></a>

`BatchUpdateDetector` 작업을 사용하여 타이머 및 변수 값을 포함하여 감지기 인스턴스를 알려진 상태로 만들 수 있습니다. 다음 예제에서 `BatchUpdateDetector` 작업은 온도 모니터링 및 제어 중인 영역의 작동 파라미터를 재설정합니다. 이 작업을 통해 감지기 모델을 삭제, 재생성 또는 업데이트할 필요 없이 이를 수행할 수 있습니다.

CLI 명령:

```
aws iotevents-data batch-update-detector --cli-input-json file://areaDM.BUD.json
```

파일: `areaDM.BUD.json`

```
{
  "detectors": [
    {
      "messageId": "0001",
      "detectorModelName": "areaDetectorModel",
      "keyValue": "Area51",
      "state": {
        "stateName": "start",
        "variables": [
          {
            "name": "desiredTemperature",
            "value": "22"
          },
          {
            "name": "averageTemperature",
            "value": "22"
          },
          {
            "name": "allowedError",
            "value": "1.0"
          },
          {
            "name": "rangeHigh",
            "value": "30.0"
          },
          {
            "name": "rangeLow",
            "value": "15.0"
          },
          {
            "name": "anomalousHigh",
            "value": "60.0"
          },
          {
            "name": "anomalousLow",
            "value": "0.0"
          },
          {
            "name": "sensorCount",
            "value": "12"
          },
          {
            "name": "noDelay",
            "value": "true"
          },
          {
            "name": "goodToGo",
            "value": "true"
          },
          {
            "name": "sensorId",
            "value": "0"
          },
          {
            "name": "reportedTemperature",
            "value": "0.1"
          },
          {
            "name": "resetMe",
            // When 'resetMe' is true, our detector model knows that we have reentered the 'start' state
            //   to reset operational parameters, and will allow the next valid temperature sensor
            //   reading to cause the transition to the 'idle' state.
            "value": "true"
          }
        ],
        "timers": [
        ]
      }
    }
  ]
}
```

응답:

```
{
    "batchUpdateDetectorErrorEntries": []
}
```

# 의 입력에 BatchPutMessage 사용 AWS IoT Events
<a name="iotevents-commented-example-input-usage-examples"></a>

**Example 1**  
`BatchPutMessage` 작업을 사용하여 온도 제어 및 모니터링 중인 특정 영역에 대한 작동 파라미터를 설정하는 `"seedTemperatureInput"` 메시지를 보낼 수 있습니다. 새가 AWS IoT Events 있는에서 수신한 모든 메시지로 `"areaId"` 인해 새 감지기 인스턴스가 생성됩니다. 하지만 새 감지기 인스턴스는 새로운 구역에 대한 `"seedTemperatureInput"` 메시지가 수신될 때까지 `"idle"`로 상태를 변경하거나 온도 모니터링과 난방 또는 냉방 장치 제어를 시작하지 않습니다.  
CLI 명령:  

```
aws iotevents-data batch-put-message --cli-input-json file://seedExample.json --cli-binary-format raw-in-base64-out
```
파일: `seedExample.json`  

```
{
  "messages": [
    {
      "messageId": "00001",
      "inputName": "seedTemperatureInput",
      "payload": "{\"areaId\": \"Area51\", \"desiredTemperature\": 20.0, \"allowedError\": 0.7, \"rangeHigh\": 30.0, \"rangeLow\": 15.0, \"anomalousHigh\": 60.0, \"anomalousLow\": 0.0, \"sensorCount\": 10, \"noDelay\": false}"
    }
  ]
}
```
응답:  

```
{
    "BatchPutMessageErrorEntries": []
}
```

**Example**  
2  
`BatchPutMessage` 작업을 통해 `"temperatureInput"` 메시지를 전송하여 지정된 제어 및 모니터링 영역에 있는 센서의 온도 센서 데이터를 보고할 수 있습니다.  
CLI 명령:  

```
aws iotevents-data batch-put-message --cli-input-json file://temperatureExample.json --cli-binary-format raw-in-base64-out
```
파일: `temperatureExample.json`  

```
{
  "messages": [
    {
      "messageId": "00005",
      "inputName": "temperatureInput",
      "payload": "{\"sensorId\": \"05\", \"areaId\": \"Area51\", \"sensorData\": {\"temperature\": 23.12} }"
    }
  ]
}
```
응답:  

```
{
    "BatchPutMessageErrorEntries": []
}
```

**Example 3**  
`BatchPutMessage` 작업을 통해 `"seedTemperatureInput"` 메시지를 전송하여 주어진 구역에 대해 원하는 온도 값을 변경할 수 있습니다.  
CLI 명령:  

```
aws iotevents-data batch-put-message --cli-input-json file://seedSetDesiredTemp.json --cli-binary-format raw-in-base64-out
```
파일: `seedSetDesiredTemp.json`  

```
{
  "messages": [
    {
      "messageId": "00001",
      "inputName": "seedTemperatureInput",
      "payload": "{\"areaId\": \"Area51\", \"desiredTemperature\": 23.0}"
    }
  ]
}
```
응답:  

```
{
    "BatchPutMessageErrorEntries": []
}
```

# 에서 MQTT 메시지 수집 AWS IoT Events
<a name="iotevents-commented-example-ingest-mqtt"></a>

센서 컴퓨팅 리소스가 `"BatchPutMessage"` API를 사용할 수 없지만 경량 MQTT 클라이언트를 사용하여 AWS IoT Core 메시지 브로커로 데이터를 전송할 수 있는 경우 AWS IoT Core 주제 규칙을 생성하여 메시지 데이터를 AWS IoT Events 입력으로 리디렉션할 수 있습니다. 다음은 MQTT AWS IoT Events 주제의 `"areaId"` 및 `"sensorId"` 입력 필드와 메시지 페이로드 `"sensorData.temperature"` 필드의 `"temp"` 필드를 가져와이 데이터를 로 수집하는 주제 규칙의 정의입니다 AWS IoT Events `"temperatureInput"`.

CLI 명령:

```
aws iot create-topic-rule --cli-input-json file://temperatureTopicRule.json
```

파일: `seedSetDesiredTemp.json`

```
{
  "ruleName": "temperatureTopicRule",
  "topicRulePayload": {
    "sql": "SELECT topic(3) as areaId, topic(4) as sensorId, temp as sensorData.temperature FROM 'update/temperature/#'",
    "description": "Ingest temperature sensor messages into IoT Events",
    "actions": [
      {
        "iotEvents": {
          "inputName": "temperatureInput",
          "roleArn": "arn:aws:iam::123456789012:role/service-role/anotheRole" 
        }
      }
    ],
    "ruleDisabled": false,
    "awsIotSqlVersion": "2016-03-23"
  }
}
```

응답: [없음]

센서가 다음 페이로드와 함께 주제 `"update/temperature/Area51/03"`에 대한 메시지를 보내는 경우.

```
{ "temp": 24.5 }
```

이렇게 하면 다음 `"BatchPutMessage"` API 호출이 이루어진 AWS IoT Events 것처럼 데이터가에 수집됩니다.

```
aws iotevents-data batch-put-message --cli-input-json file://spoofExample.json --cli-binary-format raw-in-base64-out
```

파일: `spoofExample.json`

```
{
  "messages": [
    {
      "messageId": "54321",
      "inputName": "temperatureInput",
      "payload": "{\"sensorId\": \"03\", \"areaId\": \"Area51\", \"sensorData\": {\"temperature\": 24.5} }"
    }
  ]
}
```

# 에서 Amazon SNS 메시지 생성 AWS IoT Events
<a name="iotevents-commented-example-generated-sns"></a>

다음은 `"Area51"` 감지기 인스턴스에서 생성된 SNS 메시지의 예입니다.

AWS IoT Events 는 Amazon SNS와 통합하여 감지된 이벤트를 기반으로 알림을 생성하고 게시할 수 있습니다. 이 섹션에서는 AWS IoT Events 감지기 인스턴스, 특히 "Area51" 감지기가 Amazon SNS 메시지를 생성하는 방법을 보여줍니다. 이 예제에서는 AWS IoT Events 감지기 내의 다양한 상태 및 이벤트에 의해 트리거되는 Amazon SNS 알림의 구조와 콘텐츠를 보여 주며, 실시간 알림 및 통신을 위해 Amazon SNS AWS IoT Events 와를 결합하는 기능을 보여줍니다.

```
Heating system off command> {
  "eventTime":1557520274729,
  "payload":{
    "actionExecutionId":"f3159081-bac3-38a4-96f7-74af0940d0a4",
    "detector":{
      "detectorModelName":"areaDetectorModel","keyValue":"Area51","detectorModelVersion":"1"},"eventTriggerDetails":{"inputName":"seedTemperatureInput","messageId":"00001","triggerType":"Message"},"state":{"stateName":"start","variables":{"sensorCount":10,"rangeHigh":30.0,"resetMe":false,"enteringNewState":true,"averageTemperature":20.0,"rangeLow":15.0,"noDelay":false,"allowedError":0.7,"desiredTemperature":20.0,"anomalousHigh":60.0,"reportedTemperature":0.1,"anomalousLow":0.0,"sensorId":0},"timers":{}}},"eventName":"resetHeatCool"}
```

```
Cooling system off command> {"eventTime":1557520274729,"payload":{"actionExecutionId":"98f6a1b5-8f40-3cdb-9256-93afd4d66192","detector":{"detectorModelName":"areaDetectorModel","keyValue":"Area51","detectorModelVersion":"1"},"eventTriggerDetails":{"inputName":"seedTemperatureInput","messageId":"00001","triggerType":"Message"},"state":{"stateName":"start","variables":{"sensorCount":10,"rangeHigh":30.0,"resetMe":false,"enteringNewState":true,"averageTemperature":20.0,"rangeLow":15.0,"noDelay":false,"allowedError":0.7,"desiredTemperature":20.0,"anomalousHigh":60.0,"reportedTemperature":0.1,"anomalousLow":0.0,"sensorId":0},"timers":{}}},"eventName":"resetHeatCool"}
```

# 에서 DescribeDetector API 구성 AWS IoT Events
<a name="iotevents-commented-example-describe-detector"></a>

의 `DescribeDetector` API AWS IoT Events 를 사용하면 특정 감지기 인스턴스에 대한 세부 정보를 검색할 수 있습니다. 이 작업은 감지기의 현재 상태, 변수 값 및 활성 타이머에 대한 인사이트를 제공합니다. 이 API를 사용하면 AWS IoT Events 탐지기의 실시간 상태를 모니터링하여 IoT 이벤트 처리 워크플로의 디버깅, 분석 및 관리를 용이하게 할 수 있습니다.

CLI 명령:

```
aws iotevents-data describe-detector --detector-model-name areaDetectorModel --key-value Area51
```

응답:

```
{
    "detector": {
        "lastUpdateTime": 1557521572.216, 
        "creationTime": 1557520274.405, 
        "state": {
            "variables": [
                {
                    "name": "resetMe", 
                    "value": "false"
                }, 
                {
                    "name": "rangeLow", 
                    "value": "15.0"
                }, 
                {
                    "name": "noDelay", 
                    "value": "false"
                }, 
                {
                    "name": "desiredTemperature", 
                    "value": "20.0"
                }, 
                {
                    "name": "anomalousLow", 
                    "value": "0.0"
                }, 
                {
                    "name": "sensorId", 
                    "value": "\"01\""
                }, 
                {
                    "name": "sensorCount", 
                    "value": "10"
                }, 
                {
                    "name": "rangeHigh", 
                    "value": "30.0"
                }, 
                {
                    "name": "enteringNewState", 
                    "value": "false"
                }, 
                {
                    "name": "averageTemperature", 
                    "value": "19.572"
                }, 
                {
                    "name": "allowedError", 
                    "value": "0.7"
                }, 
                {
                    "name": "anomalousHigh", 
                    "value": "60.0"
                }, 
                {
                    "name": "reportedTemperature", 
                    "value": "15.72"
                }, 
                {
                    "name": "goodToGo", 
                    "value": "false"
                }
            ], 
            "stateName": "idle", 
            "timers": [
                {
                    "timestamp": 1557520454.0, 
                    "name": "idleTimer"
                }
            ]
        }, 
        "keyValue": "Area51", 
        "detectorModelName": "areaDetectorModel", 
        "detectorModelVersion": "1"
    }
}
```

# 에 규칙 AWS IoT Core 엔진 사용 AWS IoT Events
<a name="iotevents-commented-examples-iot-rules-examples"></a>

다음 규칙은 AWS IoT Core MQTT 메시지를 섀도우 업데이트 요청 메시지로 다시 게시합니다. 감지기 모델에 의해 제어되는 각 영역의 난방 장치 및 냉각 장치에 AWS IoT Core 사물이 정의되어 있다고 가정합니다. 이 예제에서는 이름이 `"Area51HeatingUnit"` 및 `"Area51CoolingUnit"`인 항목을 정의했습니다.

CLI 명령:

```
aws iot create-topic-rule --cli-input-json file://ADMShadowCoolOffRule.json
```

파일: `ADMShadowCoolOffRule.json`

```
{
  "ruleName": "ADMShadowCoolOff",
  "topicRulePayload": {
    "sql": "SELECT topic(3) as state.desired.command FROM 'hvac/Cooling/Off'",
    "description": "areaDetectorModel mqtt topic publish to cooling unit shadow request",
    "ruleDisabled": false,
    "awsIotSqlVersion": "2016-03-23",
    "actions": [
      {
        "republish": {
          "topic": "$$aws/things/${payload.detector.keyValue}CoolingUnit/shadow/update",
          "roleArn": "arn:aws:iam::123456789012:role/service-role/ADMShadowRole" 
        }
      }
    ]
  }
}
```

응답: [비어 있음]

CLI 명령:

```
aws iot create-topic-rule --cli-input-json file://ADMShadowCoolOnRule.json
```

파일: `ADMShadowCoolOnRule.json`

```
{
  "ruleName": "ADMShadowCoolOn",
  "topicRulePayload": {
    "sql": "SELECT topic(3) as state.desired.command FROM 'hvac/Cooling/On'",
    "description": "areaDetectorModel mqtt topic publish to cooling unit shadow request",
    "ruleDisabled": false,
    "awsIotSqlVersion": "2016-03-23",
    "actions": [
      {
        "republish": {
          "topic": "$$aws/things/${payload.detector.keyValue}CoolingUnit/shadow/update",
          "roleArn": "arn:aws:iam::123456789012:role/service-role/ADMShadowRole" 
        }
      }
    ]
  }
}
```

응답: [비어 있음]

CLI 명령:

```
aws iot create-topic-rule --cli-input-json file://ADMShadowHeatOffRule.json
```

파일: `ADMShadowHeatOffRule.json`

```
{
  "ruleName": "ADMShadowHeatOff",
  "topicRulePayload": {
    "sql": "SELECT topic(3) as state.desired.command FROM 'hvac/Heating/Off'",
    "description": "areaDetectorModel mqtt topic publish to heating unit shadow request",
    "ruleDisabled": false,
    "awsIotSqlVersion": "2016-03-23",
    "actions": [
      {
        "republish": {
          "topic": "$$aws/things/${payload.detector.keyValue}HeatingUnit/shadow/update",
          "roleArn": "arn:aws:iam::123456789012:role/service-role/ADMShadowRole" 
        }
      }
    ]
  }
}
```

응답: [비어 있음]

CLI 명령:

```
aws iot create-topic-rule --cli-input-json file://ADMShadowHeatOnRule.json
```

파일: `ADMShadowHeatOnRule.json`

```
{
  "ruleName": "ADMShadowHeatOn",
  "topicRulePayload": {
    "sql": "SELECT topic(3) as state.desired.command FROM 'hvac/Heating/On'",
    "description": "areaDetectorModel mqtt topic publish to heating unit shadow request",
    "ruleDisabled": false,
    "awsIotSqlVersion": "2016-03-23",
    "actions": [
      {
        "republish": {
          "topic": "$$aws/things/${payload.detector.keyValue}HeatingUnit/shadow/update",
          "roleArn": "arn:aws:iam::123456789012:role/service-role/ADMShadowRole" 
        }
      }
    ]
  }
}
```

응답: [비어 있음]