using System; using Crestron.SimplSharp; using PepperDash.Core; namespace PepperDash.Essentials.Core.Queues { public sealed class StringResponseProcessor : IKeyed, IDisposable { private readonly Action _processStringAction; private readonly IQueue _queue; private readonly IBasicCommunication _coms; private readonly CommunicationGather _gather; private StringResponseProcessor(string key, Action processStringAction) { _processStringAction = processStringAction; _queue = new GenericQueue(key); CrestronEnvironment.ProgramStatusEventHandler += programEvent => { if (programEvent != eProgramStatusEventType.Stopping) return; Dispose(); }; } /// /// Constructor that builds an instance and subscribes to coms TextReceived for processing /// /// Com port to process strings from /// Action to process the incoming strings public StringResponseProcessor(IBasicCommunication coms, Action processStringAction) : this(coms.Key, processStringAction) { _coms = coms; coms.TextReceived += OnResponseReceived; } /// /// Constructor that builds an instance and subscribes to gather Line Received for processing /// /// Gather to process strings from /// Action to process the incoming strings public StringResponseProcessor(CommunicationGather gather, Action processStringAction) : this(gather.Port.Key, processStringAction) { _gather = gather; gather.LineReceived += OnResponseReceived; } private void OnResponseReceived(object sender, GenericCommMethodReceiveTextArgs args) { _queue.Enqueue(new ProcessStringMessage(args.Text, _processStringAction)); } /// /// Key /// public string Key { get { return _queue.Key; } } /// /// Disposes the instance and cleans up resources. /// public void Dispose() { Dispose(true); CrestronEnvironment.GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (Disposed) return; if (disposing) { if (_coms != null) _coms.TextReceived -= OnResponseReceived; if (_gather != null) { _gather.LineReceived -= OnResponseReceived; _gather.Stop(); } _queue.Dispose(); } Disposed = true; } /// /// If the instance has been disposed or not. If it has, you can not use it anymore /// public bool Disposed { get; private set; } ~StringResponseProcessor() { Dispose(false); } } }