示例#1
0
        /// <summary>
        /// Searches for all Upnp Devices on the network
        /// </summary>
        /// <returns>List of devices found</returns>
        public static async Task <List <SsdpDevice> > SearchForDevices()
        {
            // This code goes in a method somewhere.
            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var foundDevices = await deviceLocator.SearchAsync(); // Can pass search arguments here (device type, uuid). No arguments means all devices.

                foreach (var foundDevice in foundDevices)
                {
                    try
                    {
                        // Device data returned only contains basic device details and location ]
                        // of full device description.
                        Console.WriteLine("Found " + foundDevice.Usn + " at " + foundDevice.DescriptionLocation);

                        // Can retrieve the full device description easily though.
                        var fullDevice = await foundDevice.GetDeviceInfo();

                        FoundDeviceList.Add(fullDevice);
                        Console.WriteLine(fullDevice.FriendlyName);
                        Console.WriteLine();
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Exception Thrown");
                    }
                }
                Console.WriteLine("Completed Search");
            }
            return(FoundDeviceList);
        }
示例#2
0
        public static List <Roku> GetRokuList()
        {
            var deviceLocator = new SsdpDeviceLocator();
            var ipRegex       = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
            var foundDevices  = deviceLocator.SearchAsync("roku:ecp").Result;
            var rokus         = new List <Roku>();

            foreach (var device in foundDevices)
            {
                var deviceUrl   = device.DescriptionLocation.ToString();
                var detailsUrl  = deviceUrl + "query/device-info";
                var appsUrl     = deviceUrl + "query/apps";
                var result      = ipRegex.Matches(deviceUrl);
                var ipAddress   = IPAddress.Parse(result[0].ToString());
                var details     = HTTPTools.Get(detailsUrl);
                var appDetails  = HTTPTools.Get(appsUrl);
                var rokuInfo    = XMLSerialize.DeserializeRokuDeviceInfo(details);
                var rokuApps    = XMLSerialize.DeserializeApps(appDetails).FindAll(a => a.Id != ((int)RokuAppIds.Fandango).ToString());
                var deviceName  = rokuInfo.Friendlydevicename;
                var displayName = String.Format("{0} ({1})", deviceName, ipAddress);
                rokus.Add(new Roku {
                    Url = deviceUrl, DeviceName = deviceName, IPAddress = ipAddress, DisplayName = displayName, Apps = rokuApps
                });
            }
            return(rokus);
        }
