Tutorial: Publish, subscribe to events in cloud

This article walks through all the steps needed to publish and subscribe to events using Event Grid on IoT Edge. This tutorial uses and Azure Function as the Event Handler. For additional destination types, see event handlers.

See Event Grid Concepts to understand what an event grid topic and subscription are before proceeding.

Prerequisites

In order to complete this tutorial, you will need:

  • Azure subscription - Create a free account if you don't already have one.
  • Azure IoT Hub and IoT Edge device - Follow the steps in the quick start for Linux or Windows devices if you don't already have one.

Deploy Event Grid IoT Edge module

There are several ways to deploy modules to an IoT Edge device and all of them work for Azure Event Grid on IoT Edge. This article describes the steps to deploy Event Grid on IoT Edge from the Azure portal.

Note

In this tutorial, you will deploy the Event Grid module without persistence. It means that any topics and subscriptions you create in this tutorial will be deleted when you redeploy the module. For more information on how to setup persistence, see the following articles: Persist state in Linux or Persist state in Windows. For production workloads, we recommend that you install the Event Grid module with persistence.

Important

In this tutorial, Event Grid module will be deployed with client authentication turned-off, and allow HTTP subscribers. For production workloads, we recommend that you enable only HTTPS requests and subscribers with client authentication enabled. For more information on how to configure Event Grid module securely, see Security and authentication.

Select your IoT Edge device

  1. Sign in to the Azure portal
  2. Navigate to your IoT Hub.
  3. Select IoT Edge from the menu in the Automatic Device Management section.
  4. Click on the ID of the target device from the list of devices
  5. Select Set Modules. Keep the page open. You will continue with the steps in the next section.

Configure a deployment manifest

A deployment manifest is a JSON document that describes which modules to deploy, how data flows between the modules, and desired properties of the module twins. The Azure portal has a wizard that walks you through creating a deployment manifest, instead of building the JSON document manually. It has three steps: Add modules, Specify routes, and Review deployment.

Add modules

  1. In the Deployment Modules section, select Add
  2. From the types of modules in the drop-down list, select IoT Edge Module
  3. Provide the name, image, container create options of the container:

Note

Always check the version of your image to ensure it has the feautures you require. If you have a previous version of the container image already pulled on your machine, you'll need to specify the version tag you want, or delete the existing image before pulling again with the :latest tag. For more on image versions and tags, see release notes.

  • Name: eventgridmodule
  • Image URI: mcr.microsoft.com/azure-event-grid/iotedge:latest
  • Container Create Options:
    {
      "Env": [
        "inbound__clientAuth:clientCert__enabled=false",
        "outbound__webhook__httpsOnly=false"
      ],
      "HostConfig": {
        "PortBindings": {
          "4438/tcp": [
            {
              "HostPort": "4438"
            }
          ]
        }
      }
    }
  1. Click Save

  2. Click Next to continue to the routes section

    Note

    If you are using an Azure VM as an edge device, add an inbound port rule to allow inbound traffic on the port 4438. For instructions on adding the rule, see How to open ports to a VM.

Setup routes

Keep the default routes, and select Next to continue to the review section

Review deployment

  1. The review section shows you the JSON deployment manifest that was created based on your selections in the previous two sections. Confirm that you see the two modules in the list: $edgeAgent and $edgeHub. These two modules make up the IoT Edge runtime and are required defaults in every deployment.
  2. Review your deployment information, then select Submit.

Verify your deployment

  1. After you submit the deployment, you return to the IoT Edge page of your IoT hub.
  2. Select the IoT Edge device that you targeted with the deployment to open its details.
  3. In the device details, verify that the Event Grid module is listed as both Specified in deployment and Reported by device.

It may take a few moments for the module to be started on the device and then reported back to IoT Hub. Refresh the page to see an updated status.

Create an Azure function in the Azure portal

Follow the steps outlined in the tutorial to create an Azure function.

Replace the code snippet with the following code:

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);

    log.LogInformation($"C# HTTP trigger received {data}.");
    return data != null
        ? (ActionResult)new OkResult()
        : new BadRequestObjectResult("Please pass in the request body");
}

In your new function, select Get function URL at the top right, select default (Function key), and then select Copy. You will use the function URL value later in the tutorial.

Note

Refer to the Azure Functions documentation for more samples and tutorials on reacting to events an using EventGrid event triggers.

Create a topic

