Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use GetSparkplugStateMessageTopic to generate the Node stateSubscribeTopic #103

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
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
23 changes: 9 additions & 14 deletions src/SparkplugNet/Core/Application/SparkplugApplicationBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,9 @@ public SparkplugApplicationBase(
}

/// <summary>
/// Gets the node states.
/// Get the group states.
/// </summary>
public ConcurrentDictionary<string, MetricState<T>> NodeStates { get; } = new();

/// <summary>
/// Gets the device states.
/// </summary>
public ConcurrentDictionary<string, MetricState<T>> DeviceStates { get; } = new();
public ConcurrentDictionary<string, GroupState<T>> GroupStates { get; } = new();

/// <summary>
/// Gets the options.
Expand Down Expand Up @@ -85,8 +80,7 @@ public async Task Start(SparkplugApplicationOptions applicationOptions)
}

// Clear states.
this.NodeStates.Clear();
this.DeviceStates.Clear();
this.GroupStates.Clear();

// Add handlers.
this.AddEventHandlers();
Expand Down Expand Up @@ -364,7 +358,7 @@ private async Task ConnectInternal()
}
else
{
builder.WithWebSocketServer(options =>
builder.WithWebSocketServer(options =>
options.WithCookieContainer(this.Options.MqttWebSocketOptions.CookieContainer)
.WithCookieContainer(this.Options.MqttWebSocketOptions.Credentials)
.WithProxyOptions(this.Options.MqttWebSocketOptions.ProxyOptions)
Expand Down Expand Up @@ -450,11 +444,12 @@ private async Task SubscribeInternal()
/// <param name="metricState">The metric state.</param>
private void UpdateMetricState(SparkplugMetricStatus metricState)
{
var keys = new List<string>(this.NodeStates.Keys.ToList());

foreach (string key in keys)
foreach (var group in this.GroupStates)
{
this.NodeStates[key].MetricStatus = metricState;
foreach (var node in group.Value.NodeStates)
{
node.Value.MetricStatus = metricState;
}
}
}

Expand Down
22 changes: 22 additions & 0 deletions src/SparkplugNet/Core/GroupState .cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MetricState.cs" company="Hämmer Electronics">
// The project is licensed under the MIT license.
// </copyright>
// <summary>
// A state class for the metrics.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace SparkplugNet.Core;

/// <summary>
/// The group state class.
/// </summary>
/// <typeparam name="T">The type parameter.</typeparam>
public sealed class GroupState<T> where T : IMetric, new()
{
/// <summary>
/// Get the device states.
/// </summary>
public ConcurrentDictionary<string, NodeState<T>> NodeStates { get; } = new();
}
16 changes: 8 additions & 8 deletions src/SparkplugNet/Core/Messages/SparkplugMessageGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,7 @@ private MqttApplicationMessage GetSparkplugNodeBirthB(
Timestamp = (ulong)dateTime.ToUnixTimeMilliseconds()
};

var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload);
var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload, SparkplugMessageType.NodeBirth);
var serialized = PayloadHelper.Serialize(convertedPayload);

return new MqttApplicationMessageBuilder()
Expand Down Expand Up @@ -756,7 +756,7 @@ private MqttApplicationMessage GetSparkplugDeviceBirthB(
Timestamp = (ulong)dateTime.ToUnixTimeMilliseconds()
};

var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload);
var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload, SparkplugMessageType.DeviceBirth);
var serialized = PayloadHelper.Serialize(convertedPayload);

return new MqttApplicationMessageBuilder()
Expand Down Expand Up @@ -827,7 +827,7 @@ private MqttApplicationMessage GetSparkplugNodeDeathB(
Metrics = metrics.ToList()
};

var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload);
var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload, SparkplugMessageType.NodeDeath);
var serialized = PayloadHelper.Serialize(convertedPayload);

return new MqttApplicationMessageBuilder()
Expand Down Expand Up @@ -911,7 +911,7 @@ private MqttApplicationMessage GetSparkplugDeviceDeathB(
Timestamp = (ulong)dateTime.ToUnixTimeMilliseconds()
};

var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload);
var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload, SparkplugMessageType.DeviceDeath);
var serialized = PayloadHelper.Serialize(convertedPayload);

return new MqttApplicationMessageBuilder()
Expand Down Expand Up @@ -991,7 +991,7 @@ private MqttApplicationMessage GetSparkplugNodeDataB(
Timestamp = (ulong)dateTime.ToUnixTimeMilliseconds()
};

var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload);
var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload, SparkplugMessageType.NodeData);
var serialized = PayloadHelper.Serialize(convertedPayload);

return new MqttApplicationMessageBuilder()
Expand Down Expand Up @@ -1075,7 +1075,7 @@ private MqttApplicationMessage GetSparkplugDeviceDataB(
Timestamp = (ulong)dateTime.ToUnixTimeMilliseconds()
};

var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload);
var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload, SparkplugMessageType.DeviceData);
var serialized = PayloadHelper.Serialize(convertedPayload);

return new MqttApplicationMessageBuilder()
Expand Down Expand Up @@ -1154,7 +1154,7 @@ private static MqttApplicationMessage GetSparkplugNodeCommandB(
Timestamp = (ulong)dateTime.ToUnixTimeMilliseconds()
};

var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload);
var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload, SparkplugMessageType.NodeCommand);
var serialized = PayloadHelper.Serialize(convertedPayload);

return new MqttApplicationMessageBuilder()
Expand Down Expand Up @@ -1236,7 +1236,7 @@ private static MqttApplicationMessage GetSparkplugDeviceCommandB(
Timestamp = (ulong)dateTime.ToUnixTimeMilliseconds()
};

var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload);
var convertedPayload = VersionB.PayloadConverter.ConvertVersionBPayload(payload, SparkplugMessageType.DeviceCommand);
var serialized = PayloadHelper.Serialize(convertedPayload);

return new MqttApplicationMessageBuilder()
Expand Down
10 changes: 0 additions & 10 deletions src/SparkplugNet/Core/Messages/SparkplugTopicGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,6 @@ internal static string GetDeviceCommandSubscribeTopic(SparkplugNamespace nameSpa
return $"{nameSpace.GetDescription()}/{groupIdentifier}/{SparkplugMessageType.DeviceCommand.GetDescription()}/{edgeNodeIdentifier}/{deviceIdentifier}";
}

/// <summary>
/// Gets state subscription topic.
/// </summary>
/// <param name="scadaHostIdentifier">The SCADA host identifier.</param>
/// <returns>The state subscription topic <see cref="string"/>.</returns>
internal static string GetStateSubscribeTopic(string scadaHostIdentifier)
{
return $"{SparkplugMessageType.StateMessage.GetDescription()}/{scadaHostIdentifier}";
}

/// <summary>
/// Gets the topic (Except STATE messages).
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/SparkplugNet/Core/MetricState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace SparkplugNet.Core;
/// The metric state class.
/// </summary>
/// <typeparam name="T">The type parameter.</typeparam>
public sealed class MetricState<T> where T : IMetric, new()
public class MetricState<T> where T : IMetric, new()
{
/// <summary>
/// Gets or sets the metric status.
Expand Down
28 changes: 21 additions & 7 deletions src/SparkplugNet/Core/Node/SparkplugNodeBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,11 @@ public async Task Start(SparkplugNodeOptions nodeOptions, KnownMetricStorage? kn
// Connect, subscribe to incoming messages and send a state message.
await this.ConnectInternal();
await this.SubscribeInternal();
await this.PublishNodeAndDeviceBirthsInternal();

if (string.IsNullOrEmpty(this.Options.ScadaHostIdentifier))
{
await this.PublishNodeAndDeviceBirthsInternal();
}
}

/// <summary>
Expand Down Expand Up @@ -124,21 +128,30 @@ public async Task<MqttClientPublishResult> PublishMetrics(IEnumerable<T> metrics
}

/// <summary>
/// Does a node rebirth.
/// Does a node birth.
/// </summary>
/// <param name="metrics">The new metrics.</param>
public async Task Rebirth(IEnumerable<T> metrics)
public async Task Birth(IEnumerable<T> metrics)
{
// Send node death first.
await this.SendNodeDeathMessage();

// Reset the known metrics.
this.knownMetrics = new KnownMetricStorage(metrics);

// Send node birth and device births.
await this.PublishNodeAndDeviceBirthsInternal();
}

/// <summary>
/// Does a node rebirth.
/// </summary>
/// <param name="metrics">The new metrics.</param>
public async Task Rebirth(IEnumerable<T> metrics)
{
// Send node death first.
await this.SendNodeDeathMessage();

await this.Birth(metrics);
}

/// <summary>
/// Publishes metrics for a node.
/// </summary>
Expand Down Expand Up @@ -403,7 +416,8 @@ private async Task SubscribeInternal()
await this.client.SubscribeAsync(deviceCommandSubscribeTopic, (MqttQualityOfServiceLevel)SparkplugQualityOfServiceLevel.AtLeastOnce);

// Subscribe to the state topic.
var stateSubscribeTopic = SparkplugTopicGenerator.GetStateSubscribeTopic(this.Options.ScadaHostIdentifier);
//var stateSubscribeTopic = SparkplugTopicGenerator.GetStateSubscribeTopic(this.Options.ScadaHostIdentifier);
var stateSubscribeTopic = SparkplugTopicGenerator.GetSparkplugStateMessageTopic(this.Options.ScadaHostIdentifier, this.specificationVersion);
await this.client.SubscribeAsync(stateSubscribeTopic, (MqttQualityOfServiceLevel)SparkplugQualityOfServiceLevel.AtLeastOnce);
}

Expand Down
22 changes: 22 additions & 0 deletions src/SparkplugNet/Core/NodeState .cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MetricState.cs" company="Hämmer Electronics">
// The project is licensed under the MIT license.
// </copyright>
// <summary>
// A state class for the metrics.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace SparkplugNet.Core;

/// <summary>
/// The node state class.
/// </summary>
/// <typeparam name="T">The type parameter.</typeparam>
public sealed class NodeState<T> : MetricState<T> where T : IMetric, new()
{
/// <summary>
/// Get the device states.
/// </summary>
public ConcurrentDictionary<string, MetricState<T>> DeviceStates { get; set; } = new();
}
6 changes: 6 additions & 0 deletions src/SparkplugNet/Core/SparkplugBase.KnownMetricStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -313,5 +313,11 @@ private void AddVersionBMetric(T metric, Metric versionBMetric)
this.knownMetricsByName[metric.Name] = metric;
}
}

/// <summary>
/// Return the known metrics by name.
/// </summary>
/// <returns></returns>
public ConcurrentDictionary<string, T> GetKnownMetricsByName() { return this.knownMetricsByName; }
}
}
6 changes: 6 additions & 0 deletions src/SparkplugNet/Core/SparkplugBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ namespace SparkplugNet.Core;
/// <seealso cref="ISparkplugConnection"/>
public partial class SparkplugBase<T> : ISparkplugConnection where T : IMetric, new()
{
/// <summary>
/// The sparkplug specification version.
/// </summary>
internal readonly SparkplugSpecificationVersion specificationVersion;

/// <summary>
/// The message generator.
/// </summary>
Expand Down Expand Up @@ -54,6 +59,7 @@ public SparkplugBase(IEnumerable<T> knownMetrics, SparkplugSpecificationVersion
/// <seealso cref="ISparkplugConnection"/>
public SparkplugBase(KnownMetricStorage knownMetricsStorage, SparkplugSpecificationVersion specificationVersion)
{
this.specificationVersion = specificationVersion;
this.knownMetrics = knownMetricsStorage;

if (typeof(T).IsAssignableFrom(typeof(VersionAData.KuraMetric)))
Expand Down
7 changes: 2 additions & 5 deletions src/SparkplugNet/SparkplugNet.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net6.0;net8.0</TargetFrameworks>
<TargetFrameworks>net8.0</TargetFrameworks>
<AssemblyName>SparkplugNet</AssemblyName>
<RootNamespace>SparkplugNet</RootNamespace>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
Expand All @@ -28,13 +28,10 @@
<NoWarn>NU1803,CS0618,CS0809,NU1901,NU1902</NoWarn>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NuGetAuditMode>all</NuGetAuditMode>
<Configurations>Debug;Release;p1600sedac;p1000edge;p1600sedacedge;p1800epsi;p1000master</Configurations>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="GitVersion.MsBuild" Version="5.12.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
Expand Down
33 changes: 27 additions & 6 deletions src/SparkplugNet/VersionA/SparkplugApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -222,30 +222,51 @@ await this.FireDeviceBirthReceived(topic.GroupIdentifier, topic.EdgeNodeIdentifi
/// <param name="topic">The topic.</param>
/// <param name="metrics">The metrics.</param>
/// <param name="metricStatus">The metric status.</param>
/// <exception cref="InvalidOperationException">Thrown if the edge node identifier is invalid.</exception>
/// <exception cref="InvalidOperationException">Thrown if any identifier is invalid.</exception>
/// <exception cref="InvalidCastException">Thrown if the metric cast is invalid.</exception>
private IEnumerable<VersionAData.KuraMetric> ProcessPayload(
SparkplugMessageTopic topic,
List<VersionAData.KuraMetric> metrics,
SparkplugMetricStatus metricStatus)
{
var metricState = new MetricState<VersionAData.KuraMetric>
// Check group id.
if (string.IsNullOrWhiteSpace(topic.GroupIdentifier))
{
throw new InvalidOperationException($"The group identifier is invalid {topic.GroupIdentifier}.");
}

if (!this.GroupStates.ContainsKey(topic.GroupIdentifier))
{
this.GroupStates[topic.GroupIdentifier] = new GroupState<VersionAData.KuraMetric>();
}

NodeState<VersionAData.KuraMetric> metricState = new()
{
MetricStatus = metricStatus
};

// Check node id.
if (string.IsNullOrWhiteSpace(topic.EdgeNodeIdentifier))
{
throw new InvalidOperationException($"The edge node identifier is invalid {topic.EdgeNodeIdentifier}.");
}

if (!string.IsNullOrWhiteSpace(topic.DeviceIdentifier))
{
if (string.IsNullOrWhiteSpace(topic.EdgeNodeIdentifier))
if (!this.GroupStates[topic.GroupIdentifier].NodeStates.ContainsKey(topic.EdgeNodeIdentifier))
{
throw new InvalidOperationException($"The edge node identifier is invalid for device {topic.DeviceIdentifier}.");
this.GroupStates[topic.GroupIdentifier]
.NodeStates[topic.EdgeNodeIdentifier] = metricState;
}

this.DeviceStates[$"{topic.EdgeNodeIdentifier}/{topic.DeviceIdentifier}"] = metricState;
this.GroupStates[topic.GroupIdentifier]
.NodeStates[topic.EdgeNodeIdentifier]
.DeviceStates[topic.DeviceIdentifier] = metricState;
}
else
{
this.NodeStates[topic.EdgeNodeIdentifier] = metricState;
this.GroupStates[topic.GroupIdentifier]
.NodeStates[topic.EdgeNodeIdentifier] = metricState;
}

foreach (var payloadMetric in metrics)
Expand Down
Loading