Share via


Azure: Create an IoT Hub and connect your IoT Device

In this article, we will show you how to create an IoT Hub and connect your IoT Device.

Pre-requisites

Steps:

Verify you properly setup your IoT Device Connectivity

please refer to https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/using-arduino-ide

Create an IoT Hub

Now you will create an IoT Hub in the Azure Portal. Go to the Azure Portal, click Create new and type “iot hub”:

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfb573931ef.png

Now provide the following parameters to create your IoT Hub: 

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfb5c7cb626.png

Verify the IoT Hub is successfully created: 

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfb61a92802.png

NG the Shared Access Policies  

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfb6c8a0084.png

Click Shared Access Policies,

Select “iothubowner” and enable “registry write” and copy the Shared access keys:

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfb72b606fb.png

 Go back to your desktop and open the Device Explorer Twin,

If not already installed, install (https://github.com/Azure/azure-iot-sdkcsharp/releases/download/2017-10-23/SetupDeviceExplorer.msi ) and run the Device Explorer: 

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfb7dd25533.png

Provide a name for your IoT Device

Select the Management label and Click on Create Device, provide a name for your IoT Device and then paste the Shared Access Credentials you previously copied:

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfb80e82a84.png

You will see a notification when the device is successfully created: 

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfb9089abc8.png

Copy connection string for the selected device

  9. In the Management label, right-click the device you just created and click “Copy connection string for the selected device” 

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfb95bf26ca.png

 Launch Arduino.

You can download it from here:

https://www.arduino.cc/download_handler.php?f=/arduino-1.8.5-windows.exe .

 

Add the Microsoft IoT and Arduino libraries by clicking Sketch -> Include Library à-> Manage Libraries and search for “AzureIoT”. Install the library AzureIoTHub by Arduino, the AzureIoTProtocol_MQTT by Microsoft and AzureIoTUtility by Microsoft, as shown below.

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/arduino-include-library-wikiazure.png

Starting with a new sketch, copy the following code:

#include <ESP8266WiFi.h>
#include <ESP8266WiFiAP.h>
#include <ESP8266WiFiGeneric.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WiFiScan.h>
#include <ESP8266WiFiSTA.h>
#include <ESP8266WiFiType.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiServer.h>
  
#include <AzureIoTUtility.h>
#include <AzureIoTHub.h>
#include <AzureIoTProtocol_MQTT.h>
  
#include <DHT.h>
  
String ssid                         = "iot";         // your network SSID (name)
String pass                         = "microsoft";   // your network password (use for WPA, or use as key for WEP)
static const  char* connectionString = "HostName=daveiotdemo1.azure-devices.net;DeviceId=daveie;SharedAccessKey=1298128GASJDA12=";
#define DHTPIN 2                                   // what digital pin we're connected to
#define DHTTYPE DHT22                               // DHT11 or DHT22
  
IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;
IOTHUB_CLIENT_STATUS status;
  
WiFiClientSecure espClient;
  
DHT dht(DHTPIN, DHTTYPE);
  
void initWifi() {
    if (WiFi.status() != WL_CONNECTED) 
    {
        WiFi.stopSmartConfig();
        WiFi.enableAP(false);
  
        // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
        WiFi.begin(ssid.c_str(), pass.c_str());
      
        Serial.print("Waiting for Wifi connection.");
        while (WiFi.status() != WL_CONNECTED) {
            Serial.print(".");
            delay(500);
        }
      
        Serial.println("Connected to wifi");
  
        initTime();
        initIoTHub();
    }
}
  
void initTime() {
    time_t epochTime;
  
    configTime(0, 0, "pool.ntp.org", "time.nist.gov");
  
    while (true) {
        epochTime = time(NULL);
  
        if (epochTime == 0) {
            Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry.");
            delay(2000);
        } else  {
            Serial.print("Fetched NTP epoch time is: ");
            Serial.println(epochTime);
            break;
        }
    }
}
  
static void  sendMessage(const  char* message)
{
    static unsigned int messageTrackingId;
    IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromString(message);
  
    if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendMessageCallback, (void*)(uintptr_t)messageTrackingId) != IOTHUB_CLIENT_OK)
    {
        Serial.println(" ERROR: Failed to hand over the message to IoTHubClient");
    }
    else
    {
      (void)printf(" Message Id: %u Sent.\r\n", messageTrackingId);
    }
  
    IoTHubMessage_Destroy(messageHandle);
    messageTrackingId++;
}
  
void sendMessageCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
{
    unsigned int  messageTrackingId = (unsigned int)(uintptr_t)userContextCallback;
  
    (void)printf(" Message Id: %u Received.\r\n", messageTrackingId);
}
  
static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessageCallback(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback)
{
    IOTHUBMESSAGE_DISPOSITION_RESULT result = IOTHUBMESSAGE_ACCEPTED;
      
    const char* messageId = "UNKNOWN";      // in case there is not a messageId associated with the message -- not required
    messageId = IoTHubMessage_GetMessageId(message);
  
    const unsigned char* buffer;
    size_t size;
    if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK)
    {
        Serial.println(" Error: Unable to IoTHubMessage_GetByteArray");
        result = IOTHUBMESSAGE_ABANDONED;
    }
    else
    {
        char* tempBuffer = (char*)malloc(size + 1);
        if (tempBuffer == NULL)
        {
            Serial.println(" Error: failed to malloc");
            result = IOTHUBMESSAGE_ABANDONED;
        }
        else
        {
            result = IOTHUBMESSAGE_ACCEPTED;
            (void)memcpy(tempBuffer, buffer, size);
              
            String messageStringFull((char*)tempBuffer);
            String messageString = "UNKNOWN";
            messageString = messageStringFull.substring(0,size);
  
/*            if (messageString.startsWith("OTA")) {
                  String fullURL = messageString.substring(messageString.indexOf("://") - 4);;
                  // t_httpUpdate_return OTAStatus = OTA.update(fullURL.c_str());
                  // if we do OTA, then we never return the IOTHUBMESSAGE_ACCEPTED and we have issues
            }*/
              
            String messageProperties = "";
            MAP_HANDLE mapProperties = IoTHubMessage_Properties(message);
            if (mapProperties != NULL)
            {
            const char*const* keys;
            const char*const* values;
            size_t propertyCount = 0;
            if (Map_GetInternals(mapProperties, &keys, &values, &propertyCount) == MAP_OK)
                {
                if (propertyCount > 0)
                    {
                    size_t index;
                    for (index = 0; index < propertyCount; index++)
                        {
                            messageProperties += keys[index];
                            messageProperties += "=";
                            messageProperties += values[index];
                            messageProperties += ",";
                        }
                    }
                }
            }
  
            Serial.print(" Message Id: ");
            Serial.print(messageId);
            Serial.print(" Received. Message: \"");
            Serial.print(messageString);
            Serial.print("\", Properties: \"");
            Serial.print(messageProperties);
            Serial.println("\"");
        }
        free(tempBuffer);
    }
    return result;
}
  
void initIoTHub() {
  iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol);
  if (iotHubClientHandle == NULL)
  {
      (void)printf("ERROR: Failed on IoTHubClient_LL_Create\r\n");
  } else  {
    IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessageCallback, NULL);
  }
}
  
void LEDOn() {
  digitalWrite(LED_BUILTIN, LOW);
}
  
void LEDOff() {
  digitalWrite(LED_BUILTIN, HIGH);
}
  
void setup() {
  Serial.begin(115200);
  dht.begin();
  initWifi();
  pinMode(LED_BUILTIN, OUTPUT);
  LEDOff();
}
  
void loop() {
  initWifi();         // always checking the WiFi connection
  LEDOn();
  
  // we will process every message in the Hub
  while ((IoTHubClient_LL_GetSendStatus(iotHubClientHandle, &status) == IOTHUB_CLIENT_OK) && (status == IOTHUB_CLIENT_SEND_STATUS_BUSY))
  {
      IoTHubClient_LL_DoWork(iotHubClientHandle);
      ThreadAPI_Sleep(1000);
  }
    
  String  JSONMessage = "{\'temperature\':";
          JSONMessage += dht.readTemperature();
          JSONMessage += "}";
  sendMessage(JSONMessage.c_str());  
  
  LEDOff();
  delay(5000);
}
Modify the SSID, password, and connectionString on lines 18 – 20 as  shown below and click “Compile and Upload”:
String ssid                         = "iot";         // your network SSID (name)
String pass                         = "microsoft";   // your network password (use for WPA, or use as key for WEP)
static const  char* connectionString = "HostName=daveiotdemo1.azure-devices.net;DeviceId=daveie;SharedAccessKey=1298128GASJDA12=";

Go back to the Device Explorer.

Click Message To Device. Type a message, add any desired properties and click Send, as shown below:

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/Iot-Message-to-device-wikiazure.png

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfbea51ab9f.png

Tried to take a closer picture of the device in case you want to validate your sensor connectivity:

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfbf46d5839.png

Using Serial Monitor, you should be able to look the Humidity Percentage, temperature in °C and °F:

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfbd81a9e01.png

You should also be able to monitor the messages through Serial Monitor as shown below:

https://wikiazure.azureedge.net/wp-content/uploads/2018/03/img_5abfbb095fbe4.png

This completes the article on how to Create an IoT Hub and connect your IoT Device. 

Conclusion 

Azure provides a robust platform for IoT with seamless integration and a diversity of hardware providers certified to enable IoT solutions in a seamless way. 

Other Languages: