Sending Messages from the Microsoft Azure* IoT Hub to the Intel® IoT Gateway

All of the message flow so far has been from the device to the cloud (device-to-cloud messages). In this section, we'll see how to send messages from the cloud back down to the device (cloud-to-device messages).

We'll configure our Intel® NUC to turn on its buzzer for one second if it receives a message from the Microsoft Azure* IoT Hub with the following format:

{
    "type"    : "temp",
    "message" : "some message"
}

Add the Buzzer Device and Code to the Intel® NUC

1. Attach the Buzzer to D3 on the Grove Base Shield as shown below:

2. Copy the contents out of HOLs\Node-RED Flows\Flow 3 - 03 - Alert and Buzzer Nodes Only.json file into the clipboard.

3. Open the Intel® NUC Node-RED* development environment in your browser (http://your.nucs.ip.address:1880 where your.nucs.ip.address is your NUC's IP Address), from the Hamburger menu in the top right corner select Import > Clipboard

4. Paste the code copied from the HOLs\Node-RED Flows\Flow 3 - 03 - Alert and Buzzer Nodes Only.json file into the Import nodes box, and click OK.

5. Then move your mouse to place the imported nodes where you want (if you hold the shift key while you move your mouse the nodes will snap to the grid), and then connect the output of the azureiothub node to the input of the To String node as shown below. Click the Deploy button when you are done to deploy the changes.

The nodes being added do the following:

  • The To String function converts the byte data returned by the azureiothub node into a string value.
  • The json node then deserializes that string into an object.
  • The msg.payload debug node displays the object to the debug panel.
  • The If Temp Alert node checks the type property on the object to see if it is literally temp if it is, the subsequent tasks are allowed to run.
  • The Turn on Buzzer task does nothing more than create a payload with a value of 1 to cause the buzzer to turn on.
  • The Grove Buzzer then looks at the payload coming in, and if it is a 1, id sounds the buzzer for a hard coded one second (1000000 microseconds).
  • The Get the Message node extracts just the "message" property from the object and passes it to the Show the Message node.
  • The Show the Message node displays the message text on the second row of the LCD panel and flashes the background of the panel red (rgb 255,0,0).

6. Just to clarify, the azureiothub node in Node-RED behaves a little differently than other nodes. It doesn't take data in from the left, process it, and pass it out on the right. Instead whatever comes IN to it from the left is SENT to the Azure IoT Hub. If however the node RECEIVES a message FROM the IoT Hub, it sends it OUT on the right. So the nodes that are before (from a flow perspective) the azureiothub node are dealing with sending device-to-cloud messages, while the nodes after it deal with receiving cloud-to-device messages.

7. The Azure Web App we deployed in the previous task has a handy way to test the buzzer. Open up the http://*name*web.azurewebsites.net web application in browser.

8. Just to the left of each device under the Devices heading there is a small green button with a lightning bolt on it (Test Buzzer Button). Click that button next to the device where you have deployed the updated Node-RED code, and you should:

  • Hear the buzzer sound
  • See the test message Buzzer Test displayed briefly on the LCD
  • See the LCD background change to red briefly.

Note: If the test doesn't function try restarting the Azure Web App (you can open the web app in the portal, and click the Restart or Stop and Start buttons along the top), as well as ssh'ing into your Intel® NUC  and issuing a shutdown / reboot command:

shutdown 0 -raw

Create a Microsoft Azure* Function to Process the Event Hub Messages and Alert the Device

Previously, we setup our <name>job Stream Analytics Job to forward messages coming in from the IoT Hub that had a temperature value over some threshold off to the <name>alerts event hub. But we never did anything with those Event Hub alert messages. Now we will.

In this task, we'll create the TempAlert function and have it receive those alert messages from the event hub, and send a temp alert message back down to the device.

1. Open the Azure Portal (https://portal.azure.com) in the browser, and close any blades open from previous steps. Then click + New > Compute > Function App:

Note: Function apps may appear in your portal under the Virtual Machines category instead of Compute.

2. Complete the properties as follows then click the Create button:

  • App name - <name>functions
  • Subscription - Chose the same subscription used for the previous resources
  • Resource group - Choose Use existing and select the <name>group resource group created previously
  • Hosting Plan - Choose App Service Plan.
  • App Service Plan - Select the <name>plan plan we created previously.
  • Storage Account - Select Create New and name it <name>storage
  • Pin to dashboard - Checked

3. When the new Function App is deployed, and its blade open's in the portal, click the +New Function button, and select EventHubTrigger - C#.

4. SCROLL DOWN to continue configuring the new function.

  • Name - TempAlert
  • Event Hub Name - <name>alerts
  • Event Hub connection - Click the new link

5. On the Service Bus connection blade, click Add a connection string the configure the properties on the Add Service Bus connection blade as follows and click OK:

  • Connection name - <name>ns
  • Connection string - Copy the value from your Event Hub for the Root Manage Shared Access Key SAS Policy Primary Connection String: from the myresources.txt (The connection string should start with Endpoint=sb:// and contain SharedAccessKeyName=RootManageSharedAccessKey) file and paste it in here. This connection string gives your Azure Function app permissions to connect to your Service Bus Namespace, and Event Hub with all the permissions it needs.

6. Finally, click the Create button to create the function:

7. Once the TempAlert function is created, click on the Integrate link to configure its triggers, inputs and outputs. Our function comes pre-provisioned with an Azure Event Hub Trigger that will invoke this function whenever a message is available on the <name>alerts event hub. When the function is invoked the Event Hub message that caused the function to be triggered will be passed in as the myEventHubMessage parameter. The functions code can then inspect that parameter's value and act on it.

Note: There isn't a SAVE button or anything. These changes are being written into the functions configuration files as you enter them.

  • Event parameter name: myEventHubMessage
  • Event Hub consumer group: $Default
  • Event Hub name: <name>alerts
  • Event Hub connection: <name>ns

8. Switch back to the Develop page for the function. The code for our C# function is stored in the run.csx file. The default code simply logs the contents of the myEventHubMessage parameter value to the console.

9. We are going to replace the default code with something that provides a little more functionality. Back in Visual Studio Code, open the HOLs\FunctionApp\TempAlert\run.csx file. If you receive a prompt from Visual Studio Code to fix unresolved dependencies, click Close. Once the file is open though, copy the entire contents of run.csx to the clipboard:

10. Back in the portal, replace the entire contents of the run.csx file with the code you just copied, then click the Save button to save the changes:

11. The code we pasted into run.csx depends on some libraries (like Microsoft.Azure.Devices and Newtonsoft.Json as well as others. To make sure the the libraries are installed on the server, we need to specify them in a project.json file. To add a project.json file to our function, click the View Files button, then click the + Add button, and name the new file project.json (all lower case):

12. Back in Visual Studio Code, copy the contents of the HOLs\FunctionApp\TempAlert\project.json file to the clipboard:

13. And back in the portal, replace the contents of the new project.json file you just created with the contents you copied from Visual Studio Code:

14. Next, click on each file (function.json,project.json, and run.csx) to review its contents.

In the run.csx file, locate the line of code that reads (should be at line 31 or so):
static string connectionString = *Your IoT Hub "service" SAS Policy Primary Connection String goes here*";
and replace *Your IoT Hub "service" SAS Policy Primary Connection String goes here* with the IoT Hub service SAS Policy Primary Connection String" value from the myresources.txt file For example:
static string connectionString = "HostName=mic16iot.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=wQF6dryjMwQ1mMEwDFfcgkSaSscFthHVVJeIfq6iVWQ=";
Then click the Save button to save the changes.

16. In the Logs section, verify that the function compiled successfully.

17. At this point, your function should be working properly. For it to kick off, we need:

  • Our device to publish a message with a temperature sensor value that is higher than the threshold value in our <name>job Stream Analytics Job query (40 by default)
  • That will cause an event to be sent to the <name>alerts event hub
  • That will trigger our function, and allow the function to send a cloud-to-device message back to the Intel® NUC via the Azure IoT Hub.

18. To try it out:

Note: If the sensor is already publishing values that exceeds the threshold value in the <name>job Stream Analytics Job Query (40 by default), you should begin receive alerts immediately. This can become irritating if the threshold is set to low. If desired, you can go back to your <name>job Stream Analytics Job Query definition and increase the threshold value. If you do need to do that, you will need to first Stop the Stream Analytics Query, then modify the query, then Start the Stream Analytics Query.

  • Warm your hands up by rubbing them vigorously together, then pinch the Temperature sensor on both sides with your warm fingers and try to get the NUC to generate a reading of the threshold value (again, 40 by default)

  • Watch the Logs section of the Azure function. You should see the incoming event hub message get logged as well as details of the message being sent to the device:

  • And on the LCD panel, you should see yourTemp Alert message displayed along with a brief flash of red:

  • And lastly, if you have the Buzzer plugged in, you should hear it buzz for one second each time an alert comes in!

19. That's it. Your function works. However by default the app can be shutdown if it isn't being regularly accessed. To keep it active:

  • Click the Function app settings link, then pick Go to App Service Settings.

  • Click Application settings then turn the Always On setting to On and click the Save button along the top.

 

IDE or Development Framework: 
Middleware: 
For more complete information about compiler optimizations, see our Optimization Notice.