Пример #1
0
        public static Packet CreateRstPacketFor(ScanningOptions options, ushort targetPort)
        {
            TcpPacketFactory.RandomizeParameters();

            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = options.SourceMac,
                Destination = options.TargetMac,
            };
            IpV4Layer ipV4Layer = new IpV4Layer
            {
                Source             = options.SourceIP,
                CurrentDestination = options.TargetIP,
                Ttl            = TcpPacketFactory.ttl,
                Fragmentation  = TcpPacketFactory.fragmentation,
                Identification = TcpPacketFactory.identification
            };
            TcpLayer tcpLayer = new TcpLayer
            {
                SourcePort      = sourcePort,
                DestinationPort = targetPort,
                SequenceNumber  = TcpPacketFactory.sequence,
                ControlBits     = TcpControlBits.Reset,
                Window          = TcpPacketFactory.windowSize,
            };

            return(PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, tcpLayer));
        }
        private void DoScan(ScanningOptions options)
        {
            var masterDb = Sitecore.Configuration.Factory.GetDatabase("master");

            ScanItem(options.RootPath);
            void ScanItem(string path)
            {
                var rootContent = masterDb.GetItem(path);

                if (rootContent == null)
                {
                    return;
                }
                rootContent.Fields.ReadAll();
                var includedFields = rootContent.Fields.Where(f =>
                                                              options.ScanFieldTypes.Contains(f.Type) && !string.IsNullOrEmpty(f.Type) && !f.Name.StartsWith("__")).ToArray();

                CustomConsoleLogger.Log($"Reading content {rootContent.Paths.FullPath} found {includedFields.Length} fields", ConsoleColor.DarkMagenta);
                var terms = includedFields.Select(f => f.Value).ToArray();

                _termsRepository.SaveTerms(terms);
                foreach (Item child in rootContent.Children)
                {
                    ScanItem(child.Paths.FullPath);
                }
            }

            Console.Write("Done");
        }
Пример #3
0
        /// <summary>
        /// TestZXingCommand execute.
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private async Task TestZXing(object arg)
        {
            DateTime creationTime = DateTime.Now;

            ScannerPage scannerPage = new ScannerPage(ScanningOptions.ToModel());

            scannerPage.Appearing    += ScannerPage_Appearing;
            scannerPage.Disappearing += ScannerPage_Disappearing;

            //Add tap to focus.
            TapGestureRecognizer tapToFocusGesture = new TapGestureRecognizer();

            tapToFocusGesture.Tapped += (o, e) => scannerPage.SetFocus();
            scannerPage.Overlay.GestureRecognizers.Add(tapToFocusGesture);

            scannerPage.OnScanResult += (result) =>
            {
                // Stop scanning
                scannerPage.IsScanning = false;
                Barcode       = result.Text;
                BarcodeFormat = result.BarcodeFormat;

                DateTime scannedTime = DateTime.Now;
                TimeToScan = scannedTime - creationTime;

                // Pop the page and show the result
                Device.BeginInvokeOnMainThread(async() =>
                {
                    await NavigationHelper.PopAsync();
                });
            };

            // Navigate to our scanner page
            await NavigationHelper.PushAsync(scannerPage);
        }
        public static Packet CreateRequestFor(ScanningOptions options)
        {
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = options.SourceMac,
                Destination = options.TargetMac,
                EtherType   = EthernetType.Arp,
            };
            ArpLayer arpLayer = new ArpLayer
            {
                ProtocolType          = EthernetType.IpV4,
                Operation             = ArpOperation.Request,
                SenderHardwareAddress = options.SourceMac.GetBytesList().AsReadOnly(),
                SenderProtocolAddress = options.SourceIP.GetBytesList().AsReadOnly(),
                TargetHardwareAddress = options.TargetMac.GetBytesList().AsReadOnly(),
                TargetProtocolAddress = options.TargetIP.GetBytesList().AsReadOnly(),
            };
            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);

            return(builder.Build(DateTime.Now));
        }
Пример #5
0
        public static Packet CreateSynPacketFor(ScanningOptions options, ushort targetPort)
        {
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = options.SourceMac,
                Destination = options.TargetMac,
            };
            IpV4Layer ipV4Layer = new IpV4Layer
            {
                Source             = options.SourceIP,
                CurrentDestination = options.TargetIP,
                Ttl           = TcpPacketFactory.ttl,
                Fragmentation = TcpPacketFactory.fragmentation,
            };
            TcpLayer tcpLayer = new TcpLayer
            {
                SourcePort      = TcpPacketFactory.sourcePort,
                DestinationPort = targetPort,
                ControlBits     = TcpControlBits.Synchronize,
                Window          = TcpPacketFactory.windowSize,
            };

            return(PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, tcpLayer));
        }
        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);
        }
Пример #7
0
        public async Task StartScanningAsync(Action <ZXing.Result> scanCallback, MobileBarcodeScanningOptions options = null)
        {
            if (stopping)
            {
                return;
            }

            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 this.GetFilteredCameraOrDefaultAsync(ScanningOptions);

            mediaCapture = new MediaCapture();

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

            // Set the capture element's source to show it in the UI
            captureElement.Source = mediaCapture;

            // Start the preview
            await mediaCapture.StartPreviewAsync();

            // 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 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();
            }

            System.Diagnostics.Debug.WriteLine("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);

            // Set the selected resolution
            await mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, chosenProp);

            await SetPreviewRotationAsync();

            captureElement.Stretch = Stretch.UniformToFill;

            // Get our preview properties
            var previewProperties = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;

            // Setup a frame to use as the input settings
            var destFrame = new VideoFrame(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height);

            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(destFrame);

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

                ZXing.Result result = null;

                try
                {
                    // Try decoding the image
                    if (luminanceSource != null)
                    {
                        result = zxing.Decode(luminanceSource);
                    }
                }
                catch (Exception 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);
        }
Пример #8
0
        bool SetupCaptureSession()
        {
            var started = DateTime.UtcNow;

            var availableResolutions = new List <CameraResolution> ();

            var consideredResolutions = new Dictionary <NSString, CameraResolution> {
                { AVCaptureSession.Preset352x288, new CameraResolution   {
                      Width = 352, Height = 288
                  } },
                { AVCaptureSession.PresetMedium, new CameraResolution    {
                      Width = 480, Height = 360
                  } },                                                                                                          //480x360
                { AVCaptureSession.Preset640x480, new CameraResolution   {
                      Width = 640, Height = 480
                  } },
                { AVCaptureSession.Preset1280x720, new CameraResolution  {
                      Width = 1280, Height = 720
                  } },
                { AVCaptureSession.Preset1920x1080, new CameraResolution {
                      Width = 1920, Height = 1080
                  } }
            };

            // configure the capture session for low resolution, change this if your code
            // can cope with more data or volume
            session = new AVCaptureSession()
            {
                SessionPreset = AVCaptureSession.Preset640x480
            };

            // create a device input and attach it to the session
//			var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
            AVCaptureDevice captureDevice = null;
            var             devices       = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);

            foreach (var device in devices)
            {
                captureDevice = device;
                if (ScanningOptions.UseFrontCameraIfAvailable.HasValue &&
                    ScanningOptions.UseFrontCameraIfAvailable.Value &&
                    device.Position == AVCaptureDevicePosition.Front)
                {
                    break;                     //Front camera successfully set
                }
                else if (device.Position == AVCaptureDevicePosition.Back && (!ScanningOptions.UseFrontCameraIfAvailable.HasValue || !ScanningOptions.UseFrontCameraIfAvailable.Value))
                {
                    break;                     //Back camera succesfully set
                }
            }
            if (captureDevice == null)
            {
                Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }

            CameraResolution resolution = null;

            // Find resolution
            // Go through the resolutions we can even consider
            foreach (var cr in consideredResolutions)
            {
                // Now check to make sure our selected device supports the resolution
                // so we can add it to the list to pick from
                if (captureDevice.SupportsAVCaptureSessionPreset(cr.Key))
                {
                    availableResolutions.Add(cr.Value);
                }
            }

            resolution = ScanningOptions.GetResolution(availableResolutions);

            // See if the user selected a resolution
            if (resolution != null)
            {
                // Now get the preset string from the resolution chosen
                var preset = (from c in consideredResolutions
                              where c.Value.Width == resolution.Width &&
                              c.Value.Height == resolution.Height
                              select c.Key).FirstOrDefault();

                // If we found a matching preset, let's set it on the session
                if (!string.IsNullOrEmpty(preset))
                {
                    session.SessionPreset = preset;
                }
            }

            var input = AVCaptureDeviceInput.FromDevice(captureDevice);

            if (input == null)
            {
                Console.WriteLine("No input - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }
            else
            {
                session.AddInput(input);
            }


            var startedAVPreviewLayerAlloc = PerformanceCounter.Start();

            previewLayer = new AVCaptureVideoPreviewLayer(session);

            PerformanceCounter.Stop(startedAVPreviewLayerAlloc, "Alloc AVCaptureVideoPreviewLayer took {0} ms.");


            // //Framerate set here (15 fps)
            // if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0))
            // {
            //  var perf1 = PerformanceCounter.Start ();

            //  NSError lockForConfigErr = null;

            //  captureDevice.LockForConfiguration (out lockForConfigErr);
            //  if (lockForConfigErr == null)
            //  {
            //      captureDevice.ActiveVideoMinFrameDuration = new CMTime (1, 10);
            //      captureDevice.UnlockForConfiguration ();
            //  }

            //  PerformanceCounter.Stop (perf1, "PERF: ActiveVideoMinFrameDuration Took {0} ms");
            // }
            //          else
            //              previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10);


            var perf2 = PerformanceCounter.Start();

                        #if __UNIFIED__
            previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
                        #else
            previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
                        #endif
            previewLayer.Frame    = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
            previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));

            layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
            layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            layerView.Layer.AddSublayer(previewLayer);

            this.AddSubview(layerView);

            ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);

            if (overlayView != null)
            {
                this.AddSubview(overlayView);
                this.BringSubviewToFront(overlayView);

                //overlayView.LayoutSubviews ();
            }

            PerformanceCounter.Stop(perf2, "PERF: Setting up layers took {0} ms");

            var perf3 = PerformanceCounter.Start();

            session.StartRunning();

            PerformanceCounter.Stop(perf3, "PERF: session.StartRunning() took {0} ms");

            var perf4 = PerformanceCounter.Start();

            var videoSettings = NSDictionary.FromObjectAndKey(new NSNumber((int)CVPixelFormatType.CV32BGRA),
                                                              CVPixelBuffer.PixelFormatTypeKey);


            // create a VideoDataOutput and add it to the sesion
            output = new AVCaptureVideoDataOutput {
                WeakVideoSettings = videoSettings
            };

            // configure the output
            queue = new DispatchQueue("ZxingScannerView");             // (Guid.NewGuid().ToString());

            var barcodeReader = ScanningOptions.BuildBarcodeReader();

            outputRecorder = new OutputRecorder(this, img =>
            {
                var ls = img;

                if (!IsAnalyzing)
                {
                    return(false);
                }

                try
                {
                    var perfDecode = PerformanceCounter.Start();

                    if (shouldRotatePreviewBuffer)
                    {
                        ls = ls.rotateCounterClockwise();
                    }

                    var result = barcodeReader.Decode(ls);

                    PerformanceCounter.Stop(perfDecode, "Decode Time: {0} ms");

                    if (result != null)
                    {
                        resultCallback(result);
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("DECODE FAILED: " + ex);
                }

                return(false);
            });

            output.AlwaysDiscardsLateVideoFrames = true;
            output.SetSampleBufferDelegate(outputRecorder, queue);

            PerformanceCounter.Stop(perf4, "PERF: SetupCamera Finished.  Took {0} ms.");

            session.AddOutput(output);
            //session.StartRunning ();


            var perf5 = PerformanceCounter.Start();

            NSError err = null;
            if (captureDevice.LockForConfiguration(out err))
            {
                if (ScanningOptions.DisableAutofocus)
                {
                    captureDevice.FocusMode = AVCaptureFocusMode.Locked;
                }
                else
                {
                    if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
                    {
                        captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
                    }
                    else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
                    {
                        captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
                    }
                }

                if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
                }
                else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;
                }

                if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
                }
                else if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.AutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
                {
                    captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
                }

                if (captureDevice.FocusPointOfInterestSupported)
                {
                    captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f);
                }

                if (captureDevice.ExposurePointOfInterestSupported)
                {
                    captureDevice.ExposurePointOfInterest = new PointF(0.5f, 0.5f);
                }

                captureDevice.UnlockForConfiguration();
            }
            else
            {
                Console.WriteLine("Failed to Lock for Config: " + err.Description);
            }

            PerformanceCounter.Stop(perf5, "PERF: Setup Focus in {0} ms.");

            return(true);
        }
 public void Start(ScanningOptions options)
 {
     CustomConsoleLogger.Log("Content Reader Started", ConsoleColor.Green);
     DoScan(options);
 }
        bool SetupCaptureSession()
        {
            var started = DateTime.UtcNow;

            // configure the capture session for low resolution, change this if your code
            // can cope with more data or volume
            session = new AVCaptureSession()
            {
                SessionPreset = AVCaptureSession.PresetPhoto
            };

            // create a device input and attach it to the session
//			var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
            captureDevice = null;
            var devices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);

            foreach (var device in devices)
            {
                captureDevice = device;
                if (ScanningOptions.UseFrontCameraIfAvailable.HasValue &&
                    ScanningOptions.UseFrontCameraIfAvailable.Value &&
                    device.Position == AVCaptureDevicePosition.Front)
                {
                    break;                     //Front camera successfully set
                }
                else if (device.Position == AVCaptureDevicePosition.Back && (!ScanningOptions.UseFrontCameraIfAvailable.HasValue || !ScanningOptions.UseFrontCameraIfAvailable.Value))
                {
                    break;                     //Back camera succesfully set
                }
            }
            if (captureDevice == null)
            {
                Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }

            var input = AVCaptureDeviceInput.FromDevice(captureDevice);

            if (input == null)
            {
                Console.WriteLine("No input - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }
            else
            {
                session.AddInput(input);
            }


            var startedAVPreviewLayerAlloc = PerformanceCounter.Start();

            previewLayer = new AVCaptureVideoPreviewLayer(session);

            PerformanceCounter.Stop(startedAVPreviewLayerAlloc, "Alloc AVCaptureVideoPreviewLayer took {0} ms.");

            var perf2 = PerformanceCounter.Start();

                        #if __UNIFIED__
            previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
                        #else
            previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
                        #endif
            previewLayer.Frame    = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
            previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));

            layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
            layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            layerView.Layer.AddSublayer(previewLayer);

            this.AddSubview(layerView);

            ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);

            if (overlayView != null)
            {
                this.AddSubview(overlayView);
                this.BringSubviewToFront(overlayView);

                //overlayView.LayoutSubviews ();
            }

            PerformanceCounter.Stop(perf2, "PERF: Setting up layers took {0} ms");

            var perf3 = PerformanceCounter.Start();

            session.StartRunning();

            PerformanceCounter.Stop(perf3, "PERF: session.StartRunning() took {0} ms");

            var perf4 = PerformanceCounter.Start();

            var videoSettings = NSDictionary.FromObjectAndKey(new NSNumber((int)CVPixelFormatType.CV32BGRA),
                                                              CVPixelBuffer.PixelFormatTypeKey);


            // create a VideoDataOutput and add it to the sesion
            output = new AVCaptureVideoDataOutput {
                WeakVideoSettings = videoSettings
            };

            // configure the output
            queue = new DispatchQueue("ZxingScannerView");             // (Guid.NewGuid().ToString());

            var barcodeReader = ScanningOptions.BuildBarcodeReader();

            outputRecorder = new OutputRecorder(this, img =>
            {
                var ls = img;

                if (!IsAnalyzing)
                {
                    return(false);
                }

                try
                {
                    var perfDecode = PerformanceCounter.Start();

                    if (shouldRotatePreviewBuffer)
                    {
                        ls = ls.rotateCounterClockwise();
                    }

                    var result = barcodeReader.Decode(ls);

                    PerformanceCounter.Stop(perfDecode, "Decode Time: {0} ms");

                    if (result != null)
                    {
                        resultCallback(result);
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("DECODE FAILED: " + ex);
                }

                return(false);
            });

            output.AlwaysDiscardsLateVideoFrames = true;
            output.SetSampleBufferDelegate(outputRecorder, queue);

            PerformanceCounter.Stop(perf4, "PERF: SetupCamera Finished.  Took {0} ms.");

            session.AddOutput(output);
            //session.StartRunning ();


            var perf5 = PerformanceCounter.Start();

            NSError err = null;
            if (captureDevice.LockForConfiguration(out err))
            {
                if (ScanningOptions.DisableAutofocus)
                {
                    captureDevice.FocusMode = AVCaptureFocusMode.Locked;
                }
                else
                {
                    if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
                    {
                        captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
                    }
                    else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
                    {
                        captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
                    }
                }

                if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
                }
                else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;
                }

                if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
                }
                else if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.AutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
                {
                    captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
                }

                if (captureDevice.FocusPointOfInterestSupported)
                {
                    captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f);
                }

                if (captureDevice.ExposurePointOfInterestSupported)
                {
                    captureDevice.ExposurePointOfInterest = new PointF(0.5f, 0.5f);
                }

                captureDevice.UnlockForConfiguration();
            }
            else
            {
                Console.WriteLine("Failed to Lock for Config: " + err.Description);
            }

            PerformanceCounter.Stop(perf5, "PERF: Setup Focus in {0} ms.");

            return(true);
        }
Пример #11
0
        private static void Main(string[] args)
        {
            options = new ScanningOptions();
            SynPortScanner scanner = new SynPortScanner();

            bool exit = false;

            while (!exit)
            {
                Console.WriteLine("1 - Setup scanning options;");
                Console.WriteLine(!scanner.IsBusy ?
                                  "2 - Start scanning;" :
                                  "2 - Stop scanning;");
                Console.WriteLine("3 - Exit.");
                int command = GetIntFromConsole(x => x >= 1 && x <= 3);

                switch (command)
                {
                case 1:
                    PrintDevices();
                    int deviceNum = GetIntFromConsole(num => (num >= 1) && (num <= LivePacketDevice.AllLocalMachine.Count));
                    options.Device = LivePacketDevice.AllLocalMachine[deviceNum - 1];
                    Console.Write("IP address:");
                    options.TargetIP = GetIPFromConsole();
                    Console.Write("From port:");
                    options.StartPort = (ushort)GetIntFromConsole(x => x > 0 && x <= 65535);
                    Console.Write("To port:");
                    options.EndPort = (ushort)GetIntFromConsole(x => x > 0 && x <= 65535);
                    Console.WriteLine("Press Enter to continue...");
                    break;

                case 2:
                    try
                    {
                        if (!scanner.IsBusy)
                        {
                            scanner.Scan(options);
                        }
                        else
                        {
                            scanner.StopCurrentScanning();
                        }
                    }
                    catch (ArgumentException exc)
                    {
                        Console.WriteLine(exc.Message);
                    }
                    break;

                case 3:
                    exit = true;
                    Console.WriteLine("Bye-bye!");
                    break;

                default:
                    Console.WriteLine("Wrong comand!");
                    break;
                }
                Console.ReadLine();
                Console.Clear();
            }
            Console.WriteLine("Press Enter to close the application...");
        }