教學課程:與連線至解決方案的IoT 隨插即用裝置互動

IoT 隨插即用讓您無須具備基礎裝置實作的知識,即可與裝置的功能互動,而使 IoT 得以簡化。 本教學課程說明如何使用 C# 來連線及控制連線至解決方案的IoT 隨插即用裝置。

必要條件

在繼續之前,請確定您已設定環境,包括您的 IoT 中樞。

您可以在 Linux 或 Windows 上執行本教學課程。 本教學課程中的殼層命令會遵循路徑分隔符號 '/' 的 Linux 慣例,如果您在 Windows 上遵循,請務必針對 '\' 交換這些分隔符號。

使用範例程式碼複製 SDK 存放庫

如果您已完成教學課程:將 Windows 上執行的範例IoT 隨插即用裝置應用程式連線至 IoT 中樞 (C#) ,您已經複製存放庫。

從適用于 C# 的 Azure IoT SDK GitHub 存放庫複製範例。 在您選擇的資料夾中開啟命令提示字元。 執行下列命令來複製 適用于 .NET 的 Microsoft Azure IoT SDK GitHub 存放庫:

git clone https://github.com/Azure/azure-iot-sdk-csharp.git

建置裝置程式碼

您現在可以建置裝置範例並加以執行。 執行下列命令來建置範例:

cd azure-iot-sdk-csharp/iothub/device/samples/solutions/PnpDeviceSamples/Thermostat
dotnet build

執行裝置範例

若要執行範例,請執行下列命令:

dotnet run

裝置現在已可接收命令和屬性更新,並已開始將遙測資料傳送至中樞。 完成後續步驟後,請讓範例保持執行狀態。

執行範例解決方案

為IoT 隨插即用快速入門和教學課程設定環境中,您已建立兩個環境變數來設定範例以連線到 IoT 中樞:

  • IOTHUB_CONNECTION_STRING:您先前記下的 IoT 中樞連接字串。
  • IOTHUB_DEVICE_ID"my-pnp-device"

在本教學課程中,您會使用以 C# 撰寫的範例 IoT 解決方案,與您剛設定和執行的範例裝置互動。

  1. 在另一個終端機視窗中,流覽至 azure-iot-sdk-csharp/iothub/service/samples/solutions/PnpServiceSamples/Thermostat 資料夾。

  2. 執行下列命令來建置服務範例:

    dotnet build
    
  3. 執行下列命令以執行服務範例:

    dotnet run
    

取得裝置對應項

下列程式碼片段會顯示服務應用程式如何擷取裝置對應項:

// Get a Twin and retrieves model Id set by Device client
Twin twin = await s_registryManager.GetTwinAsync(s_deviceId);
s_logger.LogDebug($"Model Id of this Twin is: {twin.ModelId}");

注意

這個範例會使用 IoT 中樞服務用戶端 中的 Microsoft.Azure.Devices.Client 命名空間。 若要深入了解 API (包括數位對應項 API),請參閱服務開發人員指南

這會程式碼產生下列輸出:

[09/21/2020 11:26:04]dbug: Thermostat.Program[0]
      Model Id of this Twin is: dtmi:com:example:Thermostat;1

下列程式碼片段會示範如何使用「修補程式」,透過裝置對應項來更新屬性:

// Update the twin
var twinPatch = new Twin();
twinPatch.Properties.Desired[PropertyName] = PropertyValue;
await s_registryManager.UpdateTwinAsync(s_deviceId, twinPatch, twin.ETag);

當服務更新 targetTemperature 屬性時,此程式碼會從裝置產生下列輸出:

[09/21/2020 11:26:05]dbug: Thermostat.ThermostatSample[0]
      Property: Received - { "targetTemperature": 60°C }.
[09/21/2020 11:26:05]dbug: Thermostat.ThermostatSample[0]
      Property: Update - {"targetTemperature": 60°C } is InProgress.

...

[09/21/2020 11:26:17]dbug: Thermostat.ThermostatSample[0]
      Property: Update - {"targetTemperature": 60°C } is Completed.

叫用命令

下列程式碼片段示範如何呼叫命令:

private static async Task InvokeCommandAsync()
{
    var commandInvocation = new CloudToDeviceMethod(CommandName) { ResponseTimeout = TimeSpan.FromSeconds(30) };

    // Set command payload
    string componentCommandPayload = JsonConvert.SerializeObject(s_dateTime);
    commandInvocation.SetPayloadJson(componentCommandPayload);

    CloudToDeviceMethodResult result = await s_serviceClient.InvokeDeviceMethodAsync(s_deviceId, commandInvocation);

    if (result == null)
    {
        throw new Exception($"Command {CommandName} invocation returned null");
    }

    s_logger.LogDebug($"Command {CommandName} invocation result status is: {result.Status}");
}

當服務呼叫 getMaxMinReport 命令時,此程式碼會從裝置產生下列輸出:

[09/21/2020 11:26:05]dbug: Thermostat.ThermostatSample[0]
      Command: Received - Generating max, min and avg temperature report since 21/09/2020 11:25:58.
[09/21/2020 11:26:05]dbug: Thermostat.ThermostatSample[0]
      Command: MaxMinReport since 21/09/2020 11:25:58: maxTemp=32, minTemp=32, avgTemp=32, startTime=21/09/2020 11:25:59, endTime=21/09/2020 11:26:04

IoT 隨插即用讓您無須具備基礎裝置實作的知識,即可與裝置的功能互動,而使 IoT 得以簡化。 本教學課程說明如何使用 JAVA 連線至解決方案,以及控制連線至解決方案的IoT 隨插即用裝置。

必要條件

在繼續之前,請確定您已設定環境,包括您的 IoT 中樞。

您可以在 Linux 或 Windows 上執行本教學課程。 本教學課程中的殼層命令會遵循路徑分隔符號 '/' 的 Linux 慣例,如果您在 Windows 上遵循,請務必針對 '\' 交換這些分隔符號。

若要完成本教學課程,請在本機開發環境中安裝下列軟體:

使用範例程式碼複製 SDK 存放庫

如果您已完成教學課程:將 Windows 上執行的範例IoT 隨插即用裝置應用程式連線至 IoT 中樞 (JAVA) ,您已經複製存放庫。

在您選擇的目錄中開啟命令提示字元。 執行下列命令,將適用於 Java 的 Microsoft Azure IoT SDK GitHub 存放庫複製到下列位置:

git clone https://github.com/Azure/azure-iot-sdk-java.git

建置並執行範例裝置

流覽至所複製 JAVA SDK 存放庫中控溫器範例的根資料夾,並加以建置:

cd azure-iot-sdk-java/device/iot-device-samples/pnp-device-sample/thermostat-device-sample
mvn clean package

設定您的環境中,您建立了四個環境變數,以將範例設定為使用裝置佈建服務 (DPS) 來連線到您的 IoT 中樞:

  • 值為 DPSIOTHUB_DEVICE_SECURITY_TYPE
  • 使用 DPS 識別碼範圍的 IOTHUB_DEVICE_DPS_ID_SCOPE
  • 使用值 my-pnp-deviceIOTHUB_DEVICE_DPS_DEVICE_ID
  • 使用註冊主要金鑰的 IOTHUB_DEVICE_DPS_DEVICE_KEY
  • 使用值 global.azure-devices-provisioning.netIOTHUB_DEVICE_DPS_ENDPOINT

若要深入了解範例設定,請參閱範例讀我檔案

/device/iot-device-samples/pnp-device-sample/thermostat-device-sample 資料夾中,執行應用程式:

mvn exec:java -Dexec.mainClass="samples.com.microsoft.azure.sdk.iot.device.Thermostat"

裝置現在已可接收命令和屬性更新,並已開始將遙測資料傳送至中樞。 完成後續步驟後,請讓範例保持執行狀態。

執行範例解決方案

為IoT 隨插即用快速入門和教學課程設定環境中,您已建立兩個環境變數來設定範例以連線到 IoT 中樞:

  • IOTHUB_CONNECTION_STRING:您先前記下的 IoT 中樞連接字串。
  • IOTHUB_DEVICE_ID"my-pnp-device"

在本教學課程中,您會使用以 JAVA 撰寫的範例 IoT 解決方案,與您剛設定的範例裝置互動。

注意

這個範例會使用 IoT 中樞服務用戶端中的 com.microsoft.azure.sdk.iot.service 命名空間。 若要深入了解 API (包括數位對應項 API),請參閱服務開發人員指南

  1. 開啟另一個終端機視窗,作為您的服務終端機。

  2. 在複製的 JAVA SDK 存放庫中,流覽至 service/iot-service-samples/pnp-service-sample/thermostat-service-sample 資料夾。

  3. 若要建置並執行範例服務應用程式,請執行下列命令:

    mvn clean package
    mvn exec:java -Dexec.mainClass="samples.com.microsoft.azure.sdk.iot.service.Thermostat"
    

取得裝置對應項

下列程式碼片段示範如何在服務中擷取裝置對應項:

 // Get the twin and retrieve model Id set by Device client.
DeviceTwinDevice twin = new DeviceTwinDevice(deviceId);
twinClient.getTwin(twin);
System.out.println("Model Id of this Twin is: " + twin.getModelId());

更新裝置對應項

下列程式碼片段會示範如何使用「修補程式」,透過裝置對應項來更新屬性:

String propertyName = "targetTemperature";
double propertyValue = 60.2;
twin.setDesiredProperties(Collections.singleton(new Pair(propertyName, propertyValue)));
twinClient.updateTwin(twin);

裝置輸出會顯示裝置回應此屬性更新的方式。

叫用命令

下列程式碼片段示範如何在裝置上呼叫命令:

// The method to invoke for a device without components should be "methodName" as defined in the DTDL.
String methodToInvoke = "getMaxMinReport";
System.out.println("Invoking method: " + methodToInvoke);

Long responseTimeout = TimeUnit.SECONDS.toSeconds(200);
Long connectTimeout = TimeUnit.SECONDS.toSeconds(5);

// Invoke the command.
String commandInput = ZonedDateTime.now(ZoneOffset.UTC).minusMinutes(5).format(DateTimeFormatter.ISO_DATE_TIME);
MethodResult result = methodClient.invoke(deviceId, methodToInvoke, responseTimeout, connectTimeout, commandInput);
if(result == null)
{
    throw new IOException("Method result is null");
}

System.out.println("Method result status is: " + result.getStatus());

裝置輸出會顯示裝置回應此命令的方式。

IoT 隨插即用讓您無須具備基礎裝置實作的知識,即可與裝置的功能互動,而使 IoT 得以簡化。 本教學課程說明如何使用 Node.js 連線至解決方案,以及控制連線至解決方案的IoT 隨插即用裝置。

必要條件

在繼續之前,請確定您已設定環境,包括您的 IoT 中樞。

若要完成本教學課程,您的開發電腦上必須要有 Node.js。 您可以從 nodejs.org 下載多個平台的最新建議版本。

您可以使用下列命令,以確認開發電腦上目前的 Node.js 版本:

node --version

使用範例程式碼複製 SDK 存放庫

Node SDK 存放庫複製範例。 在您選擇的資料夾中開啟終端機視窗。 執行下列命令,以複製適用於 Node.js 的 Microsoft Azure IoT SDK GitHub 存放庫:

git clone https://github.com/Azure/azure-iot-sdk-node

執行範例裝置

設定您的環境中,您建立了四個環境變數,以將範例設定為使用裝置佈建服務 (DPS) 來連線到您的 IoT 中樞:

  • 值為 DPSIOTHUB_DEVICE_SECURITY_TYPE
  • 使用 DPS 識別碼範圍的 IOTHUB_DEVICE_DPS_ID_SCOPE
  • 使用值 my-pnp-deviceIOTHUB_DEVICE_DPS_DEVICE_ID
  • 使用註冊主要金鑰的 IOTHUB_DEVICE_DPS_DEVICE_KEY
  • 使用值 global.azure-devices-provisioning.netIOTHUB_DEVICE_DPS_ENDPOINT

若要深入了解範例設定,請參閱範例讀我檔案

在本教學課程中,您會使用以 Node.js 撰寫的範例控溫器裝置作為IoT 隨插即用裝置。 若要執行範例裝置:

  1. 開啟終端機視窗,並瀏覽至本機資料夾,此資料夾中包含從 GitHub 複製的適用於 Node.js 存放庫的 Microsoft Azure IoT SDK。

  2. 此終端機視窗會作為您的裝置終端機。 移至複製存放庫的資料夾,然後流覽至 /azure-iot-sdk-node/device/samples/javascript 資料夾。 執行下列命令以安裝所有相依性:

    npm install
    
  3. 使用下列命令來執行範例控溫器裝置:

    node pnp_simple_thermostat.js
    
  4. 您會看到訊息,指出裝置已傳送一些資訊並回報其本身的線上狀態。 這些訊息表示裝置已開始將遙測資料傳送至中樞,且已可接收命令和屬性更新。 請勿關閉此終端機,稍後您將需要用來確認服務範例也已正常運作。

執行範例解決方案

為IoT 隨插即用快速入門和教學課程設定環境中,您已建立兩個環境變數來設定範例以連線到 IoT 中樞:

  • IOTHUB_CONNECTION_STRING:您先前記下的 IoT 中樞連接字串。
  • IOTHUB_DEVICE_ID"my-pnp-device"

在本教學課程中,您會使用範例 Node.js IoT 解決方案與您剛設定和執行的範例裝置互動。

  1. 開啟另一個終端機視窗,作為您的服務終端機。

  2. 在複製的 Node SDK 存放庫中,流覽至 azure-iot-sdk-node/service/samples/javascript 資料夾。 執行下列命令以安裝所有相依性:

    npm install
    

讀取屬性

  1. 當您在裝置終端機中執行範例控溫器裝置時,您會看到下列訊息,指出裝置處於線上狀態:

    properties have been reported for component
    sending telemetry message 0...
    
  2. 移至服務終端機,並使用下列命令執行範例以讀取裝置資訊:

    node twin.js
    
  3. 服務終端機輸出中,請注意裝置對應項的回應。 您會看到已回報裝置的模型識別碼和相關聯的屬性:

    Model Id: dtmi:com:example:Thermostat;1
    {
      "deviceId": "my-pnp-device",
      "etag": "AAAAAAAAAAE=",
      "deviceEtag": "Njc3MDMxNDcy",
      "status": "enabled",
      "statusUpdateTime": "0001-01-01T00:00:00Z",
      "connectionState": "Connected",
      "lastActivityTime": "0001-01-01T00:00:00Z",
      "cloudToDeviceMessageCount": 0,
      "authenticationType": "sas",
      "x509Thumbprint": {
        "primaryThumbprint": null,
        "secondaryThumbprint": null
      },
      "modelId": "dtmi:com:example:Thermostat;1",
      "version": 4,
      "properties": {
        "desired": {
          "$metadata": {
            "$lastUpdated": "2020-10-05T11:35:19.4574755Z"
          },
          "$version": 1
        },
        "reported": {
          "maxTempSinceLastReboot": 31.343640523762232,
          "serialNumber": "123abc",
          "$metadata": {
            "$lastUpdated": "2020-10-05T11:35:23.7339042Z",
            "maxTempSinceLastReboot": {
              "$lastUpdated": "2020-10-05T11:35:23.7339042Z"
            },
            "serialNumber": {
              "$lastUpdated": "2020-10-05T11:35:23.7339042Z"
            }
          },
          "$version": 3
        }
      },
      "capabilities": {
        "iotEdge": false
      },
      "tags": {}
    }
    
  4. 下列程式碼片段顯示 twin.js 中的程式碼,可取出裝置分身的模型識別碼:

    var registry = Registry.fromConnectionString(connectionString);
    registry.getTwin(deviceId, function(err, twin) {
      if (err) {
        console.error(err.message);
      } else {
        console.log('Model Id: ' + twin.modelId);
        //...
      }
      //...
    }
    

在此案例中,會輸出 Model Id: dtmi:com:example:Thermostat;1

注意

這些服務範例會使用 IoT 中樞服務用戶端中的 Registry 類別。 若要深入了解 API (包括數位對應項 API),請參閱服務開發人員指南

更新可寫入屬性

  1. 在程式碼編輯器中開啟檔案 twin.js。

  2. 請參閱範例程式碼,其中會顯示兩種更新裝置對應項的方式。 若要使用第一種方式,請修改 twinPatch 變數,如下所示:

    var twinPatch = {
      tags: {
        city: "Redmond"
      },
      properties: {
        desired: {
          targetTemperature: 42
        }
      }
    };
    

    targetTemperature 屬性會在控溫器裝置型號中定義為可寫入的屬性。

  3. 服務終端機,使用下列命令執行範例以更新屬性:

    node twin.js
    
  4. 在您的裝置終端機中,您會看到裝置已接收更新:

    The following properties will be updated for the default component:
    {
      targetTemperature: {
        value: 42,
        ac: 200,
        ad: 'Successfully executed patch for targetTemperature',
        av: 2
      }
    }
    updated the property
    
  5. 在您的 服務終端機中,執行下列命令以確認屬性已更新:

    node twin.js
    
  6. 服務終端機輸出中,您會在 reported 屬性區段中看到回報的更新目標溫度。 裝置可能需要一段時間才能完成更新。 重複此步驟,直到裝置處理屬性更新為止:

    "reported": {
      //...
      "targetTemperature": {
        "value": 42,
        "ac": 200,
        "ad": "Successfully executed patch for targetTemperature",
        "av": 4
      },
      //...
    }
    

叫用命令

  1. 開啟檔案 device_method.js 並檢閱程式碼。

  2. 移至服務終端機。 使用下列命令來執行範例,以叫用命令:

    set IOTHUB_METHOD_NAME=getMaxMinReport
    set IOTHUB_METHOD_PAYLOAD=commandpayload
    node device_method.js
    
  3. 服務終端機中的輸出應該會顯示下列確認:

    getMaxMinReport on my-pnp-device:
    {
      "status": 200,
      "payload": {
        "maxTemp": 23.460596940801928,
        "minTemp": 23.460596940801928,
        "avgTemp": 23.460596940801928,
        "endTime": "2020-10-05T12:48:08.562Z",
        "startTime": "2020-10-05T12:47:54.450Z"
      }
    }
    
  4. 裝置終端機,您會看到命令已認可:

    MaxMinReport commandpayload
    Response to method 'getMaxMinReport' sent successfully.
    

IoT 隨插即用讓您無須具備基礎裝置實作的知識,即可與裝置的模型互動,而使 IoT 得以簡化。 本教學課程說明如何使用 Python 連線至解決方案,以及控制連線至解決方案IoT 隨插即用裝置。

必要條件

在繼續之前,請確定您已設定環境,包括您的 IoT 中樞。

若要完成此教學課程,您的開發電腦上必須要有 Python 3.7。 您可以從 python.org \(英文\) 下載適用於多個平台的最新建議版本。您可以使用下列命令來檢查 Python 版本:

python --version

在您的本機 Python 環境中,安裝 azure-iot-device 套件,如下所示:

pip install azure-iot-device

執行下列命令安裝 azure-iot-hub 套件:

pip install azure-iot-hub

執行範例裝置

設定您的環境中,您建立了四個環境變數,以將範例設定為使用裝置佈建服務 (DPS) 來連線到您的 IoT 中樞:

  • 值為 DPSIOTHUB_DEVICE_SECURITY_TYPE
  • 使用 DPS 識別碼範圍的 IOTHUB_DEVICE_DPS_ID_SCOPE
  • 使用值 my-pnp-deviceIOTHUB_DEVICE_DPS_DEVICE_ID
  • 使用註冊主要金鑰的 IOTHUB_DEVICE_DPS_DEVICE_KEY
  • 使用值 global.azure-devices-provisioning.netIOTHUB_DEVICE_DPS_ENDPOINT

若要深入了解範例設定,請參閱範例讀我檔案

在本教學課程中,您會使用以 Python 撰寫的範例控溫器裝置作為IoT 隨插即用裝置。 若要執行範例裝置:

  1. 在您選擇的資料夾中開啟終端機視窗。 執行下列命令,將 Azure IoT 裝置 Python SDK GitHub 存放庫複製到此位置:

    git clone --branch v2 https://github.com/Azure/azure-iot-sdk-python
    
  2. 此終端機視窗會作為您的裝置終端機。 移至複製存放庫的資料夾,然後流覽至 azure-iot-sdk-python/samples/pnp 資料夾。

  3. 使用下列命令來執行範例控溫器裝置:

    python simple_thermostat.py
    
  4. 您會看到訊息,指出裝置已傳送一些資訊並回報其本身的線上狀態。 這些訊息表示裝置已開始將遙測資料傳送至中樞,且已可接收命令和屬性更新。 請勿關閉此終端機,稍後您將需要用來確認服務範例也已正常運作。

執行範例解決方案

在本教學課程中,您會使用 Python 中的範例 IoT 解決方案,與您剛設定的範例裝置互動。

  1. 開啟另一個終端機視窗,作為您的服務終端機。 執行下列命令,將 Azure IoT 中樞 Python SDK GitHub 存放庫複製到此位置:

    git clone https://github.com/Azure/azure-iot-hub-python
    
  2. 安裝

  3. 流覽至所複製 Python SDK 存放庫的 /azure-iot-hub-python/samples 資料夾。

  4. 開啟 registry_manager_pnp_sample.py 檔案並檢閱程式碼。 這個範例示範如何使用 IoTHubRegistryManager 類別來與 IoT 隨插即用裝置互動。

注意

這些服務範例會使用 IoT 中樞服務用戶端中的 IoTHubRegistryManager 類別。 若要深入了解 API (包括數位對應項 API),請參閱服務開發人員指南

取得裝置對應項

為IoT 隨插即用快速入門和教學課程設定環境中,您已建立兩個環境變數來設定範例以連線到 IoT 中樞:

  • IOTHUB_CONNECTION_STRING:您先前記下的 IoT 中樞連接字串。
  • IOTHUB_DEVICE_ID"my-pnp-device"

服務終端機中使用下列命令來執行此範例:

set IOTHUB_METHOD_NAME="getMaxMinReport"
set IOTHUB_METHOD_PAYLOAD="hello world"
python registry_manager_pnp_sample.py

注意

如果您是在 Linux 上執行此範例,請使用 export 來取代 set

輸出會顯示裝置對應項,並列印其模型識別碼:

The Model ID for this device is:
dtmi:com:example:Thermostat;1

下列程式碼片段顯示來自 registry_manager_pnp_sample.py 的範例程式碼:

    # Create IoTHubRegistryManager
    iothub_registry_manager = IoTHubRegistryManager(iothub_connection_str)

    # Get device twin
    twin = iothub_registry_manager.get_twin(device_id)
    print("The device twin is: ")
    print("")
    print(twin)
    print("")

    # Print the device's model ID
    additional_props = twin.additional_properties
    if "modelId" in additional_props:
        print("The Model ID for this device is:")
        print(additional_props["modelId"])
        print("")

更新裝置對應項

此範例說明如何更新裝置中的 targetTemperature 可寫入屬性:

    # Update twin
    twin_patch = Twin()
    twin_patch.properties = TwinProperties(
        desired={"targetTemperature": 42}
    )  # this is relevant for the thermostat device sample
    updated_twin = iothub_registry_manager.update_twin(device_id, twin_patch, twin.etag)
    print("The twin patch has been successfully applied")
    print("")

您可以確認更新已套用在顯示下列輸出的裝置終端機中:

the data in the desired properties patch was: {'targetTemperature': 42, '$version': 2}

服務終端機會確認修補程式已成功:

The twin patch has been successfully applied

叫用命令

範例會接著叫用命令:

服務終端機會顯示來自裝置的確認訊息:

The device method has been successfully invoked

裝置終端機中,您會看到裝置收到命令:

Command request received with payload
hello world
Will return the max, min and average temperature from the specified time hello to the current time
Done generating
{"tempReport": {"avgTemp": 34.2, "endTime": "09/07/2020 09:58:11", "maxTemp": 49, "minTemp": 10, "startTime": "09/07/2020 09:56:51"}}

清除資源

如果您已完成快速入門和教學課程,請參閱 清除資源

下一步

在本教學課程中,您已瞭解如何將IoT 隨插即用裝置連線到 IoT 解決方案。 若要深入了解 IoT 隨插即用裝置模組,請參閱: