Beispiel #1
0
        public DeviceInformation PickSingleDevice()
        {
            var devicePicker = new DevicePicker();
            var deviceInfo   = devicePicker.PickSingleDevice();

            return(deviceInfo);
        }
Beispiel #2
0
        public MainPage()
        {
            this.DataContext = new MainPageViewModel();
            mqttService      = new MqttService();


            devicePicker = new DevicePicker();
            this.devicePicker.DeviceSelected += async(devicePicker, args) =>
            {
                var device = args.SelectedDevice;
                devicePicker.Hide();

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    try
                    {
                        await mqttService.StartAsync();


                        await PairDeviceIfNecessary(device);

                        await ConnectIGrill(device);
                        Settings.SelectedDeviceId = device.Id;
                    } catch (Exception ex)
                    {
                    }
                });
            };
            devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false));
            devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true));

            this.InitializeComponent();
        }
Beispiel #3
0
        /// <summary>
        /// Sets the global references to UI elements and event handlers for those elements.
        /// </summary>
        private void setupViewElements()
        {
            mVideoView     = (SurfaceView)findViewById(R.id.video);
            mTitleText     = (TextView)findViewById(R.id.titleText);
            mPositionText  = (TextView)findViewById(R.id.positionText);
            mDurationText  = (TextView)findViewById(R.id.durationText);
            mSubtitlesText = (TextView)findViewById(R.id.subtitlesText);
            mSeekBar       = (SeekBar)findViewById(R.id.videoPosition);
            mPlayButton    = (ImageButton)findViewById(R.id.playPause);
            mMuteButton    = (ImageButton)findViewById(R.id.mute);
            mSeekBar.OnSeekBarChangeListener = this;
            mPlayButton.OnClickListener      = this;
            mPositionText.Text = "00:00";

            mProgressDialog                  = new ProgressDialog(this);
            mProgressDialog.Message          = "Buffering...";
            mProgressDialog.Cancelable       = true;
            mProgressDialog.OnCancelListener = new OnCancelListenerAnonymousInnerClassHelper(this);

            View stopButton = findViewById(R.id.stop);

            stopButton.OnClickListener  = this;
            mMuteButton.OnClickListener = this;

            mDevicePicker                        = (DevicePicker)FragmentManager.findFragmentById(R.id.playerPicker);
            mDevicePicker.DeviceType             = SmcDevice.TYPE_AVPLAYER;
            mDevicePicker.DeviceSelectedListener = this;
        }
        private void OnCombinePickerClick(object sender, RoutedEventArgs e)
        {
            if (devicePicker== null)
            {
                devicePicker = new DevicePicker();

                // add casting
                devicePicker.Filter.SupportedDeviceSelectors.Add(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));

                // add dial
                devicePicker.Filter.SupportedDeviceSelectors.Add(DialDevice.GetDeviceSelector("castingsample"));

                // add projection
                devicePicker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());

                devicePicker.DevicePickerDismissed += DevicePicker_DevicePickerDismissed;
                devicePicker.DeviceSelected += DevicePicker_DeviceSelected;
                devicePicker.DisconnectButtonClicked += DevicePicker_DisconnectButtonClicked;
            }

            player.Pause();

            // 從按下的 button 出現 picker 内容
            Button btn = sender as Button;
            GeneralTransform transform = btn.TransformToVisual(Window.Current.Content as UIElement);
            Point pt = transform.TransformPoint(new Point(0, 0));
            devicePicker.Show(new Rect(pt.X, pt.Y, btn.ActualWidth, btn.ActualHeight), Windows.UI.Popups.Placement.Above);
        }
        /// <summary>
        /// Click handler for camera button. Spawns device picker UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void UICameraButton_Click(object sender, RoutedEventArgs e)
        {
            // Disable the top menu while handling the click
            await UpdateMediaSourceButtonsAsync(false);

            var devicePicker = new DevicePicker();

            devicePicker.Filter.SupportedDeviceClasses.Add(DeviceClass.VideoCapture);

            // Calculate the position to show the picker (right below the buttons)
            GeneralTransform ge = UICameraButton.TransformToVisual(null);

            Windows.Foundation.Point point = ge.TransformPoint(new Windows.Foundation.Point());
            Windows.Foundation.Rect  rect  = new Windows.Foundation.Rect(point, new Windows.Foundation.Point(point.X + UICameraButton.ActualWidth, point.Y + UICameraButton.ActualHeight));

            DeviceInformation di = await devicePicker.PickSingleDeviceAsync(rect);

            if (di != null)
            {
                try
                {
                    NotifyUser("Attaching to camera " + di.Name);
                    await ConfigureFrameSourceAsync(di, m_inputImageFeatureDescriptor);
                }
                catch (Exception ex)
                {
                    NotifyUser("Error occurred while initializating MediaCapture:\n" + ex.Message);
                }
            }

            // Re-enable the top menu once done handling the click
            await UpdateMediaSourceButtonsAsync(true);
        }
Beispiel #6
0
        public override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);
            ContentView                                = R.layout.main;
            mSourceDevicePicker                        = (DevicePicker)FragmentManager.findFragmentById(R.id.sourcePicker);
            mSourceDevicePicker.DeviceType             = SmcDevice.TYPE_PROVIDER;
            mSourceDevicePicker.DeviceSelectedListener = mSourceDevicePickerListener;

            mPlayerDevicePicker = (DevicePicker)FragmentManager.findFragmentById(R.id.playerPicker);
            //mPlayerDevicePicker.setDeviceType(SmcDevice.TYPE_IMAGEVIEWER);
            mPlayerDevicePicker.DeviceSelectedListener = mPlayerDevicePickerListener;

            mListView = (ListView)findViewById(R.id.listView);
            mListView.OnItemClickListener = this;
            mItemAdapter      = new ItemAdapter(this);
            mListView.Adapter = mItemAdapter;
            mListView.OnItemLongClickListener = this;
            mItemStack = new Stack <SmcItem>();

            mSmcLib = new Smc();
            try
            {
                mSmcLib.initialize(BaseContext);
            }
            catch (SsdkUnsupportedException e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);                 //TODO Handle exceptions.
            }
        }
Beispiel #7
0
        private async Task CastingVideoToScreen(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                activeDevice         = args.SelectedDevice;
                CastingDevice device = await CastingDevice.FromIdAsync(args.SelectedDevice.Id);
                castingConnection    = device.CreateCastingConnection();

                //Hook up the casting events
                //castingConnection.ErrorOccurred += Connection_ErrorOccurred;
                //castingConnection.StateChanged += Connection_StateChanged;

                // Get the casting source from the MediaElement
                CastingSource source = null;

                try
                {
                    // Get the casting source from the Media Element
                    source = player.GetAsCastingSource();

                    // Start Casting
                    CastingConnectionErrorStatus status = await castingConnection.RequestStartCastingAsync(source);

                    if (status == CastingConnectionErrorStatus.Succeeded)
                    {
                        player.Play();
                    }
                }
                catch
                {
                }
            });
        }
Beispiel #8
0
 private async void DevicePicker_DevicePickerDismissed(DevicePicker sender, object args)
 {
     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         player.Play();
     });
 }
Beispiel #9
0
        private async void DevicePicker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                DeviceInformation selectedDevice = args.SelectedDevice;

#if DEBUG
                // The args.SelectedCastingDevice is proxied from the picker process. The picker process is
                // dismissmed as soon as you break into the debugger. Creating a non-proxied version
                // allows debugging since the proxied version stops working once the picker is dismissed.
                selectedDevice = await DeviceInformation.CreateFromIdAsync(args.SelectedDevice.Id);
#endif

                if (await DialDevice.DeviceInfoSupportsDialAsync(selectedDevice))
                {
                    await SendDialParameter(sender, args);
                }
                else if (await CastingDevice.DeviceInfoSupportsCastingAsync(selectedDevice))
                {
                    await CastingVideoToScreen(sender, args);
                }
                else if (ProjectionManager.ProjectionDisplayAvailable)
                {
                    await ProjectioinViewToScreen(sender, args);
                }
            });
        }
Beispiel #10
0
        private void OnCombinePickerClick(object sender, RoutedEventArgs e)
        {
            if (devicePicker == null)
            {
                devicePicker = new DevicePicker();

                // add casting
                devicePicker.Filter.SupportedDeviceSelectors.Add(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));

                // add dial
                devicePicker.Filter.SupportedDeviceSelectors.Add(DialDevice.GetDeviceSelector("castingsample"));

                // add projection
                devicePicker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());

                devicePicker.DevicePickerDismissed   += DevicePicker_DevicePickerDismissed;
                devicePicker.DeviceSelected          += DevicePicker_DeviceSelected;
                devicePicker.DisconnectButtonClicked += DevicePicker_DisconnectButtonClicked;
            }

            player.Pause();

            // 從按下的 button 出現 picker 内容
            Button           btn       = sender as Button;
            GeneralTransform transform = btn.TransformToVisual(Window.Current.Content as UIElement);
            Point            pt        = transform.TransformPoint(new Point(0, 0));

            devicePicker.Show(new Rect(pt.X, pt.Y, btn.ActualWidth, btn.ActualHeight), Windows.UI.Popups.Placement.Above);
        }
Beispiel #11
0
        private async void Connect_Click(object sender, RoutedEventArgs e)
        {
            string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(App.ChatServiceID));

            DevicePicker picker = new DevicePicker();

            picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33);
            picker.Appearance.ForegroundColor = Colors.White;
            picker.Appearance.AccentColor     = Colors.Goldenrod;

            // add our query string
            picker.Filter.SupportedDeviceSelectors.Add(aqs);

            // prompt user to select a single device
            DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect());

            if (dev != null)
            {
                remoteService = await RfcommDeviceService.FromIdAsync(dev.Id);

                if (remoteService != null)
                {
                    InputText.IsEnabled = true;
                }
            }
        }
Beispiel #12
0
        private void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            var di = args.SelectedDevice;

            StringBuilder sb = new StringBuilder();

            sb.AppendLine(di.Name);
            sb.AppendLine(di.Id);
            sb.AppendLine(di.Kind.ToString());
            sb.AppendLine(di.Pairing.IsPaired.ToString());
            sb.AppendLine(di.Pairing.CanPair.ToString());
            sb.AppendLine("");
            foreach (var item in di.Properties.Keys)
            {
                sb.Append(item);

                string[] props = di.Properties[item] as string[];
                if (props != null)
                {
                    sb.AppendLine(":");
                    foreach (var prop in props)
                    {
                        sb.AppendLine("    " + prop);
                    }
                }
                else
                {
                    sb.AppendLine(": " + di.Properties[item]);
                }
            }

            Trace.WriteLine(sb.ToString());
        }
Beispiel #13
0
        protected internal override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);
            ContentView = R.layout.uploader;

            mTargetDevicePicker                        = (DevicePicker)FragmentManager.findFragmentById(R.id.targetPicker);
            mTargetDevicePicker.DeviceType             = SmcDevice.TYPE_PROVIDER;
            mTargetDevicePicker.DeviceSelectedListener = this;
            mUploadButton = (Button)findViewById(R.id.button);
            mUploadButton.OnClickListener = uploadClickListener;
            progressBar = (ProgressBar)findViewById(R.id.progress);


            SmcItem.LocalContent content = LocalContent;

            if (content == null)
            {
                Toast.makeText(this, "Content not supported", Toast.LENGTH_SHORT).show();
                this.finish();
            }
            else
            {
                itemToUpload = new SmcItem(content);
                ((TextView)findViewById(R.id.header)).Text = "File: " + itemToUpload.Uri.ToString();
            }
        }
Beispiel #14
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush);

            DevicePicker picker = new DevicePicker();

            picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33);
            picker.Appearance.ForegroundColor = Colors.White;
            picker.Appearance.AccentColor     = Colors.Goldenrod;

            // add our query string
            picker.Filter.SupportedDeviceSelectors.Add(aqs);

            // prompt user to select a single device
            DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect(200, 20, 50, 50));

            if (dev != null)
            {
                // if a device is selected create a BluetoothDevice instance to get more information
                RfcommDeviceService service = await RfcommDeviceService.FromIdAsync(dev.Id);

                if (service != null)
                {
                    foreach (KeyValuePair <uint, IBuffer> attrib in await service.GetSdpRawAttributesAsync())
                    {
                        SdpDataElement de = SdpDataElement.FromByteArray(attrib.Value.ToArray());
                        System.Diagnostics.Debug.WriteLine(attrib.Key.ToString("X") + " " + de.ToString());
                    }
                    // set data-binding so that device properties are displayed
                    DeviceInformationPanel.DataContext = service;
                }
            }
        }
Beispiel #15
0
		protected internal override void onCreate(Bundle savedInstanceState)
		{
			base.onCreate(savedInstanceState);
			ContentView = R.layout.uploader;

			mTargetDevicePicker = (DevicePicker) FragmentManager.findFragmentById(R.id.targetPicker);
			mTargetDevicePicker.DeviceType = SmcDevice.TYPE_PROVIDER;
			mTargetDevicePicker.DeviceSelectedListener = this;
			mUploadButton = (Button) findViewById(R.id.button);
			mUploadButton.OnClickListener = uploadClickListener;
			progressBar = (ProgressBar) findViewById(R.id.progress);


			SmcItem.LocalContent content = LocalContent;

			if (content == null)
			{
				Toast.makeText(this, "Content not supported", Toast.LENGTH_SHORT).show();
				this.finish();
			}
			else
			{
				itemToUpload = new SmcItem(content);
				((TextView)findViewById(R.id.header)).Text = "File: " + itemToUpload.Uri.ToString();
			}
		}
Beispiel #16
0
        public void StartScan(Action <BLE_Device_Info> execute)
        {
            DevicePicker picker = new DevicePicker();

            picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false));
            picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true));
            picker.Show(new Rect());
        }
Beispiel #17
0
 private void Picker_DevicePickerDismissed(DevicePicker sender, object args)
 {
     if (_selectedDeviceInformation != null)
     {
         _picker.SetDisplayStatus(_selectedDeviceInformation, "", DevicePickerDisplayStatusOptions.None);
         _selectedDeviceInformation = null;
     }
 }
        /// <summary>
        /// opens device picker and allows user to pick a single device from the list
        ///
        /// [troubleshooting]:
        /// - if no devices show up on the device list, try to pair the PC with desired device inside Windows and try again
        /// </summary>
        private static DeviceInformation PickDevice()
        {
            /* open device picker */
            var picker     = new DevicePicker();
            var deviceInfo = picker.PickSingleDevice();

            return(deviceInfo);
        }
Beispiel #19
0
        private DeviceInformation PickDevice()
        {
            var picker     = new DevicePicker();
            var deviceInfo = picker.PickSingleDevice();

            Debug.Log(deviceInfo.Id);
            return(deviceInfo);
        }
Beispiel #20
0
        private async void DevicePicker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                // 更新 picker 上設備的 status
                sender.SetDisplayStatus(args.SelectedDevice, "connecting", DevicePickerDisplayStatusOptions.ShowProgress);

                // 取得目前選到設備的資訊
                activeDevice = args.SelectedDevice;

                // 現在 view 的 Id 與 CoreDispatcher
                int currentViewId = ApplicationView.GetForCurrentView().Id;
                CoreDispatcher currentDispatcher = Window.Current.Dispatcher;

                // 建立新的 view,
                if (projectionInstance.ProjectionViewPageControl == null)
                {
                    await CoreApplication.CreateNewView().Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        // 建立新 viewe 的生命管理器
                        projectionInstance.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();
                        projectionInstance.MainViewId = currentViewId;

                        var rootFrame = new Frame();
                        rootFrame.Navigate(typeof(ProjectionPage), projectionInstance);

                        // 這裏的 Window 代表是新建立這個 view 的 Window
                        // 但是要等到呼叫 ProjectionManager.StartProjectingAsync 才會顯示
                        Window.Current.Content = rootFrame;
                        Window.Current.Activate();
                    });
                }

                // 直接切換到指定的 view id
                //bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(projectionInstance.ProjectionViewPageControl.Id);

                // 通知要使用新的 view
                projectionInstance.ProjectionViewPageControl.StartViewInUse();

                try
                {
                    txtViewId.Text = $"{projectionInstance.ProjectionViewPageControl.Id}, {currentViewId}";
                    await ProjectionManager.StartProjectingAsync(projectionInstance.ProjectionViewPageControl.Id, currentViewId, activeDevice);

                    player.Pause();

                    sender.SetDisplayStatus(args.SelectedDevice, "connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
                }
                catch (Exception ex)
                {
                    sender.SetDisplayStatus(args.SelectedDevice, ex.Message, DevicePickerDisplayStatusOptions.ShowRetryButton);
                    if (ProjectionManager.ProjectionDisplayAvailable == false)
                    {
                        throw;
                    }
                }
            });
        }
Beispiel #21
0
 private async void Picker_DevicePickerDismissed(DevicePicker sender, object args)
 {
     //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         if (activeDevice == null)
         {
             player.Play();
         }
     });
 }
Beispiel #22
0
        public Scenario2()
        {
            this.InitializeComponent();

            rootPage = MainPage.Current;

            // Get the list of available Azure videos.
            AzureDataProvider    dataProvider = new AzureDataProvider();
            List <VideoMetaData> videos       = dataProvider.GetAll(MAX_RESULTS);
            Random indexRandomizer            = new Random();

            // Pick a random video
            video = videos[indexRandomizer.Next(0, videos.Count - 1)];

            //Subscribe to player events
            player.MediaOpened         += Player_MediaOpened;
            player.MediaFailed         += Player_MediaFailed;
            player.CurrentStateChanged += Player_CurrentStateChanged;

            //Set the look and feel of the TransportControls
            player.TransportControls.IsCompact = true;

            //Set the source on the player
            rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
            player.Source = video.VideoLink;

            //Configure the DIAL launch arguments for the current video
            this.dial_launch_args_textbox.Text = string.Format("v={0}&t=0&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id);

            //Subscribe for the clicked event on the custom cast button
            ((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;

            // Instantiate the Device Picker
            picker = new DevicePicker();

            //Hook up device selected event
            picker.DeviceSelected += Picker_DeviceSelected;

            //Hook up device disconnected event
            picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;

            //Hook up device disconnected event
            picker.DevicePickerDismissed += Picker_DevicePickerDismissed;

            ////Set the Appearence of the picker
            //picker.Appearance.BackgroundColor = Colors.Black;
            //picker.Appearance.ForegroundColor = Colors.White;
            //picker.Appearance.SelectedAccentColor = Colors.LightGray;
            //picker.Appearance.SelectedForegroundColor = Colors.White;
            //picker.Appearance.AccentColor = Colors.White;
            //picker.Appearance.SelectedAccentColor = Colors.White;

            pvb.ProjectionStopping += Pvb_ProjectionStopping;
        }
        private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            string deviceId = args.SelectedDevice.Id;

            //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                //Update the display status for the selected device to connecting.
                picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress);

                // BUG: In order to support debugging it is best to retreive the device from the local app instead
                // of continuing to use the DeviceInformation instance that is proxied from the picker.
                DeviceInformation device = null;
                try { if (deviceId.IndexOf("dial", StringComparison.OrdinalIgnoreCase) == -1)
                      {
                          device = await DeviceInformation.CreateFromIdAsync(deviceId, RequiredDeviceProperties.Props, DeviceInformationKind.DeviceContainer);
                      }
                } catch { }
                try { if (device == null)
                      {
                          device = await DeviceInformation.CreateFromIdAsync(deviceId, RequiredDeviceProperties.Props, DeviceInformationKind.AssociationEndpoint);
                      }
                } catch { }
                // In case the workaround did not work
                if (device == null)
                {
                    device = args.SelectedDevice;
                }

                //Try casting using DIAL first
                bool castSucceeded = await TryLaunchDialAppAsync(device);
                //If DIAL did not work for the selected device, try the CAST API
                if (!castSucceeded)
                {
                    castSucceeded = await TryCastMediaElementAsync(device);
                }

                if (castSucceeded)
                {
                    //Update the display status for the selected device.
                    try { picker.SetDisplayStatus(device, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton); } catch { }
                    disconnectButton.IsEnabled = true;

                    // Hide the picker now that all the work is completed
                    //picker.Hide();
                }
                else
                {
                    //Show a retry button when connecting to the selected device failed.
                    picker.SetDisplayStatus(device, "Connecting failed", DevicePickerDisplayStatusOptions.ShowRetryButton);
                }
            });
        }
        public Scenario06()
        {
            this.InitializeComponent();

            rootPage = MainPage.Current;

            //Subscribe to player events
            player.MediaOpened         += Player_MediaOpened;
            player.MediaFailed         += Player_MediaFailed;
            player.CurrentStateChanged += Player_CurrentStateChanged;

            // Get an Azure hosted video
            AzureDataProvider dataProvider = new AzureDataProvider();

            video = dataProvider.GetRandomVideo();

            //Set the source on the player
            rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
            this.player.Source    = video.VideoLink;
            this.LicenseText.Text = "License: " + video.License;

            //Configure the DIAL launch arguments for the current video
            this.dial_launch_args_textbox.Text = string.Format("v={0}&t=0&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id);

            //Subscribe for the clicked event on the custom cast button
            ((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;

            // Instantiate the Device Picker
            picker = new DevicePicker();

            //Hook up device selected event
            picker.DeviceSelected += Picker_DeviceSelected;

            //Hook up device disconnected event
            picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;

            //Hook up device disconnected event
            picker.DevicePickerDismissed += Picker_DevicePickerDismissed;

            //Add the DIAL Filter, so that the application only shows DIAL devices that have the application installed or advertise that they can install them.
            //BUG: picker.Filter.SupportedDeviceSelectors.Add(DialDevice.GetDeviceSelector(this.dial_appname_textbox.Text));
            picker.Filter.SupportedDeviceSelectors.Add("System.Devices.DevObjectType:=6 AND System.Devices.AepContainer.ProtocolIds:~~{0E261DE4-12F0-46E6-91BA-428607CCEF64} AND System.Devices.AepContainer.Categories:~~Multimedia.ApplicationLauncher.DIAL");

            //Add the CAST API Filter, so that the application only shows Miracast, Bluetooth, DLNA devices that can render the video
            // BUG: picker.Filter.SupportedDeviceSelectors.Add(await CastingDevice.GetDeviceSelectorFromCastingSourceAsync(player.GetAsCastingSource()));
            // BUG: picker.Filter.SupportedDeviceSelectors.Add(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));
            picker.Filter.SupportedDeviceSelectors.Add("System.Devices.InterfaceClassGuid:=\"{D0875FB4-2196-4c7a-A63D-E416ADDD60A1}\"" + " AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");

            //Add projection manager filter
            picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());

            pvb.ProjectionStopping += Pvb_ProjectionStopping;
        }
        public Scenario06()
        {
            this.InitializeComponent();

            rootPage = MainPage.Current;

            //Subscribe to player events
            player.MediaOpened += Player_MediaOpened;
            player.MediaFailed += Player_MediaFailed;
            player.CurrentStateChanged += Player_CurrentStateChanged;

            // Get an Azure hosted video
            AzureDataProvider dataProvider = new AzureDataProvider();
            video = dataProvider.GetRandomVideo();

            //Set the source on the player
            rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
            this.player.Source = video.VideoLink;
            this.LicenseText.Text = "License: " + video.License;

            //Configure the DIAL launch arguments for the current video
            this.dial_launch_args_textbox.Text = string.Format("v={0}&t=0&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id);

            //Subscribe for the clicked event on the custom cast button
            ((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;

            // Instantiate the Device Picker
            picker = new DevicePicker();

            //Hook up device selected event
            picker.DeviceSelected += Picker_DeviceSelected;

            //Hook up device disconnected event
            picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;

            //Hook up device disconnected event
            picker.DevicePickerDismissed += Picker_DevicePickerDismissed;

            //Add the DIAL Filter, so that the application only shows DIAL devices that have the application installed or advertise that they can install them.            
            //BUG: picker.Filter.SupportedDeviceSelectors.Add(DialDevice.GetDeviceSelector(this.dial_appname_textbox.Text));            
            picker.Filter.SupportedDeviceSelectors.Add("System.Devices.DevObjectType:=6 AND System.Devices.AepContainer.ProtocolIds:~~{0E261DE4-12F0-46E6-91BA-428607CCEF64} AND System.Devices.AepContainer.Categories:~~Multimedia.ApplicationLauncher.DIAL");

            //Add the CAST API Filter, so that the application only shows Miracast, Bluetooth, DLNA devices that can render the video
            // BUG: picker.Filter.SupportedDeviceSelectors.Add(await CastingDevice.GetDeviceSelectorFromCastingSourceAsync(player.GetAsCastingSource()));
            // BUG: picker.Filter.SupportedDeviceSelectors.Add(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));
            picker.Filter.SupportedDeviceSelectors.Add("System.Devices.InterfaceClassGuid:=\"{D0875FB4-2196-4c7a-A63D-E416ADDD60A1}\"" + " AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");
            
            //Add projection manager filter
            picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());

            pvb.ProjectionStopping += Pvb_ProjectionStopping;
        }
        private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            string deviceId = args.SelectedDevice.Id;

            //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                //Update the display status for the selected device to connecting.
                try { picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress); } catch { }

                //The selectedDeviceInfo instance is needed to be able to update the picker.
                DeviceInformation selectedDeviceInfo = args.SelectedDevice;
#if DEBUG
                // The args.SelectedCastingDevice is proxied from the picker process. The picker process is
                // dismissmed as soon as you break into the debugger. Creating a non-proxied version
                // allows debugging since the proxied version stops working once the picker is dismissed.
                selectedDeviceInfo = await DeviceInformation.CreateFromIdAsync(args.SelectedDevice.Id);
#endif

                bool castSucceeded = false;

                // If the ProjectionManager API did not work and the device id will have 'dial' in it.
                castSucceeded = await TryLaunchDialAppAsync(selectedDeviceInfo);

                // If it doesn't try the ProjectionManager API.
                if (!castSucceeded)
                {
                    castSucceeded = await TryProjectionManagerCastAsync(selectedDeviceInfo);
                }

                //If DIAL and ProjectionManager did not work for the selected device, try the CAST API
                if (!castSucceeded)
                {
                    castSucceeded = await TryCastMediaElementAsync(selectedDeviceInfo);
                }

                if (castSucceeded)
                {
                    //Update the display status for the selected device.  Try Catch in case the picker is not visible anymore.
                    try { picker.SetDisplayStatus(selectedDeviceInfo, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton); } catch { }

                    // Hide the picker now that all the work is completed. Try Catch in case the picker is not visible anymore.
                    try { picker.Hide(); } catch { }
                }
                else
                {
                    //Show a retry button when connecting to the selected device failed.
                    try { picker.SetDisplayStatus(selectedDeviceInfo, "Connecting failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
                }
            });
        }
Beispiel #27
0
        /// <summary>
        /// ////////////////////////////////////////////
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void startWatcherButton_Click(object sender, RoutedEventArgs e)
        {
            startWatcherButton.IsEnabled = false;

            DevicePicker picker = new DevicePicker();

            picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false));
            //picker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true));
            picker.Show(new Rect(0, 0, 300, 400));



            stopWatcherButton.IsEnabled = true;
        }
Beispiel #28
0
    /// <summary>
    /// 장비 정보 갖고오기
    /// </summary>
    private static DeviceInformation PickDevice()
    {
        //BluetoothAdapter a;
        //BluetoothClassOfDevice b;


        var picker = new DevicePicker();


        var deviceInfo = picker.PickSingleDevice(); //picker.PickSingleDevice();

        //b = a.ClassOfDevice;
        return(deviceInfo);
    }
Beispiel #29
0
        private async Task StopProjection(DevicePicker sender, DeviceInformation device)
        {
            // 關閉新建立的 view
            projectionInstance.Content.StopProjection();

            //Update the display status for the selected device.
            sender.SetDisplayStatus(device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress);

            //Update the display status for the selected device.
            sender.SetDisplayStatus(device, "Disconnected", DevicePickerDisplayStatusOptions.None);

            // Set the active device variables to null
            activeDevice = null;
        }
Beispiel #30
0
        private async void DevicePicker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                DeviceInformation selectedDevice = args.Device;
                if (await DialDevice.DeviceInfoSupportsDialAsync(selectedDevice))
                {
                    await StopDialConnection(sender, selectedDevice);
                    return;
                }

                await StopProjection(sender, selectedDevice);
            });
        }
Beispiel #31
0
        public static IAsyncOperation <DeviceInformation> PickSingleDeviceAsync()
        {
            if (!(Window.Current.Content is Frame rootFrame))
            {
                throw new ArgumentException(nameof(rootFrame));
            }

            var devicePicker = new DevicePicker();

            devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false));
            devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true));

            return(devicePicker.PickSingleDeviceAsync(rootFrame.GetPickerRect()));
        }
        private async void DevicePicker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                DeviceInformation selectedDevice = args.Device;
                if (await DialDevice.DeviceInfoSupportsDialAsync(selectedDevice))
                {
                    await StopDialConnection(sender, selectedDevice);
                    return;
                }

                await StopProjection(sender, selectedDevice);
            });
        }
        private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            string deviceId = args.SelectedDevice.Id;

            //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                //Update the display status for the selected device to connecting.
                picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress);

                // BUG: In order to support debugging it is best to retreive the device from the local app instead
                // of continuing to use the DeviceInformation instance that is proxied from the picker.
                DeviceInformation device = await DeviceInformation.CreateFromIdAsync(deviceId);

                bool castSucceeded = false;

                // The dial AssociationEndpoint ID will have 'dial' in the string.
                // If it doesn't try the ProjectionManager API.
                if (deviceId.IndexOf("dial", StringComparison.OrdinalIgnoreCase) == -1)
                {
                    castSucceeded = await TryProjectionManagerCastAsync(device);
                }
                // If the ProjectionManager API did not work and the device id will have 'dial' in it.
                if (!castSucceeded && deviceId.IndexOf("dial", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    castSucceeded = await TryLaunchDialAppAsync(device);
                }

                //If DIAL and ProjectionManager did not work for the selected device, try the CAST API
                if (!castSucceeded)
                {
                    castSucceeded = await TryCastMediaElementAsync(device);
                }

                if (castSucceeded)
                {
                    //Update the display status for the selected device.  Try Catch in case the picker is not visible anymore.
                    try { picker.SetDisplayStatus(device, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton); } catch { }

                    // Hide the picker now that all the work is completed. Try Catch in case the picker is not visible anymore.
                    try { picker.Hide(); } catch { }
                }
                else
                {
                    //Show a retry button when connecting to the selected device failed.
                    try { picker.SetDisplayStatus(device, "Connecting failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
                }
            });
        }
Beispiel #34
0
        private void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            // Getting the selected device
            _selectedDeviceInformation = args.SelectedDevice;

            // Save a setting locally on the device
            ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

            localSettings.Values[SelectedDeviceKey] = _selectedDeviceInformation.Id;

            _onDeviceSelected(_selectedDeviceInformation.Id);

            // Set status to Connecting
            _picker.SetDisplayStatus(args.SelectedDevice, "", DevicePickerDisplayStatusOptions.None);
        }
Beispiel #35
0
        private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                try
                {
                    // Set status to Connecting
                    picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress);

                    // Getting the selected device improves debugging
                    DeviceInformation selectedDevice = args.SelectedDevice;
                    try
                    {
                        await ProjectionManager.StartProjectingAsync(ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()), thisViewId, selectedDevice);

                    }
                    catch (Exception ex)
                    {
                        if (!ProjectionManager.ProjectionDisplayAvailable)
                            throw ex;
                    }

                    try
                    {
                        
                            activeDevice = selectedDevice;
                        
                            // Set status to Connected
                            picker.SetDisplayStatus(args.SelectedDevice, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
                            picker.Hide();
                    }
                    catch (Exception)
                    {
                        try { picker.SetDisplayStatus(args.SelectedDevice, "Connection Failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
                    }
                }
                catch (Exception ex)
                {
                    
                }
            });
        }
        public Scenario05()
        {
            this.InitializeComponent();

            rootPage = MainPage.Current;

            //Subscribe to player events
            player.MediaOpened += Player_MediaOpened;
            player.MediaFailed += Player_MediaFailed;
            player.CurrentStateChanged += Player_CurrentStateChanged;

            // Get an Azure hosted video
            AzureDataProvider dataProvider = new AzureDataProvider();
            video = dataProvider.GetRandomVideo();

            //Set the source on the player
            rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
            this.player.Source = video.VideoLink;
            this.LicenseText.Text = "License: " + video.License;

            //Subscribe for the clicked event on the custom cast button
            ((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;

            // Instantiate the Device Picker
            picker = new DevicePicker ();

            // Get the device selector for Miracast devices
            picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());

            //Hook up device selected event
            picker.DeviceSelected += Picker_DeviceSelected;

            //Hook up device disconnected event
            picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;

            //Hook up picker dismissed event
            picker.DevicePickerDismissed += Picker_DevicePickerDismissed;

            // Hook up the events that are received when projection is stopped
            pvb.ProjectionStopping += Pvb_ProjectionStopping;
        }
Beispiel #37
0
        public MainPage()
        {
            this.InitializeComponent();
            thisViewId = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id;
            // Instantiate the Device Picker
            picker = new DevicePicker();

            // Get the device selecter for Miracast devices
            picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());

            //Hook up device selected event
            picker.DeviceSelected += Picker_DeviceSelected;

            //Hook up device disconnected event
            picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;

            //Hook up picker dismissed event
            picker.DevicePickerDismissed += Picker_DevicePickerDismissed;

            picker.Show(new Rect(this.ActualWidth, this.ActualHeight , this.ActualWidth, this.ActualHeight), Windows.UI.Popups.Placement.Above);
        }
 public DevicePickerEvents(DevicePicker This)
 {
     this.This = This;
 }
        /// <summary>
        /// Sets the camera object to use, in case you don't want to use the default
        /// </summary>
        private async void SetCameraDevice(object sender, TappedRoutedEventArgs e)
        {
            // Create a DevicePicker
            var devicePicker = new DevicePicker();

            // Set that we are looking for video capture devices
            devicePicker.Filter.SupportedDeviceClasses.Add(DeviceClass.VideoCapture);

            // Calculate the position to show the picker (right below the buttons)
            GeneralTransform transform = SetCameraButton.TransformToVisual(null);
            Point point = transform.TransformPoint(new Point());
            Rect rect = new Rect(point, new Point(point.X + SetCameraButton.ActualWidth, point.Y + SetCameraButton.ActualHeight));

            // Use the device picker to pick the device
            DeviceInformation deviceInfo = await devicePicker.PickSingleDeviceAsync(rect);
            if (null != deviceInfo)
            {
                _presence.CameraDeviceId = deviceInfo.Id;
                _presence.IsDefaultCapture = false;
            }
        }
        private async void DevicePicker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                DeviceInformation selectedDevice = args.SelectedDevice;

#if DEBUG
                // The args.SelectedCastingDevice is proxied from the picker process. The picker process is 
                // dismissmed as soon as you break into the debugger. Creating a non-proxied version 
                // allows debugging since the proxied version stops working once the picker is dismissed.
                selectedDevice = await DeviceInformation.CreateFromIdAsync(args.SelectedDevice.Id);
#endif

                if (await DialDevice.DeviceInfoSupportsDialAsync(selectedDevice))
                {
                    await SendDialParameter(sender, args);
                }
                else if (await CastingDevice.DeviceInfoSupportsCastingAsync(selectedDevice))
                {
                    await CastingVideoToScreen(sender, args);
                }
                else if (ProjectionManager.ProjectionDisplayAvailable)
                {
                    await ProjectioinViewToScreen(sender, args);
                }
            });
        }
        private async void DevicePicker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                // 關閉新建立的 view
                projectionInstance.Content.StopProjection();

                //Update the display status for the selected device.
                sender.SetDisplayStatus(args.Device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress);

                //Update the display status for the selected device.
                sender.SetDisplayStatus(args.Device, "Disconnected", DevicePickerDisplayStatusOptions.None);

                // Set the active device variables to null
                activeDevice = null;
            });
        }
        private async Task StopDialConnection(DevicePicker picker, DeviceInformation device)
        {
            try
            {
                // 取得被選擇的 dial device
                DialDevice selectedDialDevice = await DialDevice.FromIdAsync(device.Id);
                // 更新 picker status
                picker.SetDisplayStatus(device, "connecting", DevicePickerDisplayStatusOptions.ShowProgress);
                // 取得 dial app 
                DialApp app = selectedDialDevice.GetDialApp("castingsample");

                // 請求斷綫
                DialAppStopResult result = await app.StopAsync();

                if (result == DialAppStopResult.Stopped)
                {
                    picker.SetDisplayStatus(device, "Disconnected", DevicePickerDisplayStatusOptions.None);
                    activeDevice = null;
                    picker.Hide();
                }
                else
                {
                    if (result == DialAppStopResult.StopFailed || result == DialAppStopResult.NetworkFailure)
                    {
                        // 如果失敗的話要記得多 retry 的機制
                        picker.SetDisplayStatus(device, "Error", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
                    }
                    else
                    {
                        // 如果設備沒有支援 Stop 機制,則直接清楚連綫就好
                        activeDevice = null;
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {       
            //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                try
                { 
                // Set status to Connecting
                picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress);
                
                // Getting the selected device improves debugging
                DeviceInformation selectedDevice = args.SelectedDevice;

                thisViewId = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id;

                // If projection is already in progress, then it could be shown on the monitor again
                // Otherwise, we need to create a new view to show the presentation
                if (rootPage.ProjectionViewPageControl == null)
                {
                    // First, create a new, blank view
                    var thisDispatcher = Window.Current.Dispatcher;
                    
                    await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        // ViewLifetimeControl is a wrapper to make sure the view is closed only
                        // when the app is done with it
                        rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();

                        // Assemble some data necessary for the new page
                        pvb.MainPageDispatcher = thisDispatcher;
                        pvb.ProjectedPageDispatcher = this.Dispatcher; // Hold a reference to this new UI thread Dispatcher object
                        pvb.ProjectionViewPageControl = rootPage.ProjectionViewPageControl;
                        pvb.MainViewId = thisViewId;

                        // Display the page in the view. Note that the view will not become visible
                        // until "StartProjectingAsync" is called
                        var rootFrame = new Frame();
                        rootFrame.Navigate(typeof(ProjectionViewPage), pvb);
                        Window.Current.Content = rootFrame;

                        Window.Current.Activate();
                    });
                }

                try
                {
                    // Start/StopViewInUse are used to signal that the app is interacting with the
                    // view, so it shouldn't be closed yet, even if the user loses access to it
                    rootPage.ProjectionViewPageControl.StartViewInUse();

                    try
                    {
                        await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, selectedDevice);

                    }
                    catch (Exception ex)
                    {
                        if (!ProjectionManager.ProjectionDisplayAvailable || pvb.ProjectedPage == null)
                            throw ex;
                    }

                    // ProjectionManager currently can throw an exception even when projection has started.
                    // Re-throw the exception when projection has not been started after calling StartProjectingAsync 
                    if (ProjectionManager.ProjectionDisplayAvailable && pvb.ProjectedPage != null)
                    {
                        this.player.Pause();
                        await pvb.ProjectedPage.SetMediaSource(this.player.Source, this.player.Position);
                        activeDevice = selectedDevice;
                        // Set status to Connected
                        picker.SetDisplayStatus(args.SelectedDevice, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
                        picker.Hide(); 
                    }
                    else
                    {
                        rootPage.NotifyUser(string.Format("Projection has failed to '{0}'", selectedDevice.Name), NotifyType.ErrorMessage);
                        // Set status to Failed
                        picker.SetDisplayStatus(args.SelectedDevice, "Connection Failed", DevicePickerDisplayStatusOptions.ShowRetryButton);
                    }
                }
                catch (Exception)
                {
                    rootPage.NotifyUser(string.Format("Projection has failed to '{0}'", selectedDevice.Name), NotifyType.ErrorMessage);
                    // Set status to Failed
                    try { picker.SetDisplayStatus(args.SelectedDevice, "Connection Failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
                }
                }
                catch (Exception ex)
                {
                    UnhandledExceptionPage.ShowUnhandledException(ex);
                }
            });
        }
        private async void Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args)
        {
            //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                rootPage.NotifyUser("Disconnect Button clicked", NotifyType.StatusMessage);

                //Update the display status for the selected device.
                sender.SetDisplayStatus(args.Device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress);

                bool disconnected = false;
                if (this.activeCastConnectionHandler is ProjectionViewBroker)
                    disconnected = TryStopProjectionManagerAsync((ProjectionViewBroker)activeCastConnectionHandler);
                if (this.activeCastConnectionHandler is DialApp)
                    disconnected = await TryStopDialAppAsync((DialApp)activeCastConnectionHandler);
                if (this.activeCastConnectionHandler is CastingConnection)
                    disconnected = await TryDisconnectCastingSessionAsync((CastingConnection)activeCastConnectionHandler);

                if (disconnected)
                {
                    //Update the display status for the selected device.
                    try { sender.SetDisplayStatus(args.Device, "Disconnected", DevicePickerDisplayStatusOptions.None); } catch { }
                    // Set the active device variables to null
                    activeDevice = null;
                    activeCastConnectionHandler = null;

                    //Hide the picker
                    sender.Hide();
                }
                else
                {
                    //Update the display status for the selected device.
                    sender.SetDisplayStatus(args.Device, "Disconnect failed", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
                }
            });
        }
        private async Task ProjectioinViewToScreen(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            // 更新 picker 上設備的 status
            sender.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress);

            // 取得目前選到設備的資訊
            activeDevice = args.SelectedDevice;

            // 現在 view 的 Id 與 CoreDispatcher
            int currentViewId = ApplicationView.GetForCurrentView().Id;
            CoreDispatcher currentDispatcher = Window.Current.Dispatcher;

            // 建立新的 view,
            if (projectionInstance.ProjectionViewPageControl == null)
            {
                await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    // 建立新 viewe 的生命管理器
                    projectionInstance.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();
                    projectionInstance.MainViewId = currentViewId;

                    var rootFrame = new Frame();
                    rootFrame.Navigate(typeof(ProjectionPage), projectionInstance);

                    // 這裏的 Window 代表是新建立這個 view 的 Window
                    // 但是要等到呼叫 ProjectionManager.StartProjectingAsync 才會顯示
                    Window.Current.Content = rootFrame;
                    Window.Current.Activate();
                });
            }

            // 直接切換到指定的 view id
            //bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(projectionInstance.ProjectionViewPageControl.Id);

            // 通知要使用新的 view
            projectionInstance.ProjectionViewPageControl.StartViewInUse();
            await ProjectionManager.SwapDisplaysForViewsAsync(projectionInstance.ProjectionViewPageControl.Id, currentViewId);
            try
            {
                await ProjectionManager.StartProjectingAsync(projectionInstance.ProjectionViewPageControl.Id, currentViewId, activeDevice);

                player.Pause();

                sender.SetDisplayStatus(args.SelectedDevice, "connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
            }
            catch (Exception ex)
            {
                sender.SetDisplayStatus(args.SelectedDevice, ex.Message, DevicePickerDisplayStatusOptions.ShowRetryButton);
                if (ProjectionManager.ProjectionDisplayAvailable == false)
                {
                    throw;
                }
            }
        }
        private async Task SendDialParameter(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            try
            {
                // 設定遠端設備現在要準備連綫
                sender.SetDisplayStatus(args.SelectedDevice, "connecting", DevicePickerDisplayStatusOptions.ShowProgress);

                // 取得遠端設備中支援指定 app name 的 App              
                DialDevice dialDevice = await DialDevice.FromIdAsync(args.SelectedDevice.Id);
                DialApp app = dialDevice.GetDialApp("castingsample");

                if (app == null)
                {
                    // 嘗試建立 DIAL device,如果失敗代表那個設備不支援 DIAL
                    sender.SetDisplayStatus(args.SelectedDevice, "The app is not exist in the device.", DevicePickerDisplayStatusOptions.ShowRetryButton);
                }
                else
                {
                    // 請求送出參數到遠端設備的 App 
                    DialAppLaunchResult result = await app.RequestLaunchAsync("Test");

                    if (result == DialAppLaunchResult.Launched)
                    {
                        activeDevice = args.SelectedDevice;
                        sender.SetDisplayStatus(args.SelectedDevice, "connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
                        sender.Hide();
                    }
                    else
                    {
                        sender.SetDisplayStatus(args.SelectedDevice, "Device Error", DevicePickerDisplayStatusOptions.ShowRetryButton);
                    }
                }
            }
            catch (Exception ex)
            {
                sender.SetDisplayStatus(args.SelectedDevice, ex.Message, DevicePickerDisplayStatusOptions.None);
            }
        }
        private async void ShowDevicePicker(bool pickSingle)
        {
            showDevicePickerButton.IsEnabled = false;
            ResultCollection.Clear();

            devicePicker = new DevicePicker();

            // First get the device selector chosen by the UI.
            DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;

            if (null == deviceSelectorInfo.Selector)
            {
                // If the a pre-canned device class selector was chosen, call the DeviceClass overload
                devicePicker.Filter.SupportedDeviceClasses.Add(deviceSelectorInfo.DeviceClassSelector);
            }
            else
            {
                // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
                devicePicker.Filter.SupportedDeviceSelectors.Add(deviceSelectorInfo.Selector);
            }

            rootPage.NotifyUser("Showing Device Picker", NotifyType.StatusMessage);

            // Calculate the position to show the picker (right below the buttons)
            GeneralTransform ge = pickSingleDeviceButton.TransformToVisual(null);
            Point point = ge.TransformPoint(new Point());
            Rect rect = new Rect(point, new Point(point.X + pickSingleDeviceButton.ActualWidth, point.Y + pickSingleDeviceButton.ActualHeight));

            if (pickSingle)
            {
                DeviceInformation di = await devicePicker.PickSingleDeviceAsync(rect);
                if (null != di)
                {
                    ResultCollection.Add(new DeviceInformationDisplay(di));
                }
                showDevicePickerButton.IsEnabled = true;
            }
            else
            {
                devicePicker.DevicePickerDismissed += new TypedEventHandler<DevicePicker, object>(
                async (picker, obj) =>
                {
                    // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                    await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                    {
                        showDevicePickerButton.IsEnabled = true;
                        rootPage.NotifyUser("Hiding Device Picker", NotifyType.StatusMessage);
                    });
                });

                devicePicker.DeviceSelected += new TypedEventHandler<DevicePicker, DeviceSelectedEventArgs>(
                async (picker, args) =>
                {
                    // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
                    await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                    {
                        ResultCollection.Clear();
                        ResultCollection.Add(new DeviceInformationDisplay(args.SelectedDevice));
                    });
                });

                // Show the picker
                devicePicker.Show(rect);
            }
        }
		/// <summary>
		/// Sets the global references to UI elements and event handlers for those elements.
		/// </summary>
		private void setupViewElements()
		{
			mVideoView = (SurfaceView) findViewById(R.id.video);
			mTitleText = (TextView) findViewById(R.id.titleText);
			mPositionText = (TextView) findViewById(R.id.positionText);
			mDurationText = (TextView) findViewById(R.id.durationText);
			mSubtitlesText = (TextView) findViewById(R.id.subtitlesText);
			mSeekBar = (SeekBar) findViewById(R.id.videoPosition);
			mPlayButton = (ImageButton) findViewById(R.id.playPause);
			mMuteButton = (ImageButton) findViewById(R.id.mute);
			mSeekBar.OnSeekBarChangeListener = this;
			mPlayButton.OnClickListener = this;
			mPositionText.Text = "00:00";

			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.Message = "Buffering...";
			mProgressDialog.Cancelable = true;
			mProgressDialog.OnCancelListener = new OnCancelListenerAnonymousInnerClassHelper(this);

			View stopButton = findViewById(R.id.stop);
			stopButton.OnClickListener = this;
			mMuteButton.OnClickListener = this;

			mDevicePicker = (DevicePicker) FragmentManager.findFragmentById(R.id.playerPicker);
			mDevicePicker.DeviceType = SmcDevice.TYPE_AVPLAYER;
			mDevicePicker.DeviceSelectedListener = this;
		}
Beispiel #49
0
 private async void Picker_DevicePickerDismissed(DevicePicker sender, object args)
 {
     ////Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
     //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     //{
     //    if (activeDevice == null)
     //    {
     //        player.Play();
     //    }
     //});
 }
 private async void DevicePicker_DevicePickerDismissed(DevicePicker sender, object args)
 {
     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         player.Play();
     });
 }
        private async Task StopProjection(DevicePicker sender, DeviceInformation device)
        {
            // 關閉新建立的 view
            projectionInstance.Content.StopProjection();

            //Update the display status for the selected device.
            sender.SetDisplayStatus(device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress);

            //Update the display status for the selected device.
            sender.SetDisplayStatus(device, "Disconnected", DevicePickerDisplayStatusOptions.None);

            // Set the active device variables to null
            activeDevice = null;
        }
        private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            string deviceId = args.SelectedDevice.Id;

            //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                //Update the display status for the selected device to connecting.
                try { picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress); } catch { }

                //The selectedDeviceInfo instance is needed to be able to update the picker.
                DeviceInformation selectedDeviceInfo = args.SelectedDevice;
#if DEBUG
                // The args.SelectedCastingDevice is proxied from the picker process. The picker process is 
                // dismissmed as soon as you break into the debugger. Creating a non-proxied version 
                // allows debugging since the proxied version stops working once the picker is dismissed.
                selectedDeviceInfo = await DeviceInformation.CreateFromIdAsync(args.SelectedDevice.Id);
#endif

                bool castSucceeded = false;

                // If the ProjectionManager API did not work and the device id will have 'dial' in it.
                castSucceeded = await TryLaunchDialAppAsync(selectedDeviceInfo);

                // If it doesn't try the ProjectionManager API.
                if (!castSucceeded)
                    castSucceeded = await TryProjectionManagerCastAsync(selectedDeviceInfo);

                //If DIAL and ProjectionManager did not work for the selected device, try the CAST API
                if (!castSucceeded)
                    castSucceeded = await TryCastMediaElementAsync(selectedDeviceInfo);

                if (castSucceeded)
                {
                    //Update the display status for the selected device.  Try Catch in case the picker is not visible anymore.
                    try { picker.SetDisplayStatus(selectedDeviceInfo, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton); } catch { }

                    // Hide the picker now that all the work is completed. Try Catch in case the picker is not visible anymore.
                    try { picker.Hide(); } catch { }
                }
                else
                {
                    //Show a retry button when connecting to the selected device failed.
                    try { picker.SetDisplayStatus(selectedDeviceInfo, "Connecting failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
                }
            });
        }
        private async Task CastingVideoToScreen(DevicePicker sender, DeviceSelectedEventArgs args)
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                activeDevice = args.SelectedDevice;
                CastingDevice device =await  CastingDevice.FromIdAsync(args.SelectedDevice.Id);
                castingConnection = device.CreateCastingConnection();
                
                //Hook up the casting events
                //castingConnection.ErrorOccurred += Connection_ErrorOccurred;
                //castingConnection.StateChanged += Connection_StateChanged;

                // Get the casting source from the MediaElement
                CastingSource source = null;

                try
                {
                    // Get the casting source from the Media Element
                    source = player.GetAsCastingSource();

                    // Start Casting
                    CastingConnectionErrorStatus status = await castingConnection.RequestStartCastingAsync(source);

                    if (status == CastingConnectionErrorStatus.Succeeded)
                    {
                        player.Play();
                    }
                }
                catch
                {

                }
            });
        }
Beispiel #54
0
        private async void Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args)
        {
            ////Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
            //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            //{
            //    rootPage.NotifyUser("Disconnect Button clicked", NotifyType.StatusMessage);
            //    //Update the display status for the selected device.
            //    sender.SetDisplayStatus(args.Device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress);

            //    if (this.pvb.ProjectedPage != null)
            //        this.pvb.ProjectedPage.StopProjecting();

            //    //Update the display status for the selected device.
            //    sender.SetDisplayStatus(args.Device, "Disconnected", DevicePickerDisplayStatusOptions.None);
            //    rootPage.NotifyUser("Disconnected", NotifyType.StatusMessage);

            //    // Set the active device variables to null
            //    activeDevice = null;
            //});
        }