Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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,108 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Net;
using System.Text.Json;
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:DigitalTwinsSamplePublishTelemetry

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

#endregion Snippet:DigitalTwinsSamplePublishTelemetry

#region Snippet:DigitalTwinsSamplePublishComponentTelemetry

// construct your json telemetry payload by serializing a dictionary.
var telemetryPayload = new Dictionary<string, int>
{
{ "ComponentTelemetry1", 9}
};
Response publishTelemetryToComponentResponse = await DigitalTwinsClient.PublishComponentTelemetryAsync(twinId, "Component1", JsonSerializer.Serialize(telemetryPayload));
Console.WriteLine($"Successfully published component telemetry message, status: {publishTelemetryToComponentResponse.Status}");

#endregion Snippet:DigitalTwinsSamplePublishComponentTelemetry
}
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"": ""ComponentTelemetry1"",
""schema"": ""integer""
}
]
}";
Expand Down
25 changes: 24 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,25 @@ 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:DigitalTwinsSamplePublishTelemetry
// construct your json telemetry payload by hand.
Response publishTelemetryResponse = await DigitalTwinsClient.PublishTelemetryAsync(twinId, "{\"Telemetry1\": 5}");
Console.WriteLine($"Successfully published telemetry message, status: {publishTelemetryResponse.Status}");
```

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:DigitalTwinsSamplePublishComponentTelemetry
// construct your json telemetry payload by serializing a dictionary.
var telemetryPayload = new Dictionary<string, int>
{
{ "ComponentTelemetry1", 9}
};
Response publishTelemetryToComponentResponse = await DigitalTwinsClient.PublishComponentTelemetryAsync(twinId, "Component1", JsonSerializer.Serialize(telemetryPayload));
Console.WriteLine($"Successfully published component telemetry message, status: {publishTelemetryToComponentResponse.Status}");
```
Loading