Triggering Microsoft Flow using an Azure Function

For a recent Azure IoT workshop, we were looking for a nice ending of the Azure IoT pipeline. Because after introducing IoT Hubs, Stream Analytics, Event Hubs and Azure Functions, we wanted to show the real power of IoT.

Normally, we show a bunch of charts in PowerBI. You have seen it in my previous blogs, it’s so powerful. But this time, we wanted to do something else, something snappy.

Well, we came up with Microsoft Flow. At first, I was a bit sceptic. Will this help us to ‘sell’ Azure IoT?

Well, see for yourself… Here is an example on how to send, conditionally, an email to an email address you provide.

As always, it all start with telemetry being sent by a device. Here’s a picture showing how the arrival of telemetry in the IoT Hub, using the IoT Device Explorer:

01deviceexplorer

I have passed the telemetry to an Azure Function which contains just the standard logging:

02standardlogfunction

So the logging shows the arrival of the telemetry, only:

03standardloggingfunction

Ok, everything is set. Let’s start.

Log into the Microsoft flow portal. You will be asked to provide credentials if needed (You can create an account for free):

04flow-introduction

Select Make a flow. A lot of pre-defined flows are shown. Scroll through the list to get an impression of all combination possible. We will not use option, we will create a flow from scratch. Select My flows:

05flow-portal-my-flows

Normally, all your flows will appear here. Because there is no flow yet, a short introduction is shown:

06flow-my-flows-create

Select Create from blank:

07flow-portal-create-from-blank

An empty flow is shown. First give the flow a proper name. Name it Mail telemetry conditionally (by replacing ‘Untitled’):

07flow-input-more-with-name

You are invited to select one of many flow steps. Scroll down until a step called ‘Request’ is shown or just type in ‘request’:

08flow-input-request2

Then select the Request step. The following fields are shown:

09flow-request-step-init

This is an incoming API call and we will use Azure Functions to trigger this flow.

Note: The URL will be generated after save

The Azure Function will post a JSON object to this Request URL. Flow can not handle this JSON object directly. Therefore, enter the following ‘Request Body JSON Schema’. This is used to transform the JSON object into an entity. This way, Microsoft Flow can handle the separate fields in the message:

{
"type": "object",
"properties": {
"level": {
"type": "integer"
},
"deviceId": {
"type": "string"
},
"time": {
"type": "string"
}
},
"required": [
"deviceId"
]
}

The Request step is ready now. We will retrieve the URL after the creation of the Flow. Select New step:

10flow-portal-new-step

In this flow, we will mail conditionally. So select Add a condition:

11flow-portal-add-a-condition

This is the heart of the Flow. We provide a condition (like ‘Level is lower than 42′). And if it’s true, a certain step will be executed. Otherwise, the other step will be executed.

Note: The first or the latter are optional.

12flow-portal-condition-init

Enter the left field with ‘Choose a value’. The previous Request step will output an entity with fields like ‘deviceId’, ‘time’ and ‘level’. So here you can compare one of the fields with another value. Select the level field:

13flow-portal-condition-fields

Because we want to be warned when the level is less than a certain value, select is less then operator:

14flow-portal-condition-less-then

Finally, enter 42 in the right field:

15flow-portal-condition-less-then-42

We have created a condition, now we can fill in the ‘if then else’ blocks with steps. In the left block, Change ‘IF YES, DO NOTHING’ into ‘IF YES’ by selecting Add an Action:

16flow-condition-true-add-action

Select the Mail - Send email step (you can filter on ‘mail’):

17flow-condition-true-add-mail

Create a connection for Mail. Accept the SendGrid terms and privacy policy:

Note: SendGrid is a third party email provider.

18flow-condition-true-mail-step

Enter your own email address in the ‘To’ field. Enter Check the level of device plus the entity field ‘deviceId’ in the ‘Subject’ field. Enter Hurry up, the level just got below plus the entity field ‘level’ in the ‘Email body’ field:

19flow-condition-true-mail-step-filled-in

This Mail step is ready, and so is the flow. Select Create flow:

20flow-portal-create-flow

The flow is now being created. We have to wait a moment to get it starting up. Select Done:

21flow-portal-flow-creation-done

Although the flow is created and almost available we still need to do one thing more. By this time, the endpoint of the Request step is created. Before we can pass telemetry to this flow, we need to have that API endpoint. Select My flows again:

05flow-portal-my-flows

All your flows will appear here. The flow we just created is shown:

22flow-my-flows-list

Edit the flow by selecting the pen icon:

23flow-my-flows-list-flow-edit

The flow is shown, in detail. Select the first step, the Request step so the fields are shown:

24flow-request-step-url

The URL of the Request step endpoint is now available to copy.

Copy this URL in this piece of code (and in Microsoft Flow, go back to the list view):

using System;
using System.Text;

public static void Run(string myEventHubMessage, TraceWriter log)
{
  log.Info($"C# The triggered function processed a message: {myEventHubMessage}");

  using (var client = new System.Net.Http.HttpClient())
  {
    var response = client.PostAsync(
      "[PASTE THE REQUEST URL HERE]",
      new StringContent(myEventHubMessage,
      Encoding.UTF8,
      "application/json")
      ).Result;
    log.Info($"Microsoft Flow accepts the message: {response.IsSuccessStatusCode.ToString()}");
  }
}

And why? Because this is the actual function we are going to execute using the triggered Azure function.

Go to the portal and paste this code (including the actual URL) into the code block of the function. Save the changes:

2016-09-25T12:23:35.380 Script for function 'EventHubTriggerFunction' changed. Reloading. 
2016-09-25T12:23:35.427 Compilation succeeded. 

Check the logging if telemetry is executed. You will see something like:

2016-09-30T08:29:04.325 Function started (Id=dbd7a0c4-3710-464d-a6fe-bc32d5a856c8)
2016-09-30T08:29:04.404 </code>C# The triggered function processed a message<code>: {"level":45,"time":"2016-09-30T08:28:59.4658651Z","deviceId":"DummyDevice"} 
2016-09-30T08:29:05.252 Microsoft Flow accepts the message: True 
2016-09-30T08:29:05.252 Function completed (Success, Id=dbd7a0c4-3710-464d-a6fe-bc32d5a856c8)

Now the Azure Function is passing the telemetry towards your Microsoft Flow.

Let’s check what happened with level 45. Go to the Microsoft Flow portal. Select My flows. And select the run list of your current flow by selecting the i (for Information) icon:
25flow-portal-run-list

By now, your latest run (and maybe more) must be listed

27flow-mail-runs-list
Select that latest row and `click’ on it:

The execution of the flow is shown in detail. Green ticks will mark which steps are executed successfully. In the following example, the telemetry is received, the condition is checked and the ‘YES’ block is executed (they all have green ticks):

26flow-mail-sent-mail-true-condition

What does this mean? You just got an email from your device saying the level is too low:

28mail

Conclusion

Yes, Microsoft flow is an excellent unique selling point of Azure IoT. I think it’s a great addition to the Azure IoT Stack. For people not entirely familiar with IoT, Microsoft Flow makes clear how you can automate your life with simple ‘if this, then that’ rules and IoT can be a part of that ‘if’ or part of the ‘that’.

 

 

 

Advertenties