using System; using System.Diagnostics; using System.Text.RegularExpressions; namespace Mqtt_SWB_Dashboard { class Mosquitto : IDisposable { private Process p; private String message; public delegate void MqttMessage(Object sender, MqttEventArgs e); public event MqttMessage MessageIncomming; public Mosquitto() { //mosquitto_sub --cafile ca.pem --cert cert.pem --key cert.key -h swb.broker.flex4grid.eu -p 8883 -t /# -v this.message = ""; this.p = new Process(); this.p.StartInfo.FileName = "mosquitto_sub.exe"; this.p.StartInfo.Arguments = "--cafile ca.pem --cert cert.pem --key cert.key -h swb.broker.flex4grid.eu -p 8883 -t /# -v -d"; this.p.StartInfo.CreateNoWindow = true; this.p.StartInfo.UseShellExecute = false; this.p.StartInfo.RedirectStandardOutput = true; this.p.OutputDataReceived += this.P_OutputDataReceived; this.p.Start(); this.p.BeginOutputReadLine(); } private void P_OutputDataReceived(Object sender, DataReceivedEventArgs e) { if (e.Data != null) { if (e.Data.StartsWith("Client mosqsub")) { if (this.message != "" && this.message.IndexOf(" received PUBLISH ") > 0) { MatchCollection matches = (new Regex("^Client mosqsub\\|.*received PUBLISH \\(.*,.*,.*,.*, '(.*)'.*\\)\\)\n[^ ]* (.*)$", RegexOptions.IgnoreCase | RegexOptions.Singleline)).Matches(this.message); String topic = matches[0].Groups[1].Value; String message = matches[0].Groups[2].Value.Trim(); this.MessageIncomming?.Invoke(this, new MqttEventArgs(message, topic)); } this.message = e.Data + "\n"; } else { this.message += e.Data + "\n"; } } } #region IDisposable Support private bool disposedValue = false; // Dient zur Erkennung redundanter Aufrufe. protected virtual void Dispose(Boolean disposing) { if (!this.disposedValue) { if (disposing) { this.p.CancelOutputRead(); this.p.Kill(); this.p.Close(); } this.p = null; this.disposedValue = true; } } ~Mosquitto() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } class MqttEventArgs : EventArgs { public MqttEventArgs() : base() { } public MqttEventArgs(String message, String topic) { this.Topic = topic; this.Message = message; this.Date = DateTime.Now; } public String Topic { get; private set; } public String Message { get; private set; } public DateTime Date { get; private set; } } }