示例#3
0
        //public string AddDeviceDefinition(string uid)
        //{
        //    var device = new SsdpRootDevice();
        //    device.CacheLifetime = TimeSpan.MaxValue;
        //    device.Location = new Uri("");
        //    device.DeviceTypeNamespace = "";
        //    //device.DeviceType

        //}

        private async Task TryDiscoverSsdpDevicesAsync()
        {
            try
            {
                using (var deviceLocator = new SsdpDeviceLocator())
                {
                    var devices = new List <DiscoveredSsdpDevice>(await deviceLocator.SearchAsync(_options.SearchDuration).ConfigureAwait(false));
                    foreach (var device in devices)
                    {
                        try
                        {
                            await device.GetDeviceInfo().ConfigureAwait(false);
                        }
                        catch (Exception exception)
                        {
                            _logger.LogDebug(exception, $"Error while loading device info from '{device.DescriptionLocation}.'");
                        }
                    }

                    lock (_discoveredSsdpDevices)
                    {
                        _discoveredSsdpDevices.Clear();
                        _discoveredSsdpDevices.AddRange(devices);

                        _logger.LogInformation($"Discovered {_discoveredSsdpDevices.Count} SSDP devices.");
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Error while discovering SSDP devices.");
            }
        }
示例#4
0
 public void Stop()
 {
     if (null != _deviceLocator)
     {
         _deviceLocator.StopListeningForNotifications();
         _deviceLocator.Dispose();
         _deviceLocator = null;
     }
 }
示例#5
0
        public async void LoadDeviceInfoList()
        {
            SsdpDeviceLocator deviceLocator      = new SsdpDeviceLocator();
            List <string>     tempDeviceInfoList = new List <string>();
            var    foundDevicesTask = Task.Run(() => deviceLocator.SearchAsync(new TimeSpan(0, 0, 5)));
            string deviceInfo       = "";

            ui.ShowDialog(GUI_Handler.DialogChoice.LOADING);

            await Task.Run(() =>
            {
                while (!deviceLocator.IsSearching || !ui.GetDialogState(GUI_Handler.DialogChoice.LOADING))
                {
                    ;
                }
                while (deviceLocator.IsSearching && ui.GetDialogState(GUI_Handler.DialogChoice.LOADING))
                {
                    ;
                }

                if (!ui.GetDialogState(GUI_Handler.DialogChoice.LOADING))
                {
                    tempDeviceInfoList = null;
                    return;
                }

                tempDeviceInfoList = new List <string>();
                foreach (var foundDevice in foundDevicesTask.Result)
                {
                    try
                    {
                        deviceInfo     = "";
                        var fullDevice = Task.Run(() => foundDevice.GetDeviceInfo()).Result;
                        deviceInfo    += fullDevice.FriendlyName + "\n";
                        deviceInfo    += fullDevice.PresentationUrl;
                        if (deviceInfo.Contains("tcp://"))
                        {
                            tempDeviceInfoList.Add(deviceInfo);
                        }
                    }
                    catch (System.AggregateException)
                    {
                    }
                }

                if (ui.GetDialogState(GUI_Handler.DialogChoice.LOADING))
                {
                    ui.DismissDialog(GUI_Handler.DialogChoice.LOADING);
                }
            });

            deviceInfoList = tempDeviceInfoList;
            if (deviceInfoList != null)
            {
                this.ui.FillDeviceListView(deviceInfoList);
            }
        }
示例#6
0
 /// <summary>
 /// See the UPnP documentation at http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf
 /// UPnP library documetation is available at https://github.com/Yortw/RSSDP
 /// </summary>
 /// <returns></returns>
 async public Task Start()
 {
     _deviceLocator = new SsdpDeviceLocator();
     _deviceLocator.NotificationFilter = "upnp:rootdevice";
     _deviceLocator.NotificationFilter = "urn:schemas-upnp-org:device:Basic:1";
     _deviceLocator.NotificationFilter = "ssdp:all";
     _deviceLocator.DeviceAvailable   += DeviceLocator_DeviceAvailable;
     _deviceLocator.StartListeningForNotifications();
     IEnumerable <Discovered​Ssdp​Device> devices = await _deviceLocator.SearchAsync(TimeSpan.FromSeconds(30));
 }
示例#7
0
 public void Dispose()
 {
     if (!_disposed)
     {
         _disposed = true;
         if (_deviceLocator != null)
         {
             _deviceLocator.Dispose();
             _deviceLocator = null;
         }
     }
 }
示例#8
0
文件: Program.cs 项目: sk8tz/RSSDP
        private static async Task SearchForRootDevices()
        {
            Console.WriteLine("Searching for root devices...");

            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var results = await deviceLocator.SearchAsync(Rssdp.Infrastructure.SsdpConstants.UpnpDeviceTypeRootDevice);

                foreach (var device in results)
                {
                    WriteOutDevices(device);
                }
            }
        }
示例#9
0
文件: Program.cs 项目: sk8tz/RSSDP
        private static async Task SearchForBasicDevices()
        {
            Console.WriteLine("Searching for upnp basic devices...");

            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var results = await deviceLocator.SearchAsync(String.Format("urn:{0}:device:{1}:1", Infrastructure.SsdpConstants.UpnpDeviceTypeNamespace, Infrastructure.SsdpConstants.UpnpDeviceTypeBasicDevice));

                foreach (var device in results)
                {
                    WriteOutDevices(device);
                }
            }
        }
示例#10
0
        public async void SearchForDevices()
        {
            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var foundDevices = await deviceLocator.SearchAsync("urn:Belkin:device:controllee:1");

                foreach (var foundDevice in foundDevices)
                {
                    var fullDevice = await foundDevice.GetDeviceInfo();

                    _devices.Add(fullDevice);
                }
            }
        }
示例#11
0
文件: Program.cs 项目: sk8tz/RSSDP
        private static async Task SearchForAllDevices()
        {
            Console.WriteLine("Searching for all devices...");

            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var results = await deviceLocator.SearchAsync();

                foreach (var device in results)
                {
                    WriteOutDevices(device);
                }
            }
        }
        public async Task StartAsync(CancellationToken token)
        {
            var runningTask = Task.Run(async() => { await Task.Delay(TimeSpan.MaxValue, token).ContinueWith(_ => { }); });

            await Task.Delay(TimeSpan.FromSeconds(5), token).ContinueWith(_ => { });

            using (var deviceLocator = new SsdpDeviceLocator())
            {
                while (!token.IsCancellationRequested)
                {
                    Task <IEnumerable <DiscoveredSsdpDevice> > searchTask;

                    try
                    {
                        searchTask = deviceLocator.SearchAsync("upnp:rootdevice", TimeSpan.FromSeconds(10));
                        await Task.WhenAny(runningTask, searchTask);

                        if (searchTask.IsFaulted)
                        {
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        _log.Error(e.Message, e);
                        continue;
                    }

                    if (token.IsCancellationRequested)
                    {
                        break;
                    }

                    var devices = searchTask.Result;

                    if (devices == null)
                    {
                        continue;
                    }

                    foreach (var device in devices)
                    {
                        await UpnpDeviceFound(device);
                    }

                    await Task.Delay(TimeSpan.FromSeconds(60), token).ContinueWith(_ => { });
                }
            }
        }
示例#13
0
 // Call this method from somewhere in your code to start the search.
 public void BeginSearch()
 {
     _DeviceLocator = new SsdpDeviceLocator();
     // (Optional) Set the filter so we only see notifications for devices we care about
     // (can be any search target value i.e device type, uuid value etc - any value that appears in the
     // DiscoverdSsdpDevice.NotificationType property or that is used with the searchTarget parameter of the Search method).
     //_DeviceLocator.NotificationFilter = "upnp:rootdevice";
     // Connect our event handler so we process devices as they are found
     _DeviceLocator.DeviceAvailable += deviceLocator_DeviceAvailable;
     // Enable listening for notifications (optional)
     _DeviceLocator.StartListeningForNotifications();
     // Perform a search so we don't have to wait for devices to broadcast notifications
     // again to get any results right away (notifications are broadcast periodically).
     _DeviceLocator.SearchAsync();
 }
示例#14
0
文件: Rssdp.cs 项目: jeason0813/Antd
        public static async Task <List <NodeModel> > Discover()
        {
            var uidRegex = new Regex("uuid\\:([a-zA-Z0-9\\-]+)\\:");
            var ipRegex  = new Regex("([0-9]{0,3}\\.[0-9]{0,3}\\.[0-9]{0,3}\\.[0-9]{0,3})");
            var list     = new List <NodeModel>();

            using (var deviceLocator = new SsdpDeviceLocator()) {
                var foundDevices = await deviceLocator.SearchAsync();

                foreach (var foundDevice in foundDevices)
                {
                    var device = new NodeModel();
                    device.RawUid = foundDevice.Usn;
                    device.DescriptionLocation = foundDevice.DescriptionLocation.ToString();
                    device.PublicIp            = ipRegex.Match(device.DescriptionLocation).Groups[1].Value;
                    try {
                        var fullDevice = await foundDevice.GetDeviceInfo();

                        device.Hostname         = fullDevice.FriendlyName;
                        device.DeviceType       = fullDevice.DeviceType;
                        device.Manufacturer     = fullDevice.Manufacturer;
                        device.ModelName        = fullDevice.ModelName;
                        device.ModelDescription = fullDevice.ModelDescription;
                        device.ModelNumber      = fullDevice.ModelNumber;
                        device.ModelUrl         = device.DescriptionLocation.Replace("device/description", "");
                        device.SerialNumber     = fullDevice.SerialNumber;
                    }
                    catch (Exception) {
                        //
                    }
                    list.Add(device);
                }
            }

            var mergedList  = new List <NodeModel>();
            var groupedList = list.GroupBy(_ => _.PublicIp).ToList();

            foreach (var group in groupedList)
            {
                var mergedNode = MergeUidInformation(group.ToList());
                var tryget     = mergedList.FirstOrDefault(_ => _.MachineUid == mergedNode.MachineUid);
                if (tryget == null)
                {
                    mergedList.Add(mergedNode);
                }
            }
            return(mergedList);
        }
示例#15
0
        // Call this method from somewhere in your code to start the search.
        public void Start(ISsdpCommunicationsServer communicationsServer)
        {
            _deviceLocator = new SsdpDeviceLocator(communicationsServer, _timerFactory);

            // (Optional) Set the filter so we only see notifications for devices we care about
            // (can be any search target value i.e device type, uuid value etc - any value that appears in the
            // DiscoverdSsdpDevice.NotificationType property or that is used with the searchTarget parameter of the Search method).
            //_DeviceLocator.NotificationFilter = "upnp:rootdevice";

            // Connect our event handler so we process devices as they are found
            _deviceLocator.DeviceAvailable   += deviceLocator_DeviceAvailable;
            _deviceLocator.DeviceUnavailable += _DeviceLocator_DeviceUnavailable;

            // Perform a search so we don't have to wait for devices to broadcast notifications
            // again to get any results right away (notifications are broadcast periodically).
            StartAsyncSearch();
        }
示例#16
0
        // Call this method from somewhere in your code to start the search.
        public void Start(ISsdpCommunicationsServer communicationsServer)
        {
            _deviceLocator = new SsdpDeviceLocator(communicationsServer, _timerFactory);

            // (Optional) Set the filter so we only see notifications for devices we care about
            // (can be any search target value i.e device type, uuid value etc - any value that appears in the
            // DiscoverdSsdpDevice.NotificationType property or that is used with the searchTarget parameter of the Search method).
            //_DeviceLocator.NotificationFilter = "upnp:rootdevice";

            // Connect our event handler so we process devices as they are found
            _deviceLocator.DeviceAvailable   += deviceLocator_DeviceAvailable;
            _deviceLocator.DeviceUnavailable += _DeviceLocator_DeviceUnavailable;

            var dueTime  = TimeSpan.FromSeconds(5);
            var interval = TimeSpan.FromSeconds(_config.GetDlnaConfiguration().ClientDiscoveryIntervalSeconds);

            _deviceLocator.RestartBroadcastTimer(dueTime, interval);
        }
示例#17
0
        public async Task <DiscoveredSsdpDevice[]> SearchAsync()
        {
            _locators = NetworkInterface
                        .GetAllNetworkInterfaces()
                        .Select(x => x.GetIPProperties())
                        .Select(@interface =>
                                @interface.UnicastAddresses
                                .Where(address => (address.Address.AddressFamily == AddressFamily.InterNetwork ||
                                                   address.Address.AddressFamily == AddressFamily.InterNetworkV6) &&
                                       !IPAddress.IsLoopback(address.Address)
                                       )
                                .Select(address => address.Address))
                        .Where(x => x.Any())
                        .Aggregate(new List <IPAddress>(), (x, y) => x.Concat(y).ToList())
                        .Select(address =>
            {
                try
                {
                    var locator = new SsdpDeviceLocator(
                        new SsdpCommunicationsServer(new SocketFactory(address.ToString())))
                    {
                        NotificationFilter = "urn:control-target:device:ControlTarget:1"
                    };

                    locator.DeviceAvailable   += OnDevice;
                    locator.DeviceUnavailable += OnDeviceDisconnect;
                    locator.StartListeningForNotifications();

                    return(locator);
                }
                catch (Exception)
                {
                    return(null);
                }
            })
                        .Where(x => x != null)
                        .ToArray();

            var results = await Task.WhenAll(_locators.Select(x => x.SearchAsync()));

            return(results
                   .Aggregate((x, y) => x.Concat(y))
                   .ToArray());
        }
示例#18
0
文件: Program.cs 项目: sk8tz/RSSDP
        private static void ListenForBroadcasts()
        {
            if (_BroadcastListener != null)
            {
                Console.WriteLine("Closing previous listener...");
                _BroadcastListener.DeviceAvailable   -= _BroadcastListener_DeviceAvailable;
                _BroadcastListener.DeviceUnavailable -= _BroadcastListener_DeviceUnavailable;

                _BroadcastListener.StopListeningForNotifications();
                _BroadcastListener.Dispose();
            }

            Console.WriteLine("Starting broadcast listener");
            _BroadcastListener = new SsdpDeviceLocator();
            _BroadcastListener.DeviceAvailable   += _BroadcastListener_DeviceAvailable;
            _BroadcastListener.DeviceUnavailable += _BroadcastListener_DeviceUnavailable;
            _BroadcastListener.StartListeningForNotifications();
            Console.WriteLine("Now listening for broadcasts");
        }
示例#19
0
        public async Task StartListening()
        {
            liveviewUdpSockets = new List <IDatagramSocket>();
            var confirmedHosts = new List <string>();

            foreach (var profile in network.GetHostNames())
            {
                var liveviewUdp = network.CreateDatagramSocket();
                try
                {
                    liveviewUdp.MessageReceived += LiveviewUdp_MessageReceived;

                    await liveviewUdp.Bind(profile, LiveViewPort);

                    liveviewUdpSockets.Add(liveviewUdp);
                    confirmedHosts.Add(profile);
                }
                catch (Exception)
                {
                    liveviewUdp.Dispose();
                }
            }

            lock (foundDevices)
            {
                foundDevices.Clear();
            }

            deviceLocators = new List <SsdpDeviceLocator>();

            foreach (var host in confirmedHosts)
            {
                var deviceLocator =
                    new SsdpDeviceLocator(new SsdpCommunicationsServer(new SocketFactory(host)))
                {
                    NotificationFilter = "urn:schemas-upnp-org:device:MediaServer:1"
                };
                deviceLocator.DeviceAvailable += DeviceLocator_DeviceAvailable;
                deviceLocator.StartListeningForNotifications();
                deviceLocators.Add(deviceLocator);
            }
        }
示例#20
0
        public async Task LocateHeosDevices()
        {
            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var foundDevices = await deviceLocator.SearchAsync("urn:schemas-denon-com:device:ACT-Denon:1");

                // Can pass search arguments here (device type, uuid). No arguments means all devices.

                foreach (var foundDevice in foundDevices)
                {
                    // Device data returned only contains basic device details and location ]
                    // of full device description.

                    // Can retrieve the full device description easily though.
                    var fullDevice = await foundDevice.GetDeviceInfo() as SsdpRootDevice;

                    Devices.Add(fullDevice);
                }
            }
        }
示例#21
0
        private async Task <ObservableCollection <ChromeCast> > LocateDevicesAsync(SsdpDeviceLocator deviceLocator)
        {
            var responses = await ZeroconfResolver.ResolveAsync("_googlecast._tcp.local.");

            foreach (var resp in responses)
            {
                Uri uri;
                if (Uri.TryCreate("https://" + resp.IPAddress, UriKind.Absolute, out uri))
                {
                    var chromecast = new ChromeCast
                    {
                        DeviceUri    = uri,
                        FriendlyName = resp.Services.Select(a => a.Value.Properties.Select(b => b["fn"])).FirstOrDefault().FirstOrDefault()
                    };
                    DiscoveredDevices.Add(chromecast);
                }
            }

            return(DiscoveredDevices);
        }
示例#22
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var foundDevices = await deviceLocator.SearchAsync(); // Can pass search arguments here (device type, uuid). No arguments means all devices.

                foreach (var foundDevice in foundDevices)
                {
                    // Device data returned only contains basic device details and location ]
                    // of full device description.
                    Console.WriteLine("Found " + foundDevice.Usn + " at " + foundDevice.DescriptionLocation.ToString());

                    // Can retrieve the full device description easily though.
                    var fullDevice = await foundDevice.GetDeviceInfo();

                    Console.WriteLine(fullDevice.FriendlyName);
                    Console.WriteLine();
                }
            }
        }
示例#23
0
        private void SearchForServer()
        {
            string ip4;

            // Have to bind to all addresses on Linux, or broadcasts don't work!
            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                ip4 = GetLocalIp4Address();
            }
            else
            {
                ip4 = IPAddress.Any.ToString();
            }

            SsdpDeviceLocator deviceLocator = null;

            try {
                deviceLocator = new SsdpDeviceLocator(ip4);
                deviceLocator.StartListeningForNotifications();
                deviceLocator.DeviceAvailable += FoundDevice;
                var unused = deviceLocator.SearchAsync("uuid:6111f321-2cee-455e-b203-4abfaf14b516", new TimeSpan(0, 0, 5));
                deviceLocator.StartListeningForNotifications();

                for (int i = 0; i < 20; i += 1)
                {
                    if (!string.IsNullOrEmpty(status.Server))
                    {
                        // We found a server, let the constructor continue
                        return;
                    }

                    Thread.Sleep(500);
                }
            }
            finally {
                deviceLocator?.StopListeningForNotifications();
                deviceLocator?.Dispose();
            }

            throw new Exception("Could not locate server");
        }
示例#24
0
文件: Program.cs 项目: sk8tz/RSSDP
        private static async Task SearchForDevicesByUuid()
        {
            if (_DevicePublisher == null || !_DevicePublisher.Devices.Any())
            {
                Console.WriteLine("No devices being published. Use the (P)ublish command first.");
            }

            var uuid = _DevicePublisher.Devices.First().Uuid;

            Console.WriteLine("Searching for device with uuid of " + uuid);

            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var results = await deviceLocator.SearchAsync("uuid:" + uuid);

                foreach (var device in results)
                {
                    WriteOutDevices(device);
                }
            }
        }
示例#25
0
        public static async Task <List <SsdpRootDevice> > DiscoverSonos()
        {
            var ret = new List <SsdpRootDevice>();

            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var foundDevices = await deviceLocator.SearchAsync("urn:schemas-upnp-org:device:ZonePlayer:1");

                foreach (var foundDevice in foundDevices)
                {
                    var fullDevice = await foundDevice.GetDeviceInfo();

                    if (fullDevice is SsdpRootDevice rootDevice && fullDevice.Manufacturer.ToLowerInvariant().Contains("sonos"))
                    {
                        ret.Add(rootDevice);
                    }
                }
            }

            return(ret);
        }
示例#26
0
        public DiscoveryService()
        {
            try
            {
                _publisher     = new SsdpDevicePublisher();
                _deviceLocator = new SsdpDeviceLocator {
                    NotificationFilter = UrnSearch
                };

                _deviceLocator.StartListeningForNotifications();

                _port = Convert.ToInt32(ServerInfo.WebPort);

                AutomaticaUuid = ServerInfo.ServerUid.ToString();

                Location = new Uri($"http://{NetworkHelper.GetActiveIp()}:{_port}/webapi/discovery");
            }
            catch (Exception e)
            {
                SystemLogger.Instance.LogError($"Could not init SSDP Publisher {e}");
            }
        }
示例#27
0
        public async Task <ObservableCollection <Chromecast> > LocateDevicesAsync()
        {
            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var foundDevices = await deviceLocator.SearchAsync("urn:dial-multiscreen-org:device:dial:1", TimeSpan.FromMilliseconds(5000));

                foreach (var foundDevice in foundDevices)
                {
                    var fullDevice = await foundDevice.GetDeviceInfo();

                    Uri myUri;
                    Uri.TryCreate("https://" + foundDevice.DescriptionLocation.Host, UriKind.Absolute, out myUri);
                    var chromecast = new Chromecast
                    {
                        DeviceUri    = myUri,
                        FriendlyName = fullDevice.FriendlyName
                    };
                    DiscoveredDevices.Add(chromecast);
                }
            }
            return(DiscoveredDevices);
        }
        public async Task <IActionResult> Discover()
        {
            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var deviceType = "urn:dial-multiscreen-org:device:dial:1";
                deviceLocator.NotificationFilter = deviceType;

                var foundDevices = await deviceLocator.SearchAsync(deviceType);

                if (foundDevices.Any())
                {
                    var getChromecastTasks = foundDevices
                                             .Select(device => GetChromecastDetails(device));

                    var chromecasts = await Task.WhenAll(getChromecastTasks);

                    return(Ok(chromecasts));
                }
            }

            return(NotFound());
        }
        //public string AddDeviceDefinition(string uid)
        //{
        //    var device = new SsdpRootDevice();
        //    device.CacheLifetime = TimeSpan.MaxValue;
        //    device.Location = new Uri("");
        //    device.DeviceTypeNamespace = "";
        //    //device.DeviceType

        //}

        async Task TryDiscoverSsdpDevicesAsync(CancellationToken cancellationToken)
        {
            using (var deviceLocator = new SsdpDeviceLocator())
            {
                var devices = new List <SsdpDevice>();
                foreach (var discoveredSsdpDevice in await deviceLocator.SearchAsync(_options.SearchDuration).ConfigureAwait(false))
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    if (Convert.ToString(discoveredSsdpDevice.DescriptionLocation).Contains("0.0.0.0", StringComparison.Ordinal))
                    {
                        continue;
                    }

                    try
                    {
                        var ssdpDevice = await discoveredSsdpDevice.GetDeviceInfo(_httpClient).ConfigureAwait(false);

                        devices.Add(CreateSsdpDeviceModel(discoveredSsdpDevice, ssdpDevice));
                    }
                    catch (Exception exception)
                    {
                        _logger.LogDebug(exception, $"Error while loading device info from '{discoveredSsdpDevice.DescriptionLocation}.'");
                    }
                }

                lock (_discoveredSsdpDevices)
                {
                    _discoveredSsdpDevices.Clear();
                    _discoveredSsdpDevices.AddRange(devices);

                    _logger.LogInformation($"Discovered {_discoveredSsdpDevices.Count} SSDP devices.");
                }
            }
        }
示例#30
0
        public void Discover(Action <DiscoveredSsdpDevice, SsdpDevice> onDiscoveredIn, Action updateCounterIn)
        {
            onDiscovered  = onDiscoveredIn;
            updateCounter = updateCounterIn;

            var ipHostInfo  = Dns.GetHostEntry(Dns.GetHostName());
            var ipAddresses = GetIpAddresses(ipHostInfo);

            foreach (var ipAddress in ipAddresses)
            {
                using (var deviceLocator =
                           new SsdpDeviceLocator(
                               communicationsServer: new Rssdp.Infrastructure.SsdpCommunicationsServer(
                                   new SocketFactory(ipAddress: ipAddress.ToString())
                                   )
                               ))
                {
                    deviceLocator.NotificationFilter = ChromeCastUpnpDeviceType;
                    deviceLocator.DeviceAvailable   += OnDeviceAvailable;
                    deviceLocator.SearchAsync();
                }
            }
        }
示例#31
0
文件: Program.cs 项目: noex/RSSDP
		private static void ListenForBroadcasts()
		{
			if (_BroadcastListener != null)
			{
				Console.WriteLine("Closing previous listener...");
				_BroadcastListener.DeviceAvailable -= _BroadcastListener_DeviceAvailable;
				_BroadcastListener.DeviceUnavailable -= _BroadcastListener_DeviceUnavailable;
				
				_BroadcastListener.StopListeningForNotifications();
				_BroadcastListener.Dispose();
			}

			Console.WriteLine("Starting broadcast listener");
			_BroadcastListener = new SsdpDeviceLocator();
			_BroadcastListener.DeviceAvailable += _BroadcastListener_DeviceAvailable;
			_BroadcastListener.DeviceUnavailable += _BroadcastListener_DeviceUnavailable;
			_BroadcastListener.StartListeningForNotifications();
			Console.WriteLine("Now listening for broadcasts");
		}
示例#32
0
文件: Program.cs 项目: noex/RSSDP
		private static async Task SearchForBasicDevices()
		{
			Console.WriteLine("Searching for upnp basic devices...");

			using (var deviceLocator = new SsdpDeviceLocator())
			{
				var results = await deviceLocator.SearchAsync(String.Format("urn:{0}:device:{1}:1", Infrastructure.SsdpConstants.UpnpDeviceTypeNamespace, Infrastructure.SsdpConstants.UpnpDeviceTypeBasicDevice));
				foreach (var device in results)
				{
					WriteOutDevices(device);
				}
			}
		}
示例#33
0
文件: Program.cs 项目: noex/RSSDP
		private static async Task SearchForDevicesByUuid()
		{
			if (_DevicePublisher == null || !_DevicePublisher.Devices.Any())
			{
				Console.WriteLine("No devices being published. Use the (P)ublish command first.");
			}

			var uuid = _DevicePublisher.Devices.First().Uuid;
			Console.WriteLine("Searching for device with uuid of " + uuid);

			using (var deviceLocator = new SsdpDeviceLocator())
			{
				var results = await deviceLocator.SearchAsync("uuid:" + uuid);
				foreach (var device in results)
				{
					WriteOutDevices(device);
				}
			}
		}
示例#34
0
文件: Program.cs 项目: noex/RSSDP
		private static async Task SearchForRootDevices()
		{
			Console.WriteLine("Searching for root devices...");

			using (var deviceLocator = new SsdpDeviceLocator())
			{
				var results = await deviceLocator.SearchAsync(Rssdp.Infrastructure.SsdpConstants.UpnpDeviceTypeRootDevice);
				foreach (var device in results)
				{
					WriteOutDevices(device);
				}
			}
		}