From d70d3cac1d238f01f15c5011844e7e80dc5b7223 Mon Sep 17 00:00:00 2001 From: Patrick Ritchie Date: Tue, 28 Nov 2023 22:17:19 -0500 Subject: [PATCH] Clean up --- ...Connect.NET-AgentModule-MqttAdapter.csproj | 28 +- .../Models/ConditionModel.cs | 22 -- .../Models/DataItemModel.cs | 22 -- .../Models/DataModel - Copy.cs | 200 ---------- .../Models/DataModel.cs | 237 ------------ .../Models/MessageModel.cs | 13 - .../Models/PayloadModel.cs | 12 - .../Models/TableEntryModel.cs | 17 - .../Module - Copy.cs | 343 ------------------ .../ModuleConfiguration - Copy.cs | 64 ---- .../README.md | 32 ++ 11 files changed, 39 insertions(+), 951 deletions(-) delete mode 100644 agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/ConditionModel.cs delete mode 100644 agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataItemModel.cs delete mode 100644 agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataModel - Copy.cs delete mode 100644 agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataModel.cs delete mode 100644 agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/MessageModel.cs delete mode 100644 agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/PayloadModel.cs delete mode 100644 agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/TableEntryModel.cs delete mode 100644 agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Module - Copy.cs delete mode 100644 agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/ModuleConfiguration - Copy.cs create mode 100644 agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/README.md diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/MTConnect.NET-AgentModule-MqttAdapter.csproj b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/MTConnect.NET-AgentModule-MqttAdapter.csproj index e9fbfdf7..570e6a5d 100644 --- a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/MTConnect.NET-AgentModule-MqttAdapter.csproj +++ b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/MTConnect.NET-AgentModule-MqttAdapter.csproj @@ -54,30 +54,9 @@ - - - - - - - - - - - - - - - - - - - - - @@ -87,4 +66,11 @@ + + + \ + True + + + diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/ConditionModel.cs b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/ConditionModel.cs deleted file mode 100644 index e851cacb..00000000 --- a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/ConditionModel.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Text.Json.Serialization; - -namespace MTConnect -{ - public class ConditionModel - { - [JsonPropertyName("level")] - public string Level { get; set; } - - [JsonPropertyName("nativeCode")] - public string NativeCode { get; set; } - - [JsonPropertyName("nativeSeverity")] - public string NativeSeverity { get; set; } - - [JsonPropertyName("qualifier")] - public string Qualifier { get; set; } - - [JsonPropertyName("message")] - public string Message { get; set; } - } -} diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataItemModel.cs b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataItemModel.cs deleted file mode 100644 index 7f8c29e4..00000000 --- a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataItemModel.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Text.Json.Serialization; - -namespace MTConnect -{ - public class DataItemModel - { - [JsonPropertyName("level")] - public string Level { get; set; } - - [JsonPropertyName("nativeCode")] - public string NativeCode { get; set; } - - [JsonPropertyName("nativeSeverity")] - public string NativeSeverity { get; set; } - - [JsonPropertyName("qualifier")] - public string Qualifier { get; set; } - - [JsonPropertyName("message")] - public string Message { get; set; } - } -} diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataModel - Copy.cs b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataModel - Copy.cs deleted file mode 100644 index c28dd7e0..00000000 --- a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataModel - Copy.cs +++ /dev/null @@ -1,200 +0,0 @@ -using MTConnect.Observations; -using MTConnect.Observations.Input; -using System; -using System.Collections.Generic; -using System.Text.Json.Serialization; - -namespace MTConnect -{ - public class DataModel - { - [JsonPropertyName("timestamp")] - public DateTime Timestamp { get; set; } - - [JsonPropertyName("dataItems")] - public Dictionary DataItems { get; set; } - - [JsonPropertyName("messages")] - public Dictionary Messages { get; set; } - - [JsonPropertyName("conditions")] - public Dictionary> Conditions { get; set; } - - [JsonPropertyName("dataSets")] - public Dictionary> DataSets { get; set; } - - [JsonPropertyName("tables")] - public Dictionary>> Tables { get; set; } - - - public IEnumerable ToObservationInputs() - { - var observations = new List(); - observations.AddRange(ToObservationInputs(Timestamp, DataItems)); - observations.AddRange(ToObservationInputs(Timestamp, Messages)); - observations.AddRange(ToObservationInputs(Timestamp, Conditions)); - observations.AddRange(ToObservationInputs(Timestamp, DataSets)); - observations.AddRange(ToObservationInputs(Timestamp, Tables)); - return observations; - } - - private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary dataItems) - { - var observations = new List(); - - if (!dataItems.IsNullOrEmpty()) - { - foreach (var dataItem in dataItems) - { - if (!string.IsNullOrEmpty(dataItem.Key)) - { - var observation = new ObservationInput(); - observation.DataItemKey = dataItem.Key; - observation.Timestamp = timestamp.ToUnixTime(); - observation.AddValue(ValueKeys.Result, dataItem.Value); - observations.Add(observation); - } - } - } - - return observations; - } - - private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary messages) - { - var observations = new List(); - - if (!messages.IsNullOrEmpty()) - { - foreach (var message in messages) - { - if (!string.IsNullOrEmpty(message.Key)) - { - var observation = new ObservationInput(); - observation.DataItemKey = message.Key; - observation.Timestamp = timestamp.ToUnixTime(); - observation.AddValue(ValueKeys.NativeCode, message.Value.NativeCode); - observation.AddValue(ValueKeys.Result, message.Value.Message); - observations.Add(observation); - } - } - } - - return observations; - } - - private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary> conditionModels) - { - var observations = new List(); - - if (!conditionModels.IsNullOrEmpty()) - { - var ts = timestamp.ToUnixTime(); - - foreach (var conditionModel in conditionModels) - { - if (!string.IsNullOrEmpty(conditionModel.Key)) - { - var conditions = conditionModel.Value; - if (!conditions.IsNullOrEmpty()) - { - foreach (var condition in conditions) - { - var observation = new ObservationInput(); - observation.DataItemKey = conditionModel.Key; - observation.Timestamp = ts; - observation.AddValue(ValueKeys.Level, condition.Level); - observation.AddValue(ValueKeys.NativeCode, condition.NativeCode); - observation.AddValue(ValueKeys.NativeSeverity, condition.NativeSeverity); - observation.AddValue(ValueKeys.Qualifier, condition.Qualifier); - observation.AddValue(ValueKeys.Message, condition.Message); - observations.Add(observation); - } - } - } - } - } - - return observations; - } - - private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary> dataSetModels) - { - var observations = new List(); - - if (!dataSetModels.IsNullOrEmpty()) - { - var ts = timestamp.ToUnixTime(); - - foreach (var dataSetModel in dataSetModels) - { - if (!string.IsNullOrEmpty(dataSetModel.Key)) - { - var entries = dataSetModel.Value; - if (!entries.IsNullOrEmpty()) - { - var observation = new ObservationInput(); - observation.DataItemKey = dataSetModel.Key; - observation.Timestamp = ts; - - foreach (var entry in entries) - { - if (!string.IsNullOrEmpty(entry.Key)) - { - observation.AddValue(ValueKeys.CreateDataSetValueKey(entry.Key), entry.Value); - } - } - - observations.Add(observation); - } - } - } - } - - return observations; - } - - private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary>> tableModels) - { - var observations = new List(); - - if (!tableModels.IsNullOrEmpty()) - { - var ts = timestamp.ToUnixTime(); - - foreach (var tableModel in tableModels) - { - if (!string.IsNullOrEmpty(tableModel.Key)) - { - var entries = tableModel.Value; - if (!entries.IsNullOrEmpty()) - { - var observation = new ObservationInput(); - observation.DataItemKey = tableModel.Key; - observation.Timestamp = ts; - - foreach (var entry in entries) - { - if (!string.IsNullOrEmpty(entry.Key)) - { - var cells = entry.Value; - if (!cells.IsNullOrEmpty()) - { - foreach (var cell in cells) - { - observation.AddValue(ValueKeys.CreateTableValueKey(entry.Key, cell.Key), cell.Value); - } - } - } - } - - observations.Add(observation); - } - } - } - } - - return observations; - } - } -} diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataModel.cs b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataModel.cs deleted file mode 100644 index c32acbb4..00000000 --- a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/DataModel.cs +++ /dev/null @@ -1,237 +0,0 @@ -using MTConnect.Observations; -using MTConnect.Input; -using ProtoBuf; -using System; -using System.Collections.Generic; -using System.Text.Json.Serialization; - -namespace MTConnect -{ - [ProtoContract] - public class DataModel - { - [ProtoMember(1)] - public DateTime Timestamp { get; set; } - - [ProtoMember(2)] - public Dictionary> DataItems { get; set; } - - //[JsonPropertyName("dataItems")] - //public Dictionary DataItems { get; set; } - - //[JsonPropertyName("messages")] - //public Dictionary Messages { get; set; } - - //[JsonPropertyName("conditions")] - //public Dictionary> Conditions { get; set; } - - //[JsonPropertyName("dataSets")] - //public Dictionary> DataSets { get; set; } - - //[JsonPropertyName("tables")] - //public Dictionary>> Tables { get; set; } - - - public IEnumerable ToObservationInputs() - { - var observations = new List(); - observations.AddRange(ToObservationInputs(Timestamp, DataItems)); - //observations.AddRange(ToObservationInputs(Timestamp, Messages)); - //observations.AddRange(ToObservationInputs(Timestamp, Conditions)); - //observations.AddRange(ToObservationInputs(Timestamp, DataSets)); - //observations.AddRange(ToObservationInputs(Timestamp, Tables)); - return observations; - } - - private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary> dataItems) - { - var observations = new List(); - - if (!dataItems.IsNullOrEmpty()) - { - var ts = timestamp.ToUnixTime(); - - foreach (var dataItem in dataItems) - { - if (!string.IsNullOrEmpty(dataItem.Key) && !dataItem.Value.IsNullOrEmpty()) - { - var observation = new ObservationInput(); - observation.DataItemKey = dataItem.Key; - observation.Timestamp = ts; - - foreach (var value in dataItem.Value) - { - if (!string.IsNullOrEmpty(value.Key)) - { - observation.AddValue(value.Key, value.Value); - } - } - - observations.Add(observation); - } - } - } - - return observations; - } - - //private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary dataItems) - //{ - // var observations = new List(); - - // if (!dataItems.IsNullOrEmpty()) - // { - // foreach (var dataItem in dataItems) - // { - // if (!string.IsNullOrEmpty(dataItem.Key)) - // { - // var observation = new ObservationInput(); - // observation.DataItemKey = dataItem.Key; - // observation.Timestamp = timestamp.ToUnixTime(); - // observation.AddValue(ValueKeys.Result, dataItem.Value); - // observations.Add(observation); - // } - // } - // } - - // return observations; - //} - - //private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary messages) - //{ - // var observations = new List(); - - // if (!messages.IsNullOrEmpty()) - // { - // foreach (var message in messages) - // { - // if (!string.IsNullOrEmpty(message.Key)) - // { - // var observation = new ObservationInput(); - // observation.DataItemKey = message.Key; - // observation.Timestamp = timestamp.ToUnixTime(); - // observation.AddValue(ValueKeys.NativeCode, message.Value.NativeCode); - // observation.AddValue(ValueKeys.Result, message.Value.Message); - // observations.Add(observation); - // } - // } - // } - - // return observations; - //} - - //private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary> conditionModels) - //{ - // var observations = new List(); - - // if (!conditionModels.IsNullOrEmpty()) - // { - // var ts = timestamp.ToUnixTime(); - - // foreach (var conditionModel in conditionModels) - // { - // if (!string.IsNullOrEmpty(conditionModel.Key)) - // { - // var conditions = conditionModel.Value; - // if (!conditions.IsNullOrEmpty()) - // { - // foreach (var condition in conditions) - // { - // var observation = new ObservationInput(); - // observation.DataItemKey = conditionModel.Key; - // observation.Timestamp = ts; - // observation.AddValue(ValueKeys.Level, condition.Level); - // observation.AddValue(ValueKeys.NativeCode, condition.NativeCode); - // observation.AddValue(ValueKeys.NativeSeverity, condition.NativeSeverity); - // observation.AddValue(ValueKeys.Qualifier, condition.Qualifier); - // observation.AddValue(ValueKeys.Message, condition.Message); - // observations.Add(observation); - // } - // } - // } - // } - // } - - // return observations; - //} - - //private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary> dataSetModels) - //{ - // var observations = new List(); - - // if (!dataSetModels.IsNullOrEmpty()) - // { - // var ts = timestamp.ToUnixTime(); - - // foreach (var dataSetModel in dataSetModels) - // { - // if (!string.IsNullOrEmpty(dataSetModel.Key)) - // { - // var entries = dataSetModel.Value; - // if (!entries.IsNullOrEmpty()) - // { - // var observation = new ObservationInput(); - // observation.DataItemKey = dataSetModel.Key; - // observation.Timestamp = ts; - - // foreach (var entry in entries) - // { - // if (!string.IsNullOrEmpty(entry.Key)) - // { - // observation.AddValue(ValueKeys.CreateDataSetValueKey(entry.Key), entry.Value); - // } - // } - - // observations.Add(observation); - // } - // } - // } - // } - - // return observations; - //} - - //private static IEnumerable ToObservationInputs(DateTime timestamp, Dictionary>> tableModels) - //{ - // var observations = new List(); - - // if (!tableModels.IsNullOrEmpty()) - // { - // var ts = timestamp.ToUnixTime(); - - // foreach (var tableModel in tableModels) - // { - // if (!string.IsNullOrEmpty(tableModel.Key)) - // { - // var entries = tableModel.Value; - // if (!entries.IsNullOrEmpty()) - // { - // var observation = new ObservationInput(); - // observation.DataItemKey = tableModel.Key; - // observation.Timestamp = ts; - - // foreach (var entry in entries) - // { - // if (!string.IsNullOrEmpty(entry.Key)) - // { - // var cells = entry.Value; - // if (!cells.IsNullOrEmpty()) - // { - // foreach (var cell in cells) - // { - // observation.AddValue(ValueKeys.CreateTableValueKey(entry.Key, cell.Key), cell.Value); - // } - // } - // } - // } - - // observations.Add(observation); - // } - // } - // } - // } - - // return observations; - //} - } -} diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/MessageModel.cs b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/MessageModel.cs deleted file mode 100644 index 720ee19f..00000000 --- a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/MessageModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Text.Json.Serialization; - -namespace MTConnect -{ - public class MessageModel - { - [JsonPropertyName("nativeCode")] - public string NativeCode { get; set; } - - [JsonPropertyName("message")] - public string Message { get; set; } - } -} diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/PayloadModel.cs b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/PayloadModel.cs deleted file mode 100644 index 0fe1bd8e..00000000 --- a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/PayloadModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using ProtoBuf; -using System.Collections.Generic; - -namespace MTConnect -{ - [ProtoContract] - public class PayloadModel - { - [ProtoMember(1)] - public IEnumerable DataModels { get; set; } - } -} diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/TableEntryModel.cs b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/TableEntryModel.cs deleted file mode 100644 index da13f4e3..00000000 --- a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Models/TableEntryModel.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Collections.Generic; -using System.Text.Json.Serialization; - -namespace MTConnect -{ - public class TableEntryModel - { - [JsonPropertyName("key")] - public string Key { get; set; } - - [JsonPropertyName("removed")] - public bool Removed { get; set; } - - [JsonPropertyName("cells")] - public Dictionary Cells { get; set; } - } -} diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Module - Copy.cs b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Module - Copy.cs deleted file mode 100644 index 9c7ce6c7..00000000 --- a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/Module - Copy.cs +++ /dev/null @@ -1,343 +0,0 @@ -// Copyright (c) 2023 TrakHound Inc., All Rights Reserved. -// TrakHound Inc. licenses this file to you under the MIT license. - -using MQTTnet; -using MQTTnet.Client; -using MQTTnet.Server; -using MTConnect.Agents; -using MTConnect.Configurations; -using NLog; -using ProtoBuf; -using System; -using System.Collections.Generic; -using System.IO; -using System.Security.Cryptography.X509Certificates; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; - -namespace MTConnect.Modules -{ - public class Module : IMTConnectAgentModule - { - public const string ConfigurationTypeId = "mqtt-adapter"; - - private readonly Logger _clientLogger = LogManager.GetLogger("mqtt-adapter-logger"); - private readonly ModuleConfiguration _configuration; - private readonly IMTConnectAgentBroker _mtconnectAgent; - private readonly MqttFactory _mqttFactory; - private readonly IMqttClient _mqttClient; - - private readonly string _server; - private readonly int _port; - private readonly int _qos; - private readonly int _interval; - private readonly int _retryInterval; - private readonly string _username; - private readonly string _password; - private readonly string _clientId; - private readonly string _caCertPath; - private readonly string _pemClientCertPath; - private readonly string _pemPrivateKeyPath; - private readonly bool _allowUntrustedCertificates; - private readonly bool _useTls; - private readonly string _topic; - private readonly string _deviceKey; - - private CancellationTokenSource _stop; - - - public string Id { get; } - - public string Description { get; } - - - public Module(IMTConnectAgentBroker mtconnectAgent, object configuration) - { - _mtconnectAgent = mtconnectAgent; - _mqttFactory = new MqttFactory(); - _mqttClient = _mqttFactory.CreateMqttClient(); - _mqttClient.ApplicationMessageReceivedAsync += MessageReceived; - - _configuration = AgentApplicationConfiguration.GetConfiguration(configuration); - if (_configuration != null) - { - _server = _configuration.Server; - _port = _configuration.Port; - _interval = _configuration.Interval; - _retryInterval = _configuration.RetryInterval; - _qos = _configuration.QoS; - _username = _configuration.Username; - _password = _configuration.Password; - _clientId = _configuration.ClientId; - _caCertPath = _configuration.CertificateAuthority; - _pemClientCertPath = _configuration.PemCertificate; - _pemPrivateKeyPath = _configuration.PemPrivateKey; - _allowUntrustedCertificates = _configuration.AllowUntrustedCertificates; - _useTls = _configuration.UseTls; - _topic = _configuration.Topic; - _deviceKey = _configuration.DeviceKey; - } - } - - - public void StartBeforeLoad() { } - - public void StartAfterLoad() - { - if (_configuration != null) - { - _stop = new CancellationTokenSource(); - - _ = Task.Run(Worker, _stop.Token); - } - } - - - public void Stop() - { - if (_stop != null) _stop.Cancel(); - if (_mqttClient != null) _mqttClient.Dispose(); - } - - - private async Task Worker() - { - do - { - try - { - try - { - // Declare new MQTT Client Options with Tcp Server - var clientOptionsBuilder = new MqttClientOptionsBuilder().WithTcpServer(_server, _port); - - // Set Client ID - if (!string.IsNullOrEmpty(_clientId)) - { - clientOptionsBuilder.WithClientId(_clientId); - } - - var certificates = new List(); - - // Add CA (Certificate Authority) - if (!string.IsNullOrEmpty(_caCertPath)) - { - certificates.Add(new X509Certificate2(GetFilePath(_caCertPath))); - } - - // Add Client Certificate & Private Key - if (!string.IsNullOrEmpty(_pemClientCertPath) && !string.IsNullOrEmpty(_pemPrivateKeyPath)) - { - -#if NET5_0_OR_GREATER - certificates.Add(new X509Certificate2(X509Certificate2.CreateFromPemFile(GetFilePath(_pemClientCertPath), GetFilePath(_pemPrivateKeyPath)).Export(X509ContentType.Pfx))); -#else - throw new Exception("PEM Certificates Not Supported in .NET Framework 4.8 or older"); -#endif - - clientOptionsBuilder.WithTls(new MqttClientOptionsBuilderTlsParameters() - { - UseTls = true, - SslProtocol = System.Security.Authentication.SslProtocols.Tls12, - IgnoreCertificateRevocationErrors = _allowUntrustedCertificates, - IgnoreCertificateChainErrors = _allowUntrustedCertificates, - AllowUntrustedCertificates = _allowUntrustedCertificates, - Certificates = certificates - }); - } - - // Add Credentials - if (!string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(_password)) - { - if (_useTls) - { - clientOptionsBuilder.WithCredentials(_username, _password).WithTls(); - } - else - { - clientOptionsBuilder.WithCredentials(_username, _password); - } - } - - // Build MQTT Client Options - var clientOptions = clientOptionsBuilder.Build(); - - // Connect to the MQTT Client - _mqttClient.ConnectAsync(clientOptions).Wait(); - - - if (!string.IsNullOrEmpty(_topic)) - { - await _mqttClient.SubscribeAsync(_topic); - } - else - { - // ERROR ? - } - - - //ClientStarted?.Invoke(this, new EventArgs()); - - while (_mqttClient.IsConnected && !_stop.IsCancellationRequested) - { - await Task.Delay(100); - } - } - catch (Exception ex) - { - //if (ConnectionError != null) ConnectionError.Invoke(this, ex); - } - - await Task.Delay(_retryInterval, _stop.Token); - } - catch (TaskCanceledException) { } - catch (Exception ex) - { - //InternalError?.Invoke(this, ex); - } - - } while (!_stop.Token.IsCancellationRequested); - - - try - { - // Disconnect from the MQTT Client - if (_mqttClient != null) _mqttClient.DisconnectAsync(MqttClientDisconnectReason.NormalDisconnection).Wait(); - } - catch { } - } - - private async Task MessageReceived(MqttApplicationMessageReceivedEventArgs args) - { - if (args.ApplicationMessage.Payload != null && args.ApplicationMessage.Payload.Length > 0) - { - var topic = args.ApplicationMessage.Topic; - - var dataModels = ProcessPayload(args.ApplicationMessage.Payload); - if (!dataModels.IsNullOrEmpty()) - { - Console.WriteLine(topic); - Console.WriteLine(JsonSerializer.Serialize(dataModels)); - - foreach (var dataModel in dataModels) - { - _mtconnectAgent.AddObservations(_deviceKey, dataModel.ToObservationInputs()); - } - } - - //try - //{ - // //var json = System.Text.Encoding.UTF8.GetString(args.ApplicationMessage.Payload); - // //if (!string.IsNullOrEmpty(json)) - // //{ - // // //var dataModels = JsonSerializer.Deserialize>(json); - // // //if (!dataModels.IsNullOrEmpty()) - // // //{ - // // // Console.WriteLine(topic); - // // // Console.WriteLine(JsonSerializer.Serialize(dataModels)); - - // // // foreach (var dataModel in dataModels) - // // // { - // // // _mtconnectAgent.AddObservations(_deviceKey, dataModel.ToObservationInputs()); - // // // } - // // //} - // //} - //} - //catch (Exception ex) - //{ - - //} - } - } - - public static IEnumerable ProcessPayload(byte[] payload) - { - if (!payload.IsNullOrEmpty()) - { - try - { - //// Decompress from gzip - //byte[] uncompressedBytes; - //using (var inputStream = new MemoryStream(payload)) - //using (var outputStream = new MemoryStream()) - //using (var encodingStream = new GZipStream(inputStream, CompressionMode.Decompress, true)) - //{ - // encodingStream.CopyTo(outputStream); - // uncompressedBytes = outputStream.ToArray(); - //} - - var uncompressedBytes = payload; - if (!uncompressedBytes.IsNullOrEmpty()) - { - // Convert Protobuf to Mqtt PayloadModel - PayloadModel payloadModel = null; - using (var inputStream2 = new MemoryStream(uncompressedBytes)) - { - payloadModel = Serializer.Deserialize(inputStream2); - } - - if (payloadModel != null) - { - return payloadModel.DataModels; - } - } - } - catch (Exception ex) - { - - } - } - - return null; - } - - //public static byte[] CreatePayload(TrakHoundEntityCollection collection) - //{ - // if (collection != null) - // { - // try - // { - // // Convert to Mqtt Collection (serializable to Protobuf) - // var mqttCollection = new TrakHoundMqttEntityCollection(collection); - - // // Convert to Protobuf - // byte[] protobufBytes; - // using (var inputStream1 = new MemoryStream()) - // { - // Serializer.Serialize(inputStream1, mqttCollection); - // protobufBytes = inputStream1.ToArray(); - // } - - // // Compress to gzip - // byte[] compressedBytes; - // using (var inputStream2 = new MemoryStream()) - // { - // using (var zip = new GZipStream(inputStream2, CompressionMode.Compress, true)) - // { - // zip.Write(protobufBytes, 0, protobufBytes.Length); - // } - // compressedBytes = inputStream2.ToArray(); - // } - - // return compressedBytes; - // } - // catch { } - // } - - // return null; - //} - - - private static string GetFilePath(string path) - { - var x = path; - if (!Path.IsPathRooted(x)) - { - x = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, x); - } - - return x; - } - } -} \ No newline at end of file diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/ModuleConfiguration - Copy.cs b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/ModuleConfiguration - Copy.cs deleted file mode 100644 index d2f33230..00000000 --- a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/ModuleConfiguration - Copy.cs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2023 TrakHound Inc., All Rights Reserved. -// TrakHound Inc. licenses this file to you under the MIT license. - -using System.Text.Json.Serialization; - -namespace MTConnect.Configurations -{ - public class ModuleConfiguration - { - [JsonPropertyName("server")] - public string Server { get; set; } - - [JsonPropertyName("port")] - public int Port { get; set; } - - [JsonPropertyName("interval")] - public int Interval { get; set; } - - [JsonPropertyName("username")] - public string Username { get; set; } - - [JsonPropertyName("password")] - public string Password { get; set; } - - [JsonPropertyName("clientId")] - public string ClientId { get; set; } - - [JsonPropertyName("qos")] - public int QoS { get; set; } - - [JsonPropertyName("certificateAuthority")] - public string CertificateAuthority { get; set; } - - [JsonPropertyName("pemCertificate")] - public string PemCertificate { get; set; } - - [JsonPropertyName("pemPrivateKey")] - public string PemPrivateKey { get; set; } - - [JsonPropertyName("allowUntrustedCertificates")] - public bool AllowUntrustedCertificates { get; set; } - - [JsonPropertyName("useTls")] - public bool UseTls { get; set; } - - [JsonPropertyName("retryInterval")] - public int RetryInterval { get; set; } - - [JsonPropertyName("topic")] - public string Topic { get; set; } - - [JsonPropertyName("deviceKey")] - public string DeviceKey { get; set; } - - - public ModuleConfiguration() - { - Server = "localhost"; - Port = 1883; - QoS = 1; - RetryInterval = 5000; - } - } -} \ No newline at end of file diff --git a/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/README.md b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/README.md new file mode 100644 index 00000000..35726b9a --- /dev/null +++ b/agent/Modules/MTConnect.NET-AgentModule-MqttAdapter/README.md @@ -0,0 +1,32 @@ +![MTConnect.NET Logo](https://raw.githubusercontent.com/TrakHound/MTConnect.NET/dev/img/mtconnect-net-03-md.png) + +# MTConnect MQTT Adapter Agent Module + +## Description +This Agent Module implements an adapter to read from an MQTT broker + +## Configuration +```yaml +- mqtt-adapter: + server: localhost + port: 1883 + topic: cnc-01 + deviceKey: M12346 +``` + +* `server` - The MQTT broker hostname. + +* `port` - The MQTT broker port number. + +* `topic` - The MQTT topic to subscribe to + +* `deviceKey` - The UUID or Name of the Device to read data for. + + +## Contribution / Feedback +- Please use the [Issues](https://github.com/TrakHound/MTConnect.NET/issues) tab to create issues for specific problems that you may encounter +- Please feel free to use the [Pull Requests](https://github.com/TrakHound/MTConnect.NET/pulls) tab for any suggested improvements to the source code +- For any other questions or feedback, please contact TrakHound directly at **info@trakhound.com**. + +## License +This application and it's source code is licensed under the [MIT License](https://choosealicense.com/licenses/mit/) and is free to use.