ConnectionChecker.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Wayne.Lib
  4. {
  5. /// <summary>
  6. /// Handles a collection of IConnectable items, and checks them all so they are connected.
  7. /// </summary>
  8. public class ConnectionChecker
  9. {
  10. private readonly IList<ConnectableItem> connectableItems = new List<ConnectableItem>();
  11. private readonly object connectableItemsLock=new object();
  12. /// <summary>
  13. /// Is all connectable items connected?
  14. /// </summary>
  15. /// <returns></returns>
  16. public bool IsConnectedToAll()
  17. {
  18. lock (connectableItemsLock)
  19. {
  20. foreach (var connectableItem in connectableItems)
  21. {
  22. if (connectableItem.Connectable.ConnectionState != DeviceConnectionState.Connected)
  23. return false;
  24. }
  25. }
  26. return true;
  27. }
  28. /// <summary>
  29. /// Adds a connectable entity to the check.
  30. /// </summary>
  31. /// <param name="connectable"></param>
  32. /// <param name="connectableDisplayName"></param>
  33. public void AddConnectableToCheck(IConnectable connectable, string connectableDisplayName)
  34. {
  35. if(connectable == null)
  36. throw new ArgumentNullException("connectable", "A instance of IConnectable is required.");
  37. connectableItems.Add(new ConnectableItem() { Connectable = connectable, DisplayName = connectableDisplayName});
  38. }
  39. /// <summary>
  40. /// Gets a list of strings containingt those items that are not connected, and their current connection state.
  41. /// </summary>
  42. /// <returns></returns>
  43. public IList<string> GetUnconnectedAsText()
  44. {
  45. IList<string> reasons = new List<string>();
  46. foreach (var connectableItem in connectableItems)
  47. {
  48. if (connectableItem.Connectable.ConnectionState != DeviceConnectionState.Connected)
  49. reasons.Add(connectableItem.DisplayName + ".ConnectionState = " + connectableItem.Connectable.ConnectionState);
  50. }
  51. return reasons;
  52. }
  53. class ConnectableItem
  54. {
  55. public IConnectable Connectable { get; set; }
  56. public string DisplayName { get; set; }
  57. }
  58. }
  59. }