Skip to content

Commit

Permalink
Updated MQTT Broker Module
Browse files Browse the repository at this point in the history
  • Loading branch information
PatrickRitchie committed Dec 5, 2023
1 parent 1ddf8dc commit 9ad194a
Show file tree
Hide file tree
Showing 5 changed files with 266 additions and 176 deletions.
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup Condition="'$(Configuration)'=='Debug'">
<TargetFrameworks>net6.0</TargetFrameworks>
<TargetFrameworks>net8.0</TargetFrameworks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'">
<TargetFrameworks>net461;net462;net47;net471;net472;net48;netstandard2.0;netcoreapp3.1;net5.0;net6.0;net7.0</TargetFrameworks>
<TargetFrameworks>net461;net462;net47;net471;net472;net48;netstandard2.0;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks>
<DebugSymbols>false</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>true</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Package'">
<TargetFrameworks>net461;net462;net47;net471;net472;net48;netstandard2.0;netcoreapp3.1;net5.0;net6.0;net7.0</TargetFrameworks>
<TargetFrameworks>net461;net462;net47;net471;net472;net48;netstandard2.0;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks>
<Optimize>true</Optimize>
</PropertyGroup>

Expand All @@ -23,7 +23,7 @@
<Copyright>Copyright (c) 2023 TrakHound Inc., All Rights Reserved.</Copyright>
<RepositoryUrl>https://github.com/TrakHound/MTConnect.NET</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<Description>MTConnect.NET-MqttBroker-Module implements an MQTT Broker for use with the MTConnectAgentApplication class in the MTConnect.NET-Applications-Agent library. Supports MTConnect Versions up to 2.2. Supports .NET Framework 4.6.1 up to .NET 7</Description>
<Description>MTConnect.NET-AgentModule-MqttBroker implements an MQTT Broker for use with the MTConnectAgentApplication class in the MTConnect.NET-Applications-Agent library. Supports MTConnect Versions up to 2.2. Supports .NET Framework 4.6.1 up to .NET 7</Description>
<PackageProjectUrl>https://www.TrakHound.com</PackageProjectUrl>
<PackageTags>mtconnect;iiot;iot;cnc;</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
Expand All @@ -42,11 +42,11 @@
</PropertyGroup>

<ItemGroup Condition="'$(Configuration)'=='Debug'">
<Compile Include="..\..\src\AssemblyInfo.cs" Link="Properties\AssemblyInfo.cs" />
<Compile Include="..\..\..\build\AssemblyInfo.cs" Link="Properties\AssemblyInfo.cs" />
</ItemGroup>

<ItemGroup Condition="'$(Configuration)'=='Release'">
<Compile Include="..\..\src\AssemblyInfo.cs" Link="Properties\AssemblyInfo.cs" />
<Compile Include="..\..\..\build\AssemblyInfo.cs" Link="Properties\AssemblyInfo.cs" />
</ItemGroup>

<PropertyGroup Condition="'$(Configuration)'=='Package'">
Expand All @@ -58,7 +58,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\MTConnect.NET-MQTT\MTConnect.NET-MQTT.csproj" />
<ProjectReference Include="..\..\..\libraries\MTConnect.NET-MQTT\MTConnect.NET-MQTT.csproj" />
</ItemGroup>

</Project>

This file was deleted.

197 changes: 197 additions & 0 deletions agent/Modules/MTConnect.NET-MqttBroker-Module/Module.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
// Copyright (c) 2023 TrakHound Inc., All Rights Reserved.
// TrakHound Inc. licenses this file to you under the MIT license.

using MQTTnet;
using MQTTnet.Server;
using MTConnect.Agents;
using MTConnect.Assets;
using MTConnect.Configurations;
using MTConnect.Devices;
using MTConnect.Formatters;
using MTConnect.Streams.Output;
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

namespace MTConnect.Modules
{
public class Module : MTConnectAgentModule
{
public const string ConfigurationTypeId = "mqtt-broker";

//private readonly Logger _httpLogger = LogManager.GetLogger("http-logger");
//private readonly Logger _agentValidationLogger = LogManager.GetLogger("agent-validation-logger");
private readonly ModuleConfiguration _configuration;
private readonly MTConnectMqttServer _server;
//private IMTConnectAgentBroker _mtconnectAgent;
private MqttServer _mqttServer;


public Module(IMTConnectAgentBroker mtconnectAgent, object configuration) : base(mtconnectAgent)
{
_configuration = AgentApplicationConfiguration.GetConfiguration<ModuleConfiguration>(configuration);

_server = new MTConnectMqttServer(mtconnectAgent, _configuration);
_server.ProbeReceived += ProbeReceived;
_server.CurrentReceived += CurrentReceived;
_server.SampleReceived += SampleReceived;
_server.AssetReceived += AssetReceived;
}


protected override void OnStartBeforeLoad()
{
StartAsync().Wait();
//_ = Task.Run(StartAsync);
}

protected override void OnStop()
{
if (_mqttServer != null) _mqttServer.StopAsync();
}


private async Task StartAsync()
{
var mqttServerOptionsBuilder = new MqttServerOptionsBuilder().WithDefaultEndpoint();

// Add Certificate & Private Key
if (!string.IsNullOrEmpty(_configuration.PemCertificate) && !string.IsNullOrEmpty(_configuration.PemPrivateKey))
{
X509Certificate2 certificate = null;

#if NET5_0_OR_GREATER
certificate = new X509Certificate2(X509Certificate2.CreateFromPemFile(GetFilePath(_configuration.PemCertificate), GetFilePath(_configuration.PemPrivateKey)).Export(X509ContentType.Pfx));
#endif

if (certificate != null)
{
mqttServerOptionsBuilder.WithoutDefaultEndpoint();
mqttServerOptionsBuilder.WithEncryptedEndpoint();
mqttServerOptionsBuilder.WithEncryptedEndpointPort(_configuration.Port);
mqttServerOptionsBuilder.WithEncryptionCertificate(certificate);
mqttServerOptionsBuilder.WithEncryptionSslProtocol(System.Security.Authentication.SslProtocols.Tls12);
}
}

var mqttServerOptions = mqttServerOptionsBuilder.Build();

var mqttFactory = new MqttFactory();
_mqttServer = mqttFactory.CreateMqttServer(mqttServerOptions);

_mqttServer.ClientConnectedAsync += async (args) =>
{
//if (ClientConnected != null) ClientConnected.Invoke(this, new EventArgs());
};
_mqttServer.ClientDisconnectedAsync += async (args) =>
{
//if (ClientDisconnected != null) ClientDisconnected.Invoke(this, new EventArgs());
};

await _mqttServer.StartAsync();
_server.Start();
}


private async void ProbeReceived(IDevice device, IDevicesResponseDocument responseDocument)
{
if (_mqttServer != null && _mqttServer.IsStarted)
{
var formatResult = ResponseDocumentFormatter.Format(_configuration.DocumentFormat, responseDocument);
if (formatResult.Success)
{
var topic = $"{_configuration.TopicPrefix}/{device.Uuid}/{_configuration.ProbeTopic}";

var message = new MqttApplicationMessage();
message.Retain = true;
message.Topic = topic;
message.QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce;
message.Payload = formatResult.Content;

var injectMessage = new InjectedMqttApplicationMessage(message);

await _mqttServer.InjectApplicationMessage(injectMessage);
}
}
}

private async void CurrentReceived(IDevice device, IStreamsResponseOutputDocument responseDocument)
{
if (_mqttServer != null && _mqttServer.IsStarted)
{
var formatResult = ResponseDocumentFormatter.Format(_configuration.DocumentFormat, ref responseDocument);
if (formatResult.Success)
{
var topic = $"{_configuration.TopicPrefix}/{device.Uuid}/{_configuration.CurrentTopic}";

var message = new MqttApplicationMessage();
message.Retain = true;
message.Topic = topic;
message.QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce;
message.Payload = formatResult.Content;

var injectMessage = new InjectedMqttApplicationMessage(message);

await _mqttServer.InjectApplicationMessage(injectMessage);
}
}
}

private async void SampleReceived(IDevice device, IStreamsResponseOutputDocument responseDocument)
{
if (_mqttServer != null && _mqttServer.IsStarted)
{
var formatResult = ResponseDocumentFormatter.Format(_configuration.DocumentFormat, ref responseDocument);
if (formatResult.Success)
{
var topic = $"{_configuration.TopicPrefix}/{device.Uuid}/{_configuration.SampleTopic}";

var message = new MqttApplicationMessage();
//message.Retain = true;
message.Topic = topic;
message.QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce;
message.Payload = formatResult.Content;

var injectMessage = new InjectedMqttApplicationMessage(message);

await _mqttServer.InjectApplicationMessage(injectMessage);
}
}
}

private async void AssetReceived(IDevice device, IAssetsResponseDocument responseDocument)
{
if (_mqttServer != null && _mqttServer.IsStarted)
{
var formatResult = ResponseDocumentFormatter.Format(_configuration.DocumentFormat, responseDocument);
if (formatResult.Success)
{
var topic = $"{_configuration.TopicPrefix}/{device.Uuid}/{_configuration.AssetTopic}";

var message = new MqttApplicationMessage();
message.Retain = true;
message.Topic = topic;
message.QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce;
message.Payload = formatResult.Content;

var injectMessage = new InjectedMqttApplicationMessage(message);

await _mqttServer.InjectApplicationMessage(injectMessage);
}
}
}


private static string GetFilePath(string path)
{
var x = path;
if (!Path.IsPathRooted(x))
{
x = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, x);
}

return x;
}
}
}
Loading

0 comments on commit 9ad194a

Please sign in to comment.