Verstehen und Aufrufen direkter Methoden von IoT HubUnderstand and invoke direct methods from IoT Hub
IoT Hub gibt Ihnen die Möglichkeit, direkte Methoden auf Geräten von der Cloud aus aufzurufen.IoT Hub gives you the ability to invoke direct methods on devices from the cloud. Direkte Methoden stellen eine Anforderung-Antwort-Interaktion mit einem Gerät dar, die einem HTTP-Aufruf darin ähnelt, dass sie unverzüglich (nach einem vom Benutzer angegebenen Timeout) zu einem Erfolg oder Fehler führt.Direct methods represent a request-reply interaction with a device similar to an HTTP call in that they succeed or fail immediately (after a user-specified timeout). Dieser Ansatz eignet sich für Szenarien, in denen die Vorgehensweise bei sofortigen Aktionen unterschiedlich ist, je nachdem, ob das Gerät reagieren konnte oder nicht.This approach is useful for scenarios where the course of immediate action is different depending on whether the device was able to respond.
Hinweis
Die in diesem Artikel beschriebenen Features stehen nur im Standard-Tarif von IoT Hub zur Verfügung.The features described in this article are available only in the standard tier of IoT Hub. Weitere Informationen zu den IoT Hub-Tarifen „Basic“ und „Standard/Free“ finden Sie unter Wählen des richtigen IoT Hub-Tarifs für Ihre Lösung.For more information about the basic and standard/free IoT Hub tiers, see Choose the right IoT Hub tier.
Jedes Gerätemethode hat ein einzelnes Gerät als Ziel.Each device method targets a single device. Aufträge auf mehreren Geräten planen bietet eine Möglichkeit zum Aufrufen von direkten Methoden auf mehreren Geräten und zum Planen von Methodenaufrufen für nicht verbundene Geräte.Schedule jobs on multiple devices shows how to provide a way to invoke direct methods on multiple devices, and schedule method invocation for disconnected devices.
Jeder Benutzer mit der Berichtigung Dienstverbindung für IoT Hub kann eine Methode auf einem Gerät aufrufen.Anyone with service connect permissions on IoT Hub may invoke a method on a device.
Direkte Methoden entsprechen einem Anforderung/Antwort-Schema und sind für Kommunikation bestimmt, die sofortige Bestätigung ihres Ergebnisses erfordert.Direct methods follow a request-response pattern and are meant for communications that require immediate confirmation of their result. Ein Beispiel hierfür ist die interaktive Steuerung des Geräts, wie das Einschalten eines Lüfters.For example, interactive control of the device, such as turning on a fan.
Falls Sie weitere Informationen dazu benötigen, was die Verwendung von gewünschten Eigenschaften, direkten Methoden oder C2D-Nachrichten betrifft, hilft Ihnen der Leitfaden zur C2D-Kommunikation weiter.Refer to Cloud-to-device communication guidance if in doubt between using desired properties, direct methods, or cloud-to-device messages.
MethodenlebenszyklusMethod lifecycle
Direkte Methoden werden auf dem Gerät implementiert und können für eine ordnungsgemäße Instanziierung null oder mehr Eingaben in der Methodennutzlast erfordern.Direct methods are implemented on the device and may require zero or more inputs in the method payload to correctly instantiate. Sie rufen eine direkte Methode über einen dienstseitigen URI ({iot hub}/twins/{device id}/methods/
) auf.You invoke a direct method through a service-facing URI ({iot hub}/twins/{device id}/methods/
). Ein Gerät empfängt direkte Methoden über ein gerätespezifisches MQTT-Thema ($iothub/methods/POST/{method name}/
) oder über AMQP-Links (die Anwendungseigenschaften IoThub-methodname
und IoThub-status
).A device receives direct methods through a device-specific MQTT topic ($iothub/methods/POST/{method name}/
) or through AMQP links (the IoThub-methodname
and IoThub-status
application properties).
Hinweis
Wenn Sie eine direkte Methode auf einem Gerät aufrufen, können Eigenschaftennamen und -werte nur druckbare alphanumerische US-ASCII-Zeichen mit Ausnahme der folgenden enthalten: {'$', '(', ')', '<', '>', '@', ',', ';', ':', '\', '"', '/', '[', ']', '?', '=', '{', '}', SP, HT}
When you invoke a direct method on a device, property names and values can only contain US-ASCII printable alphanumeric, except any in the following set: {'$', '(', ')', '<', '>', '@', ',', ';', ':', '\', '"', '/', '[', ']', '?', '=', '{', '}', SP, HT}
Direkte Methoden sind synchron und werden nach dem Zeitlimit (Standardwert: 30 Sekunden, einstellbar zwischen 5 und 300 Sekunden).Direct methods are synchronous and either succeed or fail after the timeout period (default: 30 seconds, settable between 5 and 300 seconds). Direkte Methoden sind hilfreich bei interaktiven Szenarios, in denen ein Gerät genau dann agieren soll, wenn es online ist und Befehle empfängt.Direct methods are useful in interactive scenarios where you want a device to act if and only if the device is online and receiving commands. Beispiel: Einschalten von Beleuchtung über ein Telefon.For example, turning on a light from a phone. In diesen Szenarios soll der Erfolg oder Misserfolg unmittelbar erkennbar sein, damit der Clouddienst so schnell wie möglich auf das Ergebnis reagieren kann.In these scenarios, you want to see an immediate success or failure so the cloud service can act on the result as soon as possible. Das Gerät kann einen Nachrichtentext als Ergebnis der Methode zurückgeben, dies ist für die Methode aber nicht erforderlich.The device may return some message body as a result of the method, but it isn't required for the method to do so. Es gibt keine Garantie für die Sortierung oder eine Parallelitätssemantik für Methodenaufrufe.There is no guarantee on ordering or any concurrency semantics on method calls.
Direkte Methoden erfolgen von der Cloudseite nur über HTTPS und von der Geräteseite über MQTT, AMQP, MQTT über WebSockets oder AMQP über WebSockets.Direct methods are HTTPS-only from the cloud side and MQTT, AMQP, MQTT over WebSockets, or AMQP over WebSockets from the device side.
Die Nutzlast für Methodenanforderungen und -antworten ist ein JSON-Dokument mit bis zu 128 KB.The payload for method requests and responses is a JSON document up to 128 KB.
Aufrufen einer direkten Methode aus einer Back-End-AppInvoke a direct method from a back-end app
Rufen Sie jetzt eine direkte Methode aus einer Back-End-App auf.Now, invoke a direct method from a back-end app.
MethodenaufrufMethod invocation
Direkte Methodenaufrufe auf einem Gerät sind HTTPS-Aufrufe, die aus den folgenden Elementen bestehen:Direct method invocations on a device are HTTPS calls that are made up of the following items:
Der Anforderungs-URI für das Gerät neben der API-Version:The request URI specific to the device along with the API version:
https://fully-qualified-iothubname.azure-devices.net/twins/{deviceId}/methods?api-version=2018-06-30
Die POST-MethodeThe POST method
Headern, die Autorisierung, Anforderungs-ID, Inhaltstyp und Inhaltscodierung enthaltenHeaders that contain the authorization, request ID, content type, and content encoding.
Einen transparenten JSON-Haupttext im folgenden Format:A transparent JSON body in the following format:
{ "methodName": "reboot", "responseTimeoutInSeconds": 200, "payload": { "input1": "someInput", "input2": "anotherInput" } }
Der als responseTimeoutInSeconds
in der Anforderung angegebene Wert ist die Zeitspanne, die der IoT Hub-Dienst auf den Abschluss der Ausführung einer direkten Methode auf einem Gerät warten muss.The value provided as responseTimeoutInSeconds
in the request is the amount of time that IoT Hub service must await for completion of a direct method execution on a device. Legen Sie diesen Timeoutwert mindestens auf die erwartete Ausführungszeit einer direkten Methode durch ein Gerät fest.Set this timeout to be at least as long as the expected execution time of a direct method by a device. Wenn kein Timeout angegeben ist, wird der Standardwert von 30 Sekunden verwendet.If timeout is not provided, it the default value of 30 seconds is used. Die Mindest- und Höchstwerte für responseTimeoutInSeconds
betragen 5 bzw. 300 Sekunden.The minimum and maximum values for responseTimeoutInSeconds
are 5 and 300 seconds, respectively.
Der als connectTimeoutInSeconds
in der Anforderung angegebene Wert ist die Zeitspanne nach dem Aufrufen einer direkten Methode, die der IoT Hub-Dienst darauf warten muss, dass ein getrenntes Gerät online geschaltet wird.The value provided as connectTimeoutInSeconds
in the request is the amount of time upon invocation of a direct method that IoT Hub service must await for a disconnected device to come online. Der Standardwert ist 0 (Null). Das bedeutet, dass Geräte beim Aufrufen einer direkten Methode bereits online sein müssen.The default value is 0, meaning that devices must already be online upon invocation of a direct method. Der Höchstwert für connectTimeoutInSeconds
beträgt 300 Sekunden.The maximum value for connectTimeoutInSeconds
is 300 seconds.
BeispielExample
In diesem Beispiel können Sie eine Anforderung zum Aufrufen einer direkten Methode auf einem IoT-Gerät, das bei einem Azure IoT Hub registriert wurde, sicher initiieren.This example will allow you to securely initiate a request to invoke a Direct Method on an IoT device registered to an Azure IoT Hub.
Verwenden Sie zuerst die Microsoft Azure IoT-Erweiterung für Azure CLI, um eine SharedAccessSignature zu erstellen.To begin, use the Microsoft Azure IoT extension for Azure CLI to create a SharedAccessSignature.
az iot hub generate-sas-token -n <iothubName> -du <duration>
Ersetzen Sie als Nächstes den Authorization-Header durch Ihre neu generierte SharedAccessSignature, und ändern Sie dann die Parameter iothubName
, deviceId
, methodName
und payload
so, dass Sie Ihrer Implementierung im curl
-Beispielbefehl unten entsprechen.Next, replace the Authorization header with your newly generated SharedAccessSignature, then modify the iothubName
, deviceId
, methodName
and payload
parameters to match your implementation in the example curl
command below.
curl -X POST \
https://<iothubName>.azure-devices.net/twins/<deviceId>/methods?api-version=2018-06-30 \
-H 'Authorization: SharedAccessSignature sr=iothubname.azure-devices.net&sig=x&se=x&skn=iothubowner' \
-H 'Content-Type: application/json' \
-d '{
"methodName": "reboot",
"responseTimeoutInSeconds": 200,
"payload": {
"input1": "someInput",
"input2": "anotherInput"
}
}'
Führen Sie den geänderten Befehl aus, um die angegebene direkte Methode aufzurufen.Execute the modified command to invoke the specified Direct Method. Bei erfolgreichen Anforderungen wird der HTTP-Statuscode „200“ zurückgegeben.Successful requests will return an HTTP 200 status code.
Hinweis
Im vorstehenden Beispiel wird das Aufrufen einer direkten Methode auf einem Gerät veranschaulicht.The above example demonstrates invoking a Direct Method on a device. Wenn Sie in einem IoT Edge-Modul eine direkte Methode aufrufen möchten, müssen Sie die URL-Anforderung wie unten gezeigt ändern:If you wish to invoke a Direct Method in an IoT Edge Module, you would need to modify the url request as shown below:
https://<iothubName>.azure-devices.net/twins/<deviceId>/modules/<moduleName>/methods?api-version=2018-06-30
AntwortResponse
Die Back-End-App empfängt eine Antwort, die aus den folgenden Elementen besteht:The back-end app receives a response that is made up of the following items:
HTTP-Statuscode:HTTP status code:
- 200 gibt die erfolgreiche Ausführung der direkten Methode an.200 indicates successful execution of direct method;
- 404 gibt an, dass entweder die Geräte-ID ungültig ist oder das Gerät nach dem Aufruf einer direkten Methode und
connectTimeoutInSeconds
danach nicht online war (die Grundursache können Sie mithilfe der zugehörigen Fehlermeldung ermitteln).404 indicates that either device ID is invalid, or that the device was not online upon invocation of a direct method and forconnectTimeoutInSeconds
thereafter (use accompanied error message to understand the root cause); - 504 gibt an, dass ein Gatewaytimeout ausgelöst wurde, da das Gerät nicht innerhalb von
responseTimeoutInSeconds
auf den Aufruf einer direkten Methode geantwortet hat.504 indicates gateway timeout caused by device not responding to a direct method call withinresponseTimeoutInSeconds
.
Headern, die ETag, Anforderungs-ID, Inhaltstyp und Inhaltscodierung enthalten.Headers that contain the ETag, request ID, content type, and content encoding.
Einen JSON-Haupttext im folgenden Format:A JSON body in the following format:
{ "status" : 201, "payload" : {...} }
status
undbody
werden vom Gerät bereitgestellt und für die Antwort mit dem Statuscode und/oder der Beschreibung des Geräts verwendet.Bothstatus
andbody
are provided by the device and used to respond with the device's own status code and/or description.
Methodenaufruf für IoT Edge-ModuleMethod invocation for IoT Edge modules
Der Aufruf von direkten Methoden mithilfe einer Modul-ID wird im IoT Service Client C# SDK unterstützt.Invoking direct methods using a module ID is supported in the IoT Service Client C# SDK.
Zu diesem Zweck verwenden Sie die ServiceClient.InvokeDeviceMethodAsync()
-Methode und übergeben deviceId
und moduleId
als Parameter.For this purpose, use the ServiceClient.InvokeDeviceMethodAsync()
method and pass in the deviceId
and moduleId
as parameters.
Behandeln einer direkten Methode auf einem GerätHandle a direct method on a device
Sehen wir uns an, wie eine direkte Methode auf einem IoT-Gerät behandelt wird.Let's look at how to handle a direct method on an IoT device.
MQTTMQTT
Der nachstehende Abschnitt erläutert das MQTT-Protokoll.The following section is for the MQTT protocol.
MethodenaufrufMethod invocation
Geräte empfangen direkte Methodenanforderungen zum MQTT-Thema: $iothub/methods/POST/{method name}/?$rid={request id}
.Devices receive direct method requests on the MQTT topic: $iothub/methods/POST/{method name}/?$rid={request id}
. Die Anzahl der Abonnements pro Gerät ist auf 5 begrenzt.The number of subscriptions per device is limited to 5. Deshalb wird empfohlen, nicht jede direkte Methode einzeln zu abonnieren.It is therefore recommended not to subscribe to each direct method individually. Erwägen Sie stattdessen das Abonnieren von $iothub/methods/POST/#
. Filtern Sie dann die übermittelten Nachrichten, basierend auf den gewünschten Methodennamen.Instead consider subscribing to $iothub/methods/POST/#
and then filter the delivered messages based on your desired method names.
Der vom Gerät empfangene Text weist das folgende Format auf:The body that the device receives is in the following format:
{
"input1": "someInput",
"input2": "anotherInput"
}
Methodenanforderungen sind QoS 0.Method requests are QoS 0.
AntwortResponse
Das Gerät sendet Antworten an $iothub/methods/res/{status}/?$rid={request id}
, wobei Folgendes gilt:The device sends responses to $iothub/methods/res/{status}/?$rid={request id}
, where:
Die
status
-Eigenschaft ist der vom Gerät bereitgestellte Status der Methodenausführung.Thestatus
property is the device-supplied status of method execution.Die
$rid
-Eigenschaft ist die Anforderungs-ID des von IoT Hub empfangenen Methodenaufrufs.The$rid
property is the request ID from the method invocation received from IoT Hub.
Der Haupttext wird durch das Gerät festgelegt und kann jeden beliebigen Status aufweisen.The body is set by the device and can be any status.
AMQPAMQP
Der nachstehende Abschnitt erläutert das AMQP-Protokoll.The following section is for the AMQP protocol.
MethodenaufrufMethod invocation
Das Gerät empfängt Anforderungen direkter Methoden durch Erstellen eines Empfangslinks für die Adresse amqps://{hostname}:5671/devices/{deviceId}/methods/deviceBound
.The device receives direct method requests by creating a receive link on address amqps://{hostname}:5671/devices/{deviceId}/methods/deviceBound
.
Die AMQP-Nachricht geht bei dem Empfangslink ein, der die Methodenanforderung darstellt.The AMQP message arrives on the receive link that represents the method request. Sie enthält die folgenden Abschnitte:It contains the following sections:
Die Korrelations-ID-Eigenschaft mit einer Anforderungs-ID, die mit der entsprechenden Methodenantwort zurückgegeben werden sollThe correlation ID property, which contains a request ID that should be passed back with the corresponding method response.
Eine Anwendungseigenschaft namens
IoThub-methodname
, die den Namen der aufgerufenen Methode enthältAn application property namedIoThub-methodname
, which contains the name of the method being invoked.Den AMQP-Nachrichtentext mit der Methodennutzlast im JSON-FormatThe AMQP message body containing the method payload as JSON.
AntwortResponse
Das Gerät erstellt einen Sendelink, um die Methodenantwort an der Adresse amqps://{hostname}:5671/devices/{deviceId}/methods/deviceBound
zurückzugeben.The device creates a sending link to return the method response on address amqps://{hostname}:5671/devices/{deviceId}/methods/deviceBound
.
Die Antwort der Methode wird für den Sendelink zurückgegeben und enthält Folgendes:The method's response is returned on the sending link and is structured as follows:
Die Korrelations-ID-Eigenschaft mit der Anforderungs-ID, die in der Anforderungsnachricht der Methode übergeben wurdeThe correlation ID property, which contains the request ID passed in the method's request message.
Eine Anwendungseigenschaft namens
IoThub-status
, die den vom Benutzer angegebenen Methodenstatus enthältAn application property namedIoThub-status
, which contains the user supplied method status.Den AMQP-Nachrichtentext mit der Methodenantwort im JSON-FormatThe AMQP message body containing the method response as JSON.
Weiteres ReferenzmaterialAdditional reference material
Weitere Referenzthemen im IoT Hub-Entwicklerhandbuch:Other reference topics in the IoT Hub developer guide include:
Unter IoT Hub-Endpunkte werden die verschiedenen Endpunkte beschrieben, die jeder IoT Hub für Laufzeit- und Verwaltungsvorgänge verfügbar macht.IoT Hub endpoints describes the various endpoints that each IoT hub exposes for run-time and management operations.
Unter Einschränkung und Kontingente werden die Kontingente und das Einschränkungsverhalten beschrieben, die bei Verwendung von IoT Hub zu erwarten sind.Throttling and quotas describes the quotas that apply and the throttling behavior to expect when you use IoT Hub.
Unter Verstehen und Verwenden von Azure IoT Hub SDKs werden die verschiedenen Sprach-SDKs aufgelistet, die Sie bei der Entwicklung von Geräte- und Dienst-Apps für die Interaktion mit IoT Hub verwenden können.Azure IoT device and service SDKs lists the various language SDKs you can use when you develop both device and service apps that interact with IoT Hub.
Unter IoT Hub-Abfragesprache für Gerätezwillinge, Aufträge und Nachrichtenrouting wird die IoT Hub-Abfragesprache beschrieben, mit der Sie von IoT Hub Informationen zu Gerätezwillingen und Aufträgen abrufen können.IoT Hub query language for device twins, jobs, and message routing describes the IoT Hub query language you can use to retrieve information from IoT Hub about your device twins and jobs.
Kommunikation mit Ihrem IoT Hub mithilfe des Protokolls MQTT enthält weitere Informationen zur IoT Hub-Unterstützung für das MQTT-Protokoll.IoT Hub MQTT support provides more information about IoT Hub support for the MQTT protocol.
Nächste SchritteNext steps
Nachdem Sie erfahren haben, wie Sie direkte Methoden verwenden, sind möglicherweise die folgenden Themen im IoT Hub-Entwicklerhandbuch für Sie interessant:Now you have learned how to use direct methods, you may be interested in the following IoT Hub developer guide article:
Wenn Sie einige der in diesem Artikel beschriebenen Konzepte ausprobieren möchten, ist möglicherweise das folgende IoT Hub-Tutorial für Sie interessant:If you would like to try out some of the concepts described in this article, you may be interested in the following IoT Hub tutorial: