

Aviso de fim do suporte: em 20 de maio de 2026, AWS encerrará o suporte para AWS IoT Events. Depois de 20 de maio de 2026, você não poderá mais acessar o AWS IoT Events console ou os AWS IoT Events recursos. Para obter mais informações, consulte [AWS IoT Events Fim do suporte](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-end-of-support.html).

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# AWS IoT Events exemplos de modelos de detectores
<a name="iotevents-examples"></a>

 Esta página fornece uma lista de exemplos de casos de uso que demonstram como configurar vários AWS IoT Events recursos. Os exemplos variam de detecções básicas, como limites de temperatura, até cenários mais avançados de detecção de anomalias e aprendizado de máquina. Cada exemplo inclui procedimentos e trechos de código para ajudá-lo a configurar AWS IoT Events detecções, ações e integrações. Esses exemplos mostram a flexibilidade do AWS IoT Events serviço e como ele pode ser personalizado para diversos aplicativos e casos de uso de IoT. Consulte esta página ao explorar os AWS IoT Events recursos ou se precisar de orientação para implementar um fluxo de trabalho específico de detecção ou automação.

**Topics**
+ [Exemplo: Usando o controle de temperatura HVAC com AWS IoT Events](iotevents-examples-hvac.md)
+ [Exemplo: Um guindaste detectando condições usando AWS IoT Events](iotevents-examples-cranes.md)
+ [Envie comandos em resposta às condições detectadas no AWS IoT Events](iotevents-examples-cranes-commands.md)
+ [Um modelo AWS IoT Events de detector para monitoramento de guindastes](iotevents-examples-cranes-detector-models.md)
+ [AWS IoT Events entradas para monitoramento de guindastes](iotevents-examples-cranes-inputs.md)
+ [Envie mensagens operacionais e de alarme com AWS IoT Events](iotevents-examples-cranes-messages.md)
+ [Exemplo: detecção de AWS IoT Events eventos com sensores e aplicativos](iotevents-examples-edwsaa.md)
+ [Exemplo: dispositivo HeartBeat para monitorar as conexões do dispositivo com AWS IoT Events](iotevents-examples-dhb.md)
+ [Exemplo: Um alarme ISA em AWS IoT Events](iotevents-examples-bisaa.md)
+ [Exemplo: Crie um alarme simples com AWS IoT Events](iotevents-examples-bsa.md)

# Exemplo: Usando o controle de temperatura HVAC com AWS IoT Events
<a name="iotevents-examples-hvac"></a>

## História de fundo
<a name="iotevents-examples-hvac-background"></a>

Este exemplo implementa um modelo de controle de temperatura (um termostato) com os seguintes atributos:
+ Um modelo de detector definido por você que pode monitorar e controlar várias áreas. (Uma instância de detector será criada para cada área).
+ Cada instância do detector recebe dados de temperatura de vários sensores colocados em cada área de controle.
+ Você pode alterar a temperatura desejada (o ponto de ajuste) para cada área a qualquer momento.
+ Você pode definir os parâmetros operacionais para cada área e alterá-los a qualquer momento.
+ Você pode adicionar ou excluir sensores de uma área a qualquer momento.
+ Você pode ativar um tempo mínimo de funcionamento das unidades de aquecimento e resfriamento para protegê-las contra danos.
+ Os detectores rejeitarão e reportarão leituras anômalas do sensor.
+ Você pode definir pontos de ajuste de temperatura de emergência. Se algum sensor relatar uma temperatura acima ou abaixo dos pontos de ajuste que você definiu, as unidades de aquecimento ou resfriamento serão acionadas imediatamente e o detector relatará esse pico de temperatura.

Este exemplo demonstra os seguintes recursos funcionais:
+ Crie modelos de detectores de eventos.
+ Cria entradas.
+ Ingira entradas em um modelo de detector.
+ Avalie as condições do gatilho.
+ Consulte as variáveis de estado em condições e defina os valores das variáveis dependendo das condições.
+ Consulte os temporizadores em condições e defina-os de acordo com as condições.
+ Execute ações que enviem mensagens do Amazon SNS e MQTT.

# Definições de entrada para um sistema HVAC em AWS IoT Events
<a name="iotevents-examples-hvac-inputs"></a>

Uma `seedTemperatureInput` é usada para criar uma instância de detector para uma área e definir seus parâmetros operacionais.

Configurar entradas para sistemas HVAC em AWS IoT Events é importante para um controle climático eficaz. Este exemplo mostra como configurar entradas que capturam parâmetros como temperatura, umidade, ocupação e dados de consumo de energia. Aprenda a definir atributos de entrada, configurar fontes de dados e configurar regras de pré-processamento para ajudar seus modelos de detectores a receber informações precisas e oportunas para gerenciamento e eficiência ideais.

Comando CLI usado:

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

Arquivo: `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" }
    ]
  }
}
```

Resposta:

```
{
    "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."
    }
}
```

Uma `temperatureInput` deve ser enviada por cada sensor em cada área, conforme necessário.

Comando CLI usado:

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

Arquivo: `temperatureInput.json`

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

Resposta:

```
{
    "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."
    }
}
```

# Definição do modelo de detector para um sistema HVAC usando AWS IoT Events
<a name="iotevents-examples-hvac-detector-model"></a>

O `areaDetectorModel` define como cada instância do detector funciona. Cada instância `state machine` ingerirá as leituras do sensor de temperatura, depois mudará de estado e enviará mensagens de controle, dependendo dessas leituras.

Comando CLI usado:

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

Arquivo: `areaDetectorModel.json`

```
{
  "detectorModelName": "areaDetectorModel",
  "detectorModelDefinition": {
    "states": [
      {
        "stateName": "start",
        "onEnter": {
          "events": [
            {
              "eventName": "prepare",
              "condition": "true",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "sensorId",
                    "value": "0"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "reportedTemperature",
                    "value": "0.1"
                  }
                },
                {
                  "setVariable": {
                    "variableName": "resetMe",
                    "value": "false"
                  }
                }
              ]
            }
          ]
        },
        "onInput": {
          "transitionEvents": [
            {
              "eventName": "initialize",
              "condition": "$input.seedTemperatureInput.sensorCount > 0",
              "actions": [
                { 
                  "setVariable": {
                    "variableName": "rangeHigh",
                    "value": "$input.seedTemperatureInput.rangeHigh"
                  }
                },
                { 
                  "setVariable": {
                    "variableName": "rangeLow",
                    "value": "$input.seedTemperatureInput.rangeLow"
                  }
                },
                { 
                  "setVariable": {
                    "variableName": "desiredTemperature",
                    "value": "$input.seedTemperatureInput.desiredTemperature"
                  }
                },
                { 
                  "setVariable": {
                    "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)",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "averageTemperature",
                    "value": "((($variable.averageTemperature * ($variable.sensorCount - 1)) + $input.temperatureInput.sensorData.temperature) / $variable.sensorCount)"
                  }
                }
              ],
              "nextState": "idle"
            }
          ]
        },
        "onExit": {
          "events": [
            {
              "eventName": "resetHeatCool",
              "condition": "true",
              "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",
              "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)"
                  }
                }
              ]
            }
          ],
          "transitionEvents": [
            {
              "eventName": "anomalousInputArrived",
              "condition": "$input.temperatureInput.sensorData.temperature >= $variable.anomalousHigh || $input.temperatureInput.sensorData.temperature <= $variable.anomalousLow",
              "actions": [
                { 
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/anomaly"
                  }
                }
              ],
              "nextState": "idle"
            },

            {
              "eventName": "highTemperatureSpike",
              "condition": "$input.temperatureInput.sensorData.temperature > $variable.rangeHigh",
              "actions": [
                {
                  "iotTopicPublish": {
                    "mqttTopic": "temperatureSensor/spike"
                  }
                },
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:coolOn"
                  }
                },
                {
                  "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"
                  }
                },
                {
                  "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))",
              "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))",
              "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",
              "actions": [
                {
                  "setTimer": {
                    "timerName": "coolingTimer",
                    "seconds": 180
                  }
                },
                {
                  "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(\"coolingTimer\"))",
              "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": "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" 
}
```

Resposta:

```
{
    "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"
    }
}
```

# BatchPutMessage exemplos de um sistema HVAC em AWS IoT Events
<a name="iotevents-examples-hvac-input-usage-examples"></a>

Neste exemplo, `BatchPutMessage` é usado para criar uma instância de detector para uma área e definir os parâmetros operacionais iniciais.

Comando CLI usado:

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

Arquivo: `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}"
    }
  ]
}
```

Resposta:

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

Neste exemplo, `BatchPutMessage` é usado para relatar as leituras do sensor de temperatura para um único sensor em uma área.

Comando CLI usado:

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

Arquivo: `temperatureExample.json`

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

Resposta:

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

Neste exemplo, `BatchPutMessage` é usado para alterar a temperatura desejada para uma área.

Comando CLI usado:

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

Arquivo: `seedSetDesiredTemp.json`

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

Resposta:

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

 

Exemplos de mensagens do Amazon SNS geradas pela instância do `Area51` detector:

```
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"
}
```

Neste exemplo, usamos a `DescribeDetector` API para obter informações sobre o estado atual de uma instância do detector.

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

Resposta:

```
{
    "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"
    }
}
```

# BatchUpdateDetector exemplo de um sistema HVAC em AWS IoT Events
<a name="iotevents-examples-hvac-batch-update-detector"></a>

Neste exemplo, `BatchUpdateDetector` é usado para alterar os parâmetros operacionais de uma instância de detector em funcionamento.

