using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tango.Transport.Routing { /// /// Represents a transport router capable of exchanging data between two of different types. /// /// public class TransportRoutingChannel : ITransportComponent { /// /// Gets or sets the name of the transport component. /// public String ComponentName { get; set; } /// /// Occurs when component state changes. /// public event EventHandler StateChanged; /// /// Gets or sets the first adapter. /// public ITransportAdapter Adapter1 { get; private set; } /// /// Gets or sets the second adapter. /// public ITransportAdapter Adapter2 { get; private set; } private TransportComponentState _state; /// /// Gets the component state. /// public TransportComponentState State { get { return _state; } private set { _state = value; StateChanged?.Invoke(this, State); } } /// /// Initializes a new instance of the class. /// /// The first adapter. /// The second adapter. public TransportRoutingChannel(ITransportAdapter adapter1, ITransportAdapter adapter2) { ComponentName = "Routing Channel"; Adapter1 = adapter1; Adapter2 = adapter2; Adapter1.DataAvailable += OnAdapter1DataAvailable; Adapter2.DataAvailable += OnAdapter2DataAvailable; Adapter1.StateChanged += OnAdapter1StateChanged; Adapter2.StateChanged += OnAdapter2StateChanged; } /// /// Called when the first adapter state has changed. /// /// The sender. /// The state. protected virtual void OnAdapter1StateChanged(object sender, TransportComponentState state) { if (state == TransportComponentState.Failed) { State = TransportComponentState.Failed; } } /// /// Called when the second adapter state has changed. /// /// The sender. /// The state. protected virtual void OnAdapter2StateChanged(object sender, TransportComponentState state) { if (state == TransportComponentState.Failed) { State = TransportComponentState.Failed; } } /// /// Called when the first adapter has available data. /// /// The sender. /// The data. protected virtual void OnAdapter1DataAvailable(object sender, byte[] data) { Adapter2.Write(data); } /// /// Called when the second adapter has available data. /// /// The sender. /// The data. protected virtual void OnAdapter2DataAvailable(object sender, byte[] data) { Adapter1.Write(data); } /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// public void Dispose() { if (Adapter1 != null) Adapter1.Dispose(); if (Adapter2 != null) Adapter2.Dispose(); } /// /// Connects the transport component. /// /// public Task Connect() { var result = Task.WhenAll(Adapter1.Connect(), Adapter2.Connect()); State = TransportComponentState.Connected; return result; } /// /// Disconnects the transport component. /// /// public Task Disconnect() { var result = Task.WhenAll(Adapter1.Disconnect(), Adapter2.Disconnect()); State = TransportComponentState.Disconnected; return result; } } }