In this example I will show you how to use NanoFramework to send a https POST request to Azure IoT Hub. We will be using an ESP32 device but any supported NanoFramework device with WIFI and GPIO pins will do. I will be using a button to increment the temperature.
Step One - Create IoT HubLets create an Azure IoT Hub
- Create an Azure account (For Free!) here
- Create an Azure IoT Hub. Click Create a Resource
- Search for IoT hub
- Click Create
- Enter a Subscription, Region, and HubName
- Click Management on the top bar and select Free Tier and then review and create
- Great job you created an IoT Hub!
Now we will download the Azure IoT Explorer an easy wat to monitor and set up your iot devices!
- Go to this link and click on the Asset of the most recent version corresponding to your platform i.e. Windows click.msi extension IoT Explorer Download
- Open the Azure IoT Explorer and click Add Connection
- Now we just add the connection string of the Iot Hub we created in Step One. To find the string click the Where do I get an IOT hub connection string link circled below.
- Copy and paste the string and click save
- You are now connected in Azure IOT Explorer
Lets create our device
- Click on View Devices in this hub then click New
- Now Enter the Device ID and keep the Symmetric Key option selected for this example then click create
- Now that the device is created we need to get out device SAS Token!
We will now create our SAS token.
- Click on your device and go to Device Identity
- Open the connection string with SAS token. This is a private token that will be used to connect to the IOT hub it has a limited lifetime. This token can also be generated using your own C# code or the Azure CLI. This is just an easy way of doing it to get you started.
- Then select your Connection String and expiration time. Generate the string and copy and paste somewhere safe ( I throw it in a temporary notepad file).
Now we will clone the NanoFramework Sample repo into VS 2019
- Make sure you have the NanoFramework Extension installed and set up
- Go to this link and click the green code icon
- Navigate to Samples/HTTP and open the HTTP.Samples.sln file
- Navigate to the HttpAzurePOST project right click and set as Startup Project
- Now we update all packages for solution by right clicking the solution
- Click select all and update
- Simply set up a button through Pin 0 to ground!
- In NetworkHelper.cs update your SSID and Password so the device can connect to the internet
private const string c_SSID = "<replace-with-valid-ssid";
private const string c_AP_PASSWORD = "<replace-with-valid-password>";- Go to Program.cs and then copy the SAS token from step four. Paste this token in this file as the sas string
///////////////////////////////////////////////////////////////////////////////////
/// enter your Shared Access Signature. You can create this using the Azure IOT Explorer under "Device Identity" format is
/// "SharedAccessSignature sr=<iotHubName>.azure-devices.net%2Fdevices%2F<deviceName>&sig=<signature>"
/// See "Readme" for more details
string sas = "<Enter SAS Token Here See Read Me for example>";
///////////////////////////////////////////////////////////////////////////////////- Note the format, in particular only keep the SAS token after "SharedAccessSignature"
SharedAccessSignature sr=<iotHubName>.azure-devices.net%2Fdevices%2F<deviceName>&sig=<signature>- Take a look at the user button code. This code sets up pin 0, once it goes to ground (i.e. you press a button) then it triggers the value changed code. See step seven for setting up the button.
// setup user button
_userButton = GpioController.GetDefault().OpenPin(0);
_userButton.SetDriveMode(GpioPinDriveMode.Input);
_userButton.ValueChanged += UserButton_ValueChanged;- Next a URL is created that we will post to it is created by taking values from the SAS token. The worker thread is a loop that will be used to POST your value to Azure IOT Hub once the button is pressed.
//Create the url for the azure iot hub
string url = $"https://{iotHubName}.azure-devices.net/devices/{deviceName}/messages/events?api-version=2020-03-13";
Debug.WriteLine($"Your IOT Hub Name: {iotHubName} and your Device Name: {deviceName}");
Debug.WriteLine($"Performing Http request to: {url}");
//Set the Device Id from our temp class
_temp.DeviceID = deviceName;
WorkerThread(url, sas, rootCACert);- After the URL is created and we state it is a POST. We then add headers with the SAStoken.
// perform the request as a HttpWebRequest
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
// set the headers we are going to pass a json body so use a content type of Json
httpWebRequest.ContentType = "application/json";
// add an Authorization header of our SAS
httpWebRequest.Headers.Add("Authorization", sas);
// this example uses Tls 1.2 with Azure Iot Hub
httpWebRequest.SslProtocols = System.Net.Security.SslProtocols.Tls12;
// use the pem certificate we created earlier
httpWebRequest.HttpsAuthentCert = rootCACert;- It is important to note that certificates for making a HTTPS request are typically saved in your OS. Since this is an embedded device without a full OS these certificates need to be manually added. I took the.pem file from an Azure github sample and created a x.509 cert. If you are doing your own POST or GET using HTTPS you have to include a certificate in NanoFramework!
- We then take the data we want to send (I used a public class of Temp). Serialize it and then convert it to a byte array. Then we have to find the length of it and add that to the http web request. You can NOT send a body in the http web request without a content length.
//we have device name now set the new temperature
_temp.Temperature = temperature.ToString();
// convert the custom class into a serialized Json Object then convert to byte array.
// you must pass in the content length of the body
string output = JsonConvert.SerializeObject(_temp);
byte[] byteArray = Encoding.UTF8.GetBytes(output);
httpWebRequest.ContentLength = byteArray.Length;- To send the data as a POST I used the.GetRequestStream command. Once the stream is created send the data using.Write!
// start a request stream with our headers so we can write our body with the given length
Stream dataStream = httpWebRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
Debug.WriteLine($"The following data was POST to Azure IOT: {output}");- Done! you have sent a stream of data from your embedded device to the cloud! To confirm that it is working I use Azure IoT explorer Telemetry Tab.
- It might take a few resets to get a valid Date & Time on the esp32. If there is no valid date and time the code wont work because there is an expiration date on the https request.












Comments