As a publisher of an event, you need to create an event grid topic. Topic refers to an end point where publishers can send events to.

  1. Create topic2.json with the following content. See our API documentation for details about the payload.

         {
          "name": "sampleTopic2",
          "properties": {
            "inputschema": "eventGridSchema"
          }
        }
    
  2. Run the following command to create the topic. HTTP Status Code of 200 OK should be returned.

    curl -k -H "Content-Type: application/json" -X PUT -g -d @topic2.json https://<your-edge-device-public-ip-here>:4438/topics/sampleTopic2?api-version=2019-01-01-preview
    
  3. Run the following command to verify topic was created successfully. HTTP Status Code of 200 OK should be returned.

    curl -k -H "Content-Type: application/json" -X GET -g https://<your-edge-device-public-ip-here>:4438/topics/sampleTopic2?api-version=2019-01-01-preview
    

    Sample output:

         [
           {
             "id": "/iotHubs/eg-iot-edge-hub/devices/eg-edge-device/modules/eventgridmodule/topics/sampleTopic2",
             "name": "sampleTopic2",
             "type": "Microsoft.EventGrid/topics",
             "properties": {
               "endpoint": "https://<edge-vm-ip>:4438/topics/sampleTopic2/events?api-version=2019-01-01-preview",
               "inputSchema": "EventGridSchema"
             }
           }
         ]
    

Create an event subscription

Subscribers can register for events published to a topic. To receive any event, the subscribers will need to create an Event grid subscription on a topic of interest.

Note

If you need to guarantee pending events are persisted in the event of a device restart, you'll need to enable persistence for the event subscription. For more information on how to setup persistence, see the following articles: Persist state in Linux or Persist state in Windows.

  1. Create subscription2.json with the following content. Refer to our API documentation for details about the payload.

        {
          "properties": {
            "destination": {
              "endpointType": "WebHook",
              "properties": {
                "endpointUrl": "<your-az-func-cloud-url>"
              }
            }
          }
        }
    

    Note

    The endpointType specifies that the subscriber is a Webhook. The endpointUrl specifies the URL at which the subscriber is listening for events. This URL corresponds to the Azure Function sample you setup earlier.

  2. Run the following command to create the subscription. HTTP Status Code of 200 OK should be returned.

    curl -k -H "Content-Type: application/json" -X PUT -g -d @subscription2.json https://<your-edge-device-public-ip-here>:4438/topics/sampleTopic2/eventSubscriptions/sampleSubscription2?api-version=2019-01-01-preview
    
  3. Run the following command to verify subscription was created successfully. HTTP Status Code of 200 OK should be returned.

    curl -k -H "Content-Type: application/json" -X GET -g https://<your-edge-device-public-ip-here>:4438/topics/sampleTopic2/eventSubscriptions/sampleSubscription2?api-version=2019-01-01-preview
    

    Sample output:

         {
           "id": "/iotHubs/eg-iot-edge-hub/devices/eg-edge-device/modules/eventgridmodule/topics/sampleTopic2/eventSubscriptions/sampleSubscription2",
           "type": "Microsoft.EventGrid/eventSubscriptions",
           "name": "sampleSubscription2",
           "properties": {
             "Topic": "sampleTopic2",
             "destination": {
               "endpointType": "WebHook",
               "properties": {
                 "endpointUrl": "<your-az-func-cloud-url>"
               }
             }
           }
         }
    

Publish an event

  1. Create event2.json with the following content. Refer to our API documentation for details about the payload.

        [
          {
            "id": "eventId-func-1",
            "eventType": "recordInserted",
            "subject": "myapp/vehicles/motorcycles",
            "eventTime": "2019-07-28T21:03:07+00:00",
            "dataVersion": "1.0",
            "data": {
              "make": "Ducati",
              "model": "Monster"
            }
          }
        ]
    
  2. Run the following command to publish event

    curl -k -H "Content-Type: application/json" -X POST -g -d @event2.json https://<your-edge-device-public-ip-here>:4438/topics/sampleTopic2/events?api-version=2019-01-01-preview
    

Verify event delivery

You can view the event delivered in the Azure portal under the Monitor option of your function.

Cleanup resources

  • Run the following command to delete the topic and all its subscriptions

    curl -k -H "Content-Type: application/json" -X DELETE https://<your-edge-device-public-ip-here>:4438/topics/sampleTopic2?api-version=2019-01-01-preview
    
  • Delete the Azure function created in the Azure portal.

Next steps

In this tutorial, you created an event grid topic, subscription, and published events. Now that you know the basic steps, see the following articles: