Making a Connection Between Unity 3D and Azure IoT Hub

This is a technical blog post about a problem and solution that I encountered with Unity 3D and Azure. Hopefully it will be of use to someone out there.

Lately I’ve been using the Azure IoT Hub for connections to remote devices. I needed to see if there was a way to send messages from Unity 3D to the Azure IoT Hub. It turns out this is a process that takes a few steps.

First of all, set your Azure IoT Hub up on your own Azure account. (Free trials of Azure accounts are available at the Microsoft Azure site.)

There are a few components in Azure that you will need to set up to create the IoT Hub connection. First go into your Azure account and create your IoT Hub itself. (If you want more details about how to manage the IoT Hub through the Azure portal, check out this blog post.) For testing, it’s OK to create an F1 “Free” tier Azure Hub. This post has more information about scaling with IoT Hub if you are curious.

Once created, you will need to return back to the “Shared access policies” tab. Here, you will get and note the primary keys and connection strings to access the IoT hub from elsewhere in the solution. Click on “iothubowner” as shown below, and a blade will open up with keys that you can easily cut and paste into your connection strings.

 

Now there are a couple tools to install to make this process easier. For checking to see if a connection works, you can use Postman. Postman is a tool that will allow you to see if an HTTP request has made it to the server and check your APIs. You will also need the Device Explorer. From the link on GitHub you can download the Device Explorer code, or a pre-built version available here: Look for Downloads – SetupDeviceExplorer.msi to install it.

In order to connect to Azure IoT Hub, you need a SaS token. There’s a number of ways to generate one and the Device Explorer is one such way. You can use this to generate keys that are temporary and control access for a limited time. If you want all the info about the security on IoT Hub, it’s in the documentation here.

Open up Device Explorer and in the “Configuration” tab, cut and paste the IoT Hub Connection String that you got from the earlier step above. Then go to the Management tab. You can add and manage devices here. I have a few I’m working with, but you can create a generic one such as “myDeviceID” shown below for a virtual device.

Clicking on the SAS Token tab above will allow you to set up a SAS token with certain parameters, like knowing when it will expire. Obviously, I obfuscated the keys above so that you can get your own.

To test and make sure the connection was going through, this is where Postman comes into play.  Using Postman, you can test a Post query. The way it is formatted is something like:

https://NAMEOFYOURIOTHUBHERE.azure-devices.net/devices/NAMEOFYOURDEVICEHERE/messages/events?api-version=2016-02-03

In the Headers tab on Postman I set two parameters – the SAS token, and the content type. The SAS token is the token generated from the Device Explorer and cut and paste into this tab. I obfuscated the actual token here, but hopefully you get the idea!

If you return to Device Explorer and click the Data tab, you can set your dummy device to “Monitor” and listen to messages sent to it. With this turned on, if you click ‘Send’ on Postman it will send a message if your SAS token works. (It’ll be a blank message unless you add some content but a blank message is fine for testing.)

Now the trick is to get this same connection working in Unity 3D. For Unity, I have a really basic scene with just a cube in it. (Check this on my GitHub here.) The cube will be the thing I click to send the Post message. So this includes the OnMouseDown to send the message.

 

private void OnMouseDown()
    {
        // Get sockets script
        //GameObject go = GameObject.Find("TestSocketObj");
        //_testSocketScript = go.GetComponent();
       // _socket = _testSocketScript.socket;

        ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;


        string url = "https://IOTHUBNAMEHERE.azure-devices.net/devices/DEVICENAMEHERE/messages/events?api-version=2016-02-03";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Headers.Add("Authorization", "SharedAccessSignature sr=YOUR SAS TOKEN HERE");

        string postData = "{\"Name\":\"MyName\"}";
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] byte1 = encoding.GetBytes(postData);
        request.ContentType = "application/atom+xml";
        request.Method = "POST";
        request.ContentLength = byte1.Length;

        Stream newStream = request.GetRequestStream();

        newStream.Write(byte1, 0, byte1.Length);


        // Close the Stream object.
        newStream.Close();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        Stream resStream = response.GetResponseStream();
        Debug.Log(resStream);



    }

 

When it was all done, I can click on the box in my Unity application, and it sends a message to the IoT hub. In this case it just includes “Name:MyName” but that’s for the example purposes. The GitHub version generates some fake “sensor” data instead. This allows me to essentially fake up an IoT device using Unity for IoT simulations or simulated data from a virtual environment. This is going to be useful in a few projects I am working on, so maybe you can also think of an application for this!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *