author | ms.author | ms.service | ms.topic | ms.date |
---|---|---|---|---|
dominicbetts |
dobett |
iot-pnp |
include |
10/20/2020 |
The following resources are also available:
This section shows C# examples using the IoT Hub service client and the RegistryManager and ServiceClient classes. You use the RegistryManager class to interact with the device state using device twins. You can also use the RegistryManager class to query device registrations in your IoT Hub. You use the ServiceClient class to call commands on the device. The DTDL model for the device defines the properties and commands the device implements. In the code snippets, the deviceTwinId
variable holds the device ID of the IoT Plug and Play device registered with your IoT hub.
To get the device twin and model ID of the IoT Plug and Play device that connected to your IoT hub:
RegistryManager registryManager = RegistryManager.CreateFromConnectionString(parameters.HubConnectionString);
Twin twin = await registryManager.GetTwinAsync(deviceTwinId);
Console.WriteLine($"Device twin: \n{JsonConvert.SerializeObject(twin, Formatting.Indented)}");
Console.WriteLine($"Model ID: {twin.ModelId}.");
The following code snippet shows how to update the targetTemperature
property on a device. The sample shows how you need to get the twin's ETag
before you update it. The property is defined in the default component of the device:
Twin twin = await registryManager.GetTwinAsync(deviceTwinId);
int desiredTargetTemperature = 60;
// Update the twin
var twinPatch = new Twin();
twinPatch.Properties.Desired["targetTemperature"] = desiredTargetTemperature;
Console.WriteLine($"Update the targetTemperature property to {desiredTargetTemperature}.");
await registryManager.UpdateTwinAsync(deviceTwinId, twinPatch, twin.ETag);
The following snippet shows how to update the targetTemperature
property on a component. The sample shows how you need to get the twin's ETag
before you update it. The property is defined in the Thermostat1 component:
Twin twin = await registryManager.GetTwinAsync(deviceTwinId);
int desiredTargetTemperature = 60;
var twinPatch = CreatePropertyPatch("targetTemperature", desiredTargetTemperature, "thermostat1");
await registryManager.UpdateTwinAsync(deviceTwinId, twinPatch, twin.ETag);
// ...
private static Twin CreatePropertyPatch(string propertyName, object propertyValue, string componentName)
{
var twinPatch = new Twin();
twinPatch.Properties.Desired[componentName] = new
{
__t = "c"
};
twinPatch.Properties.Desired[componentName][propertyName] = JsonConvert.SerializeObject(propertyValue);
return twinPatch;
}
For a property in a component, the property patch looks like the following example:
{
"sampleComponentName":
{
"__t": "c",
"samplePropertyName": 20
}
}
The following snippet shows how to invoke the getMaxMinReport
command defined in a default component:
ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(parameters.HubConnectionString);
var commandInvocation = new CloudToDeviceMethod("getMaxMinReport") { ResponseTimeout = TimeSpan.FromSeconds(30) };
// Set command payload
DateTimeOffset since = DateTimeOffset.Now.Subtract(TimeSpan.FromMinutes(2));
string componentCommandPayload = JsonConvert.SerializeObject(since);
commandInvocation.SetPayloadJson(componentCommandPayload);
try
{
CloudToDeviceMethodResult result = await serviceClient.InvokeDeviceMethodAsync(deviceTwinId, commandInvocation);
Console.WriteLine($"Command getMaxMinReport was invoked." +
$"\nDevice returned status: {result.Status}. \nReport: {result.GetPayloadAsJson()}");
}
catch (DeviceNotFoundException)
{
Console.WriteLine($"Unable to execute command getMaxMinReport on {deviceTwinId}.";
}
The following snippet shows how to call the getMaxMinReport
command on a component. The command is defined in the Thermostat1 component:
// Create command name to invoke for component. The command is formatted as <component name>*<command name>
string commandToInvoke = "thermostat1*getMaxMinReport";
var commandInvocation = new CloudToDeviceMethod(commandToInvoke) { ResponseTimeout = TimeSpan.FromSeconds(30) };
// Set command payload
DateTimeOffset since = DateTimeOffset.Now.Subtract(TimeSpan.FromMinutes(2));
string componentCommandPayload = JsonConvert.SerializeObject(since);
commandInvocation.SetPayloadJson(componentCommandPayload);
try
{
CloudToDeviceMethodResult result = await serviceClient.InvokeDeviceMethodAsync(deviceTwinId, commandInvocation);
Console.WriteLine($"Command getMaxMinReport was invoked on component thermostat1." +
$"\nDevice returned status: {result.Status}. \nReport: {result.GetPayloadAsJson()}");
}
catch (DeviceNotFoundException)
{
Console.WriteLine("Unable to execute command getMaxMinReport on component thermostat1.");
}
You use the DigitalTwinClient class to interact with the device state using digital twins. The DTDL model for the device defines the properties and commands the device implements.
This section shows C# examples using the Digital Twins API. The following snippets use the following classes to represent the digital twin of the thermostat and temperature controller devices:
using Microsoft.Azure.Devices.Serialization;
using Newtonsoft.Json;
using System;
namespace Microsoft.Azure.Devices.Samples
{
internal class ThermostatTwin : BasicDigitalTwin
{
[JsonProperty("$metadata")]
public new ThermostatMetadata Metadata { get; set; }
[JsonProperty("maxTempSinceLastReboot")]
public double? MaxTempSinceLastReboot { get; set; }
[JsonProperty("targetTemperature")]
public double? TargetTemperature { get; set; }
}
internal class ThermostatMetadata : DigitalTwinMetadata
{
[JsonProperty("maxTempSinceLastReboot")]
public ReportedPropertyMetadata MaxTempSinceLastReboot { get; set; }
[JsonProperty("targetTemperature")]
public WritableProperty TargetTemperature { get; set; }
}
internal class ReportedPropertyMetadata
{
[JsonProperty("lastUpdateTime")]
public DateTimeOffset LastUpdateTime { get; set; }
}
internal class TemperatureControllerTwin : BasicDigitalTwin
{
[JsonProperty("$metadata")]
public new TemperatureControllerMetadata Metadata { get; set; }
[JsonProperty("serialNumber")]
public string SerialNumber { get; set; }
[JsonProperty("thermostat1")]
public ThermostatTwin Thermostat1 { get; set; }
[JsonProperty("thermostat2")]
public ThermostatTwin Thermostat2 { get; set; }
}
internal class TemperatureControllerMetadata : DigitalTwinMetadata
{
[JsonProperty("serialNumber")]
public ReportedPropertyMetadata SerialNumber { get; set; }
[JsonProperty("thermostat1")]
public WritableProperty Thermostat1 { get; set; }
[JsonProperty("thermostat2")]
public WritableProperty Thermostat2 { get; set; }
}
}
The digitalTwinId
variable holds the device ID of the IoT Plug and Play device registered with your IoT hub.
To get the digital twin and model ID of the IoT Plug and Play device that connected to your IoT hub:
DigitalTwinClient digitalTwinClient = DigitalTwinClient.CreateFromConnectionString(parameters.HubConnectionString);
HttpOperationResponse<ThermostatTwin, DigitalTwinGetHeaders> getDigitalTwinResponse = await digitalTwinClient
.GetDigitalTwinAsync<ThermostatTwin>(digitalTwinId);
ThermostatTwin thermostatTwin = getDigitalTwinResponse.Body;
Console.WriteLine($"Model ID: {thermostatTwin.Metadata.ModelId}.");
Console.WriteLine($"Digital Twin: \n{JsonConvert.SerializeObject(thermostatTwin, Formatting.Indented)}");
The following code snippet shows how to update the targetTemperature
property on a device. The property is defined in the default component of the device:
var updateOperation = new UpdateOperationsUtility();
int desiredTargetTemperature = 60;
// Get the current value of the targetTemperature property
HttpOperationResponse<ThermostatTwin, DigitalTwinGetHeaders> getDigitalTwinResponse = await digitalTwinClient
.GetDigitalTwinAsync<ThermostatTwin>(digitalTwinId);
double? currentTargetTemperature = getDigitalTwinResponse.Body.TargetTemperature;
// Has the targetTemperature property previously been set?
if (currentTargetTemperature != null)
{
// Update the existing property
// Prepend the property path with a '/'
updateOperation.AppendReplacePropertyOp($"/targetTemperature", desiredTargetTemperature);
}
else
{
// Add a new property
// Prepend the property path with a '/'
updateOperation.AppendAddPropertyOp($"/targetTemperature", desiredTargetTemperature);
}
// Update the targetTemperature property on the digital twin
HttpOperationHeaderResponse<DigitalTwinUpdateHeaders> updateDigitalTwinResponse = await digitalTwinClient
.UpdateDigitalTwinAsync(digitalTwinId, updateOperation.Serialize());
Console.WriteLine($"Update {digitalTwinId} digital twin response: {updateDigitalTwinResponse.Response.StatusCode}.");
The following snippet shows how to update the targetTemperature
property on a component. The property is defined in the Thermostat1 component:
int desiredTargetTemperature = 60;
var updateOperation = new UpdateOperationsUtility();
// Look at when the property was updated and what was it set to.
HttpOperationResponse<TemperatureControllerTwin, DigitalTwinGetHeaders> getDigitalTwinResponse = await digitalTwinClient
.GetDigitalTwinAsync<TemperatureControllerTwin>(digitalTwinId);
ThermostatTwin thermostat1 = getDigitalTwinResponse.Body.Thermostat1;
if (thermostat1 != null)
{
// Thermostat1 is present in the TemperatureController twin. You can add/replace the component-level property "targetTemperature"
double? currentComponentTargetTemperature = getDigitalTwinResponse.Body.Thermostat1.TargetTemperature;
if (currentComponentTargetTemperature != null)
{
DateTimeOffset targetTemperatureDesiredLastUpdateTime = getDigitalTwinResponse.Body.Thermostat1.Metadata.TargetTemperature.LastUpdateTime;
// The property path to be replaced should be prepended with a '/'
updateOperation.AppendReplacePropertyOp("/thermostat1/targetTemperature", desiredTargetTemperature);
}
else
{
// The property path to be added should be prepended with a '/'
updateOperation.AppendAddPropertyOp("/thermostat1/targetTemperature", desiredTargetTemperature);
}
}
else
{
// Thermostat1 is not present in the TemperatureController twin. Add the component.
var componentProperty = new Dictionary<string, object> { { "targetTemperature", desiredTargetTemperature }, { "$metadata", new object() } };
// The property path to be replaced should be prepended with a '/'
updateOperation.AppendAddComponentOp("/thermostat1", componentProperty);
}
HttpOperationHeaderResponse<DigitalTwinUpdateHeaders> updateDigitalTwinResponse = await digitalTwinClient
.UpdateDigitalTwinAsync(digitalTwinId, updateOperation.Serialize());
Console.WriteLine($"Update {digitalTwinId} digital twin response: {updateDigitalTwinResponse.Response.StatusCode}.");
The following snippet shows how to invoke the getMaxMinReport
command defined in a default component:
DateTimeOffset since = DateTimeOffset.Now.Subtract(TimeSpan.FromMinutes(2));
try
{
HttpOperationResponse<DigitalTwinCommandResponse, DigitalTwinInvokeCommandHeaders> invokeCommandResponse = await digitalTwinClient
.InvokeCommandAsync(digitalTwinId, "getMaxMinReport", JsonConvert.SerializeObject(since));
Console.WriteLine($"Command getMaxMinReport was invoked. \nDevice returned status: {invokeCommandResponse.Body.Status}." +
$"\nReport: {invokeCommandResponse.Body.Payload}");
}
catch (HttpOperationException e)
{
if (e.Response.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine($"Unable to execute command getMaxMinReport on {digitalTwinId}.");
}
}
The following snippet shows how to call the getMaxMinReport
command on a component. The command is defined in the Thermostat1 component:
DateTimeOffset since = DateTimeOffset.Now.Subtract(TimeSpan.FromMinutes(2));
try
{
HttpOperationResponse<DigitalTwinCommandResponse, DigitalTwinInvokeCommandHeaders> invokeCommandResponse = await digitalTwinClient
.InvokeComponentCommandAsync(digitalTwinId, "thermostat1", "getMaxMinReport", JsonConvert.SerializeObject(since));
Console.WriteLine("Command getMaxMinReport was invoked on component thermostat1." +
$"\nDevice returned status: {invokeCommandResponse.Body.Status}. \nReport: {invokeCommandResponse.Body.Payload}");
}
catch (HttpOperationException e)
{
if (e.Response.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine("Unable to execute command getMaxMinReport on component thermostat1.");
}
}
IoT Plug and Play devices send the telemetry defined in the DTDL model to IoT Hub. By default, IoT Hub routes the telemetry to an Event Hubs endpoint where you can consume it. To learn more, see Use IoT Hub message routing to send device-to-cloud messages to different endpoints.
The following code snippet shows how to read the telemetry from the default Event Hubs endpoint. The code in this snippet is taken from the IoT Hub quickstart Send telemetry from a device to an IoT hub and read it with a back-end application:
await using EventHubConsumerClient consumer = new EventHubConsumerClient(EventHubConsumerClient.DefaultConsumerGroupName, connectionString, EventHubName);
Console.WriteLine("Listening for messages on all partitions");
try
{
await foreach (PartitionEvent partitionEvent in consumer.ReadEventsAsync(cancellationToken))
{
Console.WriteLine("Message received on partition {0}:", partitionEvent.Partition.PartitionId);
string data = Encoding.UTF8.GetString(partitionEvent.Data.Body.ToArray());
Console.WriteLine("\t{0}:", data);
Console.WriteLine("Application properties (set by device):");
foreach (var prop in partitionEvent.Data.Properties)
{
Console.WriteLine("\t{0}: {1}", prop.Key, prop.Value);
}
Console.WriteLine("System properties (set by IoT Hub):");
foreach (var prop in partitionEvent.Data.SystemProperties)
{
Console.WriteLine("\t{0}: {1}", prop.Key, prop.Value);
}
}
}
catch (TaskCanceledException)
{
// This is expected when the token is signaled; it should not be considered an
// error in this scenario.
}
The following output from the previous code shows the temperature telemetry sent by the no-component Thermostat IoT Plug and Play device that only has the default component. The dt-dataschema
system property shows the model ID:
Message received on partition 1:
{ "temperature": 25.5 }:
Application properties (set by device):
System properties (set by IoT Hub):
iothub-connection-device-id: my-pnp-device
iothub-connection-auth-method: {"scope":"device","type":"sas","issuer":"iothub","acceptingIpFilterRule":null}
iothub-connection-auth-generation-id: 637375045610235418
iothub-enqueuedtime: 05/10/2020 14:30:58
iothub-message-source: Telemetry
dt-dataschema: dtmi:com:example:Thermostat;1
content-type: application/json
content-encoding: utf-8
The following output from the previous code shows the temperature telemetry sent by the multi-component TemperatureController IoT Plug and Play device. The dt-subject
system property shows the name of the component that sent the telemetry. In this example, the two components are thermostat1
and thermostat2
as defined in the DTDL model. The dt-dataschema
system property shows the model ID:
Message received on partition 1:
{"temperature":11.1}:
Application properties (set by device):
System properties (set by IoT Hub):
dt-subject: thermostat1
iothub-connection-device-id: my-pnp-device
iothub-connection-auth-method: {"scope":"device","type":"sas","issuer":"iothub","acceptingIpFilterRule":null}
iothub-connection-auth-generation-id: 637375045610235418
iothub-enqueuedtime: 05/10/2020 14:23:36
iothub-message-source: Telemetry
dt-dataschema: dtmi:com:example:TemperatureController;1
content-type: application/json
content-encoding: utf-8
Message received on partition 1:
{"temperature":41.2}:
Application properties (set by device):
System properties (set by IoT Hub):
dt-subject: thermostat2
iothub-connection-device-id: my-pnp-device
iothub-connection-auth-method: {"scope":"device","type":"sas","issuer":"iothub","acceptingIpFilterRule":null}
iothub-connection-auth-generation-id: 637375045610235418
iothub-enqueuedtime: 05/10/2020 14:23:36
iothub-message-source: Telemetry
dt-dataschema: dtmi:com:example:TemperatureController;1
content-type: application/json
content-encoding: utf-8
You can configure IoT Hub to generate device twin change notifications to route to a supported endpoint. To learn more, see Use IoT Hub message routing to send device-to-cloud messages to different endpoints > Non-telemetry events.
The code shown in the previous C# code snippet generates the following output when IoT Hub generates device twin change notifications for a no-component thermostat device. The application properties iothub-message-schema
and opType
give you information about the type of change notification:
Message received on partition 1:
{"version":3,"properties":{"reported":{"maxTempSinceLastReboot":9.6,"$metadata":{"$lastUpdated":"2020-10-06T10:17:41.7408552Z","maxTempSinceLastReboot":{"$lastUpdated":"2020-10-06T10:17:41.7408552Z"}},"$version":2}}}:
Application properties (set by device):
hubName: my-pnp-hub
deviceId: my-pnp-device
operationTimestamp: 2020-10-06T10:17:41.7408552+00:00
iothub-message-schema: twinChangeNotification
opType: updateTwin
System properties (set by IoT Hub):
iothub-connection-device-id: my-pnp-device
iothub-enqueuedtime: 06/10/2020 10:17:41
iothub-message-source: twinChangeEvents
user-id: System.ArraySegment`1[System.Byte]
correlation-id: 61394e8ba7d
content-type: application/json
content-encoding: utf-8
The code shown in the previous C# code snippet generates the following output when IoT Hub generates device twin change notifications for a device with components. This example shows the output when a temperature sensor device with a thermostat component generates notifications. The application properties iothub-message-schema
and opType
give you information about the type of change notification:
Message received on partition 1:
{"version":5,"properties":{"reported":{"thermostat1":{"__t":"c","maxTempSinceLastReboot":9.6},"$metadata":{"$lastUpdated":"2020-10-06T10:27:59.515972Z","thermostat1":{"$lastUpdated":"2020-10-06T10:27:59.515972Z","__t":{"$lastUpdated":"2020-10-06T10:27:59.515972Z"},"maxTempSinceLastReboot":{"$lastUpdated":"2020-10-06T10:27:59.515972Z"}}},"$version":4}}}:
Application properties (set by device):
hubName: my-pnp-hub
deviceId: my-pnp-device
operationTimestamp: 2020-10-06T10:27:59.5159720+00:00
iothub-message-schema: twinChangeNotification
opType: updateTwin
System properties (set by IoT Hub):
iothub-connection-device-id: my-pnp-device
iothub-enqueuedtime: 06/10/2020 10:27:59
iothub-message-source: twinChangeEvents
user-id: System.ArraySegment`1[System.Byte]
correlation-id: 615051f364e
content-type: application/json
content-encoding: utf-8
You can configure IoT Hub to generate digital twin change notifications to route to a supported endpoint. To learn more, see Use IoT Hub message routing to send device-to-cloud messages to different endpoints > Non-telemetry events.
The code shown in the previous C# code snippet generates the following output when IoT Hub generates digital twin change notifications for a no-component thermostat device. The application properties iothub-message-schema
and opType
give you information about the type of change notification:
Message received on partition 1:
[{"op":"add","path":"/$metadata/maxTempSinceLastReboot","value":{"lastUpdateTime":"2020-10-06T10:39:16.0209836Z"}},{"op":"add","path":"/maxTempSinceLastReboot","value":34.9}]:
Application properties (set by device):
hubName: my-pnp-hub
deviceId: my-pnp-device
operationTimestamp: 2020-10-06T10:39:16.0209836+00:00
iothub-message-schema: digitalTwinChangeNotification
opType: updateTwin
System properties (set by IoT Hub):
iothub-connection-device-id: my-pnp-device
iothub-enqueuedtime: 06/10/2020 10:39:16
iothub-message-source: digitalTwinChangeEvents
user-id: System.ArraySegment`1[System.Byte]
correlation-id: 6169857bf8c
content-type: application/json-patch+json
content-encoding: utf-8
The code shown in the previous C# code snippet generates the following output when IoT Hub generates digital twin change notifications for a device with components. This example shows the output when a temperature sensor device with a thermostat component generates notifications. The application properties iothub-message-schema
and opType
give you information about the type of change notification:
Message received on partition 1:
[{"op":"add","path":"/thermostat1","value":{"$metadata":{"maxTempSinceLastReboot":{"lastUpdateTime":"2020-10-06T10:41:44.8312666Z"}},"maxTempSinceLastReboot":29.1}}]:
Application properties (set by device):
hubName: my-pnp-hub
deviceId: my-pnp-device
operationTimestamp: 2020-10-06T10:41:44.8312666+00:00
iothub-message-schema: digitalTwinChangeNotification
opType: updateTwin
System properties (set by IoT Hub):
iothub-connection-device-id: my-pnp-device
iothub-enqueuedtime: 06/10/2020 10:41:44
iothub-message-source: digitalTwinChangeEvents
user-id: System.ArraySegment`1[System.Byte]
correlation-id: 616f108f0e3
content-type: application/json-patch+json
content-encoding: utf-8