private void AddDevice(DiscoveredSsdpDevice device, SsdpDevice fullDevice)
        {
            var existingDevice = deviceList.FirstOrDefault(d => d.GetHost().Equals(device.DescriptionLocation.Host));

            if (existingDevice == null)
            {
                if (!deviceList.Any(d => d.GetUsn().Equals(device.Usn)))
                {
                    var newDevice = DependencyFactory.Container.Resolve <Device>();
                    newDevice.SetDiscoveredDevices(device, fullDevice);
                    deviceList.Add(newDevice);
                    onAddDeviceCallback?.Invoke(newDevice);

                    if (AutoStart)
                    {
                        newDevice.OnClickDeviceButton(null, null);
                    }
                }
            }
            else
            {
                existingDevice.SetDiscoveredDevices(device, fullDevice);
                existingDevice.GetDeviceControl()?.SetDeviceName(existingDevice.GetFriendlyName());
                existingDevice.GetMenuItem().Text = existingDevice.GetFriendlyName();
            }
        }
Esempio n. 2
0
        public void DeviceLocator_Notifications_ReceivesByeByeNotificationsForKnownDevice()
        {
            var server                  = new MockCommsServer();
            var deviceLocator           = new MockDeviceLocator(server);
            var receivedNotification    = false;
            DiscoveredSsdpDevice device = null;
            bool expired                = false;

            using (var eventSignal = new System.Threading.AutoResetEvent(false))
            {
                deviceLocator.DeviceUnavailable += (sender, args) =>
                {
                    device  = args.DiscoveredDevice;
                    expired = args.Expired;
                    receivedNotification = true;
                    eventSignal.Set();
                };
                deviceLocator.StartListeningForNotifications();
                server.MockReceiveBroadcast(GetMockAliveNotification());
                server.WaitForMessageToProcess(10000);

                server.MockReceiveBroadcast(GetMockByeByeNotification());
                eventSignal.WaitOne(10000);
            }

            Assert.IsTrue(receivedNotification);
            Assert.IsNotNull(device);
            Assert.IsFalse(expired);
        }
Esempio n. 3
0
        private void ProcessByeByeNotification(HttpRequestMessage message)
        {
            var notficationType = GetFirstHeaderStringValue("NT", message);

            if (!String.IsNullOrEmpty(notficationType))
            {
                var usn = GetFirstHeaderStringValue("USN", message);

                if (!DeviceDied(usn, false))
                {
                    var deadDevice = new DiscoveredSsdpDevice()
                    {
                        AsAt                = DateTime.UtcNow,
                        CacheLifetime       = TimeSpan.Zero,
                        DescriptionLocation = null,
                        NotificationType    = GetFirstHeaderStringValue("NT", message),
                        Usn = usn
                    };

                    if (NotificationTypeMatchesFilter(deadDevice))
                    {
                        OnDeviceUnavailable(deadDevice, false);
                    }
                }

                ResetExpireCachedDevicesTimer();
            }
        }
Esempio n. 4
0
        public void DeviceLocator_Notifications_SearchResponseDefaultsToZeroMaxAge()
        {
            var server        = new MockCommsServer();
            var deviceLocator = new MockDeviceLocator(server);

            var publishedDevice = CreateDeviceTree();

            publishedDevice.CacheLifetime = TimeSpan.FromMinutes(30);

            DiscoveredSsdpDevice device = null;

            using (var eventSignal = new System.Threading.AutoResetEvent(false))
            {
                deviceLocator.DeviceAvailable += (sender, args) =>
                {
                    device = args.DiscoveredDevice;
                    eventSignal.Set();
                };

                var t = deviceLocator.SearchAsync(TimeSpan.FromSeconds(3));
                System.Threading.Thread.Sleep(500);
                server.MockReceiveMessage(GetMockSearchResponseWithCustomCacheHeader(publishedDevice, publishedDevice.Udn, String.Format("CACHE-CONTROL: public")));
                eventSignal.WaitOne(10000);
                var results = t.GetAwaiter().GetResult();

                Assert.IsNotNull(results);
                Assert.IsTrue(results.Any());
                Assert.AreEqual(TimeSpan.Zero, results.First().CacheLifetime);
            }
        }
Esempio n. 5
0
        public void DeviceLocator_SearchAsync_RaisesDeviceAvailableOnResponse()
        {
            var server        = new MockCommsServer();
            var deviceLocator = new MockDeviceLocator(server);

            var publishedDevice         = CreateDeviceTree();
            DiscoveredSsdpDevice device = null;
            bool newlyDiscovered        = false;
            var  receivedNotification   = false;

            using (var eventSignal = new System.Threading.AutoResetEvent(false))
            {
                deviceLocator.DeviceAvailable += (sender, args) =>
                {
                    device               = args.DiscoveredDevice;
                    newlyDiscovered      = args.IsNewlyDiscovered;
                    receivedNotification = true;
                    eventSignal.Set();
                };


                var task = deviceLocator.SearchAsync(TimeSpan.FromSeconds(2));
                server.MockReceiveMessage(GetMockSearchResponse(publishedDevice, publishedDevice.Udn));
                eventSignal.WaitOne(10000);
                Assert.IsTrue(receivedNotification);
                var results = task.GetAwaiter().GetResult();

                Assert.IsNotNull(results);
                Assert.IsTrue(results.Any());
                Assert.IsTrue(results.First().Usn == device.Usn);
            }
        }
Esempio n. 6
0
        public void DeviceLocator_Notifications_HandlesByeByeDuringSearch()
        {
            var server        = new MockCommsServer();
            var deviceLocator = new MockDeviceLocator(server);

            DiscoveredSsdpDevice device = null;
            var receivedNotification    = false;

            using (var eventSignal = new System.Threading.AutoResetEvent(false))
            {
                deviceLocator.DeviceUnavailable += (sender, args) =>
                {
                    device = args.DiscoveredDevice;
                    receivedNotification = true;
                    eventSignal.Set();
                };
                deviceLocator.StartListeningForNotifications();
                server.MockReceiveBroadcast(GetMockAliveNotification());
                server.WaitForMessageToProcess(10000);

                var t = deviceLocator.SearchAsync(TimeSpan.FromSeconds(3));
                System.Threading.Thread.Sleep(500);
                server.MockReceiveBroadcast(GetMockByeByeNotification());
                eventSignal.WaitOne(10000);
                var results = t.GetAwaiter().GetResult();

                Assert.IsNotNull(results);
                Assert.IsFalse(results.Any());
            }

            Assert.IsTrue(receivedNotification);
            Assert.IsNotNull(device);
        }
Esempio n. 7
0
        public void DeviceLocator_Notifications_SearchResponseMissingCacheHeaderIsNonCacheable()
        {
            var server        = new MockCommsServer();
            var deviceLocator = new MockDeviceLocator(server);

            var publishedDevice         = CreateDeviceTree();
            DiscoveredSsdpDevice device = null;
            var receivedNotification    = false;

            using (var eventSignal = new System.Threading.AutoResetEvent(false))
            {
                deviceLocator.DeviceAvailable += (sender, args) =>
                {
                    device = args.DiscoveredDevice;
                    receivedNotification = true;
                    eventSignal.Set();
                };

                var t = deviceLocator.SearchAsync(TimeSpan.FromSeconds(3));
                System.Threading.Thread.Sleep(500);
                server.MockReceiveMessage(GetMockSearchResponseWithCustomCacheHeader(publishedDevice, publishedDevice.Udn, null));
                eventSignal.WaitOne(10000);
                var results = t.GetAwaiter().GetResult();

                Assert.IsNotNull(results);
                Assert.IsTrue(results.Any());
                Assert.IsTrue(receivedNotification);
                Assert.IsNotNull(device);
                Assert.AreEqual(device.Usn, String.Format("{0}:{1}", publishedDevice.Udn, publishedDevice.FullDeviceType));
                Assert.AreEqual(device.NotificationType, publishedDevice.Udn);
            }
        }
Esempio n. 8
0
        public void DeviceLocator_Notifications_DoesNotRaiseDeviceAvailableIfDisposed()
        {
            var server                  = new MockCommsServer();
            var deviceLocator           = new MockDeviceLocator(server);
            DiscoveredSsdpDevice device = null;
            bool newlyDiscovered        = false;

            var receivedNotification = false;

            using (var eventSignal = new System.Threading.AutoResetEvent(false))
            {
                deviceLocator.DeviceAvailable += (sender, args) =>
                {
                    device               = args.DiscoveredDevice;
                    newlyDiscovered      = args.IsNewlyDiscovered;
                    receivedNotification = true;
                };
                deviceLocator.StartListeningForNotifications();

                server.MockReceiveBroadcast(GetMockAliveNotification());
                server.Dispose();
                eventSignal.WaitOne(1000);
            }

            Assert.IsFalse(receivedNotification);
        }
Esempio n. 9
0
        public void DeviceLocator_SearchAsync_ReturnsCachedDevices()
        {
            var server        = new MockCommsServer();
            var deviceLocator = new MockDeviceLocator(server);

            DiscoveredSsdpDevice device = null;
            bool newlyDiscovered        = false;
            var  receivedNotification   = false;

            using (var eventSignal = new System.Threading.AutoResetEvent(false))
            {
                deviceLocator.DeviceAvailable += (sender, args) =>
                {
                    device               = args.DiscoveredDevice;
                    newlyDiscovered      = args.IsNewlyDiscovered;
                    receivedNotification = true;
                    eventSignal.Set();
                };
                deviceLocator.StartListeningForNotifications();

                server.MockReceiveBroadcast(GetMockAliveNotification());
                eventSignal.WaitOne(10000);
                Assert.IsTrue(receivedNotification);

                var results = deviceLocator.SearchAsync(TimeSpan.Zero).GetAwaiter().GetResult();
                Assert.IsNotNull(results);
                Assert.IsTrue(results.Any());
                Assert.IsTrue(results.First().Usn == device.Usn);
            }
        }
        public void TestDevices()
        {
            asyncEvent = new AutoResetEvent(false);

            // Add a device
            var devices = new Devices();

            devices.SetCallback(OnAddDeviceCallback);
            var discoveredSsdpDevice = new DiscoveredSsdpDevice {
                Usn = "usn", DescriptionLocation = new System.Uri("http://192.168.111.111")
            };
            var ssdpDevice = new SsdpRootDevice {
                FriendlyName = "Device_Name"
            };

            devices.OnDeviceAvailable(discoveredSsdpDevice, ssdpDevice);

            asyncEvent.WaitOne(100);

            Assert.AreEqual(ssdpDevice.FriendlyName, device.GetFriendlyName());
            Assert.AreEqual(discoveredSsdpDevice.Usn, device.GetUsn());
            Assert.AreEqual(discoveredSsdpDevice.DescriptionLocation.Host, device.GetHost());

            // Not connected, volume messages are not send.
            TestMessagesWhenNotConnected(devices);

            // Connect and launch app
            TestConnectAndLoadMedia(devices);

            // Test the other messages
            TestMessages(devices);
        }
Esempio n. 11
0
        public void DiscoveredDevice_GetDeviceInfo_DoesNotMakeHttpRequestIfDataCached()
        {
            var publishedDevice = new SsdpRootDevice()
            {
                Location      = new Uri("http://192.168.1.100:1702/description"),
                CacheLifetime = TimeSpan.FromMinutes(1),
                DeviceType    = "TestDeviceType",
                Uuid          = System.Guid.NewGuid().ToString()
            };

            var discoveredDevice = new DiscoveredSsdpDevice();

            discoveredDevice.Usn                 = "test usn";
            discoveredDevice.AsAt                = DateTimeOffset.Now;
            discoveredDevice.CacheLifetime       = publishedDevice.CacheLifetime;
            discoveredDevice.DescriptionLocation = publishedDevice.Location;

            var client = new MockHttpClient(publishedDevice.ToDescriptionDocument());
            var device = discoveredDevice.GetDeviceInfo(client).GetAwaiter().GetResult();

            client = new MockHttpClient(publishedDevice.ToDescriptionDocument());
            device = discoveredDevice.GetDeviceInfo(client).GetAwaiter().GetResult();

            Assert.IsNull(client.LastRequest);
            Assert.AreEqual(device.Uuid, publishedDevice.Uuid);
            Assert.AreEqual(device.DeviceType, publishedDevice.DeviceType);
        }
