Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public async Task RunSamplesAsync()
{
PrintHeader("MODEL LIFECYCLE SAMPLE");

// For the purpose of this example We will create temporary models using random model Ids and then decommission a model.
// For the purpose of this example we will create temporary models using random model Ids and then decommission a model.
// We have to make sure these model Ids are unique within the DT instance.

string newComponentModelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryComponentModelPrefix, DigitalTwinsClient).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ public static async Task Main(string[] args)
var componentSamples = new ComponentSamples(dtClient);
await componentSamples.RunSamplesAsync().ConfigureAwait(false);

var publishTelemetrySamples = new PublishTelemetrySamples(dtClient);
await publishTelemetrySamples.RunSamplesAsync().ConfigureAwait(false);

httpClient.Dispose();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Net;
using System.Threading.Tasks;
using Azure.DigitalTwins.Core;
using Azure.DigitalTwins.Core.Samples;
using static Azure.DigitalTwins.Core.Samples.SampleLogger;
using static Azure.DigitalTwins.Core.Samples.UniqueIdHelper;

namespace Azure.DigitalTwins.Samples
{
internal class PublishTelemetrySamples
{
private DigitalTwinsClient DigitalTwinsClient { get; }

public PublishTelemetrySamples(DigitalTwinsClient dtClient)
{
DigitalTwinsClient = dtClient;
}

/// <summary>
/// Create a temporary component model, twin model and digital twin instance.
/// Publish a telemetry message and a component telemetry message to the digital twin instance.
/// </summary>
public async Task RunSamplesAsync()
{
PrintHeader("PUBLISH TELEMETRY MESSAGE SAMPLE");

// For the purpose of this example we will create temporary models using a random model Ids.
// We will also create temporary twin instances to publish the telemetry to.

string componentModelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryComponentModelPrefix, DigitalTwinsClient).ConfigureAwait(false);
string modelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryModelPrefix, DigitalTwinsClient).ConfigureAwait(false);
string twinId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, DigitalTwinsClient).ConfigureAwait(false);

string newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.Replace(SamplesConstants.ComponentId, componentModelId);

string newModelPayload = SamplesConstants.TemporaryModelPayload
.Replace(SamplesConstants.ModelId, modelId)
.Replace(SamplesConstants.ComponentId, componentModelId);

// Then we create the models.
await DigitalTwinsClient
.CreateModelsAsync(new[] { newComponentModelPayload, newModelPayload })
.ConfigureAwait(false);

Console.WriteLine($"Successfully created models with Ids: {componentModelId}, {modelId}");

// Create digital twin with Component payload
string twinPayload = SamplesConstants.TemporaryTwinPayload
.Replace(SamplesConstants.ModelId, modelId)
.Replace(SamplesConstants.ComponentId, componentModelId);

await DigitalTwinsClient.CreateDigitalTwinAsync(twinId, twinPayload).ConfigureAwait(false);
Console.WriteLine($"Created digital twin {twinId}.");

try
{
#region Snippet:DigitalTwinSamplePublishTelemetry

Response publishTelemetryResponse = await DigitalTwinsClient.PublishTelemetryAsync(twinId, "{\"Telemetry1\": 5}");
Console.WriteLine($"Successfully published telemetry message, status: {publishTelemetryResponse.Status}");

#endregion Snippet:DigitalTwinSamplePublishTelemetry

#region Snippet:DigitalTwinSamplePublishComponentTelemetry

Response publishTelemetryToComponentResponse = await DigitalTwinsClient.PublishComponentTelemetryAsync(twinId, "Component1", "{\"ComponentTelementry1\": 9}");
Console.WriteLine($"Successfully published component telemetry message, status: {publishTelemetryToComponentResponse.Status}");

#endregion Snippet:DigitalTwinSamplePublishComponentTelemetry
}
catch (Exception ex)
{
FatalError($"Failed to publish a telemetry message due to {ex.Message}");
}

try
{
// Delete the twin.
await DigitalTwinsClient.DeleteDigitalTwinAsync(twinId).ConfigureAwait(false);

// Delete the models.
await DigitalTwinsClient.DeleteModelAsync(modelId).ConfigureAwait(false);
await DigitalTwinsClient.DeleteModelAsync(componentModelId).ConfigureAwait(false);
}
catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.NotFound)
{
// Digital twin or models do not exist
}
catch (RequestFailedException ex)
{
FatalError($"Failed to delete due to {ex.Message}");
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ public static class SamplesConstants
""@type"": ""Component"",
""name"": ""Component1"",
""schema"": ""COMPONENT_ID""
},
{
""@type"": ""Telemetry"",
""name"": ""Telemetry1"",
""schema"": ""integer""
}
]
}";
Expand Down Expand Up @@ -102,6 +107,11 @@ public static class SamplesConstants
""@type"": ""Property"",
""name"": ""ComponentProp2"",
""schema"": ""string""
},
{
""@type"": ""Telemetry"",
""name"": ""ComponentTelementry1"",
""schema"": ""integer""
}
]
}";
Expand Down
17 changes: 16 additions & 1 deletion sdk/digitaltwins/Azure.DigitalTwins.Core/samples/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ Sample project demonstrates the following:
* Create, query and delete a Digital Twin
* Get and update components for a Digital Twin
* Create, get and delete relationships between Digital Twins
* Create, get and delete eventroutes for Digital Twin
* Create, get and delete event routes for Digital Twin
* Publish telemetry messages to a Digital Twin and Digital Twin component

## Creating Digital Twin Client

Expand Down Expand Up @@ -265,3 +266,17 @@ Delete an event route given event route id
```C# Snippet:DigitalTwinSampleDeleteEventRoute
Response response = await DigitalTwinsClient.DeleteEventRouteAsync(_eventRouteId).ConfigureAwait(false);
```

### Publish telemetry messages to a Digital Twin

To publish a telemetry message to a digital twin, you need to provide the digital twin id, along with the payload on which telemetry that needs the update.

```C# Snippet:DigitalTwinSamplePublishTelemetry
Response publishTelemetryResponse = await DigitalTwinsClient.PublishTelemetryAsync(twinId, "\"telemetry\": {\"Telemetry1\": 5}");
```

You can also publish a telemetry message to a specific component in a digital twin. In addition to the digital twin id and payload, you need to specify the target component id.

```C# Snippet:DigitalTwinSamplePublishComponentTelemetry
Response publishTelemetryToComponentResponse = await DigitalTwinsClient.PublishComponentTelemetryAsync(twinId, "Component1", "\"telemetry\": {\"ComponentTelementry1\": 9}");
```
10 changes: 10 additions & 0 deletions sdk/digitaltwins/Azure.DigitalTwins.Core/src/DigitalTwinsClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1194,6 +1194,11 @@ public virtual Response DeleteEventRoute(string eventRouteId, CancellationToken
/// <param name="options">The additional information to be used when processing a telemetry request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The http response.</returns>
/// <example>
/// <code snippet="Snippet:DigitalTwinSamplePublishTelemetry">
/// Response publishTelemetryResponse = await DigitalTwinsClient.PublishTelemetryAsync(twinId, &quot;\&quot;telemetry\&quot;: {\&quot;Telemetry1\&quot;: 5}&quot;);
/// </code>
/// </example>
public virtual Task<Response> PublishTelemetryAsync(string digitalTwinId, string payload, TelemetryOptions options = default, CancellationToken cancellationToken = default)
{
TelemetryOptions telemetryOptions = options ?? new TelemetryOptions();
Expand Down Expand Up @@ -1230,6 +1235,11 @@ public virtual Response PublishTelemetry(string digitalTwinId, string payload, T
/// <param name="options">The additional information to be used when processing a telemetry request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The http response.</returns>
/// <example>
/// <code snippet="Snippet:DigitalTwinSamplePublishComponentTelemetry">
/// Response publishTelemetryToComponentResponse = await DigitalTwinsClient.PublishComponentTelemetryAsync(twinId, &quot;Component1&quot;, &quot;\&quot;telemetry\&quot;: {\&quot;ComponentTelementry1\&quot;: 9}&quot;);
/// </code>
/// </example>
public virtual Task<Response> PublishComponentTelemetryAsync(string digitalTwinId, string componentName, string payload, TelemetryOptions options = default, CancellationToken cancellationToken = default)
{
TelemetryOptions telemetryOptions = options ?? new TelemetryOptions();
Expand Down