Share via


快速入門:使用 Bicep 部署 Azure IoT 中樞和記憶體帳戶

在本快速入門中,您會使用 Bicep 建立 IoT 中樞、Azure 儲存體 帳戶,以及將訊息從 IoT 中樞傳送至記憶體的路由。 已設定中樞,以便在訊息符合路由條件時,自動路由傳送至中樞的訊息至記憶體帳戶。 在本快速入門結束時,您可以開啟記憶體帳戶,並查看已傳送的訊息。

Bicep 是使用宣告式語法來部署 Azure 資源的特定領域語言 (DSL)。 其提供簡潔的語法、可靠的類型安全,並支援程式碼重複使用。 Bicep 為 Azure 中的基礎結構即程式代碼解決方案提供最佳撰寫體驗。

必要條件

檢閱 Bicep 檔案

本快速入門中使用的 Bicep 檔案會從 Azure 快速入門範本呼叫101-iothub-auto-route-messages

Bicep 檔案中定義了兩個 Azure 資源:

@description('Define the project name or prefix for all objects.')
@minLength(1)
@maxLength(11)
param projectName string = 'contoso'

@description('The datacenter to use for the deployment.')
param location string = resourceGroup().location

@description('The SKU to use for the IoT Hub.')
param skuName string = 'S1'

@description('The number of IoT Hub units.')
param skuUnits int = 1

@description('Partitions used for the event stream.')
param d2cPartitions int = 4

var iotHubName = '${projectName}Hub${uniqueString(resourceGroup().id)}'
var storageAccountName = '${toLower(projectName)}${uniqueString(resourceGroup().id)}'
var storageEndpoint = '${projectName}StorageEndpont'
var storageContainerName = '${toLower(projectName)}results'

resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {
  name: storageAccountName
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'Storage'
  properties: {
    allowBlobPublicAccess: false
    minimumTlsVersion: 'TLS1_2'
    supportsHttpsTrafficOnly: true
  }
}

resource container 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-01-01' = {
  name: '${storageAccountName}/default/${storageContainerName}'
  properties: {
    publicAccess: 'None'
  }
  dependsOn: [
    storageAccount
  ]
}

resource IoTHub 'Microsoft.Devices/IotHubs@2023-06-30' = {
  name: iotHubName
  location: location
  sku: {
    name: skuName
    capacity: skuUnits
  }
  properties: {
    eventHubEndpoints: {
      events: {
        retentionTimeInDays: 1
        partitionCount: d2cPartitions
      }
    }
    routing: {
      endpoints: {
        storageContainers: [
          {
            connectionString: 'DefaultEndpointsProtocol=https;AccountName=${storageAccountName};EndpointSuffix=${environment().suffixes.storage};AccountKey=${storageAccount.listKeys().keys[0].value}'
            containerName: storageContainerName
            fileNameFormat: '{iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}'
            batchFrequencyInSeconds: 100
            maxChunkSizeInBytes: 104857600
            encoding: 'JSON'
            name: storageEndpoint
          }
        ]
      }
      routes: [
        {
          name: 'ContosoStorageRoute'
          source: 'DeviceMessages'
          condition: 'level="storage"'
          endpointNames: [
            storageEndpoint
          ]
          isEnabled: true
        }
      ]
      fallbackRoute: {
        name: '$fallback'
        source: 'DeviceMessages'
        condition: 'true'
        endpointNames: [
          'events'
        ]
        isEnabled: true
      }
    }
    messagingEndpoints: {
      fileNotifications: {
        lockDurationAsIso8601: 'PT1M'
        ttlAsIso8601: 'PT1H'
        maxDeliveryCount: 10
      }
    }
    enableFileUploadNotifications: false
    cloudToDevice: {
      maxDeliveryCount: 10
      defaultTtlAsIso8601: 'PT1H'
      feedback: {
        lockDurationAsIso8601: 'PT1M'
        ttlAsIso8601: 'PT1H'
        maxDeliveryCount: 10
      }
    }
  }
}

output name string = IoTHub.name
output resourceId string = IoTHub.id
output resourceGroupName string = resourceGroup().name
output location string = location

部署 Bicep 檔案

本節提供部署 Bicep 檔案的步驟。

  1. 從 Azure 快速入門範本存放庫下載 main.bicep 檔案。

  2. 使用 Azure CLI 部署 Bicep 檔案來建立資源。

    az group create --name ContosoResourceGrp --location eastus
    az deployment group create --resource-group exampleRG --template-file main.bicep
    

    部署需要幾分鐘的時間才能完成。 當部署完成時,您應該會看到詳細數據所部署資源的輸出。

傳送裝置到雲端訊息

在本節中,您會在新的IoT中樞註冊裝置,然後將訊息從該裝置傳送至 IoT 中樞。 IoT 中樞中設定的 Bicep 檔案只會在包含訊息屬性 level=storage時傳送訊息至記憶體的路由。 為了測試此路由條件如預期般運作,我們會傳送一些具有該屬性的訊息,有些則沒有。

提示

本快速入門會使用 Azure CLI 模擬裝置來方便使用。 如需使用訊息屬性傳送裝置到雲端訊息的程式代碼範例,請參閱 適用於 .NET 的 Azure IoT SDK 中的 HubRoutingSample

  1. 擷取範本為您建立的IoT中樞名稱。

    如果您在上一節中使用預設命令,您的資源是在 ContosoResourceGrp 資源群組中建立的。 如果您使用不同的資源群組,請更新下列命令以符合。

    az iot hub list --resource-group ContosoResourceGrp --output table
    
  2. 從輸出複製IoT中樞的名稱。 它的格式應該像這樣 contosoHub{randomidentifier}

  3. 將裝置新增至中樞。

    az iot hub device-identity create --device-id contosoDevice --hub-name {YourIoTHubName} 
    
  4. 模擬裝置並傳送裝置到雲端訊息。

    參數 --data 可讓我們設定訊息本文。

    az iot device simulate \
      --device-id contosoDevice \
      --hub-name {YourIoTHubName} \
      --data "This message won't be routed."
    

    模擬器會傳送 100 則訊息,然後中斷連線。 您不需要等候本快速入門的所有 100 個。

    提示

    Azure CLI 不會在傳送訊息時列印訊息。 如果您想要在到達中樞時觀看訊息,您可以安裝適用於Visual Studio Code 的 Azure IoT 中樞 延伸模組,並用它來監視內建端點。

  5. 傳送要路由傳送至記憶體的裝置到雲端訊息。

    參數 --properties 可讓我們將訊息、應用程式或系統屬性新增至預設訊息。 在本快速入門中,IoT 中樞的路由會尋找包含訊息屬性 level=storage的訊息。

    az iot device simulate \
      --device-id contosoDevice \
      --hub-name {YourIoTHubName} \
      --properties level=storage \
      --data "This message will be routed to storage."
    

檢閱路由訊息

  1. 登入 Azure 入口網站 並選取資源群組,然後選取記憶體帳戶。

  2. 向下切入記憶體帳戶,直到您找到檔案為止。

    Look at the storage account files

  3. 選取其中一個檔案,然後選取 [ 下載 ] 並將檔案下載到您稍後可以找到的位置。 其名稱為數值,例如 47。 將 .txt 新增至結尾,然後按兩下檔案加以開啟。

  4. 當您開啟檔案時,每個數據列都是針對不同的訊息。 每個訊息的本文也會加密。 您必須執行查詢,才能對訊息本文執行查詢。

    View the sent messages

    注意

    這些訊息會以UTF-8和base64編碼。 如果您回讀訊息,則必須將它譯碼為base64和utf-8,才能將其讀取為ASCII。 如果您有興趣,您可以使用路由教學課程中的 ReadOneRowFromFile 方法,從其中一個訊息檔案讀取其中一個,並將它譯碼為 ASCII。 ReadOneRowFromFile 位於您針對本快速入門解壓縮的 IoT C# SDK 存放庫中。 以下是該資料夾頂端的路徑: ./iothub/device/samples/how to guides/HubRoutingSample/Program.cs 將布爾值 readTheFile 設定為 true,並將磁碟上的檔案路徑硬式編碼,而且它會開啟並轉譯檔案中的第一個數據列。

在本快速入門中,您已部署 Bicep 檔案來建立 IoT 中樞和記憶體帳戶,然後執行程式以將訊息傳送至中樞。 訊息會根據其訊息屬性路由傳送,並儲存在可檢視的記憶體帳戶中。

清除資源

當您不再需要您所建立的資源時,請刪除資源群組。

az group delete --name exampleRG

下一步