Esempio n. 12
0
        public DeviceViewModel(DiscoveredSsdpDevice discoveredDevice, SsdpDevice device)
        {
            this.discoveredDevice = discoveredDevice ?? throw new ArgumentNullException(nameof(discoveredDevice));
            this.device           = device ?? throw new ArgumentNullException(nameof(device));
            State = DeviceState.NotConnected;

            PlayCommand  = new RelayCommand(PlayAsync, () => CanPlay);
            PauseCommand = new RelayCommand(PauseAsync, () => CanPause);
            StopCommand  = new RelayCommand(StopAsync, () => CanStop);

            UpdateCommandStatus();

            deviceConnection    = new EndpointConnection(Host);
            deviceCommunication = new EndpointCommunication(deviceConnection);

            var syncContext = SynchronizationContext.Current;

            deviceCommunication.StateChanged += (EndpointCommunication com, DeviceState newState) =>
            {
                syncContext.Post((_) =>
                {
                    State = newState;

                    UpdateCommandStatus();
                }, null);
            };

            deviceCommunication.PlayingTimeChanged += delegate
            {
                syncContext.Post((_) =>
                {
                    AudioDelay = TimeSpan.FromSeconds(Math.Max(0, (playWatch.Elapsed - deviceCommunication.PlayingTime).TotalSeconds));
                }, null);
            };
        }
Esempio n. 13
0
        public void DiscoveredDevice_IsExpired_ImmediatelyReportsTrueIfCacheLifetimeIsZero()
        {
            var discoveredDevice = new DiscoveredSsdpDevice();

            discoveredDevice.AsAt          = DateTimeOffset.Now;
            discoveredDevice.CacheLifetime = TimeSpan.Zero;

            Assert.IsTrue(discoveredDevice.IsExpired());
        }
Esempio n. 14
0
        public void DiscoveredDevice_IsExpired_DoesNotImmediatelyReportTrue()
        {
            var discoveredDevice = new DiscoveredSsdpDevice();

            discoveredDevice.AsAt          = DateTimeOffset.Now;
            discoveredDevice.CacheLifetime = TimeSpan.FromSeconds(1);

            Assert.IsFalse(discoveredDevice.IsExpired());
        }
Esempio n. 15
0
        private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IpAddressInfo localIpAddress)
        {
            if (!NotificationTypeMatchesFilter(device))
            {
                return;
            }

            OnDeviceAvailable(device, isNewDevice, localIpAddress);
        }
Esempio n. 16
0
        public void DiscoveredDevice_IsExpired_ReportsTrueAfterCacheLifetimeExpires()
        {
            var discoveredDevice = new DiscoveredSsdpDevice();

            discoveredDevice.AsAt          = DateTimeOffset.Now;
            discoveredDevice.CacheLifetime = TimeSpan.FromMilliseconds(100);
            System.Threading.Thread.Sleep(500);

            Assert.IsTrue(discoveredDevice.IsExpired());
        }
Esempio n. 17
0
        private PythonDictionary ToPythonDictionary(DiscoveredSsdpDevice device)
        {
            var headersWrapper = new List();

            foreach (var header in device.ResponseHeaders)
            {
                if (header.Value == null)
                {
                    continue;
                }

                headersWrapper.Add(new PythonDictionary().WithValue("key", header.Key).WithValue("value", header.Value.FirstOrDefault()));
            }

            var deviceInfo = device.GetDeviceInfo().GetAwaiter().GetResult();

            var servicesWrapper = new List();

            foreach (var service in deviceInfo.Services)
            {
                servicesWrapper.Add(new PythonDictionary()
                                    .WithValue("control_url", service.ControlUrl.ToString())
                                    .WithValue("event_sub_url", service.EventSubUrl.ToString())
                                    .WithValue("full_service_type", service.FullServiceType)
                                    .WithValue("scpd_url", service.ScpdUrl.ToString())
                                    .WithValue("service_id", service.ServiceId)
                                    .WithValue("service_type", service.ServiceType)
                                    .WithValue("service_type_namespace", service.ServiceTypeNamespace)
                                    .WithValue("service_version", service.ServiceVersion)
                                    .WithValue("uuid", service.Uuid));
            }

            return(new PythonDictionary()
                   .WithValue("usn", device.Usn)
                   .WithValue("as_at", device.AsAt.ToString("O"))
                   .WithValue("description_location", device.DescriptionLocation.ToString())
                   .WithValue("cache_lifetime", device.CacheLifetime.ToString("c"))
                   .WithValue("notification_type", device.NotificationType)
                   .WithValue("response_headers", headersWrapper)
                   .WithValue("device_type", deviceInfo.DeviceType)
                   .WithValue("device_type_namespace", deviceInfo.DeviceTypeNamespace)
                   .WithValue("friendly_name", deviceInfo.FriendlyName)
                   .WithValue("full_device_type", deviceInfo.FullDeviceType)
                   .WithValue("device_version", deviceInfo.DeviceVersion)
                   .WithValue("serial_number", deviceInfo.SerialNumber)
                   .WithValue("udn", deviceInfo.Udn)
                   .WithValue("upc", deviceInfo.Upc)
                   .WithValue("uuid", deviceInfo.Uuid)
                   .WithValue("manufacturer", deviceInfo.Manufacturer)
                   .WithValue("manufacturer_url", deviceInfo.ManufacturerUrl.ToString())
                   .WithValue("model_description", deviceInfo.ModelDescription)
                   .WithValue("model_name", deviceInfo.ModelName)
                   .WithValue("model_number", deviceInfo.ModelNumber)
                   .WithValue("services", servicesWrapper));
        }
Esempio n. 18
0
        public void DiscoveredDevice_ToStringReturnsUsn()
        {
            var discoveredDevice = new DiscoveredSsdpDevice();

            discoveredDevice.Usn           = "test usn";
            discoveredDevice.AsAt          = DateTimeOffset.Now;
            discoveredDevice.CacheLifetime = TimeSpan.FromSeconds(1);
            System.Threading.Thread.Sleep(1000);

            Assert.AreEqual(discoveredDevice.Usn, discoveredDevice.ToString());
        }
 static SsdpDevice CreateSsdpDeviceModel(DiscoveredSsdpDevice discoveredSsdpDevice, Rssdp.SsdpDevice ssdpDevice)
 {
     return(new SsdpDevice
     {
         Usn = discoveredSsdpDevice.Usn,
         DescriptionLocation = discoveredSsdpDevice.DescriptionLocation?.ToString(),
         CacheLifetime = discoveredSsdpDevice.CacheLifetime,
         DeviceType = ssdpDevice.DeviceType,
         NotificationType = discoveredSsdpDevice.NotificationType,
         DeviceTypeNamespace = ssdpDevice.DeviceTypeNamespace,
     });
 }
Esempio n. 20
0
        /// <summary>
        /// Raises the <see cref="DeviceUnavailable"/> event.
        /// </summary>
        /// <param name="device">A <see cref="DiscoveredSsdpDevice"/> representing the device that is no longer available.</param>
        /// <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>
        /// <seealso cref="DeviceUnavailable"/>
        protected virtual void OnDeviceUnavailable(DiscoveredSsdpDevice device, bool expired)
        {
            if (this.IsDisposed)
            {
                return;
            }

            var handlers = this.DeviceUnavailable;

            if (handlers != null)
            {
                handlers(this, new DeviceUnavailableEventArgs(device, expired));
            }
        }
        /// <summary>
        /// Raises the <see cref="DeviceAvailable"/> event.
        /// </summary>
        /// <param name="device">A <see cref="DiscoveredSsdpDevice"/> representing the device that is now available.</param>
        /// <param name="isNewDevice">True if the device was not currently in the cahce before this event was raised.</param>
        /// <seealso cref="DeviceAvailable"/>
        protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice)
        {
            if (this.IsDisposed)
            {
                return;
            }

            EventHandler <DeviceAvailableEventArgs> handlers = DeviceAvailable;

            if (handlers != null)
            {
                handlers(this, new DeviceAvailableEventArgs(device, isNewDevice));
            }
        }
        private async Task <ChromecastOptions> GetChromecastDetails(DiscoveredSsdpDevice foundDevice)
        {
            if (foundDevice == null)
            {
                return(null);
            }

            var fullDevice = await foundDevice.GetDeviceInfo();

            var chromecast = new ChromecastOptions
            {
                Ip   = foundDevice.DescriptionLocation.Host,
                Name = fullDevice.FriendlyName
            };

            return(chromecast);
        }
Esempio n. 23
0
        /// <summary>
        /// Raises the <see cref="DeviceAvailable"/> event.
        /// </summary>
        /// <seealso cref="DeviceAvailable"/>
        protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IpAddressInfo localIpAddress)
        {
            if (this.IsDisposed)
            {
                return;
            }

            var handlers = this.DeviceAvailable;

            if (handlers != null)
            {
                handlers(this, new DeviceAvailableEventArgs(device, isNewDevice)
                {
                    LocalIpAddress = localIpAddress
                });
            }
        }
Esempio n. 24
0
        private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice)
        {
            // Don't raise the event if we've already done it for a cached
            // version of this device, and the cached version isn't
            // "significantly" different, i.e location and cachelifetime
            // haven't changed.
            var raiseEvent = false;

            if (!NotificationTypeMatchesFilter(device))
            {
                return;
            }

            lock (_SearchResultsSynchroniser)
            {
                if (_SearchResults != null)
                {
                    var existingDevice = FindExistingDeviceNotification(_SearchResults, device.NotificationType, device.Usn);
                    if (existingDevice == null)
                    {
                        _SearchResults.Add(device);
                        raiseEvent = true;
                    }
                    else
                    {
                        if (existingDevice.DescriptionLocation != device.DescriptionLocation || existingDevice.CacheLifetime != device.CacheLifetime)
                        {
                            _SearchResults.Remove(existingDevice);
                            _SearchResults.Add(device);
                            raiseEvent = true;
                        }
                    }
                }
                else
                {
                    raiseEvent = true;
                }
            }

            if (raiseEvent)
            {
                OnDeviceAvailable(device, isNewDevice);
            }
        }
Esempio n. 25
0
        public void DiscoveredDevice_GetDeviceInfo_CreatesDefaultClient()
        {
            var publishedDevice = new SsdpRootDevice()
            {
                Location      = new Uri("http://192.168.1.100:1702/description"),
                CacheLifetime = TimeSpan.FromMinutes(1),
                DeviceType    = "TestDeviceType",
                Uuid          = System.Guid.NewGuid().ToString()
            };

            var discoveredDevice = new DiscoveredSsdpDevice();

            discoveredDevice.Usn                 = "test usn";
            discoveredDevice.AsAt                = DateTimeOffset.Now;
            discoveredDevice.CacheLifetime       = TimeSpan.FromSeconds(1);
            discoveredDevice.DescriptionLocation = publishedDevice.Location;

            var device = discoveredDevice.GetDeviceInfo().GetAwaiter().GetResult();
        }
Esempio n. 26
0
        private void ProcessAliveNotification(HttpRequestMessage message, IpAddressInfo localIpAddress)
        {
            var location = GetFirstHeaderUriValue("Location", message);

            if (location != null)
            {
                var device = new DiscoveredSsdpDevice()
                {
                    DescriptionLocation = location,
                    Usn = GetFirstHeaderStringValue("USN", message),
                    NotificationType = GetFirstHeaderStringValue("NT", message),
                    CacheLifetime    = CacheAgeFromHeader(message.Headers.CacheControl),
                    AsAt             = DateTimeOffset.Now,
                    ResponseHeaders  = message.Headers
                };

                AddOrUpdateDiscoveredDevice(device, localIpAddress);
            }
        }
Esempio n. 27
0
        public void DeviceLocator_SearchAsync_FiltersNotificationsDuringSearch()
        {
            var server        = new MockCommsServer();
            var deviceLocator = new MockDeviceLocator(server);

            var publishedDevice  = CreateDeviceTree();
            var publishedDevice2 = CreateDeviceTree();

            deviceLocator.NotificationFilter = publishedDevice.Udn;
            deviceLocator.StartListeningForNotifications();

            DiscoveredSsdpDevice device = null;
            bool newlyDiscovered        = false;
            var  receivedNotification   = false;

            using (var eventSignal = new System.Threading.AutoResetEvent(false))
            {
                deviceLocator.DeviceAvailable += (sender, args) =>
                {
                    device = args.DiscoveredDevice;

                    newlyDiscovered      = args.IsNewlyDiscovered;
                    receivedNotification = true;
                    eventSignal.Set();
                };


                var task = deviceLocator.SearchAsync(publishedDevice.Udn);
                server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice2));
                server.WaitForMessageToProcess(5000);
                eventSignal.Reset();
                server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice));
                server.WaitForMessageToProcess(5000);
                eventSignal.WaitOne(10000);
                Assert.IsTrue(receivedNotification);
                var results = task.GetAwaiter().GetResult();

                Assert.IsNotNull(results);
                Assert.AreEqual(1, results.Count());
                Assert.IsTrue(results.First().Usn == device.Usn);
            }
        }
Esempio n. 28
0
        private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device)
        {
            bool isNewDevice = false;

            lock (_Devices)
            {
                var existingDevice = FindExistingDeviceNotification(_Devices, device.NotificationType, device.Usn);
                if (existingDevice == null)
                {
                    _Devices.Add(device);
                    isNewDevice = true;
                }
                else
                {
                    _Devices.Remove(existingDevice);
                    _Devices.Add(device);
                }
            }

            DeviceFound(device, isNewDevice);
        }
Esempio n. 29
0
        public void DeviceLocator_Notifications_IgnoresNonNotifyRequest()
        {
            var server                  = new MockCommsServer();
            var deviceLocator           = new MockDeviceLocator(server);
            var receivedNotification    = false;
            DiscoveredSsdpDevice device = null;
            bool expired                = false;

            deviceLocator.DeviceUnavailable += (sender, args) =>
            {
                device  = args.DiscoveredDevice;
                expired = args.Expired;
                receivedNotification = true;
            };
            deviceLocator.StartListeningForNotifications();

            server.MockReceiveBroadcast(GetMockNonNotifyRequest());
            server.WaitForMessageToProcess(10000);
            server.Dispose();

            Assert.IsFalse(receivedNotification);
        }
        private async Task <UpnpDeviceResponse> CreateUpnpDeviceAsync(DiscoveredSsdpDevice device)
        {
            var info = await device.GetDeviceInfo();

            var headers = device.ResponseHeaders?.ToDictionary(
                h => h.Key,
                h => string.Join(" ", h.Value),
                StringComparer.OrdinalIgnoreCase);

            headers = headers ?? new Dictionary <string, string>(0);

            string server;
            string location;
            string usn = info.Udn;

            if (!headers.TryGetValue("location", out location))
            {
                location = device.DescriptionLocation.AbsoluteUri;
            }

            if (!headers.TryGetValue("server", out server))
            {
                server = string.Empty;
            }

            var response = new UpnpDeviceResponse(location, server, usn)
            {
                FriendlyName = info.FriendlyName,
                Manufacturer = info.Manufacturer,
                ModelName    = info.ModelName
            };

            foreach (var keyValuePair in headers)
            {
                response.AddHeader(keyValuePair.Key, keyValuePair.Value);
            }

            return(response);
        }
Esempio n. 31
0
		private void ProcessByeByeNotification(HttpRequestMessage message)
		{
			var notficationType = GetFirstHeaderStringValue("NT", message);
			if (!String.IsNullOrEmpty(notficationType))
			{
				var usn = GetFirstHeaderStringValue("USN", message);
				
				if (!DeviceDied(usn, false))
				{
					var deadDevice = new DiscoveredSsdpDevice()
					{
						AsAt = DateTime.UtcNow,
						CacheLifetime = TimeSpan.Zero,
						DescriptionLocation = null,
						NotificationType = GetFirstHeaderStringValue("NT", message),
						Usn = usn
					};

					if (NotificationTypeMatchesFilter(deadDevice))
						OnDeviceUnavailable(deadDevice, false);
				}

				ResetExpireCachedDevicesTimer();
			}
		}
Esempio n. 32
0
		/// <summary>
		/// Raises the <see cref="DeviceUnavailable"/> event.
		/// </summary>
		/// <param name="device">A <see cref="DiscoveredSsdpDevice"/> representing the device that is no longer available.</param>
		/// <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>
		/// <seealso cref="DeviceUnavailable"/>
		protected virtual void OnDeviceUnavailable(DiscoveredSsdpDevice device, bool expired)
		{
			if (this.IsDisposed) return;

			var handlers = this.DeviceUnavailable;
			if (handlers != null)
				handlers(this, new DeviceUnavailableEventArgs(device, expired));
		}
Esempio n. 33
0
		private static void WriteOutDevices(DiscoveredSsdpDevice device)
		{
			Console.WriteLine(device.Usn + " - " + device.NotificationType +  "\r\n\t @ " + device.DescriptionLocation);
		}
Esempio n. 34
0
		private void ProcessAliveNotification(HttpRequestMessage message)
		{
			var location = GetFirstHeaderUriValue("Location", message);
			if (location != null)
			{
				var device = new DiscoveredSsdpDevice()
				{
					DescriptionLocation = location,
					Usn = GetFirstHeaderStringValue("USN", message),
					NotificationType = GetFirstHeaderStringValue("NT", message),
					CacheLifetime = CacheAgeFromHeader(message.Headers.CacheControl),
					AsAt = DateTimeOffset.Now
				};

				AddOrUpdateDiscoveredDevice(device);

				ResetExpireCachedDevicesTimer();
			}
		}
Esempio n. 35
0
		private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device)
		{
			bool isNewDevice = false;
			lock (_Devices)
			{
				var existingDevice = FindExistingDeviceNotification(_Devices, device.NotificationType, device.Usn);
				if (existingDevice == null)
				{
					_Devices.Add(device);
					isNewDevice = true;
				}
				else
				{
					_Devices.Remove(existingDevice);
					_Devices.Add(device);
				}
			}

			DeviceFound(device, isNewDevice);
		}
Esempio n. 36
0
		private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice)
		{
			// Don't raise the event if we've already done it for a cached
			// version of this device, and the cached version isn't
			// "significantly" different, i.e location and cachelifetime 
			// haven't changed.
			var raiseEvent = false;

			if (!NotificationTypeMatchesFilter(device)) return;

			lock (_SearchResultsSynchroniser)
			{
				if (_SearchResults != null)
				{
					var existingDevice = FindExistingDeviceNotification(_SearchResults, device.NotificationType, device.Usn);
					if (existingDevice == null)
					{
						_SearchResults.Add(device);
						raiseEvent = true;
					}
					else
					{
						if (existingDevice.DescriptionLocation != device.DescriptionLocation || existingDevice.CacheLifetime != device.CacheLifetime)
						{
							_SearchResults.Remove(existingDevice);
							_SearchResults.Add(device);
							raiseEvent = true;
						}
					}
				}
				else
					raiseEvent = true;
			}

			if (raiseEvent)
				OnDeviceAvailable(device, isNewDevice);
		}
Esempio n. 37
0
		private void ProcessSearchResponseMessage(HttpResponseMessage message)
		{
			if (!message.IsSuccessStatusCode) return;

			var location = GetFirstHeaderUriValue("Location", message);
			if (location != null)
			{
				var device = new DiscoveredSsdpDevice()
				{
					DescriptionLocation = location,
					Usn = GetFirstHeaderStringValue("USN", message),
					NotificationType = GetFirstHeaderStringValue("ST", message),
					CacheLifetime = CacheAgeFromHeader(message.Headers.CacheControl),
					AsAt = DateTimeOffset.Now
				};

				AddOrUpdateDiscoveredDevice(device);
			}
		}
Esempio n. 38
0
		private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device)
		{
			return String.IsNullOrEmpty(this.NotificationFilter) 
				|| this.NotificationFilter == SsdpConstants.SsdpDiscoverAllSTHeader 
				|| device.NotificationType == this.NotificationFilter;
		}