Log() static private method

static private Log ( string message ) : void
message string
return void
        private async Task InitializeCamera()
        {
            if (Options.UseFrontCameraIfAvailable.HasValue && Options.UseFrontCameraIfAvailable.Value)
            {
                try
                {
                    var frontCameraCaptureResolutions = AudioVideoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Front);
                    var resolution = GetResolution(frontCameraCaptureResolutions.OrderBy(r => r.Width * r.Height));
                    _photoCamera = await AudioVideoCaptureDevice.OpenForVideoOnlyAsync(CameraSensorLocation.Front, resolution);
                }
                catch (Exception ex)
                {
                    MobileBarcodeScanner.Log("Failed to create front facing camera: {0}", ex);
                }
            }

            MobileBarcodeScanner.Log("InitializeCamera");

            if (_photoCamera == null)
            {
                var backCameraCaptureResolutions = AudioVideoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
                var resolution = GetResolution(backCameraCaptureResolutions.OrderBy(r => r.Width * r.Height));
                _photoCamera = await AudioVideoCaptureDevice.OpenForVideoOnlyAsync(CameraSensorLocation.Back, resolution);
            }

            IsAnalyzing = true;

            OnPhotoCameraInitialized(this, new CameraOperationCompletedEventArgs(true, null));

            MobileBarcodeScanner.Log("Wired up Initizialied");
        }
        private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e)
        {
            MobileBarcodeScanner.Log("Initialized Camera");

            if (_photoCamera == null)
            {
                return;
            }

            MobileBarcodeScanner.Log("Creating Luminance Source");

            var width  = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
            var height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);

            _luminance = new PhotoCameraLuminanceSource(width, height);

            var supportedCameraModes = AudioVideoCaptureDevice.GetSupportedPropertyValues(_photoCamera.SensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);

            if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
            {
                _photoCamera.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
            }

            _initialized = true;

            MobileBarcodeScanner.Log("Luminance Source Created");

            OnCameraInitialized(_initialized);
        }
Beispiel #3
0
        private void ReaderOnCameraInitialized(object sender, bool initialized)
        {
            // We dispatch (invoke) to avoid access exceptions
            Dispatcher.BeginInvoke(() =>
            {
                // This must be called here - until now, _reader.Camera is null
                _previewVideo.SetSource(_reader.Camera);

                if (_reader != null && _previewTransform != null)
                {
                    _previewTransform.Rotation = _reader.CameraOrientation;
                }
            });

            MobileBarcodeScanner.Log("ReaderOnCameraInitialized");

            if (_reader != null)
            {
                // We can set if Camera should flash or not when focused
                _reader.FlashMode = FlashMode.Off;

                // Starts the capturing process
                _reader.Start();
            }
        }
Beispiel #4
0
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            try
            {
                isDeactivated            = e.NavigationMode != NavigationMode.Back;
                OnRequestAutoFocus      -= RequestAutoFocusHandler;
                OnRequestTorch          -= RequestTorchHandler;
                OnRequestToggleTorch    -= RequestToggleTorchHandler;
                OnRequestCancel         -= RequestCancelHandler;
                OnRequestIsTorchOn      -= RequestIsTorchOnHandler;
                OnRequestPauseAnalysis  -= RequestPauseAnalysisHandler;
                OnRequestResumeAnalysis -= RequestResumeAnalysisHandler;

                scannerControl.StopScanning();

                if (!ContinuousScanning)
                {
                    RaiseEmptyResult();
                }
            }
            catch (Exception ex) {
                MobileBarcodeScanner.Log("OnNavigatingFrom Error: {0}", ex);
            }

            base.OnNavigatingFrom(e);
        }
Beispiel #5
0
        private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e)
        {
            MobileBarcodeScanner.Log("Initialized Camera");

            if (_photoCamera == null)
            {
                return;
            }

            MobileBarcodeScanner.Log("Creating Luminance Source");

            var width  = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
            var height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);

            _luminance = new PhotoCameraLuminanceSource(width, height);

            if (_photoCamera.IsFlashModeSupported(FlashMode.On))
            {
                _photoCamera.FlashMode = FlashMode.Off;
            }

            _initialized = true;

            MobileBarcodeScanner.Log("Luminance Source Created");

            OnCameraInitialized(_initialized);
        }
Beispiel #6
0
        protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            try
            {
                MobileBarcodeScanner.Log("OnNavigatingFrom, stopping camera...");
                await scannerControl.StopScanningAsync();
            }
            catch (Exception ex)
            {
                MobileBarcodeScanner.Log("OnNavigatingFrom Error: {0}", ex);
            }

            base.OnNavigatingFrom(e);
        }
Beispiel #7
0
        public void StartScanning(Action <ZXing.Result> scanCallback, MobileBarcodeScanningOptions options = null)
        {
            ScanCallback    = scanCallback;
            ScanningOptions = options ?? MobileBarcodeScanningOptions.Default;

            this.topText.Text    = TopText;
            this.bottomText.Text = BottomText;

            if (UseCustomOverlay)
            {
                gridCustomOverlay.Children.Clear();
                if (CustomOverlay != null)
                {
                    gridCustomOverlay.Children.Add(CustomOverlay);
                }

                gridCustomOverlay.Visibility  = Visibility.Visible;
                gridDefaultOverlay.Visibility = Visibility.Collapsed;
            }
            else
            {
                gridCustomOverlay.Visibility  = Visibility.Collapsed;
                gridDefaultOverlay.Visibility = Visibility.Visible;
            }

            MobileBarcodeScanner.Log("ZXingScannerControl.StartScanning");

            // Initialize a new instance of SimpleCameraReader with Auto-Focus mode on
            if (_reader == null)
            {
                MobileBarcodeScanner.Log("Creating SimpleCameraReader");

                //_reader = new SimpleCameraReader(options);
                _reader = new AudioVideoCaptureDeviceCameraReader(options);
                _reader.ScanInterval = ScanningOptions.DelayBetweenAnalyzingFrames;

                // AudioVideoCaptureDevice - move this to camera initialized otherwise throws
                // We need to set the VideoBrush we're going to display the preview feed on
                // IMPORTANT that it gets set before Camera initializes
                //_previewVideo.SetSource(_reader.Camera);

                // The reader throws an event when a result is available
                _reader.DecodingCompleted += (o, r) => DisplayResult(r);

                // The reader throws an event when the camera is initialized and ready to use
                _reader.CameraInitialized += ReaderOnCameraInitialized;
            }
        }
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            try
            {
                OnRequestAutoFocus   -= RequestAutoFocusHandler;
                OnRequestTorch       -= RequestTorchHandler;
                OnRequestToggleTorch -= RequestToggleTorchHandler;
                OnRequestCancel      -= RequestCancelHandler;
                OnRequestIsTorchOn   -= RequestIsTorchOnHandler;

                scannerControl.StopScanning();
            }
            catch (Exception ex) {
                MobileBarcodeScanner.Log("OnNavigatingFrom Error: {0}", ex);
            }

            base.OnNavigatingFrom(e);
        }
Beispiel #9
0
        private void InitializeCamera()
        {
            if (Options.UseFrontCameraIfAvailable.HasValue && Options.UseFrontCameraIfAvailable.Value)
            {
                try { _photoCamera = new PhotoCamera(CameraType.FrontFacing); }
                catch (Exception ex) {
                    MobileBarcodeScanner.Log("Failed to create front facing camera: {0}", ex);
                }
            }

            MobileBarcodeScanner.Log("InitializeCamera");

            if (_photoCamera == null)
            {
                _photoCamera = new PhotoCamera();
            }
            _photoCamera.Initialized += OnPhotoCameraInitialized;

            MobileBarcodeScanner.Log("Wired up Initizialied");
        }
        protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            try
            {
                OnRequestAutoFocus      -= RequestAutoFocusHandler;
                OnRequestTorch          -= RequestTorchHandler;
                OnRequestToggleTorch    -= RequestToggleTorchHandler;
                OnRequestCancel         -= ScanPage_OnRequestCancel;
                OnRequestIsTorchOn      -= RequestIsTorchOnHandler;
                OnRequestPauseAnalysis  -= RequestPauseAnalysisHandler;
                OnRequestResumeAnalysis -= RequestResumeAnalysisHandler;

                await scannerControl.StopScanningAsync();
            }
            catch (Exception ex)
            {
                MobileBarcodeScanner.Log("OnNavigatingFrom Error: {0}", ex);
            }

            base.OnNavigatingFrom(e);
        }
        public async Task StartScanningAsync(Action <ZXing.Result> scanCallback, MobileBarcodeScanningOptions options = null)
        {
            if (stopping)
            {
                var error = "Camera is closing";
                OnScannerError?.Invoke(new[] { error });
                return;
            }


            displayRequest.RequestActive();

            isAnalyzing     = true;
            ScanCallback    = scanCallback;
            ScanningOptions = options ?? MobileBarcodeScanningOptions.Default;

            topText.Text    = TopText ?? string.Empty;
            bottomText.Text = BottomText ?? string.Empty;

            if (UseCustomOverlay)
            {
                gridCustomOverlay.Children.Clear();
                if (CustomOverlay != null)
                {
                    gridCustomOverlay.Children.Add(CustomOverlay);
                }

                gridCustomOverlay.Visibility  = Visibility.Visible;
                gridDefaultOverlay.Visibility = Visibility.Collapsed;
            }
            else
            {
                gridCustomOverlay.Visibility  = Visibility.Collapsed;
                gridDefaultOverlay.Visibility = Visibility.Visible;
            }

            // Find which device to use
            var preferredCamera = await GetFilteredCameraOrDefaultAsync(ScanningOptions);

            if (preferredCamera == null)
            {
                var error = "No camera available";
                System.Diagnostics.Debug.WriteLine(error);
                isMediaCaptureInitialized = false;
                OnScannerError?.Invoke(new[] { error });
                return;
            }

            if (preferredCamera.EnclosureLocation == null || preferredCamera.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
            {
                // No information on the location of the camera, assume it's an external camera, not integrated on the device.
                externalCamera = true;
            }
            else
            {
                // Camera is fixed on the device.
                externalCamera = false;

                // Only mirror the preview if the camera is on the front panel.
                mirroringPreview = preferredCamera.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front;
            }

            mediaCapture = new MediaCapture();

            // Initialize the capture with the settings above
            try
            {
                await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Video,
                    VideoDeviceId        = preferredCamera.Id
                });

                isMediaCaptureInitialized = true;
            }
            catch (UnauthorizedAccessException)
            {
                System.Diagnostics.Debug.WriteLine("Denied access to the camera");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception when init MediaCapture: {0}", ex);
            }

            if (!isMediaCaptureInitialized)
            {
                var error = "Unexpected error on Camera initialisation";
                OnScannerError?.Invoke(new[] { error });
                return;
            }


            // Set the capture element's source to show it in the UI
            captureElement.Source        = mediaCapture;
            captureElement.FlowDirection = mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;

            try
            {
                // Start the preview
                await mediaCapture.StartPreviewAsync();
            }
            catch (Exception ex)
            {
                var error = "Unexpected error on Camera initialisation";
                OnScannerError?.Invoke(new[] { error });
                return;
            }

            if (mediaCapture.CameraStreamState == CameraStreamState.Streaming)
            {
                OnCameraInitialized?.Invoke();
            }

            // Get all the available resolutions for preview
            var availableProperties  = mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview);
            var availableResolutions = new List <CameraResolution>();

            foreach (var ap in availableProperties)
            {
                var vp = (VideoEncodingProperties)ap;
                System.Diagnostics.Debug.WriteLine("Camera Preview Resolution: {0}x{1}", vp.Width, vp.Height);
                availableResolutions.Add(new CameraResolution {
                    Width = (int)vp.Width, Height = (int)vp.Height
                });
            }
            CameraResolution previewResolution = null;

            if (ScanningOptions.CameraResolutionSelector != null)
            {
                previewResolution = ScanningOptions.CameraResolutionSelector(availableResolutions);
            }

            if (availableResolutions == null || availableResolutions.Count < 1)
            {
                var error = "Camera is busy. Try to close all applications that use camera.";
                OnScannerError?.Invoke(new[] { error });
                return;
            }

            // If the user did not specify a resolution, let's try and find a suitable one
            if (previewResolution == null)
            {
                // Loop through all supported sizes
                foreach (var sps in availableResolutions)
                {
                    // Find one that's >= 640x360 but <= 1000x1000
                    // This will likely pick the *smallest* size in that range, which should be fine
                    if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000)
                    {
                        previewResolution = new CameraResolution
                        {
                            Width  = sps.Width,
                            Height = sps.Height
                        };
                        break;
                    }
                }
            }

            if (previewResolution == null)
            {
                previewResolution = availableResolutions.LastOrDefault();
            }

            if (previewResolution == null)
            {
                System.Diagnostics.Debug.WriteLine("No preview resolution available. Camera may be in use by another application.");
                return;
            }

            MobileBarcodeScanner.Log("Using Preview Resolution: {0}x{1}", previewResolution.Width, previewResolution.Height);

            // Find the matching property based on the selection, again
            var chosenProp = availableProperties.FirstOrDefault(ap => ((VideoEncodingProperties)ap).Width == previewResolution.Width && ((VideoEncodingProperties)ap).Height == previewResolution.Height);

            // Pass in the requested preview size properties
            // so we can set them at the same time as the preview rotation
            // to save an additional set property call
            await SetPreviewRotationAsync(chosenProp);

            // *after* the preview is setup, set this so that the UI layout happens
            // otherwise the preview gets stuck in a funny place on screen
            captureElement.Stretch = Stretch.UniformToFill;

            await SetupAutoFocus();

            var zxing = ScanningOptions.BuildBarcodeReader();

            timerPreview = new Timer(async(state) =>
            {
                var delay = ScanningOptions.DelayBetweenAnalyzingFrames;

                if (stopping || processing || !isAnalyzing ||
                    (mediaCapture == null || mediaCapture.CameraStreamState != Windows.Media.Devices.CameraStreamState.Streaming))
                {
                    timerPreview.Change(delay, Timeout.Infinite);
                    return;
                }

                processing = true;

                SoftwareBitmapLuminanceSource luminanceSource = null;

                try
                {
                    // Get preview
                    var frame = await mediaCapture.GetPreviewFrameAsync(videoFrame);

                    // Create our luminance source
                    luminanceSource = new SoftwareBitmapLuminanceSource(frame.SoftwareBitmap);
                }
                catch (Exception ex)
                {
                    MobileBarcodeScanner.Log("GetPreviewFrame Failed: {0}", ex);
                }

                ZXing.Result result = null;

                try
                {
                    // Try decoding the image
                    if (luminanceSource != null)
                    {
                        result = zxing.Decode(luminanceSource);
                    }
                }
                catch (Exception ex)
                {
                    MobileBarcodeScanner.Log("Warning: zxing.Decode Failed: {0}", ex);
                }

                // Check if a result was found
                if (result != null && !string.IsNullOrEmpty(result.Text))
                {
                    if (!ContinuousScanning)
                    {
                        delay = Timeout.Infinite;
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { await StopScanningAsync(); });
                    }
                    else
                    {
                        delay = ScanningOptions.DelayBetweenContinuousScans;
                    }

                    LastScanResult = result;
                    ScanCallback(result);
                }

                processing = false;

                timerPreview.Change(delay, Timeout.Infinite);
            }, null, ScanningOptions.InitialDelayBeforeAnalyzingFrames, Timeout.Infinite);
        }