The creation of an Azure IoT Hub is quick and simple, either through the Azure Portal or using PowerShell. But what can get more time-consuming is the registration of IoT Devices with the IoT Hub and generation of SAS Tokens for them for authentication.
In my experiments with micro-controllers and their integration with Azure IoT Services I often find I keep having to manually do tasks that should have just been automated. So I did. In this post I’ll cover using PowerShell to;
- create an Azure IoT Hub
- register an Azure IoT Device
- generate a SAS Token for the IoT Device to use for authentication to an Azure IoT Hub from a Mongoose OS enabled ESP8266 micro controller
Prerequisites
In order to fully test this, ideally you will have a micro-controller. I’m using an ESP8266 based micro-controller like this one. If you want to test this out without physical hardware, you could generate your own DeviceID (any text string) and use the AzureIoT Library detailed further on to send MQTT messages.
You will also require an Azure Subscription. I detail using a Free Tier Azure IoT Hub which is limited to 8000 messages per day. And instead of using PowerShell/PowerShell ISE get/use Visual Studio Code.
Finally you will need the AzureRM and AzureIoT PowerShell modules. With WinRM 5.x you can get them from the PowerShell Gallery with;
install-module AzureRM install-module AzureIoT
Create an Azure IoT Hub
The script below will create a Free Tier Azure IoT Hub. Change the location (line 15) for which Azure Region you will use (the commands on the lines above will list what regions are available), the Resource Group Name that will be created to hold it (line 18) and the name of the IoT Hub (line 23) and let it rip.
From your micro-controller we will need the DeviceID. I’m using the ID generated by the device which I obtained from the Device Configuration => Expert View of my Mongoose OS enabled ESP8266.
Register the IoT Device with our Azure IoT Hub
Using the AzureIoT PowerShell module we can automate the creation/registration of the IoT Device. Update the script below for the name of your IoTHub and the Resource Group that contains it that you created earlier (lines 7 and 11). Update line 21 for the DeviceID or your new IoT Device. I’m using the AzureIoT module to do this. With WinRM 5.x you can install it quickly fromt the gallery with install-module AzureIoT
Looking at our IoTHub in the Azure Portal we can see the newly registered IoT Device.
Generate an IoT Device SAS Token
The final step is to create a SAS Token for our IoT Device to use to connect to the Azure IoTHub. Historically you would use the IoT Device Explorer to do that. Alternatively you can also use the code samples to implement the SAS Device Token generation via an Azure Function App. Examples exist for JavaScript and C#. However as of mid-January 2018 you can do it direct from VS Code or Azure Cloud Shell using the Azure CLI and the IOT Extension. I’m using this method here as it is the quickest and simplest method of generating the Device SAS Token.
The command to generate a token that would work for all Devices on an IoT Hub is
az iot hub generate-sas-token --hub-name
Here I show executing it via the Azure Cloud Shell after installing the IOT Extensions as detailed here. To open the Bash Cloud Shell select the >_ icon next to the notification bell in the right top menu list.
As we have done everything else via PowerShell and VS Code we can also do it easily from VS Code. Install the Azure CLI Tools (v0.4.0 or later in VS Code as detailed here. Then from within VS Code press Control + Shift + P to open the Command Palette and enter Azure: Sign In. Sign in to Azure. Then Control + Shift + P again and enter Azure: Open Bash in Cloud Shell to open a Bash Azure CLI Shell. You can check to see if you have the Azure CLI IOT Extension (if you’ve previously used the Azure CLI for IoT operations) by typing;
az extension show --name azure-cli-iot-ext
and install it if you don’t with;
az extension add --name azure-cli-iot-ext
Then run the same command from VS Code to generate the SAS Token
az iot hub generate-sas-token --hub-name
NOTE: That token can then be used for any Device registered with that IOT Hub. Best practice is to have a token per device. To do that type
az iot hub generate-sas-token --hub-name --device-id
By default you will get a token valid for 1 hour. Use the –duration switch to specify the duration of the token you require for your environment.
We can now take the SAS Token and put it into our MQTT Config on our Mongoose OS IoT Device. Update the Device Configuration using Expert View and Save.
We can then test our IoT Device sending updates to our Azure IoT Hub. Update Init.js using the telemetry sample code from Mongoose.
load('api_config.js'); load('api_mqtt.js'); load('api_sys.js'); load('api_timer.js'); let topic = 'devices/' + Cfg.get('device.id') + '/messages/events/'; Timer.set(1000, true /* repeat */, function() { let msg = JSON.stringify({ ram: Sys.free_ram() }); let ok = MQTT.pub(topic, msg, 1); print(ok, topic, '->', msg); }, null);
We can then see the telemetry being sent to our Azure IOT Hub using MQTT. In the Device Logs after the datestamp and before device/ if you see a 0 instead of 1 (as shown below) then your conenction information or SAS Token is not correct.
On the Auzre IoT side we can then check the metrics and see the incoming telemetry using the counter Telemetry Metrics Sent as shown below.
If you don’t have an IoT Device you can simulate one using PowerShell. The following example shows sending a message to our IoT Hub (using variables from previous scripts).
$deviceParams = @{ iotConnString = $IoTConnectionString deviceId = $deviceID } $deviceKeys = Get-IoTDeviceKey @deviceParams # Get Device $device = Get-IoTDeviceClient -iotHubUri $IOTHubDeviceURI -deviceId $deviceID -deviceKey $deviceKeys.DevicePrimaryKey # Send Message $deviceMessageParams = @{ deviceClient = $device messageString = "Azure IOT Hub" } Send-IoTDeviceMessage -deviceClient $deviceMessageParams
Summary
Using PowerShell we have quickly been able to;
- Create an Azure IoT Hub
- Register an IoT Device
- Generate the SAS Token for the IoT Device to authenticate to our IoT Hub with
- Configure our IoT Device to send telemetry to our Azure IoT Hub and verify integration/connectivity
We are now ready to implement logic onto our IoT Device for whatever it is you are looking to achieve.