Skip to content

Use GetSparkplugStateMessageTopic to generate the Node stateSubscribeTopic #103

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

Open
wants to merge 12 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
2 changes: 1 addition & 1 deletion Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Change history
* **Version 1.3.3.0 (2024-03-03)**: Fixed conversion issues. Fixes https://github.com/SeppPenner/SparkplugNet/issues/64, https://github.com/SeppPenner/SparkplugNet/issues/70, https://github.com/SeppPenner/SparkplugNet/issues/71, https://github.com/SeppPenner/SparkplugNet/issues/72. Special thanks go to https://github.com/shouidar, who really helped me with the conversion of all the array types.
* **Version 1.3.2.0 (2024-02-10)**: Fixed conversion for data types (Hopefully): https://github.com/SeppPenner/SparkplugNet/issues/63, https://github.com/SeppPenner/SparkplugNet/issues/64, https://github.com/SeppPenner/SparkplugNet/issues/66. Updated some NuGet packages.
* **Version 1.3.1.0 (2024-01-05)**: Removed validation for incoming metrics on application (Still needs review).
* **Version 1.3.0.0 (2023-12-18)**: Removed support for NetCore3.1, added support for Net8.0, updated NuGet packages, tried to get towards 3.0 compatibility, updated supported data types and adjusted data type handling (Use carefully, not yet fully tested).
* **Version 1.3.0.0 (2023-12-18)**: Removed support for NetCore3.1, added support for net9.0, updated NuGet packages, tried to get towards 3.0 compatibility, updated supported data types and adjusted data type handling (Use carefully, not yet fully tested).
* **Version 1.2.0.0 (2022-11-20)**: Updated nuget packages, removed support for Net5.0, added support for Net7.0, fixed a bug with the device storage (Thanks to @Patrick2607, https://github.com/SeppPenner/SparkplugNet/pull/31).
* **Version 1.1.1.0 (2022-10-30)** : Fixed a bug within the metric conversion (Thanks to @49564B0F, https://github.com/SeppPenner/SparkplugNet/issues/30), fixed a bug with the device metrics on publishing (Thanks to @emmanuelbertho, https://github.com/SeppPenner/SparkplugNet/issues/28), unified even more things (Thanks to @Patrick2607, https://github.com/SeppPenner/SparkplugNet/pull/29), updated NuGet packages.
* **Version 1.1.0.0 (2022-10-04)** : Updated events (Thanks to @cjmurph, https://github.com/SeppPenner/SparkplugNet/pull/19), added abstract base classes (Thanks to @BoBiene, https://github.com/SeppPenner/SparkplugNet/pull/20), introducing interfaces, unified things, rework to async events (Thanks to @BoBiene, https://github.com/SeppPenner/SparkplugNet/pull/21), fixed version B metric conversion error (Thanks to @Patrick2607, https://github.com/SeppPenner/SparkplugNet/pull/26), updated NuGet packages.
Expand Down
2 changes: 1 addition & 1 deletion src/SparkplugNet.Examples/SparkplugNet.Examples.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
Expand Down
2 changes: 1 addition & 1 deletion src/SparkplugNet.Tests/SparkplugNet.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
Expand Down
2 changes: 1 addition & 1 deletion src/SparkplugNet.sln
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32210.238
Expand Down
2 changes: 1 addition & 1 deletion src/SparkplugNet.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=BDSEQ/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=DBIRTH/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=DCMD/@EntryIndexedValue">True</s:Boolean>
Expand Down
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>net9.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;p0501betafencepll</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
2 changes: 1 addition & 1 deletion src/SparkplugNet/ValueClasses.cd
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<ClassDiagram MajorVersion="1" MinorVersion="1" MembersFormat="NameAndType">
<Class Name="SparkplugNet.Core.Data.ValueBase&lt;DataTypeEnum&gt;">
<Position X="3.75" Y="0.5" Width="2.5" />
Expand Down
Loading