O gerenciamento eficiente do sistema HVAC geralmente requer atualizações em lote para vários detectores. Esta seção demonstra como usar o recurso AWS IoT Events de atualização em lote para detectores. Aprenda a modificar simultaneamente vários parâmetros de controle e atualizar os valores limite para que você possa ajustar as ações de resposta em uma frota de dispositivos, melhorando sua capacidade de gerenciar sistemas de grande escala com eficiência.

Comando CLI usado:

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

Arquivo: `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",
            "value": "true"
          }
        ],
        "timers": [
        ]
      }
    }
  ]
}
```

Resposta:

```
{
    An error occurred (InvalidRequestException) when calling the BatchUpdateDetector operation: Number of variables in the detector exceeds the limit 10
}
```

# O mecanismo de AWS IoT Core regras e AWS IoT Events
<a name="iotevents-examples-hvac-iot-rules-examples"></a>

As regras a seguir republicam mensagens AWS IoT Events MQTT como mensagens de solicitação de atualização paralela. Assumimos que AWS IoT Core as coisas são definidas para uma unidade de aquecimento e uma unidade de resfriamento para cada área controlada pelo modelo do detector.

Neste exemplo, definimos coisas chamadas `Area51HeatingUnit` e `Area51CoolingUnit`.

Comando CLI usado:

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

Arquivo: `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" 
        }
      }
    ]
  }
}
```

Resposta: [vazio]

Comando CLI usado:

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

Arquivo: `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" 
        }
      }
    ]
  }
}
```

Resposta: [vazio]

Comando CLI usado:

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

Arquivo: `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" 
        }
      }
    ]
  }
}
```

Resposta: [vazio]

Comando CLI usado:

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

Arquivo: `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" 
        }
      }
    ]
  }
}
```

Resposta: [vazio]

# Exemplo: Um guindaste detectando condições usando AWS IoT Events
<a name="iotevents-examples-cranes"></a>

Um operador de muitos guindastes deseja detectar quando as máquinas precisam de manutenção ou substituição e acionar as notificações apropriadas. Cada guindaste tem um motor. Um motor emite mensagens (entradas) com informações sobre pressão e temperatura. O operador quer dois níveis de detectores de eventos:
+ Um detector de eventos em nível de guindaste
+ Um detector de eventos em nível de motor

Usando mensagens dos motores (que contêm metadados com o `craneId` e o `motorid`), o operador pode executar os dois níveis de detectores de eventos usando o roteamento apropriado. Quando as condições do evento forem atendidas, as notificações devem ser enviadas para os tópicos apropriados do Amazon SNS. O operador pode configurar os modelos do detector para que notificações duplicadas não sejam geradas.

Este exemplo demonstra os seguintes recursos funcionais:
+ Criar, ler, atualizar, excluir (CRUD) de entradas.
+ Criar, ler, atualizar, excluir (CRUD) de modelos de detector de eventos e versões diferentes de detectores de eventos.
+ Roteamento de uma entrada para vários detectores de eventos.
+ Ingestão de entradas em um modelo de detector.
+ Avaliação das condições de gatilho e eventos do ciclo de vida.
+ Capacidade de se referir às variáveis de estado em condições e definir seus valores dependendo das condições.
+ Orquestração de runtime com definição, estado, avaliador de gatilho e executor de ações.
+ Execução de ações em `ActionsExecutor` com um alvo do SNS.

# Envie comandos em resposta às condições detectadas no AWS IoT Events
<a name="iotevents-examples-cranes-commands"></a>

Esta página fornece um exemplo de uso de AWS IoT Events comandos para configurar entradas, criar modelos de detectores e enviar dados simulados de sensores. Os exemplos demonstram como aproveitar o monitoramento AWS IoT Events de equipamentos industriais, como motores e guindastes.

```
#Create Pressure Input
aws iotevents create-input  --cli-input-json file://pressureInput.json
aws iotevents describe-input --input-name PressureInput 
aws iotevents update-input  --cli-input-json file://pressureInput.json
aws iotevents list-inputs
aws iotevents delete-input --input-name PressureInput

#Create Temperature Input
aws iotevents create-input  --cli-input-json file://temperatureInput.json
aws iotevents describe-input --input-name TemperatureInput 
aws iotevents update-input  --cli-input-json file://temperatureInput.json
aws iotevents list-inputs
aws iotevents delete-input --input-name TemperatureInput

#Create Motor Event Detector using pressure and temperature input
aws iotevents create-detector-model  --cli-input-json file://motorDetectorModel.json
aws iotevents describe-detector-model --detector-model-name motorDetectorModel 
aws iotevents update-detector-model  --cli-input-json file://updateMotorDetectorModel.json
aws iotevents list-detector-models
aws iotevents list-detector-model-versions --detector-model-name motorDetectorModel 
aws iotevents delete-detector-model --detector-model-name motorDetectorModel

#Create Crane Event Detector using temperature input
aws iotevents create-detector-model  --cli-input-json file://craneDetectorModel.json
aws iotevents describe-detector-model --detector-model-name craneDetectorModel 
aws iotevents update-detector-model  --cli-input-json file://updateCraneDetectorModel.json
aws iotevents list-detector-models
aws iotevents list-detector-model-versions --detector-model-name craneDetectorModel 
aws iotevents delete-detector-model --detector-model-name craneDetectorModel

#Replace craneIds
sed -i '' "s/100008/100009/g" messages/* 

#Replace motorIds
sed -i '' "s/200008/200009/g" messages/* 

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

#Send HighTemperature message
aws iotevents-data batch-put-message --cli-input-json file://messages/highTemperatureMessage.json --cli-binary-format raw-in-base64-out

#Send LowPressure message
aws iotevents-data batch-put-message --cli-input-json file://messages/lowPressureMessage.json --cli-binary-format raw-in-base64-out

#Send LowTemperature message
aws iotevents-data batch-put-message --cli-input-json file://messages/lowTemperatureMessage.json --cli-binary-format raw-in-base64-out
```

# Um modelo AWS IoT Events de detector para monitoramento de guindastes
<a name="iotevents-examples-cranes-detector-models"></a>

Monitore suas frotas de equipamentos ou dispositivos em busca de falhas ou mudanças na operação e acione ações quando esses eventos ocorrerem. Você define modelos de detectores em JSON que especificam estados, regras e ações. Isso permite monitorar entradas como temperatura e pressão, rastrear violações de limites e enviar alertas. Os exemplos mostram modelos de detectores para guindaste e motor, detectando problemas de superaquecimento e notificando o Amazon SNS quando um limite é excedido. Você pode atualizar os modelos para refinar o comportamento sem interromper o monitoramento.

Arquivo: `craneDetectorModel.json`

```
{
    "detectorModelName": "craneDetectorModel",
    "detectorModelDefinition": {
        "states": [
            {
                "stateName": "Running",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "init",
                            "condition": "true",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "craneThresholdBreached",
                                        "value": "0"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "onInput": {
                    "events": [
                        {
                            "eventName": "Overheated",
                            "condition": "$input.TemperatureInput.temperature > 35",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "craneThresholdBreached",
                                        "value": "$variable.craneThresholdBreached + 1"
                                    }
                                }
                            ]
                        },
                        {
                            "eventName": "Crane Threshold Breached",
                            "condition": "$variable.craneThresholdBreached > 5",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-east-1:123456789012:CraneSNSTopic"
                                    }
                                }
                            ]
                        },
                        {
                            "eventName": "Underheated",
                            "condition": "$input.TemperatureInput.temperature < 25",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "craneThresholdBreached",
                                        "value": "0"
                                    }
                                }
                            ]
                        }
                    ]
                }
            }
        ],
        "initialStateName": "Running"
    },
    "key": "craneid",
    "roleArn": "arn:aws:iam::123456789012:role/columboSNSRole"
}
```

Para atualizar um modelo de detector existente. Arquivo: `updateCraneDetectorModel.json`

```
{
    "detectorModelName": "craneDetectorModel",
    "detectorModelDefinition": {
        "states": [
            {
                "stateName": "Running",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "init",
                            "condition": "true",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "craneThresholdBreached",
                                        "value": "0"
                                    }
                                },
                                {
                                    "setVariable": {
                                        "variableName": "alarmRaised",
                                        "value": "'false'"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "onInput": {
                    "events": [
                        {
                            "eventName": "Overheated",
                            "condition": "$input.TemperatureInput.temperature > 30",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "craneThresholdBreached",
                                        "value": "$variable.craneThresholdBreached + 1"
                                    }
                                }
                            ]
                        },
                        {
                            "eventName": "Crane Threshold Breached",
                            "condition": "$variable.craneThresholdBreached > 5 && $variable.alarmRaised == 'false'",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-east-1:123456789012:CraneSNSTopic"
                                    }
                                },
                                {
                                    "setVariable": {
                                        "variableName": "alarmRaised",
                                        "value": "'true'"
                                    }
                                }
                            ]
                        },
                        {
                            "eventName": "Underheated",
                            "condition": "$input.TemperatureInput.temperature < 10",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "craneThresholdBreached",
                                        "value": "0"
                                    }
                                }
                            ]
                        }
                    ]
                }
            }
        ],
        "initialStateName": "Running"
    },
    "roleArn": "arn:aws:iam::123456789012:role/columboSNSRole"
}
```

Arquivo: `motorDetectorModel.json`

```
{
    "detectorModelName": "motorDetectorModel",
    "detectorModelDefinition": {
        "states": [
            {
                "stateName": "Running",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "init",
                            "condition": "true",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "motorThresholdBreached",
                                        "value": "0"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "onInput": {
                    "events": [
                        {
                            "eventName": "Overheated And Overpressurized",
                            "condition": "$input.PressureInput.pressure > 70 && $input.TemperatureInput.temperature > 30",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "motorThresholdBreached",
                                        "value": "$variable.motorThresholdBreached + 1"
                                    }
                                }
                            ]
                        },
                        {
                            "eventName": "Motor Threshold Breached",
                            "condition": "$variable.motorThresholdBreached > 5",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-east-1:123456789012:MotorSNSTopic"
                                    }
                                }
                            ]
                        }
                    ]
                }
            }
        ],
        "initialStateName": "Running"
    },
    "key": "motorId",
    "roleArn": "arn:aws:iam::123456789012:role/columboSNSRole"
}
```

Para atualizar um modelo de detector existente. Arquivo: `updateMotorDetectorModel.json`

```
{
    "detectorModelName": "motorDetectorModel",
    "detectorModelDefinition": {
        "states": [
            {
                "stateName": "Running",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "init",
                            "condition": "true",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "motorThresholdBreached",
                                        "value": "0"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "onInput": {
                    "events": [
                        {
                            "eventName": "Overheated And Overpressurized",
                            "condition": "$input.PressureInput.pressure > 70 && $input.TemperatureInput.temperature > 30",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "motorThresholdBreached",
                                        "value": "$variable.motorThresholdBreached + 1"
                                    }
                                }
                            ]
                        },
                        {
                            "eventName": "Motor Threshold Breached",
                            "condition": "$variable.motorThresholdBreached > 5",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-east-1:123456789012:MotorSNSTopic"
                                    }
                                }
                            ]
                        }
                    ]
                }
            }
        ],
        "initialStateName": "Running"
    },
    "roleArn": "arn:aws:iam::123456789012:role/columboSNSRole"
}
```

# AWS IoT Events entradas para monitoramento de guindastes
<a name="iotevents-examples-cranes-inputs"></a>

Neste exemplo, demonstramos como configurar entradas para um sistema de monitoramento de guindaste usando. AWS IoT Events Ele captura entradas de pressão e temperatura para ilustrar como estruturar entradas para monitoramento complexo de equipamentos industriais.

Arquivo: `pressureInput.json`

```
{
    "inputName": "PressureInput",
    "inputDescription": "this is a pressure input description",
    "inputDefinition": {
        "attributes": [
          {"jsonPath": "pressure"}
        ]
    }
}
```

Arquivo: `temperatureInput.json`

```
{
    "inputName": "TemperatureInput",
    "inputDescription": "this is temperature input description",
    "inputDefinition": {
        "attributes": [
            {"jsonPath": "temperature"}
        ]
    }
}
```

# Envie mensagens operacionais e de alarme com AWS IoT Events
<a name="iotevents-examples-cranes-messages"></a>

O tratamento eficaz de mensagens é importante nos sistemas de monitoramento de guindastes. Esta seção mostra como configurar para processar e responder AWS IoT Events a vários tipos de mensagens dos sensores do guindaste. Configurar alarmes com base em uma mensagem específica pode ajudá-lo a analisar, filtrar e rotear atualizações de status para acionar as ações apropriadas.

Arquivo: `highPressureMessage.json`

```
{
   "messages": [
        {
           "messageId": "1",
           "inputName": "PressureInput",
           "payload": "{\"craneid\": \"100009\", \"pressure\": 80, \"motorid\": \"200009\"}"

        }
    ]
}
```

Arquivo: `highTemperatureMessage.json` 

```
{
   "messages": [
        {
           "messageId": "2",
           "inputName": "TemperatureInput",
           "payload": "{\"craneid\": \"100009\", \"temperature\": 40, \"motorid\": \"200009\"}"
        }
    ]
}
```

Arquivo: `lowPressureMessage.json` 

```
{
   "messages": [
        {
           "messageId": "1",
           "inputName": "PressureInput",
           "payload": "{\"craneid\": \"100009\", \"pressure\": 20, \"motorid\": \"200009\"}"
        }
    ]
}
```

Arquivo: `lowTemperatureMessage.json` 

```
{
   "messages": [
        {
           "messageId": "2",
           "inputName": "TemperatureInput",
           "payload": "{\"craneid\": \"100009\", \"temperature\": 20, \"motorid\": \"200009\"}"
        }
    ]
}
```

# Exemplo: detecção de AWS IoT Events eventos com sensores e aplicativos
<a name="iotevents-examples-edwsaa"></a>

Esse modelo de detector é um dos modelos disponíveis no AWS IoT Events console. Está incluído aqui para a sua conveniência.

Este exemplo demonstra a detecção de eventos AWS IoT Events do aplicativo usando dados do sensor. Ele mostra como você pode criar um modelo de detector que monitora eventos específicos para que você possa acionar as ações apropriadas. Você pode criar várias entradas de sensor, definir condições complexas de eventos e configurar mecanismos de resposta graduados.

```
{
    "detectorModelName": "EventDetectionSensorsAndApplications", 
    "detectorModelDefinition": {
        "states": [
            {
                "onInput": {
                    "transitionEvents": [], 
                    "events": []
                }, 
                "stateName": "Device_exception", 
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Send_mqtt", 
                            "actions": [
                                {
                                    "iotTopicPublish": {
                                        "mqttTopic": "Device_stolen"
                                    }
                                }
                            ], 
                            "condition": "true"
                        }
                    ]
                }, 
                "onExit": {
                    "events": []
                }
            }, 
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "To_in_use", 
                            "actions": [], 
                            "condition": "$variable.position != $input.AWS_IoTEvents_Blueprints_Tracking_DeviceInput.gps_position", 
                            "nextState": "Device_in_use"
                        }
                    ], 
                    "events": []
                }, 
                "stateName": "Device_idle", 
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Set_position", 
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "position", 
                                        "value": "$input.AWS_IoTEvents_Blueprints_Tracking_DeviceInput.gps_position"
                                    }
                                }
                            ], 
                            "condition": "true"
                        }
                    ]
                }, 
                "onExit": {
                    "events": []
                }
            }, 
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "To_exception", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_Tracking_UserInput.device_id != $input.AWS_IoTEvents_Blueprints_Tracking_DeviceInput.device_id", 
                            "nextState": "Device_exception"
                        }
                    ], 
                    "events": []
                }, 
                "stateName": "Device_in_use", 
                "onEnter": {
                    "events": []
                }, 
                "onExit": {
                    "events": []
                }
            }
        ], 
        "initialStateName": "Device_idle"
    }
}
```

# Exemplo: dispositivo HeartBeat para monitorar as conexões do dispositivo com AWS IoT Events
<a name="iotevents-examples-dhb"></a>

Esse modelo de detector é um dos modelos disponíveis no AWS IoT Events console. Está incluído aqui para a sua conveniência.

O exemplo de batimento cardíaco defeituoso (DHB) ilustra como AWS IoT Events pode ser usado no monitoramento de serviços de saúde. Este exemplo mostra como você pode criar um modelo de detector que analisa dados de frequência cardíaca, detecta padrões irregulares e aciona respostas apropriadas. Aprenda a configurar entradas, definir limites e configurar alertas para possíveis problemas cardíacos, mostrando a versatilidade AWS IoT Events da empresa em aplicações relacionadas à saúde.

```
{
    "detectorModelDefinition": {
        "states": [
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "To_normal",
                            "actions": [],
                            "condition": "currentInput(\"AWS_IoTEvents_Blueprints_Heartbeat_Input\")",
                            "nextState": "Normal"
                        }
                    ],
                    "events": []
                },
                "stateName": "Offline",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Send_notification",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "sns-topic-arn"
                                    }
                                }
                            ],
                            "condition": "true"
                        }
                    ]
                },
                "onExit": {
                    "events": []
                }
            },
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "Go_offline",
                            "actions": [],
                            "condition": "timeout(\"awake\")",
                            "nextState": "Offline"
                        }
                    ],
                    "events": [
                        {
                            "eventName": "Reset_timer",
                            "actions": [
                                {
                                    "resetTimer": {
                                        "timerName": "awake"
                                    }
                                }
                            ],
                            "condition": "currentInput(\"AWS_IoTEvents_Blueprints_Heartbeat_Input\")"
                        }
                    ]
                },
                "stateName": "Normal",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Create_timer",
                            "actions": [
                                {
                                    "setTimer": {
                                        "seconds": 300,
                                        "timerName": "awake"
                                    }
                                }
                            ],
                            "condition": "$input.AWS_IoTEvents_Blueprints_Heartbeat_Input.value > 0"
                        }
                    ]
                },
                "onExit": {
                    "events": []
                }
            }
        ],
        "initialStateName": "Normal"
    }
}
```

# Exemplo: Um alarme ISA em AWS IoT Events
<a name="iotevents-examples-bisaa"></a>

Esse modelo de detector é um dos modelos disponíveis no AWS IoT Events console. Está incluído aqui para a sua conveniência.

```
{
    "detectorModelName": "AWS_IoTEvents_Blueprints_ISA_Alarm", 
    "detectorModelDefinition": {
        "states": [
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "unshelve", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"unshelve\" && $variable.state == \"rtnunack\"", 
                            "nextState": "RTN_Unacknowledged"
                        }, 
                        {
                            "eventName": "unshelve", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"unshelve\" && $variable.state == \"ack\"", 
                            "nextState": "Acknowledged"
                        }, 
                        {
                            "eventName": "unshelve", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"unshelve\" && $variable.state == \"unack\"", 
                            "nextState": "Unacknowledged"
                        }, 
                        {
                            "eventName": "unshelve", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"unshelve\" && $variable.state == \"normal\"", 
                            "nextState": "Normal"
                        }
                    ], 
                    "events": []
                }, 
                "stateName": "Shelved", 
                "onEnter": {
                    "events": []
                }, 
                "onExit": {
                    "events": []
                }
            }, 
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "abnormal_condition", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.value > $variable.higher_threshold || $input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.value < $variable.lower_threshold", 
                            "nextState": "Unacknowledged"
                        }, 
                        {
                            "eventName": "acknowledge", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"acknowledge\"", 
                            "nextState": "Normal"
                        }, 
                        {
                            "eventName": "shelve", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"shelve\"", 
                            "nextState": "Shelved"
                        }, 
                        {
                            "eventName": "remove_from_service", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"remove\"", 
                            "nextState": "Out_of_service"
                        }, 
                        {
                            "eventName": "suppression", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"suppressed\"", 
                            "nextState": "Suppressed_by_design"
                        }
                    ], 
                    "events": []
                }, 
                "stateName": "RTN_Unacknowledged", 
                "onEnter": {
                    "events": [
                        {
                            "eventName": "State Save", 
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "state", 
                                        "value": "\"rtnunack\""
                                    }
                                }
                            ], 
                            "condition": "true"
                        }
                    ]
                }, 
                "onExit": {
                    "events": []
                }
            }, 
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "abnormal_condition", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.value > $variable.higher_threshold || $input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.value < $variable.lower_threshold", 
                            "nextState": "Unacknowledged"
                        }, 
                        {
                            "eventName": "shelve", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"shelve\"", 
                            "nextState": "Shelved"
                        }, 
                        {
                            "eventName": "remove_from_service", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"remove\"", 
                            "nextState": "Out_of_service"
                        }, 
                        {
                            "eventName": "suppression", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"suppressed\"", 
                            "nextState": "Suppressed_by_design"
                        }
                    ], 
                    "events": [
                        {
                            "eventName": "Create Config variables", 
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "lower_threshold", 
                                        "value": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.lower_threshold"
                                    }
                                }, 
                                {
                                    "setVariable": {
                                        "variableName": "higher_threshold", 
                                        "value": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.higher_threshold"
                                    }
                                }
                            ], 
                            "condition": "$variable.lower_threshold != $variable.lower_threshold"
                        }
                    ]
                }, 
                "stateName": "Normal", 
                "onEnter": {
                    "events": [
                        {
                            "eventName": "State Save", 
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "state", 
                                        "value": "\"normal\""
                                    }
                                }
                            ], 
                            "condition": "true"
                        }
                    ]
                }, 
                "onExit": {
                    "events": []
                }
            }, 
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "acknowledge", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"acknowledge\"", 
                            "nextState": "Acknowledged"
                        }, 
                        {
                            "eventName": "return_to_normal", 
                            "actions": [], 
                            "condition": "($input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.value <= $variable.higher_threshold && $input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.value >= $variable.lower_threshold)", 
                            "nextState": "RTN_Unacknowledged"
                        }, 
                        {
                            "eventName": "shelve", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"shelve\"", 
                            "nextState": "Shelved"
                        }, 
                        {
                            "eventName": "remove_from_service", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"remove\"", 
                            "nextState": "Out_of_service"
                        }, 
                        {
                            "eventName": "suppression", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"suppressed\"", 
                            "nextState": "Suppressed_by_design"
                        }
                    ], 
                    "events": []
                }, 
                "stateName": "Unacknowledged", 
                "onEnter": {
                    "events": [
                        {
                            "eventName": "State Save", 
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "state", 
                                        "value": "\"unack\""
                                    }
                                }
                            ], 
                            "condition": "true"
                        }
                    ]
                }, 
                "onExit": {
                    "events": []
                }
            }, 
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "unsuppression", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"unsuppressed\" && $variable.state == \"normal\"", 
                            "nextState": "Normal"
                        }, 
                        {
                            "eventName": "unsuppression", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"unsuppressed\" && $variable.state == \"unack\"", 
                            "nextState": "Unacknowledged"
                        }, 
                        {
                            "eventName": "unsuppression", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"unsuppressed\" && $variable.state == \"ack\"", 
                            "nextState": "Acknowledged"
                        }, 
                        {
                            "eventName": "unsuppression", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"unsuppressed\" && $variable.state == \"rtnunack\"", 
                            "nextState": "RTN_Unacknowledged"
                        }
                    ], 
                    "events": []
                }, 
                "stateName": "Suppressed_by_design", 
                "onEnter": {
                    "events": []
                }, 
                "onExit": {
                    "events": []
                }
            }, 
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "return_to_service", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"add\" && $variable.state == \"rtnunack\"", 
                            "nextState": "RTN_Unacknowledged"
                        }, 
                        {
                            "eventName": "return_to_service", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"add\" && $variable.state == \"unack\"", 
                            "nextState": "Unacknowledged"
                        }, 
                        {
                            "eventName": "return_to_service", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"add\" && $variable.state == \"ack\"", 
                            "nextState": "Acknowledged"
                        }, 
                        {
                            "eventName": "return_to_service", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"add\" && $variable.state == \"normal\"", 
                            "nextState": "Normal"
                        }
                    ], 
                    "events": []
                }, 
                "stateName": "Out_of_service", 
                "onEnter": {
                    "events": []
                }, 
                "onExit": {
                    "events": []
                }
            }, 
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "re-alarm", 
                            "actions": [], 
                            "condition": "timeout(\"snooze\")", 
                            "nextState": "Unacknowledged"
                        }, 
                        {
                            "eventName": "return_to_normal", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"reset\"", 
                            "nextState": "Normal"
                        }, 
                        {
                            "eventName": "shelve", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"shelve\"", 
                            "nextState": "Shelved"
                        }, 
                        {
                            "eventName": "remove_from_service", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"remove\"", 
                            "nextState": "Out_of_service"
                        }, 
                        {
                            "eventName": "suppression", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_ISA_Alarm_Input.command == \"suppressed\"", 
                            "nextState": "Suppressed_by_design"
                        }
                    ], 
                    "events": []
                }, 
                "stateName": "Acknowledged", 
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Create Timer", 
                            "actions": [
                                {
                                    "setTimer": {
                                        "seconds": 60, 
                                        "timerName": "snooze"
                                    }
                                }
                            ], 
                            "condition": "true"
                        }, 
                        {
                            "eventName": "State Save", 
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "state", 
                                        "value": "\"ack\""
                                    }
                                }
                            ], 
                            "condition": "true"
                        }
                    ]
                }, 
                "onExit": {
                    "events": []
                }
            }
        ], 
        "initialStateName": "Normal"
    },
    "detectorModelDescription": "This detector model is used to detect if a monitored device is in an Alarming State in accordance to the ISA 18.2.", 
    "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole", 
    "key": "alarmId" 
}
```

# Exemplo: Crie um alarme simples com AWS IoT Events
<a name="iotevents-examples-bsa"></a>

Esse modelo de detector é um dos modelos disponíveis no AWS IoT Events console. Está incluído aqui para a sua conveniência.

```
{
    "detectorModelDefinition": {
        "states": [
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "not_fixed", 
                            "actions": [], 
                            "condition": "timeout(\"snoozeTime\")", 
                            "nextState": "Alarming"
                        }, 
                        {
                            "eventName": "reset", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_Simple_Alarm_Input.command == \"reset\"", 
                            "nextState": "Normal"
                        }
                    ], 
                    "events": [
                        {
                            "eventName": "DND", 
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "dnd_active", 
                                        "value": "1"
                                    }
                                }
                            ], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_Simple_Alarm_Input.command == \"dnd\""
                        }
                    ]
                }, 
                "stateName": "Snooze", 
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Create Timer", 
                            "actions": [
                                {
                                    "setTimer": {
                                        "seconds": 120, 
                                        "timerName": "snoozeTime"
                                    }
                                }
                            ], 
                            "condition": "true"
                        }
                    ]
                }, 
                "onExit": {
                    "events": []
                }
            }, 
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "out_of_range", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_Simple_Alarm_Input.value > $variable.threshold", 
                            "nextState": "Alarming"
                        }
                    ], 
                    "events": [
                        {
                            "eventName": "Create Config variables", 
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "threshold", 
                                        "value": "$input.AWS_IoTEvents_Blueprints_Simple_Alarm_Input.threshold"
                                    }
                                }
                            ], 
                            "condition": "$variable.threshold != $variable.threshold"
                        }
                    ]
                }, 
                "stateName": "Normal", 
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Init", 
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "dnd_active", 
                                        "value": "0"
                                    }
                                }
                            ], 
                            "condition": "true"
                        }
                    ]
                }, 
                "onExit": {
                    "events": []
                }
            }, 
            {
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "reset", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_Simple_Alarm_Input.command == \"reset\"", 
                            "nextState": "Normal"
                        }, 
                        {
                            "eventName": "acknowledge", 
                            "actions": [], 
                            "condition": "$input.AWS_IoTEvents_Blueprints_Simple_Alarm_Input.command == \"acknowledge\"", 
                            "nextState": "Snooze"
                        }
                    ], 
                    "events": [
                        {
                            "eventName": "Escalated Alarm Notification", 
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-west-2:123456789012:escalatedAlarmNotification"
                                    }
                                }
                            ], 
                            "condition": "timeout(\"unacknowledgeTIme\")"
                        }
                    ]
                }, 
                "stateName": "Alarming", 
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Alarm Notification", 
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-west-2:123456789012:alarmNotification"
                                    }
                                }, 
                                {
                                    "setTimer": {
                                        "seconds": 300, 
                                        "timerName": "unacknowledgeTIme"
                                    }
                                }
                            ], 
                            "condition": "$variable.dnd_active != 1"
                        }
                    ]
                }, 
                "onExit": {
                    "events": []
                }
            }
        ], 
        "initialStateName": "Normal"
    }, 
    "detectorModelDescription": "This detector model is used to detect if a monitored device is in an Alarming State.", 
    "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole", 
    "key": "alarmId" 
}
```