예제 #1
0
        public async Task <List <SmartMirrorModel> > SearchForSmartMirrors()
        {
            List <SmartMirrorModel> mirrors = new List <SmartMirrorModel>();
            WifiManager             wifi    = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
            var wifiLock = wifi.CreateMulticastLock("Zeroconf lock");

            try
            {
                wifiLock.Acquire();
                ILookup <string, string> domains = await ZeroconfResolver.BrowseDomainsAsync();

                var responses = await ZeroconfResolver.ResolveAsync(domains.Select(g => g.Key));

                foreach (var domain in responses)
                {
                    if (domain.DisplayName.Contains("smartmirror"))
                    {
                        mirrors.Add(new SmartMirrorModel()
                        {
                            HostName = domain.DisplayName,
                            IP       = IPAddress.Parse(domain.IPAddress)
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                wifiLock.Release();
            }
            return(mirrors);
        }
예제 #2
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);

            wifi  = (WifiManager)ApplicationContext.GetSystemService(Context.WifiService);
            mlock = wifi.CreateMulticastLock("Zeroconf lock");
            mlock.Acquire();
            SetPage(App.GetMainPage());
        }
 protected override void OnCreate(Bundle bundle)
 {
     _wifi  = (WifiManager)ApplicationContext.GetSystemService(WifiService);
     _mlock = _wifi.CreateMulticastLock("Zeroconf lock");
     _mlock.Acquire();
     TabLayoutResource = Resource.Layout.Tabbar;
     ToolbarResource   = Resource.Layout.Toolbar;
     base.SetTheme(Resource.Style.MainTheme);
     base.OnCreate(bundle);
     CrossFingerprint.SetCurrentActivityResolver(() => this);
     Forms.Init(this, bundle);
     LoadApplication(new App());
 }
예제 #4
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            wifi  = (WifiManager)ApplicationContext.GetSystemService(Context.WifiService);
            mlock = wifi.CreateMulticastLock("Zeroconf lock");
            mlock.Acquire();
#pragma warning disable CS0618 // Type or member is obsolete
            SetPage(App.GetMainPage());
#pragma warning restore CS0618 // Type or member is obsolete
        }
예제 #5
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Devices);

            // Create WiFi locks and mDNS scanner
            wifi   = (WifiManager)ApplicationContext.GetSystemService(Context.WifiService);
            mlock  = wifi.CreateMulticastLock("Zeroconf Lock");
            finder = new MDNSFinder(this);

            // Set events
            FindViewById <Button>(Resource.Id.btnScanNetwork).Click  += (sender, args) => ScanNetwork(false);
            FindViewById <ListView>(Resource.Id.lvDevices).ItemClick += lvDevices_ItemClick;
        }
예제 #6
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            AppCenter.Start("b17f9c9d-e90c-488f-8c4b-92ef3e305c0d", typeof(Analytics), typeof(Distribute));


            WifiManager wifiMgr = (WifiManager)ApplicationContext.GetSystemService(Context.WifiService);

            castLock = wifiMgr.CreateMulticastLock("TacControl-udp");
            castLock.SetReferenceCounted(true);
            castLock.Acquire();


            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            Android.Views.Window window = Window;
            window.AddFlags(WindowManagerFlags.KeepScreenOn);
            window.AddFlags(WindowManagerFlags.Fullscreen);

            LoadApplication(new App((action) =>
            {
                TaskCompletionSource <object> tcs = new TaskCompletionSource <object>();
                bool isMain = MainThread.IsMainThread;

                RunOnUiThread(() =>
                {
                    try
                    {
                        action();
                        tcs.SetResult(null);
                    }
                    catch (Exception ex)
                    {
                        tcs.SetException(ex);
                    }
                });

                return(tcs.Task);
            }));
        }
 public UdpHelper(WifiManager manager)
 {
     mylock = manager.CreateMulticastLock("UDPwifi");
 }
예제 #8
0
        async Task NetworkRequestAsync(byte[] requestBytes,
                                       TimeSpan scanTime,
                                       int retries,
                                       int retryDelayMilliseconds,
                                       Action <string, byte[]> onResponse,
                                       System.Net.NetworkInformation.NetworkInterface adapter,
                                       CancellationToken cancellationToken)
        {
            // http://stackoverflow.com/questions/2192548/specifying-what-network-interface-an-udp-multicast-should-go-to-in-net

#if !XAMARIN
            if (!adapter.GetIPProperties().MulticastAddresses.Any())
            {
                return; // most of VPN adapters will be skipped
            }
#endif
            if (!adapter.SupportsMulticast)
            {
                return; // multicast is meaningless for this type of connection
            }
            if (OperationalStatus.Up != adapter.OperationalStatus)
            {
                return; // this adapter is off or not connected
            }
            if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback)
            {
                return; // strip out loopback addresses
            }
            var p = adapter.GetIPProperties().GetIPv4Properties();
            if (null == p)
            {
                return; // IPv4 is not configured on this adapter
            }
            var ipv4Address = adapter.GetIPProperties().UnicastAddresses
                              .FirstOrDefault(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)?.Address;

            if (ipv4Address == null)
            {
                return; // could not find an IPv4 address for this adapter
            }
            var ifaceIndex = p.Index;

            Debug.WriteLine($"Scanning on iface {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}");

            using (var client = new UdpClient())
            {
                for (var i = 0; i < retries; i++)
                {
#if ANDROID
                    var mlock = wifi.CreateMulticastLock("Zeroconf lock");
#endif
                    try
                    {
#if ANDROID
                        mlock.Acquire();
#endif
                        client.Client.SetSocketOption(SocketOptionLevel.IP,
                                                      SocketOptionName.MulticastInterface,
                                                      IPAddress.HostToNetworkOrder(ifaceIndex));



                        client.ExclusiveAddressUse = false;
                        client.Client.SetSocketOption(SocketOptionLevel.Socket,
                                                      SocketOptionName.ReuseAddress,
                                                      true);
                        client.Client.SetSocketOption(SocketOptionLevel.Socket,
                                                      SocketOptionName.ReceiveTimeout,
                                                      scanTime.Milliseconds);
                        client.ExclusiveAddressUse = false;


                        var localEp = new IPEndPoint(IPAddress.Any, 5353);

                        Debug.WriteLine($"Attempting to bind to {localEp} on adapter {adapter.Name}");
                        client.Client.Bind(localEp);
                        Debug.WriteLine($"Bound to {localEp}");

                        var multicastAddress = IPAddress.Parse("224.0.0.251");
                        var multOpt          = new MulticastOption(multicastAddress, ifaceIndex);
                        client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt);


                        Debug.WriteLine("Bound to multicast address");

                        // Start a receive loop
                        var shouldCancel = false;
                        var recTask      = Task.Run(async
                                                        () =>
                        {
                            try
                            {
                                while (!shouldCancel)
                                {
                                    var res = await client.ReceiveAsync()
                                              .ConfigureAwait(false);
                                    onResponse(res.RemoteEndPoint.Address.ToString(), res.Buffer);
                                }
                            }
                            catch (ObjectDisposedException)
                            {
                            }
                        }, cancellationToken);

                        var broadcastEp = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353);
                        Debug.WriteLine($"About to send on iface {adapter.Name}");
                        await client.SendAsync(requestBytes, requestBytes.Length, broadcastEp)
                        .ConfigureAwait(false);

                        Debug.WriteLine($"Sent mDNS query on iface {adapter.Name}");


                        // wait for responses
                        await Task.Delay(scanTime, cancellationToken)
                        .ConfigureAwait(false);

                        shouldCancel = true;
#if CORECLR
                        client.Dispose();
#else
                        client.Close();
#endif

                        Debug.WriteLine("Done Scanning");


                        await recTask.ConfigureAwait(false);

                        return;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine($"Execption with network request, IP {ipv4Address}\n: {e}");
                        if (i + 1 >= retries) // last one, pass underlying out
                        {
                            throw;
                        }
                    }
                    finally
                    {
#if ANDROID
                        mlock.Release();
#endif
                    }

                    await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false);
                }
            }
        }
예제 #9
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            AppCenter.Start("b17f9c9d-e90c-488f-8c4b-92ef3e305c0d", typeof(Analytics), typeof(Distribute));

            var versionInfo = Application.Context.ApplicationContext?.PackageManager?.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0);

            //var username = System.Security.Principal.WindowsIdentity.GetCurrent();

            SentryXamarin.Init(o =>
            {
                o.AddXamarinFormsIntegration();
                o.Dsn         = "https://[email protected]/5390642";
                o.Release     = $"TacControl@{versionInfo?.VersionName}:{versionInfo?.LongVersionCode}";
                o.Environment = //username == "Dedmen-PC\\dedmen" ? "Dev" :
                                "Alpha";
            });


            WifiManager wifiMgr = (WifiManager)ApplicationContext.GetSystemService(Context.WifiService);

            wifiLock = wifiMgr.CreateWifiLock(WifiMode.Full, "TacControl-udp");
            wifiLock.SetReferenceCounted(true);
            wifiLock.Acquire();
            castLock = wifiMgr.CreateMulticastLock("TacControl-udp");
            castLock.SetReferenceCounted(true);
            castLock.Acquire();


            ConnectivityManager conMgr = (ConnectivityManager)ApplicationContext.GetSystemService(Context.ConnectivityService);
            var stuff   = conMgr.GetAllNetworks();
            var wifiNet = stuff.FirstOrDefault(x => conMgr.GetNetworkInfo(x).Type == ConnectivityType.Wifi);

            if (wifiNet != null)
            {
                var res  = conMgr.BindProcessToNetwork(wifiNet);
                var info = conMgr.GetNetworkInfo(wifiNet);

                var connInfo = wifiMgr.ConnectionInfo;
            }


            //Networking.ConnectionInfo

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            Android.Views.Window window = Window;
            window.AddFlags(WindowManagerFlags.KeepScreenOn);
            window.AddFlags(WindowManagerFlags.Fullscreen);

            LoadApplication(new App((action) =>
            {
                TaskCompletionSource <object> tcs = new TaskCompletionSource <object>();
                bool isMain = MainThread.IsMainThread;

                RunOnUiThread(() =>
                {
                    try
                    {
                        action();
                        tcs.SetResult(null);
                    }
                    catch (Exception ex)
                    {
                        tcs.SetException(ex);
                    }
                });

                return(tcs.Task);
            }));
        }
예제 #10
0
        public async Task NetworkRequestAsync(byte[] requestBytes,
                                              TimeSpan scanTime,
                                              int retries,
                                              int retryDelayMilliseconds,
                                              Action <string, byte[]> onResponse,
                                              CancellationToken cancellationToken)
        {
            using (var client = new UdpClient())
            {
                for (var i = 0; i < retries; i++)
                {
#if ANDROID
                    var mlock = wifi.CreateMulticastLock("Zeroconf lock");
#endif
                    try
                    {
#if ANDROID
                        mlock.Acquire();
#endif

                        var localEp = new IPEndPoint(IPAddress.Any, 5353);

                        // There could be multiple adapters, get the default one
                        uint index = 0;
#if XAMARIN
                        const int ifaceIndex = 0;
#else
                        GetBestInterface(0, out index);
                        var ifaceIndex = (int)index;
#endif

                        client.Client.SetSocketOption(SocketOptionLevel.IP,
                                                      SocketOptionName.MulticastInterface,
                                                      (int)IPAddress.HostToNetworkOrder(ifaceIndex));



                        client.ExclusiveAddressUse = false;
                        client.Client.SetSocketOption(SocketOptionLevel.Socket,
                                                      SocketOptionName.ReuseAddress,
                                                      true);
                        client.Client.SetSocketOption(SocketOptionLevel.Socket,
                                                      SocketOptionName.ReceiveTimeout,
                                                      scanTime.Milliseconds);
                        client.ExclusiveAddressUse = false;

                        client.Client.Bind(localEp);

                        var multicastAddress = IPAddress.Parse("224.0.0.251");

                        var multOpt = new MulticastOption(multicastAddress, ifaceIndex);
                        client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt);


                        Debug.WriteLine("Bound to multicast address");

                        // Start a receive loop
                        var shouldCancel = false;
                        var recTask      = Task.Run(async
                                                        () =>
                        {
                            try
                            {
                                while (!shouldCancel)
                                {
                                    var res = await client.ReceiveAsync()
                                              .ConfigureAwait(false);
                                    onResponse(res.RemoteEndPoint.Address.ToString(), res.Buffer);
                                }
                            }
                            catch (ObjectDisposedException)
                            {
                            }
                        }, cancellationToken);

                        var broadcastEp = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353);


                        await client.SendAsync(requestBytes, requestBytes.Length, broadcastEp)
                        .ConfigureAwait(false);

                        Debug.WriteLine("Sent mDNS query");


                        // wait for responses
                        await Task.Delay(scanTime, cancellationToken)
                        .ConfigureAwait(false);

                        shouldCancel = true;
                        client.Close();
                        Debug.WriteLine("Done Scanning");


                        await recTask.ConfigureAwait(false);

                        return;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("Execption: ", e);
                        if (i + 1 >= retries) // last one, pass underlying out
                        {
                            throw;
                        }
                    }
                    finally
                    {
#if ANDROID
                        mlock.Release();
#endif
                    }

                    await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false);
                }
            }
        }