Sending Data to Azure IoT Hub via MQTT with Gravio (CreateRecord)

In this post, we will explore using Gravio to publish temperature sensor data to Azure IoT Hub via the MQTT protocol. 

_This post will use the [CreateRecord](https://doc.gravio.com/manuals/gravio-setup-guide/1/en/topic/createrecord-action-component) component. A [sibling post](https://qiita.com/0xNF/items/fbcd2da7bebeffff2498) does the same thing with the [SensorDataDb](https://doc.gravio.com/manuals/gravio-setup-guide/1/en/topic/sensordb-recent) component._

![Data flow from our sensor to Azure](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/5ac0226d-d687-8b72-bf2e-58ab7c34c413.png)

# Prerequisites
## Hardware

Windows 10 (minimum version 1809)
Gravio Client Sensor (e.g., [Temperature Sensor](https://www.gravio.com/sensor-setup-guide))

## Software
[Gravio](https://www.gravio.com/product)
* Gravio Studio (minimum version 3.8)
* Gravio Server (minimum version 3.8)
[Azure IoT Explorer](https://github.com/Azure/azure-iot-explorer/releases)
* This tutorial is using version 0.10.18 (Preview)

# Azure IoT Hub Setup
## Resource Creation
First we need to create an _IoT Hub Resource_ in Azure.
![Create an IoT Hub Resource](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/35f79734-32b2-ce8d-bacb-ea1b7bd747e5.png)

### Resource Assignment
We need to fill in some required information. You can consult the following table for the values we will use:

|Item|Value|
-----|-----
Subscription|Pay as you go
Resource Group|Your choice of group. If none, create a new one
Region|Your choice of region. This tutorial will use `East US`
IoT Hub Name|Your choice of name. This tutorial will use `gravio-demo`.

![Azure IoT Hub Resources](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/eccd268c-1fe6-d261-036d-1dac98b7bd9b.png)

### Network Settings
Next we will select the network settings. Make sure that `Public Endpoint` is selected.
![Azure IoT Hub Network Settings](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/f5184236-1779-dc3d-5b8c-a141192bd743.png)

### Size and Scale
Select `F1: Free Tier`
![Azure IoT Hub Size and Scale Settings](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/63717259-739d-b9b5-d46d-a773a15d2c37.png)
### Tags
Any tags you want can be added here. This is an optional step. We're using `GravioDemo:TemperatureSensorDemo`.
![Azure IoT Hub Tags Settings](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/979433ba-3b3e-e2b1-791f-577f8d4240a6.png)

### Review and Create
Review the settings before creating our new IoT Hub.
![Azure IoT Hub Review](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/85668eec-77e1-63ea-4df0-29664558d49c.png)

### Deployment in Progress
After clicking `Create`, you may have to wait a few minutes while Azure provisions your new resource:
![Azure IoT Hub Deployment in Progress](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/e8ac1d0d-d03b-8171-de8d-d610f16dfad3.png)

### Deployment Complete
Once the deployent finishes, click on `Go to resource`
![Azure IoT Hub Deployment Complete](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/a53c0193-5683-31e3-2607-d8176509d373.png)

## Device Assignment
Click on `IoT Devices`, then `+ New` to create a new IoT Device linked to this IoT Hub:

![Azure Device Creation](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/b91dc9df-c1e3-6eac-c5f5-794bf3a3ddb6.png)

## Device Creation
The choice of name for your new device is up to you. We will use `TemperatureSensor`. Leave the default choices as is: 

|Item|Value|
|-----|-----|
|Authentication Type|Symmetric key|
|Auto-Generate Keys|Checked|
|Connect this device to an IoT Hub|Enable|

![Azure Device Access Settings](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/05058248-f4f5-99b0-57c4-596fd0452ac2.png)

## Access Settings

From the side menu, select `Shared access policies`, click `iothubowner`, and copy the `Connection string - primary key` field:

![Azure IoT Hub Connection String](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/08a4d6ab-3032-6f37-26e9-54e412880328.png)

We'll use this connection string in the following section.

# Azure IoT Explorer

## Connect to the IoT Hub
Using the Azure IoT Explorer, paste in the connection string from earlier, then connect to the IoT Hub.
![Explorer Connection](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/4abb5b1f-7e96-b9a9-1b2b-a8cd06785893.png)


## Select the IoT Device
Select the IoT Device we made earlier.
![Explorer Device Selection](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/e345f5fa-f688-8e9b-7003-efab11bb795e.png)

## SAS Token Acquisition
Select `Device Identity` and scroll down to `Connection string with SAS Token`. We'll use the following settings:

|Item|Value|
|-----|-----|
|Symmetric Key|Primary key|
|Expiration (minutes)|Your choice. Default is `5`, this tutorial will use `60`.|

Then click `Generate`. 

![Explorer SAS Token Generation](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/a25fd2c9-262c-4c85-4eca-23cc9f994d63.png)

The generated key will look like this.
```HostName=gravio-iot-demo.azure-devices.net;DeviceId=TemperatureSensor;SharedAccessSignature=
SharedAccessSignature sr=gravio-iot-demo.azure-devices.net%2Fdevices%2FTemperatureSensor&sig=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%3D&se=1591932352```


The important part is the highlighted section:
`SharedAccessSignature sr=gravio-iot-demo.azure-devices.net%2Fdevices%2FTemperatureSensor&sig=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%3D&se=1591932352`

This is the actual SAS Token. Keep this token in mind for the next section.

**Be aware that these keys have a limited lifetime. You will need to regenerate them frequently!**
## Live Monitoring of Data
Click the `Telemetry` tab, then `Start` to begin monitoring data sent to our IoT Device. In the next section, we will set up Gravio to send data to this device.
![Explorer Telemetry View](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/1733d7e5-9d90-e0e1-0741-bf31def0ebd8.png)






# Gravio Setup
Now we can begin to use Gravio to send data over to Azure.

## Sensor Setup
For pairing and setting up the sensor in Gravio, please refer to this article:
[Setting up a temperature sensor to send data to Excel with Gravio (Japanese)](https://qiita.com/mikawan/items/3d93543566680afda868#step1%E3%82%BB%E3%83%B3%E3%82%B5%E3%83%BC%E3%81%AE%E8%A8%AD%E5%AE%9A)

## Action Setup
Our action will use the single most recent record from the CreateRecord component.

On the Action Creation screen, we'll use the following component flow:

CreateRecord > MQTTPublish

### (1) CreateRecord
The create record component is an unusual component because it has no properties. Its use is to create and propagate a record to another component. You can think of it as a plumbing component

### Step Variable Creation
We'll send over a subset of the data recorded by the sensor: 

1. The actual Sensor Data (av.Data)
2. the area the sensor is located in (av.AreaName)
3. the timestamp of the recording (av.Timestamp)

![Add Step Variables to CreateRecord](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/ae94a505-1b28-0f3f-6115-490c40147cd8.png)


Create the following variables under Step Results:

|Output Field Name|Type|Expression Formula|
|-----------------|----|------------------|
|Area|String|av.AreaName|
|Data|Int|av.Data|
|Timestamp|Datetime|av.Timestamp|

For `Data`, you can set the `Type` to `Int` if you want the mqtt service to record sensor data as numeric.

![Set Data to type int](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/e96a81d4-4827-54f6-846f-f90f7a37bb7d.png)

After you finish, you should have 3 Step Variables that look like this:

![Completed Step Variables for the CreateRecord Component](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/78ed43c9-df6b-8ee0-ee8d-7c4bd2e10e9b.png)


That's all we need to do to set up the SendRecord component.

### (2) MQTTPublish
#### Property Setup
We'll use the following settings for our MQTT Publish component:

NB: The quotes around some fields (`""`) are not optional and must be included.

|Property|Description|Example|
|--------|-----------|-----|
|Broker Hostname|IoT Hub Hostname|<span>gravio-iot-demo.azure-devices.net</span>|
|Broker Port||8883|
|Client ID|Device Id|TemperatureSensor|
|MQTT Username|"\<IoT Hub Hostname>/\<Device ID>/api-version=2019-03-31"|"<span>gravio-iot-demo.azure-devices.net/TemperatureSensor/api-version=2019-03-31</span>"|
|MQTT Password|The generated SAS Token|SharedAccessSignature sr=gravio-iot-demo.azure-devices.net%2Fdevices%2FTemperatureSensor&sig=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%3D&se=1591932352|
|Topic|"devices/\<Device ID>/messages/events"|"devices/TemperatureSensor/messages/events"|
|Data Format||JSON|
|QoS|Anything below QoS2|QoS 1 (At most once)|
|Secure Connection||Checked|
|Client Certificate File*|||
|Client Certificate Password*|||
|CA Certificate File*|||
\* Leave blank


After setting up the properties, the component screen should look like this:

![Gravio MQTT Creation](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/7d05ec4b-38e6-effb-18bc-0430908cd415.png)


#### Step Results
Because this is an Output type component, we must set the data to send to the next component. In our case, there is no next component. Nevertheless, this step is still required.

This time, instead of copying from `Step Variables`, we'll copy from `Step InFields`:

![Gravio MQTT Step Results](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/65322fc5-8edb-d3fe-6995-5561a9063bab.png)



## Running the Action
Click the Run button to run the component. If things were set up properly, we should have a successfully run action:

![Gravio Action Results](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/96aab19a-b2f1-539c-c93f-39df2e7a9d8d.png)

# Viewing the Data
Going back to the Telemetry view of the Azure IoT Explorer, we can see the data that was sent to it:

![Explorer Result Viewing](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/9bdabd42-3e9b-d802-811d-cd473c6dd2f6.png)


# Automatic Trigger Settings
## Settings
We'll set up a Trigger to send sensor data to our MQTT service whenever new data is received by the temperature sensor.

Here's the basic settings we'll use:

|Property|Value|
|-----|-----|
|Area|Demo*|
|Layer|Temperature*|
|Action Name|MQTT Test*|
|Interval|5|
|Use Threshold Trigger|Unchecked|
|Temperture|Any 0|
\* Use whatever area and layer has your Temperature sensor, as well the name of whatever action you created earlier.

![Trigger Property Setup](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/cdcb9be8-08bb-2283-22fd-a46a4ce52340.png)

## Enable the Trigger

Make sure to enable the trigger after creating it:

![Trigger Enabling](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/597474/cc005098-a274-8e1b-4ab7-730bd9e45440.png)


# Trigger Confirmation

Using the Azure IoT Explorer's telemetry screen from before, you can see the the data being sent to the IoT Hub.

The trigger is configured to send all data it records to the MQTT service.  

# Conclusion

Gravio makes it easy to send data to services like Microsoft Azure, even for relative newcomers to both technologies.