/// <summary>
        /// Get a given camera id if provided
        /// </summary>
        /// <returns></returns>
        private async Task <DeviceInformation> GetDesiredWebcameraDeviceAsync()
        {
            // Finds all video capture devices
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            DeviceInformation desiredDevice = devices.FirstOrDefault(x => x.Name.Equals(AppSettings.GetString("CameraDeviceName")));

            return(desiredDevice ?? devices.FirstOrDefault());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Queries the available video capture devices to try and find one mounted on the desired panel
        /// </summary>
        /// <param name="desiredPanel">The panel on the device that the desired camera is mounted on</param>
        /// <returns>A DeviceInformation instance with a reference to the camera mounted on the desired panel if available,
        ///          any other camera if not, or null if no camera is available.</returns>
        private static async Task <DeviceInformation> FindCameraDeviceByPanelAsync(Panel desiredPanel)
        {
            // Get available devices for capturing pictures
            DeviceInformationCollection allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            // Get the desired camera by panel
            DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);

            // If there is no device mounted on the desired panel, return the first device found
            return(desiredDevice ?? allVideoDevices.FirstOrDefault());
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 起始化捕捉元件
        /// </summary>
        private async Task InitializeCapture()
        {
            // 案例化MediaCapture
            this.AppMediaCapture = new MediaCapture();
            // 查詢後置攝影機
            DeviceInformationCollection dvcls = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            DeviceInformation backCamera = dvcls.FirstOrDefault(d => d.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            if (backCamera == null)
            {
                throw new NullReferenceException("沒有找到後置攝影機");
            }
            MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();

            // 參考後置攝影機的ID
            settings.VideoDeviceId = backCamera.Id;
            // 不使用音頻輸入裝置
            settings.AudioDeviceId = "";
            // 僅捕捉視訊
            settings.StreamingCaptureMode = StreamingCaptureMode.Video;
            // 起始化MediaCapture物件
            await AppMediaCapture.InitializeAsync(settings);

            System.Diagnostics.Debug.WriteLine("捕捉元件已經起始化。");
        }
        /// <summary>
        /// Gets the device for the desired panel.
        /// </summary>
        /// <returns>The device. If none found, null is returned.</returns>
        private async Task <DeviceInformation> GetDevice()
        {
            _devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

#if DEBUG
            foreach (var device in _devices)
            {
                Debug.WriteLine("{0} {1}", device.Name, device.EnclosureLocation);
            }
#endif

            if (_devices.Count > 0)
            {
                var panelDevices = _devices.Where(d => d.EnclosureLocation != null &&
                                                  d.EnclosureLocation.Panel == DesiredPanel);

                var deviceInformations = panelDevices as IList <DeviceInformation> ?? panelDevices.ToList();

                if (deviceInformations.Any())
                {
                    return(deviceInformations.First());
                }

                // Return any available device if desired panel is not available.
                // This is especially useful with tablets/PCs.
                return(_devices.FirstOrDefault());
            }

            return(null);
        }
        public async void Connect(Action <bool> action)
        {
            string DeviceName = "";

            try
            {
                //получаем все сопряжённые устройства RFCOMM (Dev B)
                var device = DeviceList.FirstOrDefault(x => x.Name == DeviceName);
                //BT_Device = await BluetoothDevice.FromIdAsync(device.Id);

                var _service = await RfcommDeviceService.FromIdAsync(device.Id);

                _socket = new StreamSocket();
                await _socket.ConnectAsync(
                    _service.ConnectionHostName,
                    _service.ConnectionServiceName,
                    SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                conectionStatus = true;
            }
            catch (Exception e)
            {
                conectionStatus = false;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initialize and start the camera preview
        /// </summary>
        public async Task InitializeAsync()
        {
            Status = "Starting camera...";

            // Create a camera preview image source (from Imaging SDK)
            _cameraPreviewImageSource = new CameraPreviewImageSource();

            DeviceInformationCollection devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture);

            String backCameraId = devices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back).Id;

            await _cameraPreviewImageSource.InitializeAsync(backCameraId);

            var properties = await _cameraPreviewImageSource.StartPreviewAsync();

            // Create a preview bitmap with the correct aspect ratio
            var width  = 640.0;
            var height = (width / properties.Width) * properties.Height;
            var bitmap = new WriteableBitmap((int)width, (int)height);

            PreviewBitmap = bitmap;

            // Create a filter effect to be used with the source (no filters yet)

            _writeableBitmapRenderer = new WriteableBitmapRenderer(_cameraPreviewImageSource, _writeableBitmap);

            // Attach preview frame delegate
            _cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;

            Status = "Initialized";

            Initialized = true;
        }
Ejemplo n.º 7
0
        public async Task RunAsync(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            Configuration configuration = new Configuration();

            DefaultConfigurationLoader.Load(configuration);
            ApplicationTriggerConfigurationLoader.Load(configuration, taskInstance.TriggerDetails as ApplicationTriggerDetails);
            ApplicationTriggerDetails triggerDetails = taskInstance.TriggerDetails as ApplicationTriggerDetails;

            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            DeviceInformation device = devices.Where(d => d.EnclosureLocation != null).FirstOrDefault(d => d.EnclosureLocation.Panel == Panel.Back);

            if (device == null)
            {
                device = devices.FirstOrDefault();
            }

            captureService = new CaptureService(configuration.Interval, configuration.Delay, device);
            captureService.ExceptionHandler += OnCaptureException;
            captureService.TryStartIfNotStopped();

            IHttpHandler httpHandler = new AuthenticationHttpHandler(configuration.AuthenticationToken, this);

            server = new HttpServer(httpHandler);
            await server.StartAsync(configuration.Port);
        }
Ejemplo n.º 8
0
        public static CM11AServer GetInstance()
        {
            string aqs = SerialDevice.GetDeviceSelector();
            DeviceInformationCollection dic = DeviceInformation.FindAllAsync(aqs).AsTask().Result;
            DeviceInformation           di  = dic.FirstOrDefault();

            return(GetInstance(di.Id));
        }
Ejemplo n.º 9
0
        private async void InitDevices()
        {
            cameraDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            backFacingDevice = cameraDevices.FirstOrDefault(c => c.EnclosureLocation?.Panel == Windows.Devices.Enumeration.Panel.Back);

            // but if that doesn't exist, take the first camera device available
            preferredDevice = cameraDevices[1];
        }
Ejemplo n.º 10
0
        public async Task InitializeCameraAsync()
        {
            try
            {
                if (_mediaCapture == null)
                {
                    _mediaCapture         = new MediaCapture();
                    _mediaCapture.Failed += MediaCapture_Failed;

                    _cameraDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                    if (_cameraDevices == null || !_cameraDevices.Any())
                    {
                        throw new NotSupportedException();
                    }

                    var device = _cameraDevices.FirstOrDefault(camera => camera.EnclosureLocation?.Panel == Panel);

                    var cameraId = device?.Id ?? _cameraDevices.First().Id;

                    await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = cameraId });

                    if (Panel == Panel.Back)
                    {
                        _mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
                        _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                        _mirroringPreview = false;
                    }
                    else
                    {
                        _mirroringPreview = true;
                    }

                    IsInitialized = true;
                    CanSwitch     = _cameraDevices?.Count > 1;
                    RegisterOrientationEventHandlers();
                    await StartPreviewAsync();
                }
            }
            catch (UnauthorizedAccessException)
            {
                errorMessage.Text = "Camera_Exception_UnauthorizedAccess".GetLocalized();
            }
            catch (NotSupportedException)
            {
                errorMessage.Text = "Camera_Exception_NotSupported".GetLocalized();
            }
            catch (TaskCanceledException)
            {
                errorMessage.Text = "Camera_Exception_InitializationCanceled".GetLocalized();
            }
            catch (Exception)
            {
                errorMessage.Text = "Camera_Exception_InitializationError".GetLocalized();
            }
        }
        public async Task <DeviceInformation> GetDevice(CameraType cameraType)
        {
            if (_deviceCollection == null)
            {
                _deviceCollection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
            }

            var panel = cameraType == CameraType.FrontFacing ? Panel.Front : Panel.Back;

            var device = _deviceCollection.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == panel);

            return(device);
        }
Ejemplo n.º 12
0
        private async void InitializeComPort()
        {
            string aqs = SerialDevice.GetDeviceSelector();
            DeviceInformationCollection dic = await DeviceInformation.FindAllAsync(aqs).AsTask();

            DeviceInformation di = dic.FirstOrDefault();

            _serialPort = await SerialDevice.FromIdAsync(di.Id).AsTask();

            _serialPort.IsDataTerminalReadyEnabled = true;
            _serialPort.BaudRate = 9600;

            _readCancellationTokenSource = new CancellationTokenSource();
        }
Ejemplo n.º 13
0
        private void Initialize()
        {
            string query = HidDevice.GetDeviceSelector(UsagePage, UsageId, VendorId, ProductId);
            DeviceInformationCollection deviceInfos = DeviceInformation.FindAllAsync(query).AsTask().Result;
            string deviceId = deviceInfos.FirstOrDefault()?.Id;

            if (deviceId == null)
            {
                throw new NotSupportedException();
            }

            _device = HidDevice.FromIdAsync(deviceId, FileAccessMode.Read).AsTask().Result;
            _device.InputReportReceived += DeviceInputReportReceived;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
        /// </summary>
        /// <returns>Task</returns>
        private async Task InitializeCameraAsync()
        {
            if (_mediaCapture == null)
            {
                _mediaCapture         = new MediaCapture();
                _mediaCapture.Failed += MediaCapture_Failed;

                _cameraDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                if (_cameraDevices == null)
                {
                    throw new NotSupportedException();
                }

                try
                {
                    var device = _cameraDevices.FirstOrDefault(camera => camera.EnclosureLocation?.Panel == Panel);

                    var cameraId = device != null ? device.Id : _cameraDevices.First().Id;

                    await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = cameraId });

                    if (Panel == Panel.Back)
                    {
                        _mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
                        _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                        _mirroringPreview = false;
                    }
                    else
                    {
                        _mirroringPreview = true;
                    }

                    IsInitialized = true;
                }
                catch (UnauthorizedAccessException ex)
                {
                    throw ex;
                }

                if (IsInitialized)
                {
                    CanSwitch             = _cameraDevices?.Count > 1;
                    PreviewControl.Source = _mediaCapture;
                    RegisterOrientationEventHandlers();
                    await StartPreviewAsync();
                }
            }
        }
        public async Task Initialize(int rotation_offset)
        {
            // it collects informations about avaible devices that can capture video
            Devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            // if there is no current preview running in program or and if there is at least 1 camera avaible
            // then execute operations below - otherwise set error code
            if (Capture == null && Devices.Count > 0)
            {
                // it chooses first avaible device to capture video
                var preferredDevice = Devices.FirstOrDefault();

                // it creates new object from MediaCapture class to capture image
                Capture = new MediaCapture();

                // it prevents display from going to sleep when is inactive
                RequestDisplay.RequestActive();

                // initialization of camera preview
                await Capture.InitializeAsync(
                    new MediaCaptureInitializationSettings
                {
                    VideoDeviceId = preferredDevice.Id
                });

                // it saves all supported resolutions of the camera to 1D array
                var resolutions = Capture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo).ToList();

                // it sets the type of saved data as picture with choosen resolution
                await Capture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, resolutions[47]); // 5 - 1280x720; 47 - 1280x800;

                // it sets the source of UI element as data stream from camera module
                Preview.Source = Capture;

                // it starts previewing the screen in UI
                await Capture.StartPreviewAsync();

                // it sets rotation (variable is sent to method) of the preview
                var rotation_settings = Capture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
                rotation_settings.Properties.Add(RotationKey, rotation_offset);
                await Capture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, rotation_settings, null);
            }
            else
            {
                ErrorCode = "Camera not found";
            }
        }
Ejemplo n.º 16
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            await SharedState.LogAsync($"BackgroundScanner ({taskInstance.InstanceId}): Starting run of background task...");

            _taskInstance           = taskInstance;
            _deferral               = taskInstance.GetDeferral();
            _taskInstance.Progress  = 1;
            _taskInstance.Canceled += TaskInstance_Canceled;

            string selector = SmartCardReader.GetDeviceSelector();
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            var reader = await SmartCardReader.FromIdAsync(devices.FirstOrDefault().Id);

            await SharedState.LogAsync($"BackgroundScanner ({taskInstance.InstanceId}): Got card reader device.");

            reader.CardAdded += Reader_CardAdded;
        }
        /// <summary>
        /// acquires Lamp instance by getting class selection string
        /// for Lamp devices, then selecting the first lamp device on
        /// the back of the device
        /// </summary>
        /// <param name="sender">Contains information regarding button that fired event</param>
        /// <param name="e">Contains state information and event data associated with the event</param>
        private async void InitLampBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                await LogStatusToOutputBoxAsync("Getting class selection string for lamp devices...");

                // Returns class selection string for Lamp devices
                string selectorStr = Lamp.GetDeviceSelector();
                await LogStatusToOutputBoxAsync(string.Format(CultureInfo.InvariantCulture, "Lamp class selection string:\n {0}", selectorStr));

                await LogStatusToOutputBoxAsync("Finding all lamp devices...");

                // Finds all devices based on lamp class selector string
                DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selectorStr);
                await LogStatusToOutputBoxAsync(string.Format(CultureInfo.InvariantCulture, "Number of lamp devices found: {0}", devices.Count.ToString()));

                // Select the first lamp device found on the back of the device
                await LogStatusToOutputBoxAsync("Selecting first lamp device found on back of the device");

                DeviceInformation deviceInfo = devices.FirstOrDefault(di => di.EnclosureLocation != null && di.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

                if (deviceInfo == null)
                {
                    throw new InvalidOperationException("Error: No lamp device was found");
                }

                await LogStatusToOutputBoxAsync(string.Format(CultureInfo.InvariantCulture, "Acquiring Lamp instance from Id:\n {0}", deviceInfo.Id));

                Lamp lamp = await Lamp.FromIdAsync(deviceInfo.Id);
                await LogStatusAsync(string.Format(CultureInfo.InvariantCulture, "Lamp instance acquired, Device Id:\n {0}", lamp.DeviceId), NotifyType.StatusMessage);

                // Here we must Dispose of the lamp object once we are no longer
                // using it to release any native resources
                await LogStatusToOutputBoxAsync("Disposing of lamp instance");

                lamp.Dispose();
                lamp = null;
                await LogStatusToOutputBoxAsync("Disposed");
            }
            catch (Exception eX)
            {
                await LogStatusAsync(eX.Message, NotifyType.ErrorMessage);
            }
        }
        private async Task ConnectAsyncInternal()
        {
            string selector = HidDevice.GetDeviceSelector(UsagePage, UsageId, VID, PID);
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            DeviceInformation brick = devices.FirstOrDefault();

            if (brick == null)
            {
                ThrowException("No LEGO EV3 bricks found.");
            }

            _hidDevice = await HidDevice.FromIdAsync(brick.Id, FileAccessMode.ReadWrite);

            if (_hidDevice == null)
            {
                ThrowException("Unable to connect to LEGO EV3 brick... Is the manifest set properly ?");
            }

            _hidDevice.InputReportReceived += OnHidDeviceInputReportReceived;
        }
Ejemplo n.º 19
0
        private async Task <SerialDevice> TryGetSerialDevice(DeviceInformationCollection devices, string name)
        {
            SerialDevice device = null;

            try
            {
                var id = devices.FirstOrDefault(x => x.Name.Contains(name))?.Id;
                if (id != null)
                {
                    device = await SerialDevice.FromIdAsync(id);
                }
                else
                {
                    device = await SerialDevice.FromIdAsync(devices[0].Id);
                }
            }
            catch (Exception)
            {
            }
            return(device);
        }
Ejemplo n.º 20
0
        public async void GetLampUsingSelectionString()
        {
            //<SnippetGetLampWithSelectionString>
            string selectorString = Lamp.GetDeviceSelector();


            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selectorString);

            DeviceInformation deviceInfo =
                devices.FirstOrDefault(di => di.EnclosureLocation != null &&
                                       di.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            if (deviceInfo == null)
            {
                ShowErrorMessage("No Lamp device found");
            }

            lamp = await Lamp.FromIdAsync(deviceInfo.Id);

            //</SnippetGetLampWithSelectionString>
        }
Ejemplo n.º 21
0
        private async Task DoRead()
        {
            string selector = SmartCardReader.GetDeviceSelector();

            DeviceInformationCollection smartCardReaders =
                await DeviceInformation.FindAllAsync(selector);

            var device = smartCardReaders.FirstOrDefault();

            SmartCardReader reader = await SmartCardReader.FromIdAsync(device.Id);

            IReadOnlyList <SmartCard> cards =
                await reader.FindAllCardsAsync();

            var card = cards.FirstOrDefault();

            if (card == null)
            {
                return;
            }

            (Dictionary <byte, string> address, Dictionary <byte, string> identity)? data = null;

            using (SmartCardConnection connection = await card.ConnectAsync())
            {
                data = await connection.ReadEIdData();
            }
            var identityData = data.Value.identity;
            var addressData  = data.Value.address;

            var dateOfBirth = EIdDateHelper.GetDateTime(identityData[Tags.ID_BIRTH_DATE]);

            FullName.Text       = $"{identityData[Tags.ID_FIRST_NAME]} {identityData[Tags.ID_LAST_NAME]}";
            PlaceOfBirth.Text   = identityData[Tags.ID_BIRTH_LOCATION];
            DateOfBirth.Text    = dateOfBirth.Value.ToString("dd/MM/yyyy");
            Gender.Text         = identityData[Tags.ID_SEX];
            Nationality.Text    = identityData[Tags.ID_NATIONALITY];
            NationalNumber.Text = identityData[Tags.ID_NATIONAL_NUMBER];
            Address.Text        = $"{addressData[Tags.ADDRESS_STREET_NUMBER]} {addressData[Tags.ADDRESS_ZIP_CODE]} {addressData[Tags.ADDRESS_MUNICIPALITY]}";
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Handles midi creation on navigated to
        /// </summary>
        /// <param name="e"></param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            LoadPreset(0);
            if (e.Parameter is int)
            {
                LoadPreset((int)e.Parameter);
            }

            // Find Microsoft synth and instantiate midi
            DeviceInformationCollection deviceInformationCollection = await DeviceInformation.FindAllAsync(MidiOutPort.GetDeviceSelector());

            DeviceInformation synthObject = deviceInformationCollection.FirstOrDefault(x => x.Name == "Microsoft GS Wavetable Synth");

            this.synth = await MidiOutPort.FromIdAsync(synthObject.Id);

            if (this.synth == null)
            {
                _ = await new MessageDialog("Could not find Microsoft GS Wavetable Synth.  Failed to open MIDI port.", "Error Starting App").ShowAsync();
            }

            base.OnNavigatedTo(e);
        }
Ejemplo n.º 23
0
        private static async void EnableFlashlightAsync(WSANativeColour colour = null)
        {
            string selectorString = Lamp.GetDeviceSelector();

            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selectorString);

            DeviceInformation deviceInfo =
                devices.FirstOrDefault(di => di.EnclosureLocation != null &&
                                       di.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            if (deviceInfo != null)
            {
                _lamp = await Lamp.FromIdAsync(deviceInfo.Id);

                if (_lamp.IsColorSettable && colour != null)
                {
                    _lamp.Color = Windows.UI.Color.FromArgb(255, colour.Red, colour.Green, colour.Blue);
                }

                _lamp.IsEnabled = true;
            }
        }
Ejemplo n.º 24
0
        public async Task <bool> ConnectServiceAsync()
        {
            if (ServiceUUID != null)
            {
                if (ServiceInfo == null)
                {
                    string deviceSelector = GattDeviceService.GetDeviceSelectorFromUuid(ServiceUUID);
                    DeviceInformationCollection collection = await DeviceInformation.FindAllAsync(deviceSelector);

                    ServiceInfo = collection.FirstOrDefault();
                }

                if (ServiceInfo != null)
                {
                    Service = await GattDeviceService.FromIdAsync(ServiceInfo.Id);

                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 25
0
        private async Task EnumerateMidiInputDevices()
        {
            // Find all input MIDI devices
            string midiInputQueryString = MidiInPort.GetDeviceSelector();
            DeviceInformationCollection midiInputDevices = await DeviceInformation.FindAllAsync(midiInputQueryString);

            DeviceInformation firstMidiDevice = midiInputDevices.FirstOrDefault();

            if (firstMidiDevice == null)
            {
                return;
            }

            var midiInPort = await MidiInPort.FromIdAsync(firstMidiDevice.Id);

            if (midiInPort == null)
            {
                System.Diagnostics.Debug.WriteLine("Unable to create MidiInPort from input device");
                return;
            }

//todo move me            midiInPort.MessageReceived += MidiInPort_MessageReceived;
        }
Ejemplo n.º 26
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            rfcommServiceInfoCollection = await DeviceInformation.FindAllAsync(
                RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush));

            var count = rfcommServiceInfoCollection.Count;

            Debug.WriteLine("Count of RFCOMM Service: " + count);

            if (count > 0)
            {
                lock (this)
                {
                    streamSocket = new StreamSocket();
                }

                var defaultSvcInfo = rfcommServiceInfoCollection.FirstOrDefault();

                rfcommDeviceService = await RfcommDeviceService.FromIdAsync(defaultSvcInfo.Id);

                if (rfcommDeviceService == null)
                {
                    Debug.WriteLine("Rfcomm Device Service is NULL, ID = {0}", defaultSvcInfo.Id);

                    return;
                }

                Debug.WriteLine("ConnectionHostName: {0}, ConnectionServiceName: {1}", rfcommDeviceService.ConnectionHostName, rfcommDeviceService.ConnectionServiceName);

                await streamSocket.ConnectAsync(rfcommDeviceService.ConnectionHostName, rfcommDeviceService.ConnectionServiceName);

                dataWriter = new DataWriter(streamSocket.OutputStream);

                connectButton.Visibility = Visibility.Collapsed;
            }
        }
Ejemplo n.º 27
0
        private async void CodeScanner_Loaded(object sender, RoutedEventArgs e)
        {
            BarcodeList.ItemsSource = BarcodeHistory = new ObservableCollection <BarcodeItem>();
            ExitLocker = new AutoResetEvent(false);

            string Selector = BarcodeScanner.GetDeviceSelector(PosConnectionTypes.Local);
            DeviceInformationCollection DeviceCollection = await DeviceInformation.FindAllAsync(Selector);

            if (DeviceCollection == null || DeviceCollection.Count == 0)
            {
                Pro.Visibility = Visibility.Collapsed;
                ProText.Text   = "无摄像头可用";
                return;
            }

            if (ApplicationData.Current.LocalSettings.Values["LastSelectedCameraSource"] is string StorageCameraSource)
            {
                foreach (var DeviceID in from Device in DeviceCollection
                         where Device.Name.Contains(StorageCameraSource)
                         select Device.Id)
                {
                    using (BarcodeScanner Scanner = await BarcodeScanner.FromIdAsync(DeviceID))
                    {
                        Capture = new MediaCapture();
                        var InitializeSettings = new MediaCaptureInitializationSettings
                        {
                            VideoDeviceId        = Scanner.VideoDeviceId,
                            StreamingCaptureMode = StreamingCaptureMode.Video,
                            PhotoCaptureSource   = PhotoCaptureSource.VideoPreview
                        };
                        await Capture.InitializeAsync(InitializeSettings);

                        var CameraFocusControl = Capture.VideoDeviceController.FocusControl;
                        if (CameraFocusControl.Supported)
                        {
                            await CameraFocusControl.UnlockAsync();

                            CameraFocusControl.Configure(new FocusSettings {
                                Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange
                            });
                            await CameraFocusControl.FocusAsync();
                        }
                        PreviewControl.Source = Capture;

                        ClaimedScanner = await Scanner.ClaimScannerAsync();

                        ClaimedScanner.IsDisabledOnDataReceived = false;
                        ClaimedScanner.IsDecodeDataEnabled      = true;
                        ClaimedScanner.DataReceived            += ClaimedScanner_DataReceived;
                        await ClaimedScanner.EnableAsync();

                        await ClaimedScanner.StartSoftwareTriggerAsync();

                        await Capture.StartPreviewAsync();
                    }
                    break;
                }

                if (Capture == null)
                {
                    ContentDialog dialog = new ContentDialog
                    {
                        Title           = "提示",
                        Content         = "    设置所指定的摄像头无法应用于条码识别\r\r    已自动选择最合适的摄像头",
                        CloseButtonText = "确定",
                        Background      = Application.Current.Resources["DialogAcrylicBrush"] as Brush
                    };
                    _ = await dialog.ShowAsync();

                    using (BarcodeScanner Scanner = await BarcodeScanner.FromIdAsync(DeviceCollection.FirstOrDefault().Id))
                    {
                        Capture = new MediaCapture();
                        var InitializeSettings = new MediaCaptureInitializationSettings
                        {
                            VideoDeviceId        = Scanner.VideoDeviceId,
                            StreamingCaptureMode = StreamingCaptureMode.Video,
                            PhotoCaptureSource   = PhotoCaptureSource.VideoPreview
                        };
                        await Capture.InitializeAsync(InitializeSettings);

                        var CameraFocusControl = Capture.VideoDeviceController.FocusControl;
                        if (CameraFocusControl.Supported)
                        {
                            await CameraFocusControl.UnlockAsync();

                            CameraFocusControl.Configure(new FocusSettings {
                                Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange
                            });
                            await CameraFocusControl.FocusAsync();
                        }
                        PreviewControl.Source = Capture;

                        ClaimedScanner = await Scanner.ClaimScannerAsync();

                        ClaimedScanner.IsDisabledOnDataReceived = false;
                        ClaimedScanner.IsDecodeDataEnabled      = true;
                        ClaimedScanner.DataReceived            += ClaimedScanner_DataReceived;
                        await ClaimedScanner.EnableAsync();

                        await ClaimedScanner.StartSoftwareTriggerAsync();

                        await Capture.StartPreviewAsync();
                    }
                }
            }
            else
            {
                using (BarcodeScanner Scanner = await BarcodeScanner.FromIdAsync(DeviceCollection.FirstOrDefault().Id))
                {
                    Capture = new MediaCapture();
                    var InitializeSettings = new MediaCaptureInitializationSettings
                    {
                        VideoDeviceId        = Scanner.VideoDeviceId,
                        StreamingCaptureMode = StreamingCaptureMode.Video,
                        PhotoCaptureSource   = PhotoCaptureSource.VideoPreview
                    };
                    await Capture.InitializeAsync(InitializeSettings);

                    var CameraFocusControl = Capture.VideoDeviceController.FocusControl;
                    if (CameraFocusControl.Supported)
                    {
                        await CameraFocusControl.UnlockAsync();

                        CameraFocusControl.Configure(new FocusSettings {
                            Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange
                        });
                        await CameraFocusControl.FocusAsync();
                    }
                    PreviewControl.Source = Capture;

                    ClaimedScanner = await Scanner.ClaimScannerAsync();

                    ClaimedScanner.IsDisabledOnDataReceived = false;
                    ClaimedScanner.IsDecodeDataEnabled      = true;
                    ClaimedScanner.DataReceived            += ClaimedScanner_DataReceived;
                    await ClaimedScanner.EnableAsync();

                    await ClaimedScanner.StartSoftwareTriggerAsync();

                    await Capture.StartPreviewAsync();
                }
            }
            LoadingControl.IsLoading = false;

            ExitLocker.Set();
        }
        /// <summary>
        /// When the user presses the run button, check to see if any of the currently paired devices support the Rfcomm chat service and display them in a list.  
        /// Note that in this case, the other device must be running the Rfcomm Chat Server before being paired.  
        /// </summary>
        /// <param name="sender">Instance that triggered the event.</param>
        /// <param name="e">Event data describing the conditions that led to the event.</param>
        private async void findDevices_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            // Disable the button while we do async operations so the user can't Run twice.
            button.IsEnabled = false;

            // Clear any previous messages
            statusTextBlock.Text = "";

            // Find all paired instances of the Rfcomm chat service and display them in a list
            chatServiceDeviceCollection = await DeviceInformation.FindAllAsync(
                RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid)));

            if (chatServiceDeviceCollection.Count > 0)
            {
                deviceName = chatServiceDeviceCollection.First().Name;
                statusTextBlock.Text = "STATUS: Found device: " + chatServiceDeviceCollection.FirstOrDefault().Name;
            }
            else
            {
                statusTextBlock.Text = "STATUS: No devices found!";
            }

            button.IsEnabled = true;
        }
Ejemplo n.º 29
0
        private async void OnConnectClicked(object sender, RoutedEventArgs e)
        {
            //var serviceUIID = new Guid("F000AA20-0451-4000-B000-000000000000");

            //Find the devices that expose the service
            try
            {
                DeviceInformationCollection devices = await DeviceInformation.FindAllAsync();

                DeviceInformation device = devices.FirstOrDefault(x => x.Name == "MI1S");

                if (device == null)
                {
                    return;
                }

                Output(device);

                GattDeviceService service = await GattDeviceService.FromIdAsync(device.Id);

                if (service == null)
                {
                    return;
                }

                /*
                 * IReadOnlyList<GattCharacteristic> features = service.GetAllCharacteristics();
                 * Output(features);
                 * IReadOnlyList<GattDeviceService> includedServices = service.GetAllIncludedServices();
                 * Output(includedServices);
                 * // */

                BluetoothLEDevice bleDevice = service.Device;

                _band = new MiBand(bleDevice);
                //await band.PairAsync();

                //string name = await band.ReadNameAsync();
                //Debug.WriteLine("Got a name ! : " + name);

                /*
                 *  GattDeviceService batteryService = bleDevice.GetGattService(new Guid("0000fee0-0000-1000-8000-00805f9b34fb"));
                 *  Debug.WriteLine("Battery service");
                 *  Output(batteryService);
                 */
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Exception : {ex.Message}");
                Debug.WriteLine($"Trace : {ex.StackTrace}");
            }

            /*
             *  var device = devices.FirstOrDefault(d => d.Name == "TI BLE Sensor Tag");
             *
             *  if (device != null)
             *  {
             *          //Connect to the service
             *          var service = await GattDeviceService.FromIdAsync(device.Id);
             *  }
             */
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            this.taskInstance = taskInstance;
            this.deferral = taskInstance.GetDeferral();

            // Find all paired instances of the Rfcomm chat service and display them in a list
            chatServiceDeviceCollection = await DeviceInformation.FindAllAsync(
                RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid)));

            if (chatServiceDeviceCollection.Count > 0)
            {
                deviceName = chatServiceDeviceCollection.First().Name;                
            }

            if (deviceName != null)
                await SendMessage(chatServiceDeviceCollection.FirstOrDefault().Id);
            else
            {
                ApplicationData.Current.LocalSettings.Values["ReceivedMessage"] = "Device not found";
                deferral.Complete();
            }
        }
Ejemplo n.º 31
0
        public async Task InitializeCameraAsync()
        {
            try
            {
                if (_setup == null)
                {
                    _setup = new SetupService();
                }
                isAutoShot = await _setup.GetAutomode();

                if (_mediaCapture == null)
                {
                    _mediaCapture         = new MediaCapture();
                    _mediaCapture.Failed += MediaCapture_Failed;

                    _cameraDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

                    if (_cameraDevices == null || !_cameraDevices.Any())
                    {
                        throw new NotSupportedException();
                    }
                    DeviceInformation device;
                    if (_cameraDevices.Count > 1)
                    {
                        device = _cameraDevices.FirstOrDefault(camera => camera.EnclosureLocation?.Panel == Windows.Devices.Enumeration.Panel.Back);
                    }
                    else
                    {
                        device = _cameraDevices.FirstOrDefault(camera => camera.EnclosureLocation?.Panel == Panel);
                    }

                    var cameraId = device?.Id ?? _cameraDevices.First().Id;


                    await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = cameraId });

                    if (_mediaCapture.VideoDeviceController.FocusControl.Supported)
                    {
                        isAutoFocusCapable = true;
                        errorMessage.Text  = "VIZZoneInFront".GetLocalized();
                    }
                    else
                    {
                        isAutoFocusCapable = false;
                        errorMessage.Text  = "NoFocusCamera".GetLocalized();
                    }

                    IMediaEncodingProperties IProps = this._mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
                    vep = (VideoEncodingProperties)IProps;

                    DrawLineOnCanvas(vep.Width, vep.Height);


                    if (Panel == Windows.Devices.Enumeration.Panel.Back)
                    {
                        //_mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
                        //_mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                        _mirroringPreview = false;
                    }
                    else
                    {
                        _mirroringPreview = false;
                    }

                    IsInitialized = true;

                    CanSwitch = _cameraDevices?.Count > 1;
                    RegisterOrientationEventHandlers();
                    await StartPreviewAsync();
                }
            }
            catch (UnauthorizedAccessException)
            {
                errorMessage.Text = "Camera_Exception_UnauthorizedAccess".GetLocalized();
            }
            catch (NotSupportedException)
            {
                errorMessage.Text = "Camera_Exception_NotSupported".GetLocalized();
            }
            catch (TaskCanceledException)
            {
                errorMessage.Text = "Camera_Exception_InitializationCanceled".GetLocalized();
            }
            catch (Exception)
            {
                errorMessage.Text = "Camera_Exception_InitializationError".GetLocalized();
            }
        }
        /// <summary>
        /// Gets the device for the desired panel.
        /// </summary>
        /// <returns>The device. If none found, null is returned.</returns>
        private async Task<DeviceInformation> GetDevice()
        {
            _devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

#if DEBUG
            foreach (var device in _devices)
            {
                Debug.WriteLine("{0} {1}", device.Name, device.EnclosureLocation);
            }
#endif

            if (_devices.Count > 0)
            {
                var panelDevices = _devices.Where(d => d.EnclosureLocation != null
                                                       && d.EnclosureLocation.Panel == DesiredPanel);

                var deviceInformations = panelDevices as IList<DeviceInformation> ?? panelDevices.ToList();

                if (deviceInformations.Any())
                    return deviceInformations.First();

                // Return any available device if desired panel is not available.
                // This is especially useful with tablets/PCs.
                return _devices.FirstOrDefault();
            }

            return null;
        }
Ejemplo n.º 33
0
        async Task StartMediaCapture()
        {
            Debug.WriteLine("Starting MediaCapture");
            app.MediaCapture = new MediaCapture();
            var selectedDevice = _devices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            if (selectedDevice == null)
            {
                selectedDevice = _devices.First();
            }
            await app.MediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
            {
                VideoDeviceId = selectedDevice.Id
            });

            app.PreviewElement.Source = app.MediaCapture;

            _encodingPreviewProperties  = app.MediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview);
            _encodingRecorderProperties = app.MediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoRecord);
            ListAllResolutionDetails();

            var selectedPreviewProperties = _encodingPreviewProperties.First(x => ((VideoEncodingProperties)x).Width == 800);

            ListResolutionDetails((VideoEncodingProperties)selectedPreviewProperties);
            await app.MediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, selectedPreviewProperties);

            var selectedRecordingProperties = _encodingRecorderProperties.First(x => ((VideoEncodingProperties)x).Width == _encodingRecorderProperties.Max(y => ((VideoEncodingProperties)y).Width));

            ListResolutionDetails((VideoEncodingProperties)selectedRecordingProperties);
            await app.MediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoRecord, selectedRecordingProperties);


            PropertySet testSet = new PropertySet();

            FilterEffect effect = new FilterEffect();
            //LomoFilter lomoFilter = new LomoFilter();
            //VignettingFilter vignettingFilter = new VignettingFilter();
            //effect.Filters = new IFilter[] { lomoFilter, vignettingFilter };

            HdrEffect hdrEffect = new HdrEffect(effect);

            List <IImageProvider> providers = new List <IImageProvider>();

            providers.Add(effect);
            providers.Add(hdrEffect);

            testSet.Add(new KeyValuePair <string, object>("IImageProviders", providers));



            await app.MediaCapture.AddEffectAsync(MediaStreamType.VideoPreview, "ImagingEffects.ImagingEffect", testSet);

            //app.MediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);  //need this if portrait mode or landscapeflipped.
            app.IsPreviewing = true;
            await app.MediaCapture.StartPreviewAsync();

            if (app.MediaCapture.VideoDeviceController.FocusControl.Supported) //.SetPresetAsync(Windows.Media.Devices.FocusPreset.Manual);
            {
                await app.MediaCapture.VideoDeviceController.FocusControl.SetPresetAsync(Windows.Media.Devices.FocusPreset.Manual);
            }
            else
            {
                app.MediaCapture.VideoDeviceController.Focus.TrySetAuto(false);
            }
        }