使用 Azure IoT Edge 发布和订阅Publish and subscribe with Azure IoT Edge

可以使用 Azure IoT Edge MQTT 中转站发布和订阅消息。You can use Azure IoT Edge MQTT broker to publish and subscribe messages. 本文介绍如何连接到此代理,如何针对用户定义的主题发布和订阅消息,以及如何使用 IoT 中心消息传送基元。This article shows you how to connect to this broker, publish and subscribe to messages over user-defined topics, and use IoT Hub messaging primitives. IoT Edge MQTT 中转站内置于 IoT Edge 中心。The IoT Edge MQTT broker is built-in the IoT Edge hub. 有关详细信息,请参阅 IoT Edge 中心的中转站功能For more information, see the brokering capabilities of the IoT Edge hub.

备注

IoT Edge MQTT 中转站目前提供公开预览版。IoT Edge MQTT broker is currently in public preview.

先决条件Pre-requisites

  • 含有效订阅的 Azure 帐户An Azure account with a valid subscription

  • 安装了 azure-iot CLI 扩展的 Azure CLIAzure CLI with the azure-iot CLI extension installed. 有关详细信息,请参阅 Azure Azure CLI 的 Azure IoT 扩展安装步骤For more information, see the Azure IoT extension installation steps for Azure Azure CLI.

  • SKU 的 IoT 中心(F1、S1、S2 或 S3)。An IoT Hub of SKU either F1, S1, S2 or S3.

  • 拥有版本 1.2 或更高版本的 IoT Edge 设备。Have an IoT Edge device with version 1.2 or above. 由于 IoT Edge MQTT 中转站当前处于公共预览状态,请在 edgeHub 容器上将以下环境变量设置为 true 以启用 MQTT 中转站:Since IoT Edge MQTT broker is currently in public preview, set the following environment variables to true on the edgeHub container to enable the MQTT broker:

    “属性”Name “值”Value
    experimentalFeatures__enabled true
    experimentalFeatures__mqttBrokerEnabled true
  • 已在 IoT Edge 设备上安装 Mosquitto 客户端。Mosquitto clients installed on the IoT Edge device. 本文使用常用的 Mosquitto 客户端 MOSQUITTO_PUBMOSQUITTO_SUBThis article uses the popular Mosquitto clients MOSQUITTO_PUB and MOSQUITTO_SUB. 可以改用其他 MQTT 客户端。Other MQTT clients could be used instead. 若要在 Ubuntu 设备上安装 Mosquitto 客户端,请运行以下命令:To install the Mosquitto clients on an Ubuntu device, run the following command:

    sudo apt-get update && sudo apt-get install mosquitto-clients
    

    请勿安装 Mosquitto 服务器,因为它可能会导致 MQTT 端口(8883 和 1883)阻塞并与 IoT Edge 中心发生冲突。Do not install the Mosquitto server since it may cause blocking the MQTT ports (8883 and 1883) and conflict with the IoT Edge hub.

连接到 IoT Edge 中心Connect to IoT Edge hub

连接到 IoT Edge 中心遵循与使用通用 MQTT 客户端连接到 IoT 中心一文IoT Edge 中心的概念说明一文中描述的相同步骤。Connecting to IoT Edge hub follows the same steps as described in the connecting to IoT Hub with a generic MQTT client article or in the conceptual description of the IoT Edge hub article. 这些步骤包括:These steps are:

  1. 或者,MQTT 客户端使用传输层安全性 (TLS) 与 IoT Edge 中心建立安全连接Optionally, the MQTT client establishes a secure connection with the IoT Edge hub using Transport Layer Security (TLS)
  2. MQTT 客户端向 IoT Edge 中心进行自身验证The MQTT client authenticates itself to IoT Edge hub
  3. IoT Edge 中心根据其授权策略对 MQTT 客户端进行授权The IoT Edge hub authorizes the MQTT client per its authorization policy

安全连接 (TLS)Secure connection (TLS)

传输层安全性 (TLS) 用于在客户端和 IoT Edge 中心之间建立加密通信。Transport Layer Security (TLS) is used to establish an encrypted communication between the client and the IoT Edge hub.

若要禁用 TLS,请使用端口 1883 (MQTT) 并将 edgeHub 容器绑定到端口 1883。To disable TLS, use port 1883(MQTT) and bind the edgeHub container to port 1883.

若要启用 TLS,如果客户端通过端口 8883 (MQTTS) 连接到 MQTT 代理,则将会启动一个 TLS 通道。To enable TLS, if a client connects on port 8883 (MQTTS) to the MQTT broker, a TLS channel will be initiated. 中转站发送客户端需要验证的证书链。The broker sends its certificate chain that the client needs to validate. 为了验证证书链,MQTT 中转站的根证书必须作为受信任的证书安装在客户端上。In order to validate the certificate chain, the root certificate of the MQTT broker must be installed as a trusted certificate on the client. 如果根证书不受信任,则 MQTT 中转站将拒绝客户端库,并出现证书验证错误。If the root certificate is not trusted, the client library will be rejected by the MQTT broker with a certificate verification error. 在客户端上安装中转站的该根证书的步骤与透明网关案例中的步骤相同,并在准备下游设备文档中进行了描述。The steps to follow to install this root certificate of the broker on the client are the same as in the transparent gateway case and are described in the prepare a downstream device documentation.

身份验证Authentication

若要使 MQTT 客户端进行自身身份验证,它首先需要向 MQTT 代理发送 CONNECT 数据包,以便用它的名称来启动连接。For an MQTT client to authenticate itself, it first needs to send a CONNECT packet to the MQTT broker to initiate a connection in its name. 此数据包提供三条身份验证信息:client identifierusernamepasswordThis packet provides three pieces of authentication information: a client identifier, a username, and a password:

  • client identifier 字段是 IoT 中心内设备的名称或模块名称。The client identifier field is the name of the device or module name in IoT Hub. 它使用以下语法:It uses the following syntax:

    • 对于设备:<device_name>For a device: <device_name>

    • 对于模块:<device_name>/<module_name>For a module: <device_name>/<module_name>

    为了连接到 MQTT 中转站,必须在 IoT 中心中注册设备或模块。In order to connect to the MQTT broker, a device or a module must be registered in IoT Hub.

    该代理不允许来自使用相同凭据的多个客户端的连接。The broker won't allow connections from multiple clients using the same credentials. 如果第二个客户端使用相同的凭据进行连接,则中转站将断开已连接的客户端。The broker will disconnect the already connected client if a second client connects using the same credentials.

  • username 字段使用以下语法从设备/模块名称和设备所属的 IoTHub 名称派生:The username field is derived from the device or module name, and the IoTHub name the device belongs to using the following syntax:

    • 对于设备:<iot_hub_name>.azure-devices.net/<device_name>/?api-version=2018-06-30For a device: <iot_hub_name>.azure-devices.net/<device_name>/?api-version=2018-06-30

    • 对于模块:<iot_hub_name>.azure-devices.net/<device_name>/<module_name>/?api-version=2018-06-30For a module: <iot_hub_name>.azure-devices.net/<device_name>/<module_name>/?api-version=2018-06-30

  • CONNECT 数据包的 password 字段取决于身份验证模式:The password field of the CONNECT packet depends on the authentication mode:

    • 在使用对称密钥身份验证时,password 字段是 SAS 令牌。When using symmetric keys authentication, the password field is a SAS token.
    • 在使用 X.509 自签名身份验证时,password 字段不存在。When using X.509 self-signed authentication, the password field is not present. 在此身份验证模式下,需要一个 TLS 通道。In this authentication mode, a TLS channel is required. 客户端需要连接到端口 8883 以建立 TLS 连接。The client needs to connect to port 8883 to establish a TLS connection. 在 TLS 握手期间,MQTT 中转站请求客户端证书。During the TLS handshake, the MQTT broker requests a client certificate. 此证书用于验证客户端的身份,因此在发送 CONNECT 数据包时不需要 password 字段。This certificate is used to verify the identity of the client and thus the password field is not needed later when the CONNECT packet is sent. 同时发送客户端证书和密码字段将导致错误,且连接将关闭。Sending both a client certificate and the password field will lead to an error and the connection will be closed. MQTT 库和 TLS 客户端库通常可以在启动连接时发送客户端证书。MQTT libraries and TLS client libraries usually have a way to send a client certificate when initiating a connection. 你可以在 使用 X509 证书进行客户端身份验证部分中查看分步示例。You can see a step-by-step example in section Using X509 Certificate for client authentication.

通过 IoT Edge 部署的模块使用对称密钥身份验证,并且可以调用本地 IoT Edge 工作负载 API 以编程方式获取 SAS 令牌,即使脱机时也是如此。Modules deployed by IoT Edge use symmetric keys authentication and can call the local IoT Edge workload API to programmatically get a SAS token even when offline.

授权Authorization

在 MQTT 客户端向 IoT Edge 中心进行身份验证后,它需要获得授权才能进行连接。Once an MQTT client is authenticated to IoT Edge hub, it needs to be authorized to connect. 连接后,它需要获得授权才可针对特定主题进行发布或订阅。Once connected, it needs to be authorized to publish or subscribe on specific topics. 这些授权由 IoT Edge 中心根据其授权策略授予。These authorizations are granted by the IoT Edge hub based on its authorization policy. 授权策略是一组以 JSON 结构表示的语句,通过其孪生体发送到 IoT Edge 中心。The authorization policy is a set of statements expressed as a JSON structure that is sent to the IoT Edge hub via its twin. 编辑 IoT Edge 中心孪生体以配置其授权策略。Edit an IoT Edge hub twin to configure its authorization policy.

备注

对于公共预览版,只有通过 Visual Studio、Visual Studio Code 或 Azure CLI 才能编辑 MQTT 代理的授权策略。For the public preview, the editing of authorization policies of the MQTT broker is only available via Visual Studio, Visual Studio Code, or the Azure CLI. Azure 门户目前不支持编辑 IoT Edge 中心孪生体及其授权策略。The Azure portal currently does not support editing the IoT Edge hub twin and its authorization policy.

每个授权策略语句由 identitiesallowdeny 效果、operationsresources 的组合构成:Each authorization policy statement consists of the combination of identities, allow or deny effects, operations, and resources:

  • identities 描述策略的主题。identities describe the subject of the policy. 它必须映射到客户端在其 CONNECT 数据包中发送的 client identifierIt must map to the client identifier sent by clients in their CONNECT packet.
  • allowdeny 效果定义是允许还是拒绝操作。allow or deny effects define whether to allow or deny operations.
  • operations 定义要授权的操作。operations define the actions to authorize. mqtt:connectmqtt:publishmqtt:subscribe 是目前支持的三种操作。mqtt:connect, mqtt:publish and mqtt:subscribe are the three supported actions today.
  • resources 定义策略的对象。resources define the object of the policy. 它可以是主题,也可以是用 MQTT 通配符定义的主题模式。It can be a topic or a topic pattern defined with MQTT wildcards.

下面是授权策略的示例,它明确不允许“rogue_client”客户端进行连接,允许任何 Azure IoT 客户端进行连接,并允许“sensor_1”发布到主题 events/alertsBelow is an example of an authorization policy that explicitly does not allow "rogue_client" client to connect, allows any Azure IoT clients to connect and allows "sensor_1" to publish to topic events/alerts.

{
   "$edgeHub":{
      "properties.desired":{
         "schemaVersion":"1.2",
         "routes":{
            "Route1":"FROM /messages/* INTO $upstream"
         },
         "storeAndForwardConfiguration":{
            "timeToLiveSecs":7200
         },
         "mqttBroker":{
            "authorizations":[
               {
                  "identities":[
                     "rogue_client"
                  ],
                  "deny":[
                     {
                        "operations":[
                           "mqtt:connect"
                        ]
                     }
                  ]
               },
               {
                  "identities":[
                     "{{iot:identity}}"
                  ],
                  "allow":[
                     {
                        "operations":[
                           "mqtt:connect"
                        ]
                     }
                  ]
               },
               {
                  "identities":[
                     "sensor_1"
                  ],
                  "allow":[
                     {
                        "operations":[
                           "mqtt:publish"
                        ],
                        "resources":[
                           "events/alerts"
                        ]
                     }
                  ]
               }
            ]
         }
      }
   }
}

在编写授权策略时要记住以下几点:A couple of things to keep in mind when writing your authorization policy:

  • 它需要 $edgeHub 孪生体架构版本 1.2It requires $edgeHub twin schema version 1.2
  • 默认情况下,所有操作都将被拒绝。By default, all operations are denied.
  • 授权语句会按照它们在 JSON 定义中出现的顺序接受评估。Authorization statements are evaluated in the order that they appear in the JSON definition. 它首先查看 identities,然后选择与请求匹配的第一个允许或拒绝语句。It starts by looking at identities and then select the first allow or deny statements that match the request. 如果允许和拒绝语句之间发生冲突,则以拒绝语句为准。In case of conflicts between allow and deny statements, the deny statement wins.
  • 授权策略中可以使用多个变量(例如替换):Several variables (for example, substitutions) can be used in the authorization policy:
    • {{iot:identity}} 表示当前连接的客户端的标识。{{iot:identity}} represents the identity of the currently connected client. 例如,myDevice 等设备标识或 myEdgeDevice/SampleModule 等模块标识。For example, a device identity like myDevice or a module identity like myEdgeDevice/SampleModule.
    • {{iot:device_id}} 表示当前连接的设备的标识。{{iot:device_id}} represents the identity of the currently connected device. 例如,myDevice 等设备标识或 myEdgeDevice 等运行模块的设备标识。For example, a device identity like myDevice or the device identity where a module is running like myEdgeDevice.
    • {{iot:module_id}} 表示当前连接的模块的标识。{{iot:module_id}} represents the identity of the currently connected module. 此变量对于已连接的设备为空,或者是模块标识(如 SampleModule)。This variable is blank for connected devices, or a module identity like SampleModule.
    • {{iot:this_device_id}} 表示运行授权策略的 IoT Edge 设备的标识。{{iot:this_device_id}} represents the identity of the IoT Edge device running the authorization policy. 例如,myIoTEdgeDeviceFor example, myIoTEdgeDevice.

与用户定义的主题相比,IoT 中心主题的授权处理方式略有不同。Authorizations for IoT hub topics are handled slightly differently than user-defined topics. 以下是需要记住的要点:Here are the key points to remember:

  • Azure IoT 设备或模块需要显式授权规则才能连接到 IoT Edge 中心 MQTT 中转站。Azure IoT devices or modules need an explicit authorization rule to connect to IoT Edge hub MQTT broker. 下面提供了默认的连接授权策略。A default connect authorization policy is provided below.
  • 默认情况下,Azure IoT 设备或模块可以访问自己的 IoT 中心主题,而无需任何显式授权规则。Azure IoT devices or modules can access their own IoT hub topics by default without any explicit authorization rule. 但是,在这种情况下,授权源于父/子关系,必须设置这些关系。However, authorizations stem from parent/child relationships in that case and these relationships must be set. IoT Edge 模块自动设置为其 IoT Edge 设备的子项,但设备需要显式设置为其 IoT Edge 网关的子项。IoT Edge modules are automatically set as children of their IoT Edge device but devices need to explicitly be set as children of their IoT Edge gateway.

以下是默认授权策略,可用于使所有 Azure IoT 设备或模块能够连接到中转站:Here is a default authorization policy that can be used to enable all Azure IoT devices or modules to connect to the broker:

{
   "$edgeHub":{
      "properties.desired":{
         "schemaVersion":"1.2",
         "mqttBroker":{
            "authorizations":[
               {
                  "identities": [
                     "{{iot:identity}}"
                  ],
                  "allow":[
                     {
                        "operations":[
                           "mqtt:connect"
                        ]
                     }
                  ]
               }
            ]
         }
      }
   }
}

现在,你已经了解如何连接到 IoT Edge MQTT 中转站,接下来让我们依次了解如何使用它针对用户定义的主题发布和订阅消息,针对 IoT 中心主题发布和订阅消息,以及向另一个 MQTT 中转站发布和订阅消息。Now that you understand how to connect to the IoT Edge MQTT broker, let's see how it can be used to publish and subscribe messages first on user-defined topics, then on IoT hub topics and finally to another MQTT broker.

针对用户定义的主题进行发布和订阅Publish and subscribe on user-defined topics

在本文中,你将使用一个名为 sub_client 的客户端(它针对一个主题进行订阅)和另一个名为 pub_client 的客户端(它针对一个主题进行发布) 。In this article, you'll use one client named sub_client that subscribes to a topic and another client named pub_client that publishes to a topic. 我们将使用对称密钥身份验证,但使用 X.509 自签名身份验证X.509 CA 签名身份验证可实现同样的操作。We'll use the symmetric key authentication but the same can be done with X.509 self-signed authentication or X.509 CA-signed authentication.

创建发布服务器和订阅服务器客户端Create publisher and subscriber clients

在 IoT 中心创建两个 IoT 设备并获取其密码。Create two IoT Devices in IoT Hub and get their passwords. 使用终端中的 Azure CLI 执行以下操作:Using the Azure CLI from your terminal to:

  1. 在 IoT 中心中创建两个 IoT 设备,将它们作为 IoT Edge 设备的父级:Create two IoT Devices in IoT Hub, parent them to your IoT Edge device:

    az iot hub device-identity create --device-id  sub_client --hub-name <iot_hub_name> --pd <edge_device_id>
    az iot hub device-identity create --device-id  pub_client --hub-name <iot_hub_name> --pd <edge_device_id>
    
  2. 通过生成 SAS 令牌获取其密码:Get their passwords by generating a SAS token:

    • 对于设备:For a device:

      az iot hub generate-sas-token -n <iot_hub_name> -d <device_name> --key-type primary --du 3600
      

      其中 3600 是 SAS 令牌的持续时间(以秒为单位,例如 3600 = 1 小时)。where 3600 is the duration of SAS token in seconds (for example, 3600 = 1 hour).

    • 对于模块:For a module:

      az iot hub generate-sas-token -n <iot_hub_name> -d <device_name> -m <module_name> --key-type primary --du 3600
      

      其中 3600 是 SAS 令牌的持续时间(以秒为单位,例如 3600 = 1 小时)。where 3600 is the duration of SAS token in seconds (for example, 3600 = 1 hour).

  3. 复制 SAS 令牌,即输出中与“sas”键对应的值。Copy the SAS token, which is the value corresponding to the "sas" key from the output. 以下是上述 Azure CLI 命令的输出示例:Here is an example output from the Azure CLI command above:

    {
       "sas": "SharedAccessSignature sr=example.azure-devices.net%2Fdevices%2Fdevice_1%2Fmodules%2Fmodule_a&sig=H5iMq8ZPJBkH3aBWCs0khoTPdFytHXk8VAxrthqIQS0%3D&se=1596249190"
    }
    

对发布服务器和订阅服务器客户端授权Authorize publisher and subscriber clients

若要对发布服务器和订阅服务器进行授权,请通过 Azure CLI、Visual Studio 或 Visual Studio Code 编辑 IoT Edge 中心孪生体,以包含以下授权策略:To authorize the publisher and subscriber, edit the IoT Edge hub twin either via Azure CLI, Visual Studio or Visual Studio code to include the following authorization policy:

{
   "$edgeHub":{
      "properties.desired":{
         "schemaVersion":"1.2",
         "mqttBroker":{
            "authorizations":[
               {
                  "identities": [
                     "{{iot:identity}}"
                  ],
                  "allow":[
                     {
                        "operations":[
                           "mqtt:connect"
                        ]
                     }
                  ]
               },
               {
                  "identities": [
                     "<iot_hub_name>.azure-devices.cn/sub_client"
                  ],
                  "allow":[
                     {
                        "operations":[
                           "mqtt:subscribe"
                        ],
                        "resources":[
                           "test_topic"
                        ]
                     }
                  ],
               },
               {
                  "identities": [
                     "<iot_hub_name>.azure-devices.cn/pub_client"
                  ],
                  "allow":[
                     {
                        "operations":[
                           "mqtt:publish"
                        ],
                        "resources":[
                           "test_topic"
                        ]
                     }
                  ]
               }
            ]
         }
      }
   }
}

无 TLS 的对称密钥身份验证Symmetric keys authentication without TLS

订阅Subscribe

通过在 IoT Edge 设备上运行以下命令,将 MQTT 客户端 sub_client 连接到 MQTT 中转站,并针对 test_topic 进行订阅:Connect your sub_client MQTT client to the MQTT broker and subscribe to the test_topic by running the following command on your IoT Edge device:

mosquitto_sub \
    -t "test_topic" \
    -i "sub_client" \
    -u "<iot_hub_name>.azure-devices.net/sub_client/?api-version=2018-06-30" \
    -P "<sas_token>" \
    -h "<edge_device_address>" \
    -V mqttv311 \
    -p 1883

在本例中为 <edge_device_address> = localhost,因为客户端与 IoT Edge 在同一设备上运行。where <edge_device_address> = localhost in this example since the client is running on the same device as IoT Edge.

请注意,在这第一个示例中使用了未启用 TLS 的端口 1883 (MQTT)。Note that port 1883 (MQTT), without TLS, is used in this first example. 下一部分中将显示另一个示例,其中使用了已启用 TLS 的端口 8883 (MQTTS)。Another example with port 8883 (MQTTS), with TLS enabled, is shown in next section.

MQTT 客户端 sub_client 现在已启动,正在等待有关 test_topic 的传入消息。The sub_client MQTT client is now started and is waiting for incoming messages on test_topic.

发布Publish

将 MQTT 客户端 pub_client 连接到 MQTT 中转站,并通过从另一个终端在 IoT Edge 设备上运行以下命令,针对与上面相同的 test_topic 发布消息:Connect your pub_client MQTT client to the MQTT broker and publishes a message on the same test_topic as above by running the following command on your IoT Edge device from another terminal:

mosquitto_pub \
    -t "test_topic" \
    -i "pub_client" \
    -u "<iot_hub_name>.azure-devices.net/pub_client/?api-version=2018-06-30" \
    -P "<sas_token>" \
    -h "<edge_device_address>" \
    -V mqttv311 \
    -p 1883 \
    -m "hello"

在本例中为 <edge_device_address> = localhost,因为客户端与 IoT Edge 在同一设备上运行。where <edge_device_address> = localhost in this example since the client is running on the same device as IoT Edge.

执行该命令时,MQTT 客户端 sub_client 接收到“hello”消息。Executing the command, the sub_client MQTT client receives the "hello" message.

带 TLS 的对称密钥身份验证Symmetric keys authentication with TLS

若要启用 TLS,端口必须从 1883 (MQTT) 更改为 8883 (MQTTS),并且客户端必须具有 MQTT 中转站的根证书才能验证 MQTT 中转站发送的证书链。To enable TLS, the port must be changed from 1883(MQTT) to 8883(MQTTS) and clients must have the root certificate of the MQTT broker to be able to validate the certificate chain sent by the MQTT broker. 这可以通过遵循安全连接 (TLS) 部分中提供的步骤来完成。This can be done by following the steps provided in section Secure connection (TLS).

在上面的示例中,因为客户端与 MQTT 中转站在同一设备上运行,所以只需将端口号从 1883 (MQTT) 更改为 8883 (MQTTS) 即可使用相同的步骤来启用 TLS。Because the clients are running on the same device as the MQTT broker in the example above, the same steps apply to enable TLS just by changing the port number from 1883 (MQTT) to 8883 (MQTTS).

针对 IoT 中心主题进行发布和订阅Publish and subscribe on IoT Hub topics

Azure IoT 设备 SDK 已经允许客户端执行 IoT 中心操作,但不允许针对用户定义的主题进行发布/订阅。The Azure IoT Device SDKs already let clients perform IoT Hub operations but they do not allow publishing / subscribing on user-defined topics. 只要遵守 IoT 中心基元协议,就可以使用任何采用发布和订阅语义的 MQTT 客户端执行 IoT 中心操作。IoT Hub operations can be performed using any MQTT clients using publish and subscribe semantics as long as IoT hub primitives protocols are respected. 我们将探讨这些协议的特性,了解这些协议的工作方式。We'll go through the specificities to understand how these protocols work.

将遥测数据发送到 IoT 中心Send telemetry data to IoT Hub

向 IoT 中心发送遥测数据类似于针对用户定义的主题进行发布,只不过使用的是特定的 IoT 中心主题:Sending telemetry data to IoT Hub is similar to publishing on a user-defined topic, but using a specific IoT Hub topic:

  • 对于设备,遥测按主题发送:devices/<device_name>/messages/eventsFor a device, telemetry is sent on topic: devices/<device_name>/messages/events
  • 对于模块,遥测按主题发送:devices/<device_name>/<module_name>/messages/eventsFor a module, telemetry is sent on topic: devices/<device_name>/<module_name>/messages/events

此外,创建一个诸如 FROM /messages/* INTO $upstream 的路由,将遥测从 IoT Edge MQTT 中转站发送到 IoT 中心。Additionally, create a route such as FROM /messages/* INTO $upstream to send telemetry from the IoT Edge MQTT broker to IoT hub. 若要了解有关路由的详细信息,请参阅声明路由To learn more about routing, see Declare routes.

获取孪生体Get twin

获取设备/模块孪生不是典型的 MQTT 模式。Getting the device/module twin is not a typical MQTT pattern. 客户端需要对 IoT 中心将要服务的孪生体发出请求。The client needs to issue a request for the twin that IoT Hub is going to serve.

若要接收孪生体,客户端需要针对一个 IoT 中心特定的主题 $iothub/twin/res/# 进行订阅。In order to receive twins, the client needs to subscribe to an IoT Hub specific topic $iothub/twin/res/#. 此主题名称继承自 IoT 中心,所有客户端都需要针对相同的主题进行订阅。This topic name is inherited from IoT Hub, and all clients need to subscribe to the same topic. 这并不意味着设备或模块接收彼此的孪生体。It does not mean that devices or modules receive the twin of each other. IoT 中心和 IoT Edge 中心知道哪个孪生体应在何处交付(即使所有设备都侦听相同的主题名)。IoT Hub and IoT Edge hub knows which twin should be delivered where, even if all devices listen to the same topic name.

订阅完成后,客户端需要针对 IoT 中心特定的主题 $iothub/twin/GET/?rid=<request_id>/#(其中 <request_id> 是任意标识符)发布消息以请求孪生体。Once the subscription is made, the client needs to ask for the twin by publishing a message to an IoT Hub specific topic $iothub/twin/GET/?rid=<request_id>/# where <request_id> is an arbitrary identifier. 然后,IoT 中心将发送响应,其中包含有关主题 $iothub/twin/res/200/?rid=<request_id>(客户端针对其进行订阅)的请求数据。IoT hub will then send its response with the requested data on topic $iothub/twin/res/200/?rid=<request_id>, which the client subscribes to. 这就是客户端如何将其请求与响应配对。This is how a client can pair its requests with the responses.

接收孪生体修补程序Receive twin patches

若要接收孪生体修补程序,客户端需要针对特定的 IoT 中心主题 $iothub/twin/PATCH/properties/desired/# 进行订阅。To receive twin patches, a client needs to subscribe to special IoTHub topic $iothub/twin/PATCH/properties/desired/#. 订阅完成后,客户端将收到 IoT 中心发送的关于此主题的孪生体修补程序。Once the subscription is made, the client receives the twin patches sent by IoT Hub on this topic.

接收直接方法Receive direct methods

接收直接方法与接收完整孪生体类似,但客户端还需要发送回有关它已收到调用的确认信息。Receiving a direct method is similar to receiving full twins with the addition that the client needs to confirm back that it has received the call. 首先,客户端订阅 IoT 中心特殊主题 $iothub/methods/POST/#First the client subscribes to IoT hub special topic $iothub/methods/POST/#. 然后,在收到关于该主题的直接方法后,客户端需要从针对其接收到直接方法的子主题中提取请求标识符 rid,最终针对 IoT 中心特定主题 $iothub/methods/res/200/<request_id> 发布确认消息。Then once a direct method is received on this topic the client needs to extract the request identifier rid from the sub-topic on which the direct method is received and finally publish a confirmation message on IoT hub special topic $iothub/methods/res/200/<request_id>.

发送直接方法Send direct methods

发送直接方法是 HTTP 调用,因此不需要通过 MQTT 中转站。Sending a direct method is an HTTP call and thus does not go through the MQTT broker. 若要将直接方法发送到 IoT 中心,请参阅了解并调用直接方法To send a direct method to IoT hub, see Understand and invoke direct methods. 若要将直接方法本地发送到其他模块,请参阅这一 Azure IoT C# SDK 直接方法调用示例To send a direct method locally to another module, see this Azure IoT C# SDK direct method invocation example.

在 MQTT 中转站之间发布和订阅Publish and subscribe between MQTT brokers

为了连接两个 MQTT 代理,IoT Edge 中心会包含一个 MQTT 桥。To connect two MQTT brokers, the IoT Edge hub includes an MQTT bridge. MQTT 桥通常用于将正在运行的 MQTT 代理连接到另一个 MQTT 代理。An MQTT bridge is commonly used to connect an MQTT broker running to another MQTT broker. 通常只将一部分的本地流量推送到其他中转站。Only a subset of the local traffic is typically pushed to another broker.

备注

IoT Edge 中心桥目前只能在嵌套的 IoT Edge 设备之间使用。The IoT Edge hub bridge can currently only be used between nested IoT Edge devices. 它不能用于向 IoT 中心发送数据,因为 IoT 中心不是功能齐全的 MQTT 中转站。It cannot be used to send data to IoT hub since IoT hub is not a full-featured MQTT broker. 若要了解 IoT 中心 MQTT 中转站功能支持的详细信息,请参阅使用 MQTT 协议与 IoT 中心通信To learn more IoT hub MQTT broker features support, see Communicate with your IoT hub using the MQTT protocol. 若要详细了解如何嵌套 IoT Edge 设备,请参阅将下游 IoT Edge 设备连接到 Azure IoT Edge 网关To learn more about nesting IoT Edge devices, see Connect a downstream IoT Edge device to an Azure IoT Edge gateway

在嵌套配置中,IoT Edge 中心 MQTT 桥充当父 MQTT 中转站的客户端,因此必须对父 EdgeHub 设置授权规则,以允许子 EdgeHub 针对为其配置桥的特定用户定义主题进行发布和订阅。In a nested configuration, the IoT Edge hub MQTT bridge acts as a client of the parent MQTT broker, so authorization rules must be set on the parent EdgeHub to allow the child EdgeHub to publish and subscribe to specific user-defined topics that the bridge is configured for.

IoT Edge MQTT 桥通过 JSON 结构进行配置,JSON 结构通过其孪生体发送到 IoT Edge 中心。The IoT Edge MQTT bridge is configured via a JSON structure that is sent to the IoT Edge hub via its twin. 编辑 IoT Edge 中心孪生体以配置其 MQTT 桥。Edit an IoT Edge hub twin to configure its MQTT bridge.

备注

对于公共预览版,MQTT 桥的配置仅可通过 Visual Studio、Visual Studio Code 或 Azure CLI 进行。For the public preview, the configuration of the MQTT bridge is only available via Visual Studio, Visual Studio Code or Azure CLI. Azure 门户目前不支持编辑 IoT Edge 中心孪生体及其 MQTT 桥配置。The Azure portal currently does not support editing the IoT Edge hub twin and its MQTT bridge configuration.

可配置 MQTT 桥以将 IoT Edge 中心 MQTT 中转站连接到多个外部中转站。The MQTT bridge can be configured to connect an IoT Edge hub MQTT broker to multiple external brokers. 对于每个外部中转站,需要进行以下设置:For each external broker, the following settings are required:

  • endpoint 是要连接到的远程 MQTT 中转站的地址。endpoint is the address of the remote MQTT broker to connect to. 当前仅支持父 IoT Edge 设备,且该设备由变量 $upstream 定义。Only parent IoT Edge devices are currently supported and are defined by the variable $upstream.
  • settings 定义要为终结点桥接的主题。settings defines which topics to bridge for an endpoint. 每个终结点可以有多个设置,以下值用于配置它:There can be multiple settings per endpoint and the following values are used to configure it:
    • directionin(针对远程中转站的主题进行订阅)或 out(针对远程中转站的主题进行发布)direction: either in to subscribe to the remote broker's topics or out to publish to the remote broker's topics
    • topic:要匹配的核心主题模式。topic: core topic pattern to be matched. MQTT 通配符可用于定义此模式。MQTT wildcards can be used to define this pattern. 在本地中转站和远程中转站上,可以将不同的前缀应用于此主题模式。Different prefixes can be applied to this topic pattern on the local broker and remote broker.
    • outPrefix:在远程代理上应用于 topic 模式的前缀。outPrefix: Prefix that is applied to the topic pattern on the remote broker.
    • inPrefix:在本地代理上应用于 topic 模式的前缀。inPrefix: Prefix that is applied to the topic pattern on the local broker.

以下是 IoT Edge MQTT 桥配置的示例,该配置将父 IoT Edge 设备收到的所有关于主题 alerts/# 的消息重新发布到关于相同主题的子 IoT Edge 设备,并将子 IoT Edge 设备发送的所有关于主题 /local/telemetry/# 的消息重新发布到关于主题 /remote/messages/# 的父 IoT Edge 设备。Below is an example of an IoT Edge MQTT bridge configuration that republishes all messages received on topics alerts/# of a parent IoT Edge device to a child IoT Edge device on the same topics, and republishes all messages sent on topics /local/telemetry/# of a child IoT Edge device to a parent IoT Edge device on topics /remote/messages/#.

{
    "schemaVersion": "1.2",
    "mqttBroker": {
        "bridges": [{
            "endpoint": "$upstream",
            "settings": [{
                    "direction": "in",
                    "topic": "alerts/#"
                },
                {
                    "direction": "out",
                    "topic": "",
                    "inPrefix": "/local/telemetry",
                    "outPrefix": "/remote/messages"
                }
            ]
        }]
    }
}

关于 IoT Edge 中心 MQTT 桥的其他说明:Other notes on the IoT Edge hub MQTT bridge:

  • 当使用 MQTT 中转站并且 IoT Edge 在嵌套配置(例如指定了 parent_hostname)中使用时,MQTT 协议将自动用作上游协议。The MQTT protocol will automatically be used as upstream protocol when the MQTT broker is used and that IoT Edge is used in a nested configuration, e.g. with a parent_hostname specified. 若要了解有关上游协议的详细信息,请参阅云通信To learn more about upstream protocols, see Cloud communication.

后续步骤Next steps

了解 IoT Edge 中心Understand the IoT Edge hub