Azure IoT 中級(4)-(案例2)使用DPS通過對稱密鑰進行設備組註冊

Azure IoT 中級(4)-(案例2)使用DPS通過對稱密鑰進行設備組註冊

 

視頻講解:

您可以在B站觀看視頻講解:https://www.bilibili.com/video/av92782084/

 

 

圖文講解:

1. 在DPS添加組註冊:

img-1f1efca6-b390-406e-9684-164efc297c22.png

注意:組註冊中,沒有註冊ID的概念,也沒有Device ID的概念。

機制

有三種:x509證書,對稱密鑰

在本例中,我們使用對稱密鑰方式以便我們快速理解和驗證組註冊的業務邏輯;

密鑰我們採用自動生成,當然也可以手動輸入符合要求的自定義密鑰;

 

注意:本文中使用對稱密鑰方式做演示,後續章節介紹X509證書的方式,證書也是推薦的海量設備方案中應用的方案。

如何分配設備到中心

  1. 最低延遲:將設備預配到具有最低延遲的 IoT 中心,注意最低延遲不是指地理位置,例如中國北部的設備根據網絡情況可能出現分配到中國東部IoT Hub的情況。

  2. 均勻加權分發(默認):鏈接的 IoT 中心等可能地獲得預配到它們的設備。 此設置爲默認設置。 如果只將設備預配到一個 IoT 中心,則可以保留此設置。 

  3. 通過註冊列表進行靜態配置:註冊列表中所需 IoT 中心的規範優先於設備預配服務級別的分配策略。

  4. 使用Azure Function(自定義):該方案可以使用自定義邏輯判斷分發到哪個IoT Hub。

在本例中,我們只配置了一個IoT Hub,因此採用默認的均勻加權即可。

初始設備孿生狀態

例如可以設置版本號爲 1.11,會按照device twin的邏輯進行版本升級;

添加之後的狀態爲:

img-fb3fee95-d723-463e-952d-57445ef29876.png

註冊記錄爲空:

img-77e164ce-e139-407d-8b36-398e90468d27.png

 

2.準備示例代碼

項目中使用的示例代碼,https://codeload.github.com/Azure-Samples/azure-iot-samples-csharp/zip/master

關鍵處請參加如下代碼中的中文註釋:

// Copyright (c) Microsoft. All rights reserved.// Licensed under the MIT license. See LICENSE file in the project root for full license information.using Microsoft.Azure.Devices.Provisioning.Client;using Microsoft.Azure.Devices.Provisioning.Client.Samples;using Microsoft.Azure.Devices.Provisioning.Client.Transport;using Microsoft.Azure.Devices.Shared;using System;using System.Security.Cryptography;using System.Text;namespace SymmetricKeySample{    class Program
    {        // The Provisioning Hub IDScope.

        // For this sample either:
        // - pass this value as a command-prompt argument
        // - set the DPS_IDSCOPE environment variable 
        // - create a launchSettings.json (see launchSettings.json.template) containing the variable
        //private static string s_idScope = Environment.GetEnvironmentVariable("DPS_IDSCOPE");
        private static string s_idScope = "此處需要修改成dps的ID";        // In your Device Provisioning Service please go to "Manage enrollments" and select "Individual Enrollments".
        // Select "Add individual enrollment" then fill in the following:
        // Mechanism: Symmetric Key
        // Auto-generate keys should be checked
        // DeviceID: iothubSymmetricKeydevice1

        // Symmetric Keys may also be used for enrollment groups.
        // In your Device Provisioning Service please go to "Manage enrollments" and select "Enrollment Groups".
        // Select "Add enrollment group" then fill in the following:
        // Group name: <your  group name>
        // Attestation Type: Symmetric Key
        // Auto-generate keys should be checked
        // You may also change other enrollment group parameters according to your needs

       
        //private const string GlobalDeviceEndpoint = "global.azure-devices-provisioning.net";
        //此處應該改成中國的終結點.CN結尾
        private const string GlobalDeviceEndpoint = "global.azure-devices-provisioning.cn";        //These are the two keys that belong to your enrollment group. 
        // Leave them blank if you want to try this sample for an individual enrollment instead
        private const string enrollmentGroupPrimaryKey = "僅當使用組註冊時,必須填寫此值";        private const string enrollmentGroupSecondaryKey = "僅當使用組註冊時,必須填寫此值";        //registration id for enrollment groups can be chosen arbitrarily and do not require any portal setup. 
        //The chosen value will become the provisioned device's device id.
        //
        //registration id for individual enrollments must be retrieved from the portal and will be unrelated to the provioned
        //device's device id
        //
        //This field is mandatory to provide for this sample
        private static string registrationId = "對於組註冊,此處爲待註冊的設備DeviceID,通常填寫諸如MAC地址等唯一值";        //These are the two keys that belong to your individual enrollment. 
        // Leave them blank if you want to try this sample for an individual enrollment instead
        private const string individualEnrollmentPrimaryKey = "";        private const string individualEnrollmentSecondaryKey = "";        public static int Main(string[] args)
        {            if (string.IsNullOrWhiteSpace(s_idScope) && (args.Length > 0))
            {
                s_idScope = args[0];
            }            if (string.IsNullOrWhiteSpace(s_idScope))
            {
                Console.WriteLine("ProvisioningDeviceClientSymmetricKey <IDScope>");                return 1;
            }            string primaryKey = "";            string secondaryKey = "";            if (!String.IsNullOrEmpty(registrationId) && !String.IsNullOrEmpty(enrollmentGroupPrimaryKey) && !String.IsNullOrEmpty(enrollmentGroupSecondaryKey))
            {                //Group enrollment flow, the primary and secondary keys are derived from the enrollment group keys and from the desired registration id
                //注意,此處的primaryKey和secondryKey即IoT Hub中新增Device 的primaryKey和secondryKey
                primaryKey = ComputeDerivedSymmetricKey(Convert.FromBase64String(enrollmentGroupPrimaryKey), registrationId);
                secondaryKey = ComputeDerivedSymmetricKey(Convert.FromBase64String(enrollmentGroupSecondaryKey), registrationId);
            }            else if (!String.IsNullOrEmpty(registrationId) && !String.IsNullOrEmpty(individualEnrollmentPrimaryKey) && !String.IsNullOrEmpty(individualEnrollmentSecondaryKey))
            {                //Individual enrollment flow, the primary and secondary keys are the same as the individual enrollment keys
                primaryKey = individualEnrollmentPrimaryKey;
                secondaryKey = individualEnrollmentSecondaryKey;
            }            else
            {
                Console.WriteLine("Invalid configuration provided, must provide group enrollment keys or individual enrollment keys");                return -1;
            }            using (var security = new SecurityProviderSymmetricKey(registrationId, primaryKey, secondaryKey))            // Select one of the available transports:
            // To optimize for size, reference only the protocols used by your application.
            using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))            // using (var transport = new ProvisioningTransportHandlerHttp())
            // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
            // using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.WebSocketOnly))
            {
                ProvisioningDeviceClient provClient =
                    ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);                var sample = new ProvisioningDeviceClientSample(provClient, security);
                sample.RunSampleAsync().GetAwaiter().GetResult();
            }
            Console.WriteLine("Enter any key to exit");
            Console.ReadLine();            return 0;
        }        /// <summary>
        /// Generate the derived symmetric key for the provisioned device from the enrollment group symmetric key used in attestation
        /// </summary>
        /// <param name="masterKey">Symmetric key enrollment group primary/secondary key value</param>
        /// <param name="registrationId">the registration id to create</param>
        /// <returns>the primary/secondary key for the member of the enrollment group</returns>
        public static string ComputeDerivedSymmetricKey(byte[] masterKey, string registrationId)
        {            using (var hmac = new HMACSHA256(masterKey))
            {                return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(registrationId)));
            }
        }
    }
}

 

3.運行程序,得到分配的IoT Hub名稱以及DeviceID

設備側程序可以得到IoT Hub的名稱設備的ID,加上代碼裏的key,則具備了連接IoT Hub的所有參數,此時可以直接連接到IoT Hub。

img-935443ac-f4ef-4e67-a069-7f0cb0cc70af.png

 

此時,可以在組註冊中的註冊列表中看到對應的註冊記錄:

img-7e83e7ca-cdc9-48fd-9ad0-9c0dc5ba2dfe.png

 

此時,在IoT Hub中能夠看到由DPS註冊過來的Device:

img-e6c4146f-526d-43ae-be8f-dc6103dac5c8.png

 

將代碼中的  private static string registrationId = "對於組註冊,此處爲待註冊的設備DeviceID,通常填寫諸如MAC地址等唯一值"; 替換,可以通過DPS的這個組註冊添加多臺設備到IoT Hub中:

img-473070c3-e021-45df-96bf-601227ce6a25.png


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章