AzureTipsAndTricks/blog/tip114.md

3.0 KiB

type title excerpt tags date
post Tip 114 - Easily Send JSON to IoT Hub with C# A tutorial on how to quickly send JSON to IoT Hub with C#
Management and Governance
Internet of Things
2018-04-15 17:00:00

::: tip 💡 Learn more : Azure IoT Hub Overview. :::

Easily Send JSON to IoT Hub with C#

I recently needed to send JSON that an IoT Hub could receive and display on an AZ3166 device. Once the AZ3166 device receives the message, then it could do a number of things with the data such as open an door.

Part 1:

  • Create an IoT Hub and provision the MX Chip (AZ3166) as a device. While we could go into the Azure Portal and create a new IoT Hub and walk through the setup of our device, etc. There is an easier way.
  • Download the tools
  • Open VS Code, look under Arduino Examples and open the GetStarted sample and run task cloud-provision in the VS Code terminal..
  • If you switch over to the Azure Portal, and look under your new IoT, then Devices - you should see your new device.

Part 2:

  • I took the code from the “GetStarted” sample found in VS Code and tweaked the Screen.print(0, "Unlock Door"); lines in the GetStarted.ino file in the Setup method.
  • Now on my deivce it prints the “Unlock Door” message in fancy yellow and displays the IP Address and waits for a message to be sent to IoT Hub.

Part 3:

  • Open Visual Studio and create a console application.
  • Add NuGet package : Microsoft.Azure.Devices (Service SDK for Azure IoT Hub)
  • I hardcoded my connection string (found in IoT Hub) and mocked the JSON data.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices;

namespace SendMessageToIoTHub
{
    class Program
    {
        static ServiceClient serviceClient;
        static string connectionString = "mykey";

        static void Main(string[] args)

        {
            serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
            SendCloudToDeviceMessageAsync().Wait();
            Console.ReadLine();
        }

        private async static Task SendCloudToDeviceMessageAsync()
        {
            string mockedJsonData =

                "{ \"Locked\":true}";

            var commandMessage = new Message(Encoding.ASCII.GetBytes(mockedJsonData));
            await serviceClient.SendAsync("AZ3166", commandMessage);
        }
    }
}

Part 4:

  • The MX Board receives the message from IoT Hub
  • It prints the JSON message from the serviceClient code above to the board display.