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

IoT 隨插即用 可讓您與裝置的功能互動,而不需要瞭解基礎裝置實作,即可簡化IoT。 本教學課程說明如何使用 C# 來連線並控制連線至解決方案的 IoT 隨插即用 裝置。

必要條件

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

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

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

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

從適用於 C# 的 Azure IoT SDK GitHub 存放庫複製範例。 在您選擇的資料夾開啟命令提示字元。 執行下列命令以複製 Microsoft Azure IoT SDK for .NET 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 GitHub 的 Microsoft Azure IoT SDK 儲存機制複製到此位置:

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 中樞:

  • 具有 值的IOTHUB_DEVICE_SECURITY_TYPEDPS
  • 具有 DPS 識別碼範圍的IOTHUB_DEVICE_DPS_ID_SCOPE
  • IOTHUB_DEVICE_DPS_DEVICE_ID 值 my-pnp-device
  • 使用註冊主鍵IOTHUB_DEVICE_DPS_DEVICE_KEY。
  • IOTHUB_DEVICE_DPS_ENDPOINT 值 global.azure-devices-provisioning.net

若要深入瞭解範例組態,請參閱 範例自述檔

從 /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 GitHub 存放庫的 Microsoft Azure IoT SDK:

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

執行範例裝置

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

  • 具有 值的IOTHUB_DEVICE_SECURITY_TYPEDPS
  • 具有 DPS 識別碼範圍的IOTHUB_DEVICE_DPS_ID_SCOPE
  • IOTHUB_DEVICE_DPS_DEVICE_ID 值 my-pnp-device
  • 使用註冊主鍵IOTHUB_DEVICE_DPS_DEVICE_KEY。
  • IOTHUB_DEVICE_DPS_ENDPOINT 值 global.azure-devices-provisioning.net

若要深入瞭解範例組態,請參閱 範例自述檔

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

  1. 開啟終端機視窗,並流覽至本機資料夾,其中包含您從 GitHub 複製的 Microsoft Azure IoT SDK for Node.js存放庫。

  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。 請查看 Azure IoT Python SDK 以取得目前的 Python 版本需求。 您可以使用下列命令來檢查 Python 版本:

python --version

您可以從 python.org 下載多個平臺的最新建議版本。

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

pip install azure-iot-device

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

pip install azure-iot-hub

執行範例裝置

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

  • 具有 值的IOTHUB_DEVICE_SECURITY_TYPEDPS
  • 具有 DPS 識別碼範圍的IOTHUB_DEVICE_DPS_ID_SCOPE
  • IOTHUB_DEVICE_DPS_DEVICE_ID 值 my-pnp-device
  • 使用註冊主鍵IOTHUB_DEVICE_DPS_DEVICE_KEY。
  • IOTHUB_DEVICE_DPS_ENDPOINT 值 global.azure-devices-provisioning.net

若要深入瞭解範例組態,請參閱 範例自述檔

在本教學課程中,您會使用以 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 隨插即用 裝置型號,請參閱: