SsdpDeviceLocatorBase.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Model.Net;
  11. using MediaBrowser.Model.Threading;
  12. using RSSDP;
  13. namespace Rssdp.Infrastructure
  14. {
  15. /// <summary>
  16. /// Allows you to search the network for a particular device, device types, or UPnP service types. Also listenings for broadcast notifications of device availability and raises events to indicate changes in status.
  17. /// </summary>
  18. public abstract class SsdpDeviceLocatorBase : DisposableManagedObjectBase
  19. {
  20. #region Fields & Constants
  21. private List<DiscoveredSsdpDevice> _Devices;
  22. private ISsdpCommunicationsServer _CommunicationsServer;
  23. private ITimer _BroadcastTimer;
  24. private ITimerFactory _timerFactory;
  25. private object _timerLock = new object();
  26. private static readonly TimeSpan DefaultSearchWaitTime = TimeSpan.FromSeconds(4);
  27. private static readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1);
  28. #endregion
  29. #region Constructors
  30. /// <summary>
  31. /// Default constructor.
  32. /// </summary>
  33. protected SsdpDeviceLocatorBase(ISsdpCommunicationsServer communicationsServer, ITimerFactory timerFactory)
  34. {
  35. if (communicationsServer == null) throw new ArgumentNullException("communicationsServer");
  36. _CommunicationsServer = communicationsServer;
  37. _timerFactory = timerFactory;
  38. _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived;
  39. _Devices = new List<DiscoveredSsdpDevice>();
  40. }
  41. #endregion
  42. #region Events
  43. /// <summary>
  44. /// Raised for when
  45. /// <list type="bullet">
  46. /// <item>An 'alive' notification is received that a device, regardless of whether or not that device is not already in the cache or has previously raised this event.</item>
  47. /// <item>For each item found during a device <see cref="SearchAsync()"/> (cached or not), allowing clients to respond to found devices before the entire search is complete.</item>
  48. /// <item>Only if the notification type matches the <see cref="NotificationFilter"/> property. By default the filter is null, meaning all notifications raise events (regardless of ant </item>
  49. /// </list>
  50. /// <para>This event may be raised from a background thread, if interacting with UI or other objects with specific thread affinity invoking to the relevant thread is required.</para>
  51. /// </summary>
  52. /// <seealso cref="NotificationFilter"/>
  53. /// <seealso cref="DeviceUnavailable"/>
  54. /// <seealso cref="StartListeningForNotifications"/>
  55. /// <seealso cref="StopListeningForNotifications"/>
  56. public event EventHandler<DeviceAvailableEventArgs> DeviceAvailable;
  57. /// <summary>
  58. /// Raised when a notification is received that indicates a device has shutdown or otherwise become unavailable.
  59. /// </summary>
  60. /// <remarks>
  61. /// <para>Devices *should* broadcast these types of notifications, but not all devices do and sometimes (in the event of power loss for example) it might not be possible for a device to do so. You should also implement error handling when trying to contact a device, even if RSSDP is reporting that device as available.</para>
  62. /// <para>This event is only raised if the notification type matches the <see cref="NotificationFilter"/> property. A null or empty string for the <see cref="NotificationFilter"/> will be treated as no filter and raise the event for all notifications.</para>
  63. /// <para>The <see cref="DeviceUnavailableEventArgs.DiscoveredDevice"/> property may contain either a fully complete <see cref="DiscoveredSsdpDevice"/> instance, or one containing just a USN and NotificationType property. Full information is available if the device was previously discovered and cached, but only partial information if a byebye notification was received for a previously unseen or expired device.</para>
  64. /// <para>This event may be raised from a background thread, if interacting with UI or other objects with specific thread affinity invoking to the relevant thread is required.</para>
  65. /// </remarks>
  66. /// <seealso cref="NotificationFilter"/>
  67. /// <seealso cref="DeviceAvailable"/>
  68. /// <seealso cref="StartListeningForNotifications"/>
  69. /// <seealso cref="StopListeningForNotifications"/>
  70. public event EventHandler<DeviceUnavailableEventArgs> DeviceUnavailable;
  71. #endregion
  72. #region Public Methods
  73. #region Search Overloads
  74. public void RestartBroadcastTimer(TimeSpan dueTime, TimeSpan period)
  75. {
  76. lock (_timerLock)
  77. {
  78. if (_BroadcastTimer == null)
  79. {
  80. _BroadcastTimer = _timerFactory.Create(OnBroadcastTimerCallback, null, dueTime, period);
  81. }
  82. else
  83. {
  84. _BroadcastTimer.Change(dueTime, period);
  85. }
  86. }
  87. }
  88. public void DisposeBroadcastTimer()
  89. {
  90. lock (_timerLock)
  91. {
  92. if (_BroadcastTimer != null)
  93. {
  94. _BroadcastTimer.Dispose();
  95. _BroadcastTimer = null;
  96. }
  97. }
  98. }
  99. private async void OnBroadcastTimerCallback(object state)
  100. {
  101. StartListeningForNotifications();
  102. RemoveExpiredDevicesFromCache();
  103. try
  104. {
  105. await SearchAsync(CancellationToken.None).ConfigureAwait(false);
  106. }
  107. catch (Exception ex)
  108. {
  109. }
  110. }
  111. /// <summary>
  112. /// Performs a search for all devices using the default search timeout.
  113. /// </summary>
  114. private Task SearchAsync(CancellationToken cancellationToken)
  115. {
  116. return SearchAsync(SsdpConstants.SsdpDiscoverAllSTHeader, DefaultSearchWaitTime, cancellationToken);
  117. }
  118. /// <summary>
  119. /// Performs a search for the specified search target (criteria) and default search timeout.
  120. /// </summary>
  121. /// <param name="searchTarget">The criteria for the search. Value can be;
  122. /// <list type="table">
  123. /// <item><term>Root devices</term><description>upnp:rootdevice</description></item>
  124. /// <item><term>Specific device by UUID</term><description>uuid:&lt;device uuid&gt;</description></item>
  125. /// <item><term>Device type</term><description>Fully qualified device type starting with urn: i.e urn:schemas-upnp-org:Basic:1</description></item>
  126. /// </list>
  127. /// </param>
  128. private Task SearchAsync(string searchTarget)
  129. {
  130. return SearchAsync(searchTarget, DefaultSearchWaitTime, CancellationToken.None);
  131. }
  132. /// <summary>
  133. /// Performs a search for all devices using the specified search timeout.
  134. /// </summary>
  135. /// <param name="searchWaitTime">The amount of time to wait for network responses to the search request. Longer values will likely return more devices, but increase search time. A value between 1 and 5 seconds is recommended by the UPnP 1.1 specification, this method requires the value be greater 1 second if it is not zero. Specify TimeSpan.Zero to return only devices already in the cache.</param>
  136. private Task SearchAsync(TimeSpan searchWaitTime)
  137. {
  138. return SearchAsync(SsdpConstants.SsdpDiscoverAllSTHeader, searchWaitTime, CancellationToken.None);
  139. }
  140. private Task SearchAsync(string searchTarget, TimeSpan searchWaitTime, CancellationToken cancellationToken)
  141. {
  142. if (searchTarget == null) throw new ArgumentNullException("searchTarget");
  143. if (searchTarget.Length == 0) throw new ArgumentException("searchTarget cannot be an empty string.", "searchTarget");
  144. if (searchWaitTime.TotalSeconds < 0) throw new ArgumentException("searchWaitTime must be a positive time.");
  145. if (searchWaitTime.TotalSeconds > 0 && searchWaitTime.TotalSeconds <= 1) throw new ArgumentException("searchWaitTime must be zero (if you are not using the result and relying entirely in the events), or greater than one second.");
  146. ThrowIfDisposed();
  147. return BroadcastDiscoverMessage(searchTarget, SearchTimeToMXValue(searchWaitTime), cancellationToken);
  148. }
  149. #endregion
  150. /// <summary>
  151. /// Starts listening for broadcast notifications of service availability.
  152. /// </summary>
  153. /// <remarks>
  154. /// <para>When called the system will listen for 'alive' and 'byebye' notifications. This can speed up searching, as well as provide dynamic notification of new devices appearing on the network, and previously discovered devices disappearing.</para>
  155. /// </remarks>
  156. /// <seealso cref="StopListeningForNotifications"/>
  157. /// <seealso cref="DeviceAvailable"/>
  158. /// <seealso cref="DeviceUnavailable"/>
  159. /// <exception cref="System.ObjectDisposedException">Throw if the <see cref="DisposableManagedObjectBase.IsDisposed"/> ty is true.</exception>
  160. public void StartListeningForNotifications()
  161. {
  162. ThrowIfDisposed();
  163. _CommunicationsServer.RequestReceived -= CommsServer_RequestReceived;
  164. _CommunicationsServer.RequestReceived += CommsServer_RequestReceived;
  165. _CommunicationsServer.BeginListeningForBroadcasts();
  166. }
  167. /// <summary>
  168. /// Stops listening for broadcast notifications of service availability.
  169. /// </summary>
  170. /// <remarks>
  171. /// <para>Does nothing if this instance is not already listening for notifications.</para>
  172. /// </remarks>
  173. /// <seealso cref="StartListeningForNotifications"/>
  174. /// <seealso cref="DeviceAvailable"/>
  175. /// <seealso cref="DeviceUnavailable"/>
  176. /// <exception cref="System.ObjectDisposedException">Throw if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true.</exception>
  177. public void StopListeningForNotifications()
  178. {
  179. ThrowIfDisposed();
  180. _CommunicationsServer.RequestReceived -= CommsServer_RequestReceived;
  181. }
  182. /// <summary>
  183. /// Raises the <see cref="DeviceAvailable"/> event.
  184. /// </summary>
  185. /// <seealso cref="DeviceAvailable"/>
  186. protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IpAddressInfo localIpAddress)
  187. {
  188. if (this.IsDisposed) return;
  189. var handlers = this.DeviceAvailable;
  190. if (handlers != null)
  191. handlers(this, new DeviceAvailableEventArgs(device, isNewDevice)
  192. {
  193. LocalIpAddress = localIpAddress
  194. });
  195. }
  196. /// <summary>
  197. /// Raises the <see cref="DeviceUnavailable"/> event.
  198. /// </summary>
  199. /// <param name="device">A <see cref="DiscoveredSsdpDevice"/> representing the device that is no longer available.</param>
  200. /// <param name="expired">True if the device expired from the cache without being renewed, otherwise false to indicate the device explicitly notified us it was being shutdown.</param>
  201. /// <seealso cref="DeviceUnavailable"/>
  202. protected virtual void OnDeviceUnavailable(DiscoveredSsdpDevice device, bool expired)
  203. {
  204. if (this.IsDisposed) return;
  205. var handlers = this.DeviceUnavailable;
  206. if (handlers != null)
  207. handlers(this, new DeviceUnavailableEventArgs(device, expired));
  208. }
  209. #endregion
  210. #region Public Properties
  211. /// <summary>
  212. /// Sets or returns a string containing the filter for notifications. Notifications not matching the filter will not raise the <see cref="ISsdpDeviceLocator.DeviceAvailable"/> or <see cref="ISsdpDeviceLocator.DeviceUnavailable"/> events.
  213. /// </summary>
  214. /// <remarks>
  215. /// <para>Device alive/byebye notifications whose NT header does not match this filter value will still be captured and cached internally, but will not raise events about device availability. Usually used with either a device type of uuid NT header value.</para>
  216. /// <para>If the value is null or empty string then, all notifications are reported.</para>
  217. /// <para>Example filters follow;</para>
  218. /// <example>upnp:rootdevice</example>
  219. /// <example>urn:schemas-upnp-org:device:WANDevice:1</example>
  220. /// <example>uuid:9F15356CC-95FA-572E-0E99-85B456BD3012</example>
  221. /// </remarks>
  222. /// <seealso cref="ISsdpDeviceLocator.DeviceAvailable"/>
  223. /// <seealso cref="ISsdpDeviceLocator.DeviceUnavailable"/>
  224. /// <seealso cref="ISsdpDeviceLocator.StartListeningForNotifications"/>
  225. /// <seealso cref="ISsdpDeviceLocator.StopListeningForNotifications"/>
  226. public string NotificationFilter
  227. {
  228. get;
  229. set;
  230. }
  231. #endregion
  232. #region Overrides
  233. /// <summary>
  234. /// Disposes this object and all internal resources. Stops listening for all network messages.
  235. /// </summary>
  236. /// <param name="disposing">True if managed resources should be disposed, or false is only unmanaged resources should be cleaned up.</param>
  237. protected override void Dispose(bool disposing)
  238. {
  239. if (disposing)
  240. {
  241. DisposeBroadcastTimer();
  242. var commsServer = _CommunicationsServer;
  243. _CommunicationsServer = null;
  244. if (commsServer != null)
  245. {
  246. commsServer.ResponseReceived -= this.CommsServer_ResponseReceived;
  247. commsServer.RequestReceived -= this.CommsServer_RequestReceived;
  248. if (!commsServer.IsShared)
  249. commsServer.Dispose();
  250. }
  251. }
  252. }
  253. #endregion
  254. #region Private Methods
  255. #region Discovery/Device Add
  256. private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IpAddressInfo localIpAddress)
  257. {
  258. bool isNewDevice = false;
  259. lock (_Devices)
  260. {
  261. var existingDevice = FindExistingDeviceNotification(_Devices, device.NotificationType, device.Usn);
  262. if (existingDevice == null)
  263. {
  264. _Devices.Add(device);
  265. isNewDevice = true;
  266. }
  267. else
  268. {
  269. _Devices.Remove(existingDevice);
  270. _Devices.Add(device);
  271. }
  272. }
  273. DeviceFound(device, isNewDevice, localIpAddress);
  274. }
  275. private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IpAddressInfo localIpAddress)
  276. {
  277. if (!NotificationTypeMatchesFilter(device)) return;
  278. OnDeviceAvailable(device, isNewDevice, localIpAddress);
  279. }
  280. private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device)
  281. {
  282. return String.IsNullOrEmpty(this.NotificationFilter)
  283. || this.NotificationFilter == SsdpConstants.SsdpDiscoverAllSTHeader
  284. || device.NotificationType == this.NotificationFilter;
  285. }
  286. #endregion
  287. #region Network Message Processing
  288. private Task BroadcastDiscoverMessage(string serviceType, TimeSpan mxValue, CancellationToken cancellationToken)
  289. {
  290. var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  291. values["HOST"] = "239.255.255.250:1900";
  292. values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2";
  293. //values["X-EMBY-SERVERID"] = _appHost.SystemId;
  294. values["MAN"] = "\"ssdp:discover\"";
  295. // Search target
  296. values["ST"] = "ssdp:all";
  297. // Seconds to delay response
  298. values["MX"] = "3";
  299. var header = "M-SEARCH * HTTP/1.1";
  300. var message = SsdpHelper.BuildMessage(header, values);
  301. return _CommunicationsServer.SendMulticastMessage(message, cancellationToken);
  302. }
  303. private void ProcessSearchResponseMessage(HttpResponseMessage message, IpAddressInfo localIpAddress)
  304. {
  305. if (!message.IsSuccessStatusCode) return;
  306. var location = GetFirstHeaderUriValue("Location", message);
  307. if (location != null)
  308. {
  309. var device = new DiscoveredSsdpDevice()
  310. {
  311. DescriptionLocation = location,
  312. Usn = GetFirstHeaderStringValue("USN", message),
  313. NotificationType = GetFirstHeaderStringValue("ST", message),
  314. CacheLifetime = CacheAgeFromHeader(message.Headers.CacheControl),
  315. AsAt = DateTimeOffset.Now,
  316. ResponseHeaders = message.Headers
  317. };
  318. AddOrUpdateDiscoveredDevice(device, localIpAddress);
  319. }
  320. }
  321. private void ProcessNotificationMessage(HttpRequestMessage message, IpAddressInfo localIpAddress)
  322. {
  323. if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0) return;
  324. var notificationType = GetFirstHeaderStringValue("NTS", message);
  325. if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0)
  326. ProcessAliveNotification(message, localIpAddress);
  327. else if (String.Compare(notificationType, SsdpConstants.SsdpByeByeNotification, StringComparison.OrdinalIgnoreCase) == 0)
  328. ProcessByeByeNotification(message);
  329. }
  330. private void ProcessAliveNotification(HttpRequestMessage message, IpAddressInfo localIpAddress)
  331. {
  332. var location = GetFirstHeaderUriValue("Location", message);
  333. if (location != null)
  334. {
  335. var device = new DiscoveredSsdpDevice()
  336. {
  337. DescriptionLocation = location,
  338. Usn = GetFirstHeaderStringValue("USN", message),
  339. NotificationType = GetFirstHeaderStringValue("NT", message),
  340. CacheLifetime = CacheAgeFromHeader(message.Headers.CacheControl),
  341. AsAt = DateTimeOffset.Now,
  342. ResponseHeaders = message.Headers
  343. };
  344. AddOrUpdateDiscoveredDevice(device, localIpAddress);
  345. }
  346. }
  347. private void ProcessByeByeNotification(HttpRequestMessage message)
  348. {
  349. var notficationType = GetFirstHeaderStringValue("NT", message);
  350. if (!String.IsNullOrEmpty(notficationType))
  351. {
  352. var usn = GetFirstHeaderStringValue("USN", message);
  353. if (!DeviceDied(usn, false))
  354. {
  355. var deadDevice = new DiscoveredSsdpDevice()
  356. {
  357. AsAt = DateTime.UtcNow,
  358. CacheLifetime = TimeSpan.Zero,
  359. DescriptionLocation = null,
  360. NotificationType = GetFirstHeaderStringValue("NT", message),
  361. Usn = usn,
  362. ResponseHeaders = message.Headers
  363. };
  364. if (NotificationTypeMatchesFilter(deadDevice))
  365. OnDeviceUnavailable(deadDevice, false);
  366. }
  367. }
  368. }
  369. #region Header/Message Processing Utilities
  370. private static string GetFirstHeaderStringValue(string headerName, HttpResponseMessage message)
  371. {
  372. string retVal = null;
  373. IEnumerable<string> values;
  374. if (message.Headers.Contains(headerName))
  375. {
  376. message.Headers.TryGetValues(headerName, out values);
  377. if (values != null)
  378. retVal = values.FirstOrDefault();
  379. }
  380. return retVal;
  381. }
  382. private static string GetFirstHeaderStringValue(string headerName, HttpRequestMessage message)
  383. {
  384. string retVal = null;
  385. IEnumerable<string> values;
  386. if (message.Headers.Contains(headerName))
  387. {
  388. message.Headers.TryGetValues(headerName, out values);
  389. if (values != null)
  390. retVal = values.FirstOrDefault();
  391. }
  392. return retVal;
  393. }
  394. private static Uri GetFirstHeaderUriValue(string headerName, HttpRequestMessage request)
  395. {
  396. string value = null;
  397. IEnumerable<string> values;
  398. if (request.Headers.Contains(headerName))
  399. {
  400. request.Headers.TryGetValues(headerName, out values);
  401. if (values != null)
  402. value = values.FirstOrDefault();
  403. }
  404. Uri retVal;
  405. Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out retVal);
  406. return retVal;
  407. }
  408. private static Uri GetFirstHeaderUriValue(string headerName, HttpResponseMessage response)
  409. {
  410. string value = null;
  411. IEnumerable<string> values;
  412. if (response.Headers.Contains(headerName))
  413. {
  414. response.Headers.TryGetValues(headerName, out values);
  415. if (values != null)
  416. value = values.FirstOrDefault();
  417. }
  418. Uri retVal;
  419. Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out retVal);
  420. return retVal;
  421. }
  422. private static TimeSpan CacheAgeFromHeader(System.Net.Http.Headers.CacheControlHeaderValue headerValue)
  423. {
  424. if (headerValue == null) return TimeSpan.Zero;
  425. return (TimeSpan)(headerValue.MaxAge ?? headerValue.SharedMaxAge ?? TimeSpan.Zero);
  426. }
  427. #endregion
  428. #endregion
  429. #region Expiry and Device Removal
  430. private void RemoveExpiredDevicesFromCache()
  431. {
  432. if (this.IsDisposed) return;
  433. DiscoveredSsdpDevice[] expiredDevices = null;
  434. lock (_Devices)
  435. {
  436. expiredDevices = (from device in _Devices where device.IsExpired() select device).ToArray();
  437. foreach (var device in expiredDevices)
  438. {
  439. if (this.IsDisposed) return;
  440. _Devices.Remove(device);
  441. }
  442. }
  443. // Don't do this inside lock because DeviceDied raises an event
  444. // which means public code may execute during lock and cause
  445. // problems.
  446. foreach (var expiredUsn in (from expiredDevice in expiredDevices select expiredDevice.Usn).Distinct())
  447. {
  448. if (this.IsDisposed) return;
  449. DeviceDied(expiredUsn, true);
  450. }
  451. }
  452. private IEnumerable<DiscoveredSsdpDevice> GetUnexpiredDevices()
  453. {
  454. lock (_Devices)
  455. {
  456. return (from device in _Devices where !device.IsExpired() select device).ToArray();
  457. }
  458. }
  459. private bool DeviceDied(string deviceUsn, bool expired)
  460. {
  461. IEnumerable<DiscoveredSsdpDevice> existingDevices = null;
  462. lock (_Devices)
  463. {
  464. existingDevices = FindExistingDeviceNotifications(_Devices, deviceUsn);
  465. foreach (var existingDevice in existingDevices)
  466. {
  467. if (this.IsDisposed) return true;
  468. _Devices.Remove(existingDevice);
  469. }
  470. }
  471. if (existingDevices != null && existingDevices.Any())
  472. {
  473. foreach (var removedDevice in existingDevices)
  474. {
  475. if (NotificationTypeMatchesFilter(removedDevice))
  476. OnDeviceUnavailable(removedDevice, expired);
  477. }
  478. return true;
  479. }
  480. return false;
  481. }
  482. #endregion
  483. private static TimeSpan SearchTimeToMXValue(TimeSpan searchWaitTime)
  484. {
  485. if (searchWaitTime.TotalSeconds < 2 || searchWaitTime == TimeSpan.Zero)
  486. return OneSecond;
  487. else
  488. return searchWaitTime.Subtract(OneSecond);
  489. }
  490. private static DiscoveredSsdpDevice FindExistingDeviceNotification(IEnumerable<DiscoveredSsdpDevice> devices, string notificationType, string usn)
  491. {
  492. return (from d in devices where d.NotificationType == notificationType && d.Usn == usn select d).FirstOrDefault();
  493. }
  494. private static IEnumerable<DiscoveredSsdpDevice> FindExistingDeviceNotifications(IList<DiscoveredSsdpDevice> devices, string usn)
  495. {
  496. return (from d in devices where d.Usn == usn select d).ToArray();
  497. }
  498. #endregion
  499. #region Event Handlers
  500. private void CommsServer_ResponseReceived(object sender, ResponseReceivedEventArgs e)
  501. {
  502. ProcessSearchResponseMessage(e.Message, e.LocalIpAddress);
  503. }
  504. private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
  505. {
  506. ProcessNotificationMessage(e.Message, e.LocalIpAddress);
  507. }
  508. #endregion
  509. }
  510. }