DeviceDiscovery.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Dlna;
  5. using MediaBrowser.Model.Logging;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Model.Dlna;
  14. using MediaBrowser.Model.Events;
  15. using MediaBrowser.Model.Net;
  16. using MediaBrowser.Model.Threading;
  17. using Rssdp;
  18. using Rssdp.Infrastructure;
  19. namespace Emby.Dlna.Ssdp
  20. {
  21. public class DeviceDiscovery : IDeviceDiscovery, IDisposable
  22. {
  23. private bool _disposed;
  24. private readonly ILogger _logger;
  25. private readonly IServerConfigurationManager _config;
  26. private readonly CancellationTokenSource _tokenSource;
  27. public event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceDiscovered;
  28. public event EventHandler<GenericEventArgs<UpnpDeviceInfo>> DeviceLeft;
  29. private SsdpDeviceLocator _deviceLocator;
  30. private readonly ITimerFactory _timerFactory;
  31. private readonly ISocketFactory _socketFactory;
  32. public DeviceDiscovery(ILogger logger, IServerConfigurationManager config, ISocketFactory socketFactory, ITimerFactory timerFactory)
  33. {
  34. _tokenSource = new CancellationTokenSource();
  35. _logger = logger;
  36. _config = config;
  37. _socketFactory = socketFactory;
  38. _timerFactory = timerFactory;
  39. }
  40. // Call this method from somewhere in your code to start the search.
  41. public void Start(ISsdpCommunicationsServer communicationsServer)
  42. {
  43. _deviceLocator = new SsdpDeviceLocator(communicationsServer, _timerFactory);
  44. // (Optional) Set the filter so we only see notifications for devices we care about
  45. // (can be any search target value i.e device type, uuid value etc - any value that appears in the
  46. // DiscoverdSsdpDevice.NotificationType property or that is used with the searchTarget parameter of the Search method).
  47. //_DeviceLocator.NotificationFilter = "upnp:rootdevice";
  48. // Connect our event handler so we process devices as they are found
  49. _deviceLocator.DeviceAvailable += deviceLocator_DeviceAvailable;
  50. _deviceLocator.DeviceUnavailable += _DeviceLocator_DeviceUnavailable;
  51. // Perform a search so we don't have to wait for devices to broadcast notifications
  52. // again to get any results right away (notifications are broadcast periodically).
  53. StartAsyncSearch();
  54. }
  55. private void StartAsyncSearch()
  56. {
  57. Task.Factory.StartNew(async (o) =>
  58. {
  59. while (!_tokenSource.IsCancellationRequested)
  60. {
  61. try
  62. {
  63. // Enable listening for notifications (optional)
  64. _deviceLocator.StartListeningForNotifications();
  65. await _deviceLocator.SearchAsync().ConfigureAwait(false);
  66. }
  67. catch (Exception ex)
  68. {
  69. _logger.ErrorException("Error searching for devices", ex);
  70. }
  71. var delay = _config.GetDlnaConfiguration().ClientDiscoveryIntervalSeconds * 1000;
  72. await Task.Delay(delay, _tokenSource.Token).ConfigureAwait(false);
  73. }
  74. }, CancellationToken.None, TaskCreationOptions.LongRunning);
  75. }
  76. // Process each found device in the event handler
  77. void deviceLocator_DeviceAvailable(object sender, DeviceAvailableEventArgs e)
  78. {
  79. var originalHeaders = e.DiscoveredDevice.ResponseHeaders;
  80. var headerDict = originalHeaders == null ? new Dictionary<string, KeyValuePair<string, IEnumerable<string>>>() : originalHeaders.ToDictionary(i => i.Key, StringComparer.OrdinalIgnoreCase);
  81. var headers = headerDict.ToDictionary(i => i.Key, i => i.Value.Value.FirstOrDefault(), StringComparer.OrdinalIgnoreCase);
  82. var args = new GenericEventArgs<UpnpDeviceInfo>
  83. {
  84. Argument = new UpnpDeviceInfo
  85. {
  86. Location = e.DiscoveredDevice.DescriptionLocation,
  87. Headers = headers,
  88. LocalIpAddress = e.LocalIpAddress
  89. }
  90. };
  91. EventHelper.FireEventIfNotNull(DeviceDiscovered, this, args, _logger);
  92. }
  93. private void _DeviceLocator_DeviceUnavailable(object sender, DeviceUnavailableEventArgs e)
  94. {
  95. var originalHeaders = e.DiscoveredDevice.ResponseHeaders;
  96. var headerDict = originalHeaders == null ? new Dictionary<string, KeyValuePair<string, IEnumerable<string>>>() : originalHeaders.ToDictionary(i => i.Key, StringComparer.OrdinalIgnoreCase);
  97. var headers = headerDict.ToDictionary(i => i.Key, i => i.Value.Value.FirstOrDefault(), StringComparer.OrdinalIgnoreCase);
  98. var args = new GenericEventArgs<UpnpDeviceInfo>
  99. {
  100. Argument = new UpnpDeviceInfo
  101. {
  102. Location = e.DiscoveredDevice.DescriptionLocation,
  103. Headers = headers
  104. }
  105. };
  106. EventHelper.FireEventIfNotNull(DeviceLeft, this, args, _logger);
  107. }
  108. public void Dispose()
  109. {
  110. if (!_disposed)
  111. {
  112. _disposed = true;
  113. _tokenSource.Cancel();
  114. }
  115. }
  116. }
  117. }